{"repo_name": "SpeedyNote", "file_name": "/SpeedyNote/source/PdfOpenDialog.h", "inference_info": {"prefix_code": "", "suffix_code": ";", "middle_code": "class PdfOpenDialog {\n Q_OBJECT\npublic:\n enum Result {\n Cancel,\n CreateNewFolder,\n UseExistingFolder\n };\n explicit PdfOpenDialog(const QString &pdfPath, QWidget *parent = nullptr) {\n setWindowTitle(tr(\"Open PDF with SpeedyNote\"));\n setWindowIcon(QIcon(\":/resources/icons/mainicon.png\"));\n setModal(true);\n QScreen *screen = QGuiApplication::primaryScreen();\n qreal dpr = screen ? screen->devicePixelRatio() : 1.0;\n int baseWidth = 500;\n int baseHeight = 200;\n int scaledWidth = static_cast(baseWidth * qMax(1.0, dpr * 0.8));\n int scaledHeight = static_cast(baseHeight * qMax(1.0, dpr * 0.8));\n setMinimumSize(scaledWidth, scaledHeight);\n setMaximumSize(scaledWidth + 100, scaledHeight + 50); \n setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);\n setupUI();\n adjustSize();\n if (parent) {\n move(parent->geometry().center() - rect().center());\n } else {\n move(screen->geometry().center() - rect().center());\n }\n}\n static bool hasValidNotebookFolder(const QString &pdfPath, QString &folderPath) {\n QFileInfo fileInfo(pdfPath);\n QString suggestedFolderName = fileInfo.baseName(); \n QString pdfDir = fileInfo.absolutePath(); \n QString potentialFolderPath = pdfDir + \"/\" + suggestedFolderName;\n if (isValidNotebookFolder(potentialFolderPath, pdfPath)) {\n folderPath = potentialFolderPath;\n return true;\n }\n return false;\n}\n protected:\n void resizeEvent(QResizeEvent *event) override {\n if (event->size() != event->oldSize()) {\n QDialog::resizeEvent(event);\n QSize newSize = event->size();\n QSize minSize = minimumSize();\n QSize maxSize = maximumSize();\n newSize = newSize.expandedTo(minSize).boundedTo(maxSize);\n if (newSize != event->size()) {\n resize(newSize);\n }\n } else {\n QDialog::resizeEvent(event);\n }\n}\n private:\n void onCreateNewFolder() {\n QFileInfo fileInfo(pdfPath);\n QString suggestedFolderName = fileInfo.baseName();\n QString pdfDir = fileInfo.absolutePath();\n QString newFolderPath = pdfDir + \"/\" + suggestedFolderName;\n if (QDir(newFolderPath).exists()) {\n QMessageBox::StandardButton reply = QMessageBox::question(\n this, \n tr(\"Folder Exists\"), \n tr(\"A folder named \\\"%1\\\" already exists in the same directory as the PDF.\\n\\nDo you want to use this existing folder?\").arg(suggestedFolderName),\n QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel\n );\n if (reply == QMessageBox::Yes) {\n selectedFolder = newFolderPath;\n result = UseExistingFolder;\n accept();\n return;\n } else if (reply == QMessageBox::Cancel) {\n return; \n }\n int counter = 1;\n do {\n newFolderPath = pdfDir + \"/\" + suggestedFolderName + QString(\"_%1\").arg(counter);\n counter++;\n } while (QDir(newFolderPath).exists() && counter < 100);\n if (counter >= 100) {\n QMessageBox::warning(this, tr(\"Error\"), tr(\"Could not create a unique folder name.\"));\n return;\n }\n }\n QDir dir;\n if (dir.mkpath(newFolderPath)) {\n selectedFolder = newFolderPath;\n result = CreateNewFolder;\n accept();\n } else {\n QMessageBox::warning(this, tr(\"Error\"), tr(\"Failed to create folder: %1\").arg(newFolderPath));\n }\n}\n void onUseExistingFolder() {\n QString folder = QFileDialog::getExistingDirectory(\n this, \n tr(\"Select Existing Notebook Folder\"), \n QFileInfo(pdfPath).absolutePath()\n );\n if (!folder.isEmpty()) {\n selectedFolder = folder;\n result = UseExistingFolder;\n accept();\n }\n}\n void onCancel() {\n result = Cancel;\n reject();\n}\n private:\n void setupUI() {\n QVBoxLayout *mainLayout = new QVBoxLayout(this);\n mainLayout->setSpacing(15);\n mainLayout->setContentsMargins(20, 20, 20, 20);\n mainLayout->setSizeConstraint(QLayout::SetMinAndMaxSize);\n QHBoxLayout *headerLayout = new QHBoxLayout();\n headerLayout->setSpacing(10);\n QLabel *iconLabel = new QLabel();\n QPixmap icon = QIcon(\":/resources/icons/mainicon.png\").pixmap(48, 48);\n iconLabel->setPixmap(icon);\n iconLabel->setFixedSize(48, 48);\n iconLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);\n QLabel *titleLabel = new QLabel(tr(\"Open PDF with SpeedyNote\"));\n titleLabel->setStyleSheet(\"font-size: 16px; font-weight: bold;\");\n titleLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);\n headerLayout->addWidget(iconLabel);\n headerLayout->addWidget(titleLabel);\n headerLayout->addStretch();\n mainLayout->addLayout(headerLayout);\n QFileInfo fileInfo(pdfPath);\n QString fileName = fileInfo.fileName();\n QString folderName = fileInfo.baseName(); \n QLabel *messageLabel = new QLabel(tr(\"PDF File: %1\\n\\nHow would you like to open this PDF?\").arg(fileName));\n messageLabel->setWordWrap(true);\n messageLabel->setStyleSheet(\"font-size: 12px; color: #666;\");\n messageLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);\n mainLayout->addWidget(messageLabel);\n QVBoxLayout *buttonLayout = new QVBoxLayout();\n buttonLayout->setSpacing(10);\n QPushButton *createFolderBtn = new QPushButton(tr(\"Create New Notebook Folder (\\\"%1\\\")\").arg(folderName));\n createFolderBtn->setIcon(QApplication::style()->standardIcon(QStyle::SP_DirIcon));\n createFolderBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);\n createFolderBtn->setMinimumHeight(40);\n createFolderBtn->setStyleSheet(R\"(\n QPushButton {\n text-align: left;\n padding: 10px;\n border: 1px solid palette(mid);\n border-radius: 5px;\n background: palette(button);\n }\n QPushButton:hover {\n background: palette(light);\n border-color: palette(dark);\n }\n QPushButton:pressed {\n background: palette(midlight);\n }\n )\");\n connect(createFolderBtn, &QPushButton::clicked, this, &PdfOpenDialog::onCreateNewFolder);\n QPushButton *existingFolderBtn = new QPushButton(tr(\"Use Existing Notebook Folder...\"));\n existingFolderBtn->setIcon(QApplication::style()->standardIcon(QStyle::SP_DirOpenIcon));\n existingFolderBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);\n existingFolderBtn->setMinimumHeight(40);\n existingFolderBtn->setStyleSheet(R\"(\n QPushButton {\n text-align: left;\n padding: 10px;\n border: 1px solid palette(mid);\n border-radius: 5px;\n background: palette(button);\n }\n QPushButton:hover {\n background: palette(light);\n border-color: palette(dark);\n }\n QPushButton:pressed {\n background: palette(midlight);\n }\n )\");\n connect(existingFolderBtn, &QPushButton::clicked, this, &PdfOpenDialog::onUseExistingFolder);\n buttonLayout->addWidget(createFolderBtn);\n buttonLayout->addWidget(existingFolderBtn);\n mainLayout->addLayout(buttonLayout);\n QHBoxLayout *cancelLayout = new QHBoxLayout();\n cancelLayout->addStretch();\n QPushButton *cancelBtn = new QPushButton(tr(\"Cancel\"));\n cancelBtn->setIcon(QApplication::style()->standardIcon(QStyle::SP_DialogCancelButton));\n cancelBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);\n cancelBtn->setMinimumSize(80, 30);\n cancelBtn->setStyleSheet(R\"(\n QPushButton {\n padding: 8px 20px;\n border: 1px solid palette(mid);\n border-radius: 3px;\n background: palette(button);\n }\n QPushButton:hover {\n background: palette(light);\n }\n QPushButton:pressed {\n background: palette(midlight);\n }\n )\");\n connect(cancelBtn, &QPushButton::clicked, this, &PdfOpenDialog::onCancel);\n cancelLayout->addWidget(cancelBtn);\n mainLayout->addLayout(cancelLayout);\n}\n static bool isValidNotebookFolder(const QString &folderPath, const QString &pdfPath) {\n QDir folder(folderPath);\n if (!folder.exists()) {\n return false;\n }\n QString pdfPathFile = folderPath + \"/.pdf_path.txt\";\n if (QFile::exists(pdfPathFile)) {\n QFile file(pdfPathFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString storedPdfPath = in.readLine().trimmed();\n file.close();\n if (!storedPdfPath.isEmpty()) {\n QFileInfo currentPdf(pdfPath);\n QFileInfo storedPdf(storedPdfPath);\n if (storedPdf.exists() && \n currentPdf.absoluteFilePath() == storedPdf.absoluteFilePath()) {\n return true;\n }\n }\n }\n }\n QString notebookIdFile = folderPath + \"/.notebook_id.txt\";\n if (QFile::exists(notebookIdFile)) {\n QStringList contentFiles = folder.entryList(\n QStringList() << \"*.png\" << \".pdf_path.txt\" << \".bookmarks.txt\" << \".background_config.txt\", \n QDir::Files\n );\n if (!contentFiles.isEmpty()) {\n return false;\n }\n }\n return false;\n}\n Result result;\n QString selectedFolder;\n QString pdfPath;\n}", "code_description": null, "fill_type": "CLASS_TYPE", "language_type": "cpp", "sub_task_type": null}, "context_code": [["/SpeedyNote/source/MainWindow.h", "class QTreeWidgetItem {\n Q_OBJECT\n\npublic:\n explicit MainWindow(QWidget *parent = nullptr);\n virtual ~MainWindow() {\n\n saveButtonMappings(); // ✅ Save on exit, as backup\n delete canvas;\n}\n int getCurrentPageForCanvas(InkCanvas *canvas) {\n return pageMap.contains(canvas) ? pageMap[canvas] : 0;\n}\n bool lowResPreviewEnabled = true;\n void setLowResPreviewEnabled(bool enabled) {\n lowResPreviewEnabled = enabled;\n\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"lowResPreviewEnabled\", enabled);\n}\n bool isLowResPreviewEnabled() const {\n return lowResPreviewEnabled;\n}\n bool areBenchmarkControlsVisible() const {\n return benchmarkButton->isVisible() && benchmarkLabel->isVisible();\n}\n void setBenchmarkControlsVisible(bool visible) {\n benchmarkButton->setVisible(visible);\n benchmarkLabel->setVisible(visible);\n}\n bool zoomButtonsVisible = true;\n bool areZoomButtonsVisible() const {\n return zoomButtonsVisible;\n}\n void setZoomButtonsVisible(bool visible) {\n zoom50Button->setVisible(visible);\n dezoomButton->setVisible(visible);\n zoom200Button->setVisible(visible);\n\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"zoomButtonsVisible\", visible);\n \n // Update zoomButtonsVisible flag and trigger layout update\n zoomButtonsVisible = visible;\n \n // Trigger layout update to adjust responsive thresholds\n if (layoutUpdateTimer) {\n layoutUpdateTimer->stop();\n layoutUpdateTimer->start(50); // Quick update for settings change\n } else {\n updateToolbarLayout(); // Direct update if no timer exists yet\n }\n}\n bool scrollOnTopEnabled = false;\n bool isScrollOnTopEnabled() const {\n return scrollOnTopEnabled;\n}\n void setScrollOnTopEnabled(bool enabled) {\n scrollOnTopEnabled = enabled;\n\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"scrollOnTopEnabled\", enabled);\n}\n bool touchGesturesEnabled = true;\n bool areTouchGesturesEnabled() const {\n return touchGesturesEnabled;\n}\n void setTouchGesturesEnabled(bool enabled) {\n touchGesturesEnabled = enabled;\n \n // Apply to all canvases\n for (int i = 0; i < canvasStack->count(); ++i) {\n InkCanvas *canvas = qobject_cast(canvasStack->widget(i));\n if (canvas) {\n canvas->setTouchGesturesEnabled(enabled);\n }\n }\n \n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"touchGesturesEnabled\", enabled);\n}\n QColor customAccentColor;\n bool useCustomAccentColor = false;\n QColor getAccentColor() const {\n if (useCustomAccentColor && customAccentColor.isValid()) {\n return customAccentColor;\n }\n \n // Return system accent color\n QPalette palette = QGuiApplication::palette();\n return palette.highlight().color();\n}\n void setCustomAccentColor(const QColor &color) {\n if (customAccentColor != color) {\n customAccentColor = color;\n saveThemeSettings();\n // Always update theme if custom accent color is enabled\n if (useCustomAccentColor) {\n updateTheme();\n }\n }\n}\n void setUseCustomAccentColor(bool use) {\n if (useCustomAccentColor != use) {\n useCustomAccentColor = use;\n updateTheme();\n saveThemeSettings();\n }\n}\n void setUseBrighterPalette(bool use) {\n if (useBrighterPalette != use) {\n useBrighterPalette = use;\n \n // Update all colors - call updateColorPalette which handles null checks\n updateColorPalette();\n \n // Save preference\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"useBrighterPalette\", useBrighterPalette);\n }\n}\n QColor getDefaultPenColor() {\n return isDarkMode() ? Qt::white : Qt::black;\n}\n SDLControllerManager *controllerManager = nullptr;\n QThread *controllerThread = nullptr;\n QString getHoldMapping(const QString &buttonName) {\n return buttonHoldMapping.value(buttonName, \"None\");\n}\n QString getPressMapping(const QString &buttonName) {\n return buttonPressMapping.value(buttonName, \"None\");\n}\n void saveButtonMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n\n settings.beginGroup(\"ButtonHoldMappings\");\n for (auto it = buttonHoldMapping.begin(); it != buttonHoldMapping.end(); ++it) {\n settings.setValue(it.key(), it.value());\n }\n settings.endGroup();\n\n settings.beginGroup(\"ButtonPressMappings\");\n for (auto it = buttonPressMapping.begin(); it != buttonPressMapping.end(); ++it) {\n settings.setValue(it.key(), it.value());\n }\n settings.endGroup();\n}\n void loadButtonMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n\n // First, check if we need to migrate old settings\n migrateOldButtonMappings();\n\n settings.beginGroup(\"ButtonHoldMappings\");\n QStringList holdKeys = settings.allKeys();\n for (const QString &key : holdKeys) {\n buttonHoldMapping[key] = settings.value(key, \"none\").toString();\n }\n settings.endGroup();\n\n settings.beginGroup(\"ButtonPressMappings\");\n QStringList pressKeys = settings.allKeys();\n for (const QString &key : pressKeys) {\n QString value = settings.value(key, \"none\").toString();\n buttonPressMapping[key] = value;\n\n // ✅ Convert internal key to action enum\n buttonPressActionMapping[key] = stringToAction(value);\n }\n settings.endGroup();\n}\n void setHoldMapping(const QString &buttonName, const QString &dialMode) {\n buttonHoldMapping[buttonName] = dialMode;\n}\n void setPressMapping(const QString &buttonName, const QString &action) {\n buttonPressMapping[buttonName] = action;\n buttonPressActionMapping[buttonName] = stringToAction(action); // ✅ THIS LINE WAS MISSING\n}\n DialMode dialModeFromString(const QString &mode) {\n // Convert internal key to our existing DialMode enum\n InternalDialMode internalMode = ButtonMappingHelper::internalKeyToDialMode(mode);\n \n switch (internalMode) {\n case InternalDialMode::None: return PageSwitching; // Default fallback\n case InternalDialMode::PageSwitching: return PageSwitching;\n case InternalDialMode::ZoomControl: return ZoomControl;\n case InternalDialMode::ThicknessControl: return ThicknessControl;\n\n case InternalDialMode::ToolSwitching: return ToolSwitching;\n case InternalDialMode::PresetSelection: return PresetSelection;\n case InternalDialMode::PanAndPageScroll: return PanAndPageScroll;\n }\n return PanAndPageScroll; // Default fallback\n}\n void importNotebookFromFile(const QString &packageFile) {\n\n QString destDir = QFileDialog::getExistingDirectory(this, tr(\"Select Working Directory for Notebook\"));\n\n if (destDir.isEmpty()) {\n QMessageBox::warning(this, tr(\"Import Cancelled\"), tr(\"No directory selected. Notebook will not be opened.\"));\n return;\n }\n\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n\n canvas->importNotebookTo(packageFile, destDir);\n\n // Change saveFolder in InkCanvas\n canvas->setSaveFolder(destDir);\n canvas->loadPage(0);\n updateZoom(); // ✅ Update zoom and pan range after importing notebook\n}\n void openPdfFile(const QString &pdfPath) {\n // Check if the PDF file exists\n if (!QFile::exists(pdfPath)) {\n QMessageBox::warning(this, tr(\"File Not Found\"), tr(\"The PDF file could not be found:\\n%1\").arg(pdfPath));\n return;\n }\n \n // First, check if there's already a valid notebook folder for this PDF\n QString existingFolderPath;\n if (PdfOpenDialog::hasValidNotebookFolder(pdfPath, existingFolderPath)) {\n // Found a valid notebook folder, open it directly without showing dialog\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n \n // Save current work if edited\n if (canvas->isEdited()) {\n saveCurrentPage();\n }\n \n // Set the existing folder as save folder\n canvas->setSaveFolder(existingFolderPath);\n \n // Load the PDF\n canvas->loadPdf(pdfPath);\n \n // Update tab label and recent notebooks\n updateTabLabel();\n if (recentNotebooksManager) {\n recentNotebooksManager->addRecentNotebook(existingFolderPath, canvas);\n }\n \n // Switch to page 1 and update UI\n switchPageWithDirection(1, 1);\n pageInput->setValue(1);\n updateZoom();\n updatePanRange();\n \n return; // Exit early, no need to show dialog\n }\n \n // No valid notebook folder found, show the dialog with options\n PdfOpenDialog dialog(pdfPath, this);\n dialog.exec();\n \n PdfOpenDialog::Result result = dialog.getResult();\n QString selectedFolder = dialog.getSelectedFolder();\n \n if (result == PdfOpenDialog::Cancel) {\n return; // User cancelled, do nothing\n }\n \n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n \n // Save current work if edited\n if (canvas->isEdited()) {\n saveCurrentPage();\n }\n \n if (result == PdfOpenDialog::CreateNewFolder) {\n // Set the new folder as save folder\n canvas->setSaveFolder(selectedFolder);\n \n // Load the PDF\n canvas->loadPdf(pdfPath);\n \n // Update tab label and recent notebooks\n updateTabLabel();\n if (recentNotebooksManager) {\n recentNotebooksManager->addRecentNotebook(selectedFolder, canvas);\n }\n \n // Switch to page 1 and update UI\n switchPageWithDirection(1, 1);\n pageInput->setValue(1);\n updateZoom();\n updatePanRange();\n \n } else if (result == PdfOpenDialog::UseExistingFolder) {\n // Check if the existing folder is linked to the same PDF\n QString metadataFile = selectedFolder + \"/.pdf_path.txt\";\n bool isLinkedToSamePdf = false;\n \n if (QFile::exists(metadataFile)) {\n QFile file(metadataFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString existingPdfPath = in.readLine().trimmed();\n file.close();\n \n // Compare absolute paths\n QFileInfo existingInfo(existingPdfPath);\n QFileInfo newInfo(pdfPath);\n isLinkedToSamePdf = (existingInfo.absoluteFilePath() == newInfo.absoluteFilePath());\n }\n }\n \n if (!isLinkedToSamePdf && QFile::exists(metadataFile)) {\n // Folder is linked to a different PDF, ask user what to do\n QMessageBox::StandardButton reply = QMessageBox::question(\n this,\n tr(\"Different PDF Linked\"),\n tr(\"This notebook folder is already linked to a different PDF file.\\n\\nDo you want to replace the link with the new PDF?\"),\n QMessageBox::Yes | QMessageBox::No\n );\n \n if (reply == QMessageBox::No) {\n return; // User chose not to replace\n }\n }\n \n // Set the existing folder as save folder\n canvas->setSaveFolder(selectedFolder);\n \n // Load the PDF\n canvas->loadPdf(pdfPath);\n \n // Update tab label and recent notebooks\n updateTabLabel();\n if (recentNotebooksManager) {\n recentNotebooksManager->addRecentNotebook(selectedFolder, canvas);\n }\n \n // Switch to page 1 and update UI\n switchPageWithDirection(1, 1);\n pageInput->setValue(1);\n updateZoom();\n updatePanRange();\n }\n}\n void setPdfDPI(int dpi) {\n if (dpi != pdfRenderDPI) {\n pdfRenderDPI = dpi;\n savePdfDPI(dpi);\n\n // Apply immediately to current canvas if needed\n if (currentCanvas()) {\n currentCanvas()->setPDFRenderDPI(dpi);\n currentCanvas()->clearPdfCache();\n currentCanvas()->loadPdfPage(getCurrentPageForCanvas(currentCanvas())); // Optional: add this if needed\n updateZoom();\n updatePanRange();\n }\n }\n}\n void savePdfDPI(int dpi) {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"pdfRenderDPI\", dpi);\n}\n void saveDefaultBackgroundSettings(BackgroundStyle style, QColor color, int density) {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"defaultBackgroundStyle\", static_cast(style));\n settings.setValue(\"defaultBackgroundColor\", color.name());\n settings.setValue(\"defaultBackgroundDensity\", density);\n}\n void loadDefaultBackgroundSettings(BackgroundStyle &style, QColor &color, int &density) {\n QSettings settings(\"SpeedyNote\", \"App\");\n style = static_cast(settings.value(\"defaultBackgroundStyle\", static_cast(BackgroundStyle::Grid)).toInt());\n color = QColor(settings.value(\"defaultBackgroundColor\", \"#FFFFFF\").toString());\n density = settings.value(\"defaultBackgroundDensity\", 30).toInt();\n \n // Ensure valid values\n if (!color.isValid()) color = Qt::white;\n if (density < 10) density = 10;\n if (density > 200) density = 200;\n}\n void saveThemeSettings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"useCustomAccentColor\", useCustomAccentColor);\n if (customAccentColor.isValid()) {\n settings.setValue(\"customAccentColor\", customAccentColor.name());\n }\n settings.setValue(\"useBrighterPalette\", useBrighterPalette);\n}\n void loadThemeSettings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n useCustomAccentColor = settings.value(\"useCustomAccentColor\", false).toBool();\n QString colorName = settings.value(\"customAccentColor\", \"#0078D4\").toString();\n customAccentColor = QColor(colorName);\n useBrighterPalette = settings.value(\"useBrighterPalette\", false).toBool();\n \n // Ensure valid values\n if (!customAccentColor.isValid()) {\n customAccentColor = QColor(\"#0078D4\"); // Default blue\n }\n \n // Apply theme immediately after loading\n updateTheme();\n}\n void updateTheme() {\n // Update control bar background color\n QColor accentColor = getAccentColor();\n if (controlBar) {\n controlBar->setStyleSheet(QString(R\"(\n QWidget#controlBar {\n background-color: %1;\n }\n )\").arg(accentColor.name()));\n }\n \n // Update dial background color\n if (pageDial) {\n pageDial->setStyleSheet(QString(R\"(\n QDial {\n background-color: %1;\n }\n )\").arg(accentColor.name()));\n }\n \n // Update add tab button styling\n if (addTabButton) {\n bool darkMode = isDarkMode();\n QString buttonBgColor = darkMode ? \"rgba(80, 80, 80, 255)\" : \"rgba(220, 220, 220, 255)\";\n QString buttonHoverColor = darkMode ? \"rgba(90, 90, 90, 255)\" : \"rgba(200, 200, 200, 255)\";\n QString buttonPressColor = darkMode ? \"rgba(70, 70, 70, 255)\" : \"rgba(180, 180, 180, 255)\";\n QString borderColor = darkMode ? \"rgba(100, 100, 100, 255)\" : \"rgba(180, 180, 180, 255)\";\n \n addTabButton->setStyleSheet(QString(R\"(\n QPushButton {\n background-color: %1;\n border: 1px solid %2;\n border-radius: 12px;\n margin: 2px;\n }\n QPushButton:hover {\n background-color: %3;\n }\n QPushButton:pressed {\n background-color: %4;\n }\n )\").arg(buttonBgColor).arg(borderColor).arg(buttonHoverColor).arg(buttonPressColor));\n }\n \n // Update PDF outline sidebar styling\n if (outlineSidebar && outlineTree) {\n bool darkMode = isDarkMode();\n QString bgColor = darkMode ? \"rgba(45, 45, 45, 255)\" : \"rgba(250, 250, 250, 255)\";\n QString borderColor = darkMode ? \"rgba(80, 80, 80, 255)\" : \"rgba(200, 200, 200, 255)\";\n QString textColor = darkMode ? \"#E0E0E0\" : \"#333\";\n QString hoverColor = darkMode ? \"rgba(60, 60, 60, 255)\" : \"rgba(240, 240, 240, 255)\";\n QString selectedColor = QString(\"rgba(%1, %2, %3, 100)\").arg(accentColor.red()).arg(accentColor.green()).arg(accentColor.blue());\n \n outlineSidebar->setStyleSheet(QString(R\"(\n QWidget {\n background-color: %1;\n border-right: 1px solid %2;\n }\n QLabel {\n color: %3;\n background: transparent;\n }\n )\").arg(bgColor).arg(borderColor).arg(textColor));\n \n outlineTree->setStyleSheet(QString(R\"(\n QTreeWidget {\n background-color: %1;\n border: none;\n color: %2;\n outline: none;\n }\n QTreeWidget::item {\n padding: 4px;\n border: none;\n }\n QTreeWidget::item:hover {\n background-color: %3;\n }\n QTreeWidget::item:selected {\n background-color: %4;\n color: %2;\n }\n QTreeWidget::branch {\n background: transparent;\n }\n QTreeWidget::branch:has-children:!has-siblings:closed,\n QTreeWidget::branch:closed:has-children:has-siblings {\n border-image: none;\n image: url(:/resources/icons/down_arrow.png);\n }\n QTreeWidget::branch:open:has-children:!has-siblings,\n QTreeWidget::branch:open:has-children:has-siblings {\n border-image: none;\n image: url(:/resources/icons/up_arrow.png);\n }\n QScrollBar:vertical {\n background: rgba(200, 200, 200, 80);\n border: none;\n margin: 0px;\n width: 16px !important;\n max-width: 16px !important;\n }\n QScrollBar:vertical:hover {\n background: rgba(200, 200, 200, 120);\n }\n QScrollBar::handle:vertical {\n background: rgba(100, 100, 100, 150);\n border-radius: 2px;\n min-height: 120px;\n }\n QScrollBar::handle:vertical:hover {\n background: rgba(80, 80, 80, 210);\n }\n QScrollBar::add-line:vertical, \n QScrollBar::sub-line:vertical {\n width: 0px;\n height: 0px;\n background: none;\n border: none;\n }\n QScrollBar::add-page:vertical, \n QScrollBar::sub-page:vertical {\n background: transparent;\n }\n )\").arg(bgColor).arg(textColor).arg(hoverColor).arg(selectedColor));\n \n // Apply same styling to bookmarks tree\n bookmarksTree->setStyleSheet(QString(R\"(\n QTreeWidget {\n background-color: %1;\n border: none;\n color: %2;\n outline: none;\n }\n QTreeWidget::item {\n padding: 2px;\n border: none;\n min-height: 26px;\n }\n QTreeWidget::item:hover {\n background-color: %3;\n }\n QTreeWidget::item:selected {\n background-color: %4;\n color: %2;\n }\n QScrollBar:vertical {\n background: rgba(200, 200, 200, 80);\n border: none;\n margin: 0px;\n width: 16px !important;\n max-width: 16px !important;\n }\n QScrollBar:vertical:hover {\n background: rgba(200, 200, 200, 120);\n }\n QScrollBar::handle:vertical {\n background: rgba(100, 100, 100, 150);\n border-radius: 2px;\n min-height: 120px;\n }\n QScrollBar::handle:vertical:hover {\n background: rgba(80, 80, 80, 210);\n }\n QScrollBar::add-line:vertical, \n QScrollBar::sub-line:vertical {\n width: 0px;\n height: 0px;\n background: none;\n border: none;\n }\n QScrollBar::add-page:vertical, \n QScrollBar::sub-page:vertical {\n background: transparent;\n }\n )\").arg(bgColor).arg(textColor).arg(hoverColor).arg(selectedColor));\n }\n \n // Update horizontal tab bar styling with accent color\n if (tabList) {\n bool darkMode = isDarkMode();\n QString bgColor = darkMode ? \"rgba(60, 60, 60, 255)\" : \"rgba(240, 240, 240, 255)\";\n QString itemBgColor = darkMode ? \"rgba(80, 80, 80, 255)\" : \"rgba(220, 220, 220, 255)\";\n QString selectedBgColor = darkMode ? \"rgba(45, 45, 45, 255)\" : \"white\";\n QString borderColor = darkMode ? \"rgba(100, 100, 100, 255)\" : \"rgba(180, 180, 180, 255)\";\n QString hoverBgColor = darkMode ? \"rgba(90, 90, 90, 255)\" : \"rgba(230, 230, 230, 255)\";\n \n tabList->setStyleSheet(QString(R\"(\n QListWidget {\n background-color: %1;\n border: none;\n border-bottom: 2px solid %2;\n outline: none;\n }\n QListWidget::item {\n background-color: %3;\n border: 1px solid %4;\n border-bottom: none;\n margin-right: 1px;\n margin-top: 2px;\n padding: 0px;\n min-width: 80px;\n max-width: 120px;\n }\n QListWidget::item:selected {\n background-color: %5;\n border: 1px solid %4;\n border-bottom: 2px solid %2;\n margin-top: 1px;\n }\n QListWidget::item:hover:!selected {\n background-color: %6;\n }\n QScrollBar:horizontal {\n background: %1;\n height: 8px;\n border: none;\n margin: 0px;\n border-top: 1px solid %4;\n }\n QScrollBar::handle:horizontal {\n background: rgba(150, 150, 150, 120);\n border-radius: 4px;\n min-width: 20px;\n margin: 1px;\n }\n QScrollBar::handle:horizontal:hover {\n background: rgba(120, 120, 120, 200);\n }\n QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal {\n width: 0px;\n height: 0px;\n background: none;\n border: none;\n }\n QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {\n background: transparent;\n }\n )\").arg(bgColor)\n .arg(accentColor.name())\n .arg(itemBgColor)\n .arg(borderColor)\n .arg(selectedBgColor)\n .arg(hoverBgColor));\n }\n \n\n \n // Force icon reload for all buttons that use themed icons\n if (loadPdfButton) loadPdfButton->setIcon(loadThemedIcon(\"pdf\"));\n if (clearPdfButton) clearPdfButton->setIcon(loadThemedIcon(\"pdfdelete\"));\n if (pdfTextSelectButton) pdfTextSelectButton->setIcon(loadThemedIcon(\"ibeam\"));\n if (exportNotebookButton) exportNotebookButton->setIcon(loadThemedIcon(\"export\"));\n if (importNotebookButton) importNotebookButton->setIcon(loadThemedIcon(\"import\"));\n if (benchmarkButton) benchmarkButton->setIcon(loadThemedIcon(\"benchmark\"));\n if (toggleTabBarButton) toggleTabBarButton->setIcon(loadThemedIcon(\"tabs\"));\n if (toggleOutlineButton) toggleOutlineButton->setIcon(loadThemedIcon(\"outline\"));\n if (toggleBookmarksButton) toggleBookmarksButton->setIcon(loadThemedIcon(\"bookmark\"));\n if (toggleBookmarkButton) toggleBookmarkButton->setIcon(loadThemedIcon(\"star\"));\n if (selectFolderButton) selectFolderButton->setIcon(loadThemedIcon(\"folder\"));\n if (saveButton) saveButton->setIcon(loadThemedIcon(\"save\"));\n if (saveAnnotatedButton) saveAnnotatedButton->setIcon(loadThemedIcon(\"saveannotated\"));\n if (fullscreenButton) fullscreenButton->setIcon(loadThemedIcon(\"fullscreen\"));\n if (backgroundButton) backgroundButton->setIcon(loadThemedIcon(\"background\"));\n if (straightLineToggleButton) straightLineToggleButton->setIcon(loadThemedIcon(\"straightLine\"));\n if (ropeToolButton) ropeToolButton->setIcon(loadThemedIcon(\"rope\"));\n if (markdownButton) markdownButton->setIcon(loadThemedIcon(\"markdown\"));\n if (deletePageButton) deletePageButton->setIcon(loadThemedIcon(\"trash\"));\n if (zoomButton) zoomButton->setIcon(loadThemedIcon(\"zoom\"));\n if (dialToggleButton) dialToggleButton->setIcon(loadThemedIcon(\"dial\"));\n if (fastForwardButton) fastForwardButton->setIcon(loadThemedIcon(\"fastforward\"));\n if (jumpToPageButton) jumpToPageButton->setIcon(loadThemedIcon(\"bookpage\"));\n if (thicknessButton) thicknessButton->setIcon(loadThemedIcon(\"thickness\"));\n if (btnPageSwitch) btnPageSwitch->setIcon(loadThemedIcon(\"bookpage\"));\n if (btnZoom) btnZoom->setIcon(loadThemedIcon(\"zoom\"));\n if (btnThickness) btnThickness->setIcon(loadThemedIcon(\"thickness\"));\n if (btnTool) btnTool->setIcon(loadThemedIcon(\"pen\"));\n if (btnPresets) btnPresets->setIcon(loadThemedIcon(\"preset\"));\n if (btnPannScroll) btnPannScroll->setIcon(loadThemedIcon(\"scroll\"));\n if (addPresetButton) addPresetButton->setIcon(loadThemedIcon(\"savepreset\"));\n if (openControlPanelButton) openControlPanelButton->setIcon(loadThemedIcon(\"settings\"));\n if (openRecentNotebooksButton) openRecentNotebooksButton->setIcon(loadThemedIcon(\"recent\"));\n if (penToolButton) penToolButton->setIcon(loadThemedIcon(\"pen\"));\n if (markerToolButton) markerToolButton->setIcon(loadThemedIcon(\"marker\"));\n if (eraserToolButton) eraserToolButton->setIcon(loadThemedIcon(\"eraser\"));\n \n // Update button styles with new theme\n bool darkMode = isDarkMode();\n QString newButtonStyle = createButtonStyle(darkMode);\n \n // Update all buttons that use the buttonStyle\n if (loadPdfButton) loadPdfButton->setStyleSheet(newButtonStyle);\n if (clearPdfButton) clearPdfButton->setStyleSheet(newButtonStyle);\n if (pdfTextSelectButton) pdfTextSelectButton->setStyleSheet(newButtonStyle);\n if (exportNotebookButton) exportNotebookButton->setStyleSheet(newButtonStyle);\n if (importNotebookButton) importNotebookButton->setStyleSheet(newButtonStyle);\n if (benchmarkButton) benchmarkButton->setStyleSheet(newButtonStyle);\n if (toggleTabBarButton) toggleTabBarButton->setStyleSheet(newButtonStyle);\n if (toggleOutlineButton) toggleOutlineButton->setStyleSheet(newButtonStyle);\n if (toggleBookmarksButton) toggleBookmarksButton->setStyleSheet(newButtonStyle);\n if (toggleBookmarkButton) toggleBookmarkButton->setStyleSheet(newButtonStyle);\n if (selectFolderButton) selectFolderButton->setStyleSheet(newButtonStyle);\n if (saveButton) saveButton->setStyleSheet(newButtonStyle);\n if (saveAnnotatedButton) saveAnnotatedButton->setStyleSheet(newButtonStyle);\n if (fullscreenButton) fullscreenButton->setStyleSheet(newButtonStyle);\n if (redButton) redButton->setStyleSheet(newButtonStyle);\n if (blueButton) blueButton->setStyleSheet(newButtonStyle);\n if (yellowButton) yellowButton->setStyleSheet(newButtonStyle);\n if (greenButton) greenButton->setStyleSheet(newButtonStyle);\n if (blackButton) blackButton->setStyleSheet(newButtonStyle);\n if (whiteButton) whiteButton->setStyleSheet(newButtonStyle);\n if (thicknessButton) thicknessButton->setStyleSheet(newButtonStyle);\n if (penToolButton) penToolButton->setStyleSheet(newButtonStyle);\n if (markerToolButton) markerToolButton->setStyleSheet(newButtonStyle);\n if (eraserToolButton) eraserToolButton->setStyleSheet(newButtonStyle);\n if (backgroundButton) backgroundButton->setStyleSheet(newButtonStyle);\n if (straightLineToggleButton) straightLineToggleButton->setStyleSheet(newButtonStyle);\n if (ropeToolButton) ropeToolButton->setStyleSheet(newButtonStyle);\n if (markdownButton) markdownButton->setStyleSheet(newButtonStyle);\n if (deletePageButton) deletePageButton->setStyleSheet(newButtonStyle);\n if (zoomButton) zoomButton->setStyleSheet(newButtonStyle);\n if (dialToggleButton) dialToggleButton->setStyleSheet(newButtonStyle);\n if (fastForwardButton) fastForwardButton->setStyleSheet(newButtonStyle);\n if (jumpToPageButton) jumpToPageButton->setStyleSheet(newButtonStyle);\n if (btnPageSwitch) btnPageSwitch->setStyleSheet(newButtonStyle);\n if (btnZoom) btnZoom->setStyleSheet(newButtonStyle);\n if (btnThickness) btnThickness->setStyleSheet(newButtonStyle);\n if (btnTool) btnTool->setStyleSheet(newButtonStyle);\n if (btnPresets) btnPresets->setStyleSheet(newButtonStyle);\n if (btnPannScroll) btnPannScroll->setStyleSheet(newButtonStyle);\n if (addPresetButton) addPresetButton->setStyleSheet(newButtonStyle);\n if (openControlPanelButton) openControlPanelButton->setStyleSheet(newButtonStyle);\n if (openRecentNotebooksButton) openRecentNotebooksButton->setStyleSheet(newButtonStyle);\n if (zoom50Button) zoom50Button->setStyleSheet(newButtonStyle);\n if (dezoomButton) dezoomButton->setStyleSheet(newButtonStyle);\n if (zoom200Button) zoom200Button->setStyleSheet(newButtonStyle);\n if (prevPageButton) prevPageButton->setStyleSheet(newButtonStyle);\n if (nextPageButton) nextPageButton->setStyleSheet(newButtonStyle);\n \n // Update color buttons with palette-based icons\n if (redButton) {\n QString redIconPath = useBrighterPalette ? \":/resources/icons/pen_light_red.png\" : \":/resources/icons/pen_dark_red.png\";\n redButton->setIcon(QIcon(redIconPath));\n }\n if (blueButton) {\n QString blueIconPath = useBrighterPalette ? \":/resources/icons/pen_light_blue.png\" : \":/resources/icons/pen_dark_blue.png\";\n blueButton->setIcon(QIcon(blueIconPath));\n }\n if (yellowButton) {\n QString yellowIconPath = useBrighterPalette ? \":/resources/icons/pen_light_yellow.png\" : \":/resources/icons/pen_dark_yellow.png\";\n yellowButton->setIcon(QIcon(yellowIconPath));\n }\n if (greenButton) {\n QString greenIconPath = useBrighterPalette ? \":/resources/icons/pen_light_green.png\" : \":/resources/icons/pen_dark_green.png\";\n greenButton->setIcon(QIcon(greenIconPath));\n }\n if (blackButton) {\n QString blackIconPath = darkMode ? \":/resources/icons/pen_light_black.png\" : \":/resources/icons/pen_dark_black.png\";\n blackButton->setIcon(QIcon(blackIconPath));\n }\n if (whiteButton) {\n QString whiteIconPath = darkMode ? \":/resources/icons/pen_light_white.png\" : \":/resources/icons/pen_dark_white.png\";\n whiteButton->setIcon(QIcon(whiteIconPath));\n }\n \n // Update tab close button icons and label styling\n if (tabList) {\n bool darkMode = isDarkMode();\n QString labelColor = darkMode ? \"#E0E0E0\" : \"#333\";\n \n for (int i = 0; i < tabList->count(); ++i) {\n QListWidgetItem *item = tabList->item(i);\n if (item) {\n QWidget *tabWidget = tabList->itemWidget(item);\n if (tabWidget) {\n QPushButton *closeButton = tabWidget->findChild();\n if (closeButton) {\n closeButton->setIcon(loadThemedIcon(\"cross\"));\n }\n \n QLabel *tabLabel = tabWidget->findChild(\"tabLabel\");\n if (tabLabel) {\n tabLabel->setStyleSheet(QString(\"color: %1; font-weight: 500; padding: 2px; text-align: left;\").arg(labelColor));\n }\n }\n }\n }\n }\n \n // Update dial display\n updateDialDisplay();\n}\n void migrateOldButtonMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n \n // Check if migration is needed by looking for old format strings\n settings.beginGroup(\"ButtonHoldMappings\");\n QStringList holdKeys = settings.allKeys();\n bool needsMigration = false;\n \n for (const QString &key : holdKeys) {\n QString value = settings.value(key).toString();\n // If we find old English strings, we need to migrate\n if (value == \"PageSwitching\" || value == \"ZoomControl\" || value == \"ThicknessControl\" ||\n value == \"ToolSwitching\" || value == \"PresetSelection\" ||\n value == \"PanAndPageScroll\") {\n needsMigration = true;\n break;\n }\n }\n settings.endGroup();\n \n if (!needsMigration) {\n settings.beginGroup(\"ButtonPressMappings\");\n QStringList pressKeys = settings.allKeys();\n for (const QString &key : pressKeys) {\n QString value = settings.value(key).toString();\n // Check for old English action strings\n if (value == \"Toggle Fullscreen\" || value == \"Toggle Dial\" || value == \"Zoom 50%\" ||\n value == \"Add Preset\" || value == \"Delete Page\" || value == \"Fast Forward\" ||\n value == \"Open Control Panel\" || value == \"Custom Color\") {\n needsMigration = true;\n break;\n }\n }\n settings.endGroup();\n }\n \n if (!needsMigration) return;\n \n // Perform migration\n // qDebug() << \"Migrating old button mappings to new format...\";\n \n // Migrate hold mappings\n settings.beginGroup(\"ButtonHoldMappings\");\n holdKeys = settings.allKeys();\n for (const QString &key : holdKeys) {\n QString oldValue = settings.value(key).toString();\n QString newValue = migrateOldDialModeString(oldValue);\n if (newValue != oldValue) {\n settings.setValue(key, newValue);\n }\n }\n settings.endGroup();\n \n // Migrate press mappings\n settings.beginGroup(\"ButtonPressMappings\");\n QStringList pressKeys = settings.allKeys();\n for (const QString &key : pressKeys) {\n QString oldValue = settings.value(key).toString();\n QString newValue = migrateOldActionString(oldValue);\n if (newValue != oldValue) {\n settings.setValue(key, newValue);\n }\n }\n settings.endGroup();\n \n // qDebug() << \"Button mapping migration completed.\";\n}\n QString migrateOldDialModeString(const QString &oldString) {\n // Convert old English strings to new internal keys\n if (oldString == \"None\") return \"none\";\n if (oldString == \"PageSwitching\") return \"page_switching\";\n if (oldString == \"ZoomControl\") return \"zoom_control\";\n if (oldString == \"ThicknessControl\") return \"thickness_control\";\n\n if (oldString == \"ToolSwitching\") return \"tool_switching\";\n if (oldString == \"PresetSelection\") return \"preset_selection\";\n if (oldString == \"PanAndPageScroll\") return \"pan_and_page_scroll\";\n return oldString; // Return as-is if not found (might already be new format)\n}\n QString migrateOldActionString(const QString &oldString) {\n // Convert old English strings to new internal keys\n if (oldString == \"None\") return \"none\";\n if (oldString == \"Toggle Fullscreen\") return \"toggle_fullscreen\";\n if (oldString == \"Toggle Dial\") return \"toggle_dial\";\n if (oldString == \"Zoom 50%\") return \"zoom_50\";\n if (oldString == \"Zoom Out\") return \"zoom_out\";\n if (oldString == \"Zoom 200%\") return \"zoom_200\";\n if (oldString == \"Add Preset\") return \"add_preset\";\n if (oldString == \"Delete Page\") return \"delete_page\";\n if (oldString == \"Fast Forward\") return \"fast_forward\";\n if (oldString == \"Open Control Panel\") return \"open_control_panel\";\n if (oldString == \"Red\") return \"red_color\";\n if (oldString == \"Blue\") return \"blue_color\";\n if (oldString == \"Yellow\") return \"yellow_color\";\n if (oldString == \"Green\") return \"green_color\";\n if (oldString == \"Black\") return \"black_color\";\n if (oldString == \"White\") return \"white_color\";\n if (oldString == \"Custom Color\") return \"custom_color\";\n if (oldString == \"Toggle Sidebar\") return \"toggle_sidebar\";\n if (oldString == \"Save\") return \"save\";\n if (oldString == \"Straight Line Tool\") return \"straight_line_tool\";\n if (oldString == \"Rope Tool\") return \"rope_tool\";\n if (oldString == \"Set Pen Tool\") return \"set_pen_tool\";\n if (oldString == \"Set Marker Tool\") return \"set_marker_tool\";\n if (oldString == \"Set Eraser Tool\") return \"set_eraser_tool\";\n if (oldString == \"Toggle PDF Text Selection\") return \"toggle_pdf_text_selection\";\n return oldString; // Return as-is if not found (might already be new format)\n}\n InkCanvas* currentCanvas();\n void saveCurrentPage() {\n currentCanvas()->saveToFile(getCurrentPageForCanvas(currentCanvas()));\n}\n void saveCurrentPageConcurrent() {\n InkCanvas *canvas = currentCanvas();\n if (!canvas || !canvas->isEdited()) return;\n \n int pageNumber = getCurrentPageForCanvas(canvas);\n QString saveFolder = canvas->getSaveFolder();\n \n if (saveFolder.isEmpty()) return;\n \n // Create a copy of the buffer for concurrent saving\n QPixmap bufferCopy = canvas->getBuffer();\n \n // Save markdown windows for this page (this must be done on the main thread)\n if (canvas->getMarkdownManager()) {\n canvas->getMarkdownManager()->saveWindowsForPage(pageNumber);\n }\n \n // Run the save operation concurrently\n QFuture future = QtConcurrent::run([saveFolder, pageNumber, bufferCopy]() {\n // Get notebook ID from the save folder (similar to how InkCanvas does it)\n QString notebookId = \"notebook\"; // Default fallback\n QString idFile = saveFolder + \"/.notebook_id.txt\";\n if (QFile::exists(idFile)) {\n QFile file(idFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n notebookId = in.readLine().trimmed();\n file.close();\n }\n }\n \n QString filePath = saveFolder + QString(\"/%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n \n QImage image(bufferCopy.size(), QImage::Format_ARGB32);\n image.fill(Qt::transparent);\n QPainter painter(&image);\n painter.drawPixmap(0, 0, bufferCopy);\n image.save(filePath, \"PNG\");\n });\n \n // Mark as not edited since we're saving\n canvas->setEdited(false);\n}\n void switchPage(int pageNumber) {\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n\n if (currentCanvas()->isEdited()){\n saveCurrentPageConcurrent(); // Use concurrent saving for smoother page flipping\n }\n\n int oldPage = getCurrentPageForCanvas(currentCanvas()) + 1; // Convert to 1-based for comparison\n int newPage = pageNumber - 1;\n pageMap[canvas] = newPage; // ✅ Save the page for this tab\n\n if (canvas->isPdfLoadedFunc() && pageNumber - 1 < canvas->getTotalPdfPages()) {\n canvas->loadPdfPage(newPage);\n } else {\n canvas->loadPage(newPage);\n }\n\n canvas->setLastActivePage(newPage);\n updateZoom();\n // It seems panXSlider and panYSlider can be null here during startup.\n if(panXSlider && panYSlider){\n canvas->setLastPanX(panXSlider->maximum());\n canvas->setLastPanY(panYSlider->maximum());\n \n // ✅ Enhanced scroll-on-top functionality\n if (scrollOnTopEnabled && panYSlider->maximum() > 0) {\n if (pageNumber > oldPage) {\n // Forward page switching → scroll to top\n panYSlider->setValue(0);\n } else if (pageNumber < oldPage) {\n // Backward page switching → scroll to bottom\n panYSlider->setValue(panYSlider->maximum());\n }\n }\n }\n updateDialDisplay();\n updateBookmarkButtonState(); // Update bookmark button state when switching pages\n}\n void switchPageWithDirection(int pageNumber, int direction) {\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n\n if (currentCanvas()->isEdited()){\n saveCurrentPageConcurrent(); // Use concurrent saving for smoother page flipping\n }\n\n int newPage = pageNumber - 1;\n pageMap[canvas] = newPage; // ✅ Save the page for this tab\n\n if (canvas->isPdfLoadedFunc() && pageNumber - 1 < canvas->getTotalPdfPages()) {\n canvas->loadPdfPage(newPage);\n } else {\n canvas->loadPage(newPage);\n }\n\n canvas->setLastActivePage(newPage);\n updateZoom();\n // It seems panXSlider and panYSlider can be null here during startup.\n if(panXSlider && panYSlider){\n canvas->setLastPanX(panXSlider->maximum());\n canvas->setLastPanY(panYSlider->maximum());\n \n // ✅ Enhanced scroll-on-top functionality with explicit direction\n if (scrollOnTopEnabled && panYSlider->maximum() > 0) {\n if (direction > 0) {\n // Forward page switching → scroll to top\n panYSlider->setValue(0);\n } else if (direction < 0) {\n // Backward page switching → scroll to bottom\n panYSlider->setValue(panYSlider->maximum());\n }\n }\n }\n updateDialDisplay();\n updateBookmarkButtonState(); // Update bookmark button state when switching pages\n}\n void updateTabLabel() {\n int index = tabList->currentRow();\n if (index < 0) return;\n\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n\n QString folderPath = canvas->getSaveFolder(); // ✅ Get save folder\n if (folderPath.isEmpty()) return;\n\n QString tabName;\n\n // ✅ Check if there is an assigned PDF\n QString metadataFile = folderPath + \"/.pdf_path.txt\";\n if (QFile::exists(metadataFile)) {\n QFile file(metadataFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString pdfPath = in.readLine().trimmed();\n file.close();\n\n // ✅ Extract just the PDF filename (not full path)\n QFileInfo pdfInfo(pdfPath);\n if (pdfInfo.exists()) {\n tabName = elideTabText(pdfInfo.fileName(), 90); // e.g., \"mydocument.pdf\" (elided)\n }\n }\n }\n\n // ✅ If no PDF, use the folder name\n if (tabName.isEmpty()) {\n QFileInfo folderInfo(folderPath);\n tabName = elideTabText(folderInfo.fileName(), 90); // e.g., \"MyNotebook\" (elided)\n }\n\n QListWidgetItem *tabItem = tabList->item(index);\n if (tabItem) {\n QWidget *tabWidget = tabList->itemWidget(tabItem); // Get the tab's custom widget\n if (tabWidget) {\n QLabel *tabLabel = tabWidget->findChild(); // Get the QLabel inside\n if (tabLabel) {\n tabLabel->setText(tabName); // ✅ Update tab label\n tabLabel->setWordWrap(false); // No wrapping for horizontal tabs\n }\n }\n }\n}\n QSpinBox *pageInput;\n QPushButton *prevPageButton;\n QPushButton *nextPageButton;\n void addKeyboardMapping(const QString &keySequence, const QString &action) {\n // List of IME-related shortcuts that should not be intercepted\n QStringList imeShortcuts = {\n \"Ctrl+Space\", // Primary IME toggle\n \"Ctrl+Shift\", // Language switching\n \"Ctrl+Alt\", // IME functions\n \"Shift+Alt\", // Alternative language switching\n \"Alt+Shift\" // Alternative language switching (reversed)\n };\n \n // Don't allow mapping of IME-related shortcuts\n if (imeShortcuts.contains(keySequence)) {\n qWarning() << \"Cannot map IME-related shortcut:\" << keySequence;\n return;\n }\n \n keyboardMappings[keySequence] = action;\n keyboardActionMapping[keySequence] = stringToAction(action);\n saveKeyboardMappings();\n}\n void removeKeyboardMapping(const QString &keySequence) {\n keyboardMappings.remove(keySequence);\n keyboardActionMapping.remove(keySequence);\n saveKeyboardMappings();\n}\n QMap getKeyboardMappings() const {\n return keyboardMappings;\n}\n void reconnectControllerSignals() {\n if (!controllerManager || !pageDial) {\n return;\n }\n \n // Reset internal dial state\n tracking = false;\n accumulatedRotation = 0;\n grossTotalClicks = 0;\n tempClicks = 0;\n lastAngle = 0;\n startAngle = 0;\n pendingPageFlip = 0;\n accumulatedRotationAfterLimit = 0;\n \n // Disconnect all existing connections to avoid duplicates\n disconnect(controllerManager, nullptr, this, nullptr);\n disconnect(controllerManager, nullptr, pageDial, nullptr);\n \n // Reconnect all controller signals\n connect(controllerManager, &SDLControllerManager::buttonHeld, this, &MainWindow::handleButtonHeld);\n connect(controllerManager, &SDLControllerManager::buttonReleased, this, &MainWindow::handleButtonReleased);\n connect(controllerManager, &SDLControllerManager::leftStickAngleChanged, pageDial, &QDial::setValue);\n connect(controllerManager, &SDLControllerManager::leftStickReleased, pageDial, &QDial::sliderReleased);\n connect(controllerManager, &SDLControllerManager::buttonSinglePress, this, &MainWindow::handleControllerButton);\n \n // Re-establish dial mode connections by changing to current mode\n DialMode currentMode = currentDialMode;\n changeDialMode(currentMode);\n \n // Update dial display to reflect current state\n updateDialDisplay();\n \n // qDebug() << \"Controller signals reconnected successfully\";\n}\n void updateDialButtonState() {\n // Check if dial is visible\n bool isDialVisible = dialContainer && dialContainer->isVisible();\n \n if (dialToggleButton) {\n dialToggleButton->setProperty(\"selected\", isDialVisible);\n \n // Force style update\n dialToggleButton->style()->unpolish(dialToggleButton);\n dialToggleButton->style()->polish(dialToggleButton);\n }\n}\n void updateFastForwardButtonState() {\n if (fastForwardButton) {\n fastForwardButton->setProperty(\"selected\", fastForwardMode);\n \n // Force style update\n fastForwardButton->style()->unpolish(fastForwardButton);\n fastForwardButton->style()->polish(fastForwardButton);\n }\n}\n void updateToolButtonStates() {\n if (!currentCanvas()) return;\n \n // Reset all tool buttons\n penToolButton->setProperty(\"selected\", false);\n markerToolButton->setProperty(\"selected\", false);\n eraserToolButton->setProperty(\"selected\", false);\n \n // Set the selected property for the current tool\n ToolType currentTool = currentCanvas()->getCurrentTool();\n switch (currentTool) {\n case ToolType::Pen:\n penToolButton->setProperty(\"selected\", true);\n break;\n case ToolType::Marker:\n markerToolButton->setProperty(\"selected\", true);\n break;\n case ToolType::Eraser:\n eraserToolButton->setProperty(\"selected\", true);\n break;\n }\n \n // Force style update\n penToolButton->style()->unpolish(penToolButton);\n penToolButton->style()->polish(penToolButton);\n markerToolButton->style()->unpolish(markerToolButton);\n markerToolButton->style()->polish(markerToolButton);\n eraserToolButton->style()->unpolish(eraserToolButton);\n eraserToolButton->style()->polish(eraserToolButton);\n}\n void handleColorButtonClick() {\n if (!currentCanvas()) return;\n \n ToolType currentTool = currentCanvas()->getCurrentTool();\n \n // If in eraser mode, switch back to pen mode\n if (currentTool == ToolType::Eraser) {\n currentCanvas()->setTool(ToolType::Pen);\n updateToolButtonStates();\n updateThicknessSliderForCurrentTool();\n }\n \n // If rope tool is enabled, turn it off\n if (currentCanvas()->isRopeToolMode()) {\n currentCanvas()->setRopeToolMode(false);\n updateRopeToolButtonState();\n }\n \n // For marker and straight line mode, leave them as they are\n // No special handling needed - they can work with color changes\n}\n void updateThicknessSliderForCurrentTool() {\n if (!currentCanvas() || !thicknessSlider) return;\n \n // Block signals to prevent recursive calls\n thicknessSlider->blockSignals(true);\n \n // Update slider to reflect current tool's thickness\n qreal currentThickness = currentCanvas()->getPenThickness();\n \n // Convert thickness back to slider value (reverse of updateThickness calculation)\n qreal visualThickness = currentThickness * (currentCanvas()->getZoom() / 100.0);\n int sliderValue = qBound(1, static_cast(qRound(visualThickness)), 50);\n \n thicknessSlider->setValue(sliderValue);\n thicknessSlider->blockSignals(false);\n}\n void updatePdfTextSelectButtonState() {\n // Check if PDF text selection is enabled\n bool isEnabled = currentCanvas() && currentCanvas()->isPdfTextSelectionEnabled();\n \n if (pdfTextSelectButton) {\n pdfTextSelectButton->setProperty(\"selected\", isEnabled);\n \n // Force style update (uses the same buttonStyle as other toggle buttons)\n pdfTextSelectButton->style()->unpolish(pdfTextSelectButton);\n pdfTextSelectButton->style()->polish(pdfTextSelectButton);\n }\n}\n private:\n void toggleBenchmark() {\n benchmarking = !benchmarking;\n if (benchmarking) {\n currentCanvas()->startBenchmark();\n benchmarkTimer->start(1000); // Update every second\n } else {\n currentCanvas()->stopBenchmark();\n benchmarkTimer->stop();\n benchmarkLabel->setText(tr(\"PR:N/A\"));\n }\n}\n void updateBenchmarkDisplay() {\n int sampleRate = currentCanvas()->getProcessedRate();\n benchmarkLabel->setText(QString(tr(\"PR:%1 Hz\")).arg(sampleRate));\n}\n void applyCustomColor() {\n QString colorCode = customColorInput->text();\n if (!colorCode.startsWith(\"#\")) {\n colorCode.prepend(\"#\");\n }\n currentCanvas()->setPenColor(QColor(colorCode));\n updateDialDisplay(); \n}\n void updateThickness(int value) {\n // Calculate thickness based on the slider value at 100% zoom\n // The slider value represents the desired visual thickness\n qreal visualThickness = value; // Scale slider value to reasonable thickness\n \n // Apply zoom scaling to maintain visual consistency\n qreal actualThickness = visualThickness * (100.0 / currentCanvas()->getZoom()); \n \n currentCanvas()->setPenThickness(actualThickness);\n}\n void adjustThicknessForZoom(int oldZoom, int newZoom) {\n // Adjust all tool thicknesses to maintain visual consistency when zoom changes\n if (oldZoom == newZoom || oldZoom <= 0 || newZoom <= 0) return;\n \n InkCanvas* canvas = currentCanvas();\n if (!canvas) return;\n \n qreal zoomRatio = qreal(oldZoom) / qreal(newZoom);\n ToolType currentTool = canvas->getCurrentTool();\n \n // Adjust thickness for all tools, not just the current one\n canvas->adjustAllToolThicknesses(zoomRatio);\n \n // Update the thickness slider to reflect the current tool's new thickness\n updateThicknessSliderForCurrentTool();\n \n // ✅ FIXED: Update dial display to show new thickness immediately during zoom changes\n updateDialDisplay();\n}\n void changeTool(int index) {\n if (index == 0) {\n currentCanvas()->setTool(ToolType::Pen);\n } else if (index == 1) {\n currentCanvas()->setTool(ToolType::Marker);\n } else if (index == 2) {\n currentCanvas()->setTool(ToolType::Eraser);\n }\n updateToolButtonStates();\n updateThicknessSliderForCurrentTool();\n updateDialDisplay();\n}\n void selectFolder() {\n QString folder = QFileDialog::getExistingDirectory(this, tr(\"Select Save Folder\"));\n if (!folder.isEmpty()) {\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n if (canvas->isEdited()){\n saveCurrentPage();\n }\n canvas->setSaveFolder(folder);\n switchPageWithDirection(1, 1); // Going to page 1 is forward direction\n pageInput->setValue(1);\n updateTabLabel();\n recentNotebooksManager->addRecentNotebook(folder, canvas); // Track when folder is selected\n }\n }\n}\n void saveCanvas() {\n currentCanvas()->saveToFile(getCurrentPageForCanvas(currentCanvas()));\n}\n void saveAnnotated() {\n currentCanvas()->saveAnnotated(getCurrentPageForCanvas(currentCanvas()));\n}\n void deleteCurrentPage() {\n currentCanvas()->deletePage(getCurrentPageForCanvas(currentCanvas()));\n}\n void loadPdf() {\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n\n QString saveFolder = canvas->getSaveFolder();\n QString tempDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\";\n \n // Check if no save folder is set or if it's the temporary directory\n if (saveFolder.isEmpty() || saveFolder == tempDir) {\n QMessageBox::warning(this, tr(\"Cannot Load PDF\"), \n tr(\"Please select a permanent save folder before loading a PDF.\\n\\nClick the folder icon to choose a location for your notebook.\"));\n return;\n }\n\n QString filePath = QFileDialog::getOpenFileName(this, tr(\"Select PDF\"), \"\", \"PDF Files (*.pdf)\");\n if (!filePath.isEmpty()) {\n currentCanvas()->loadPdf(filePath);\n updateTabLabel(); // ✅ Update the tab name after assigning a PDF\n updateZoom(); // ✅ Update zoom and pan range after PDF is loaded\n \n // Refresh PDF outline if sidebar is visible\n if (outlineSidebarVisible) {\n loadPdfOutline();\n }\n }\n}\n void clearPdf() {\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n \n canvas->clearPdf();\n updateZoom(); // ✅ Update zoom and pan range after PDF is cleared\n}\n void updateZoom() {\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n canvas->setZoom(zoomSlider->value());\n canvas->setLastZoomLevel(zoomSlider->value()); // ✅ Store zoom level per tab\n updatePanRange();\n // updateThickness(thicknessSlider->value()); // ✅ REMOVED: This was resetting thickness on page switch\n // updateDialDisplay();\n }\n}\n void onZoomSliderChanged(int value) {\n // This handles manual zoom slider changes and preserves thickness\n int oldZoom = currentCanvas() ? currentCanvas()->getZoom() : 100;\n int newZoom = value;\n \n updateZoom();\n adjustThicknessForZoom(oldZoom, newZoom); // Maintain visual thickness consistency\n}\n void applyZoom() {\n bool ok;\n int zoomValue = zoomInput->text().toInt(&ok);\n if (ok && zoomValue > 0) {\n currentCanvas()->setZoom(zoomValue);\n updatePanRange(); // Update slider range after zoom change\n }\n}\n void updatePanRange() {\n int zoom = currentCanvas()->getZoom();\n\n QSize canvasSize = currentCanvas()->getCanvasSize();\n QSize viewportSize = QGuiApplication::primaryScreen()->size() * QGuiApplication::primaryScreen()->devicePixelRatio();\n qreal dpr = initialDpr;\n \n // Get the actual widget size instead of screen size for more accurate calculation\n QSize actualViewportSize = size();\n \n // Adjust viewport size for toolbar and tab bar layout\n QSize effectiveViewportSize = actualViewportSize;\n int toolbarHeight = isToolbarTwoRows ? 80 : 50; // Toolbar height\n int tabBarHeight = (tabBarContainer && tabBarContainer->isVisible()) ? 38 : 0; // Tab bar height\n effectiveViewportSize.setHeight(actualViewportSize.height() - toolbarHeight - tabBarHeight);\n \n // Calculate scaled canvas size using proper DPR scaling\n int scaledCanvasWidth = canvasSize.width() * zoom / 100;\n int scaledCanvasHeight = canvasSize.height() * zoom / 100;\n \n // Calculate max pan values - if canvas is smaller than viewport, pan should be 0\n int maxPanX = qMax(0, scaledCanvasWidth - effectiveViewportSize.width());\n int maxPanY = qMax(0, scaledCanvasHeight - effectiveViewportSize.height());\n\n // Scale the pan range properly\n int maxPanX_scaled = maxPanX * 100 / zoom;\n int maxPanY_scaled = maxPanY * 100 / zoom;\n\n // Set range to 0 when canvas is smaller than viewport (centered)\n if (scaledCanvasWidth <= effectiveViewportSize.width()) {\n panXSlider->setRange(0, 0);\n panXSlider->setValue(0);\n // No need for horizontal scrollbar\n panXSlider->setVisible(false);\n } else {\n panXSlider->setRange(0, maxPanX_scaled);\n // Show scrollbar only if mouse is near and timeout hasn't occurred\n if (scrollbarsVisible && !scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->start();\n }\n }\n \n if (scaledCanvasHeight <= effectiveViewportSize.height()) {\n panYSlider->setRange(0, 0);\n panYSlider->setValue(0);\n // No need for vertical scrollbar\n panYSlider->setVisible(false);\n } else {\n panYSlider->setRange(0, maxPanY_scaled);\n // Show scrollbar only if mouse is near and timeout hasn't occurred\n if (scrollbarsVisible && !scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->start();\n }\n }\n}\n void updatePanX(int value) {\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n canvas->setPanX(value);\n canvas->setLastPanX(value); // ✅ Store panX per tab\n \n // Show horizontal scrollbar temporarily\n if (panXSlider->maximum() > 0) {\n panXSlider->setVisible(true);\n scrollbarsVisible = true;\n \n // Make sure scrollbar position matches the canvas position\n if (panXSlider->value() != value) {\n panXSlider->blockSignals(true);\n panXSlider->setValue(value);\n panXSlider->blockSignals(false);\n }\n \n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n scrollbarHideTimer->start();\n }\n }\n}\n void updatePanY(int value) {\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n canvas->setPanY(value);\n canvas->setLastPanY(value); // ✅ Store panY per tab\n \n // Show vertical scrollbar temporarily\n if (panYSlider->maximum() > 0) {\n panYSlider->setVisible(true);\n scrollbarsVisible = true;\n \n // Make sure scrollbar position matches the canvas position\n if (panYSlider->value() != value) {\n panYSlider->blockSignals(true);\n panYSlider->setValue(value);\n panYSlider->blockSignals(false);\n }\n \n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n scrollbarHideTimer->start();\n }\n }\n}\n void selectBackground() {\n QString filePath = QFileDialog::getOpenFileName(this, tr(\"Select Background Image\"), \"\", \"Images (*.png *.jpg *.jpeg)\");\n if (!filePath.isEmpty()) {\n currentCanvas()->setBackground(filePath, getCurrentPageForCanvas(currentCanvas()));\n updateZoom(); // ✅ Update zoom and pan range after background is set\n }\n}\n void forceUIRefresh() {\n setWindowState(Qt::WindowNoState); // Restore first\n setWindowState(Qt::WindowMaximized); // Maximize again\n}\n void switchTab(int index) {\n if (!canvasStack || !tabList || !pageInput || !zoomSlider || !panXSlider || !panYSlider) {\n // qDebug() << \"Error: switchTab() called before UI was fully initialized!\";\n return;\n }\n\n if (index >= 0 && index < canvasStack->count()) {\n canvasStack->setCurrentIndex(index);\n \n // Ensure the tab list selection is properly set and styled\n if (tabList->currentRow() != index) {\n tabList->setCurrentRow(index);\n }\n \n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n int savedPage = canvas->getLastActivePage();\n \n // ✅ Only call blockSignals if pageInput is valid\n if (pageInput) { \n pageInput->blockSignals(true);\n pageInput->setValue(savedPage + 1);\n pageInput->blockSignals(false);\n }\n\n // ✅ Ensure zoomSlider exists before calling methods\n if (zoomSlider) {\n zoomSlider->blockSignals(true);\n zoomSlider->setValue(canvas->getLastZoomLevel());\n zoomSlider->blockSignals(false);\n canvas->setZoom(canvas->getLastZoomLevel());\n }\n\n // ✅ Ensure pan sliders exist before modifying values\n if (panXSlider && panYSlider) {\n panXSlider->blockSignals(true);\n panYSlider->blockSignals(true);\n panXSlider->setValue(canvas->getLastPanX());\n panYSlider->setValue(canvas->getLastPanY());\n panXSlider->blockSignals(false);\n panYSlider->blockSignals(false);\n updatePanRange();\n }\n updateDialDisplay();\n updateColorButtonStates(); // Update button states when switching tabs\n updateStraightLineButtonState(); // Update straight line button state when switching tabs\n updateRopeToolButtonState(); // Update rope tool button state when switching tabs\n updateMarkdownButtonState(); // Update markdown button state when switching tabs\n updatePdfTextSelectButtonState(); // Update PDF text selection button state when switching tabs\n updateBookmarkButtonState(); // Update bookmark button state when switching tabs\n updateDialButtonState(); // Update dial button state when switching tabs\n updateFastForwardButtonState(); // Update fast forward button state when switching tabs\n updateToolButtonStates(); // Update tool button states when switching tabs\n updateThicknessSliderForCurrentTool(); // Update thickness slider for current tool when switching tabs\n \n // Refresh PDF outline if sidebar is visible\n if (outlineSidebarVisible) {\n loadPdfOutline();\n }\n }\n }\n}\n void addNewTab() {\n if (!tabList || !canvasStack) return; // Ensure tabList and canvasStack exist\n\n int newTabIndex = tabList->count(); // New tab index\n QWidget *tabWidget = new QWidget(); // Custom tab container\n tabWidget->setObjectName(\"tabWidget\"); // Name the widget for easy retrieval later\n QHBoxLayout *tabLayout = new QHBoxLayout(tabWidget);\n tabLayout->setContentsMargins(5, 2, 5, 2);\n\n // ✅ Create the label (Tab Name) - optimized for horizontal layout\n QLabel *tabLabel = new QLabel(QString(\"Tab %1\").arg(newTabIndex + 1), tabWidget); \n tabLabel->setObjectName(\"tabLabel\"); // ✅ Name the label for easy retrieval later\n tabLabel->setWordWrap(false); // ✅ No wrapping for horizontal tabs\n tabLabel->setFixedWidth(115); // ✅ Narrower width for compact layout\n tabLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);\n tabLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter); // Left-align to show filename start\n tabLabel->setTextFormat(Qt::PlainText); // Ensure plain text for proper eliding\n // Tab label styling will be updated by theme\n\n // ✅ Create the close button (❌) - styled for browser-like tabs\n QPushButton *closeButton = new QPushButton(tabWidget);\n closeButton->setFixedSize(14, 14); // Smaller to fit narrower tabs\n closeButton->setIcon(loadThemedIcon(\"cross\")); // Set themed icon\n closeButton->setStyleSheet(R\"(\n QPushButton { \n border: none; \n background: transparent; \n border-radius: 6px;\n padding: 1px;\n }\n QPushButton:hover { \n background: rgba(255, 100, 100, 150); \n border-radius: 6px;\n }\n QPushButton:pressed { \n background: rgba(255, 50, 50, 200); \n border-radius: 6px;\n }\n )\"); // Themed styling with hover and press effects\n \n // ✅ Create new InkCanvas instance EARLIER so it can be captured by the lambda\n InkCanvas *newCanvas = new InkCanvas(this);\n \n // ✅ Handle tab closing when the button is clicked\n connect(closeButton, &QPushButton::clicked, this, [=]() { // newCanvas is now captured\n\n // Prevent closing if it's the last remaining tab\n if (tabList->count() <= 1) {\n // Optional: show a message or do nothing silently\n QMessageBox::information(this, tr(\"Notice\"), tr(\"At least one tab must remain open.\"));\n\n return;\n }\n\n // Find the index of the tab associated with this button's parent (tabWidget)\n int indexToRemove = -1;\n // newCanvas is captured by the lambda, representing the canvas of the tab being closed.\n // tabWidget is also captured.\n for (int i = 0; i < tabList->count(); ++i) {\n if (tabList->itemWidget(tabList->item(i)) == tabWidget) {\n indexToRemove = i;\n break;\n }\n }\n\n if (indexToRemove == -1) {\n qWarning() << \"Could not find tab to remove based on tabWidget.\";\n // Fallback or error handling if needed, though this shouldn't happen if tabWidget is valid.\n // As a fallback, try to find the index based on newCanvas if lists are in sync.\n for (int i = 0; i < canvasStack->count(); ++i) {\n if (canvasStack->widget(i) == newCanvas) {\n indexToRemove = i;\n break;\n }\n }\n if (indexToRemove == -1) {\n qWarning() << \"Could not find tab to remove based on newCanvas either.\";\n return; // Critical error, cannot proceed.\n }\n }\n \n // At this point, newCanvas is the InkCanvas instance for the tab being closed.\n // And indexToRemove is its index in tabList and canvasStack.\n\n // 1. Ensure the notebook has a unique save folder if it's temporary/edited\n ensureTabHasUniqueSaveFolder(newCanvas); // Pass the specific canvas\n\n // 2. Get the final save folder path\n QString folderPath = newCanvas->getSaveFolder();\n QString tempDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\";\n\n // 3. Update cover preview and recent list if it's a permanent notebook\n if (!folderPath.isEmpty() && folderPath != tempDir && recentNotebooksManager) {\n recentNotebooksManager->generateAndSaveCoverPreview(folderPath, newCanvas);\n // Add/update in recent list. This also moves it to the top.\n recentNotebooksManager->addRecentNotebook(folderPath, newCanvas);\n }\n \n // 4. Update the tab's label directly as folderPath might have changed\n QLabel *label = tabWidget->findChild(\"tabLabel\");\n if (label) {\n QString tabNameText;\n if (!folderPath.isEmpty() && folderPath != tempDir) { // Only for permanent notebooks\n QString metadataFile = folderPath + \"/.pdf_path.txt\";\n if (QFile::exists(metadataFile)) {\n QFile file(metadataFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString pdfPath = in.readLine().trimmed();\n file.close();\n if (QFile::exists(pdfPath)) { // Check if PDF file actually exists\n tabNameText = elideTabText(QFileInfo(pdfPath).fileName(), 90); // Elide to fit tab width\n }\n }\n }\n // Fallback to folder name if no PDF or PDF path invalid\n if (tabNameText.isEmpty()) {\n tabNameText = elideTabText(QFileInfo(folderPath).fileName(), 90); // Elide to fit tab width\n }\n }\n // Only update the label if a new valid name was determined.\n // If it's still a temp folder, the original \"Tab X\" label remains appropriate.\n if (!tabNameText.isEmpty()) {\n label->setText(tabNameText);\n }\n }\n\n // 5. Remove the tab\n removeTabAt(indexToRemove);\n });\n\n\n // ✅ Add widgets to the tab layout\n tabLayout->addWidget(tabLabel);\n tabLayout->addWidget(closeButton);\n tabLayout->setStretch(0, 1);\n tabLayout->setStretch(1, 0);\n \n // ✅ Create the tab item and set widget (horizontal layout)\n QListWidgetItem *tabItem = new QListWidgetItem();\n tabItem->setSizeHint(QSize(135, 22)); // ✅ Narrower and thinner for compact layout\n tabList->addItem(tabItem);\n tabList->setItemWidget(tabItem, tabWidget); // Attach tab layout\n\n canvasStack->addWidget(newCanvas);\n\n // ✅ Connect touch gesture signals\n connect(newCanvas, &InkCanvas::zoomChanged, this, &MainWindow::handleTouchZoomChange);\n connect(newCanvas, &InkCanvas::panChanged, this, &MainWindow::handleTouchPanChange);\n connect(newCanvas, &InkCanvas::touchGestureEnded, this, &MainWindow::handleTouchGestureEnd);\n connect(newCanvas, &InkCanvas::ropeSelectionCompleted, this, &MainWindow::showRopeSelectionMenu);\n connect(newCanvas, &InkCanvas::pdfLinkClicked, this, [this](int targetPage) {\n // Navigate to the target page when a PDF link is clicked\n if (targetPage >= 0 && targetPage < 9999) {\n switchPageWithDirection(targetPage + 1, (targetPage + 1 > getCurrentPageForCanvas(currentCanvas()) + 1) ? 1 : -1);\n pageInput->setValue(targetPage + 1);\n }\n });\n connect(newCanvas, &InkCanvas::pdfLoaded, this, [this]() {\n // Refresh PDF outline if sidebar is visible\n if (outlineSidebarVisible) {\n loadPdfOutline();\n }\n });\n connect(newCanvas, &InkCanvas::markdownSelectionModeChanged, this, &MainWindow::updateMarkdownButtonState);\n \n // Install event filter to detect mouse movement for scrollbar visibility\n newCanvas->setMouseTracking(true);\n newCanvas->installEventFilter(this);\n \n // Disable tablet tracking for canvases for now to prevent crashes\n // TODO: Find a safer way to implement hover tooltips without tablet tracking\n // QTimer::singleShot(50, this, [newCanvas]() {\n // try {\n // if (newCanvas && newCanvas->window() && newCanvas->window()->windowHandle()) {\n // newCanvas->setAttribute(Qt::WA_TabletTracking, true);\n // }\n // } catch (...) {\n // // Silently ignore tablet tracking errors\n // }\n // });\n \n // ✅ Apply touch gesture setting\n newCanvas->setTouchGesturesEnabled(touchGesturesEnabled);\n\n pageMap[newCanvas] = 0;\n\n // ✅ Select the new tab\n tabList->setCurrentItem(tabItem);\n canvasStack->setCurrentWidget(newCanvas);\n\n zoomSlider->setValue(100 / initialDpr); // Set initial zoom level based on DPR\n updateDialDisplay();\n updateStraightLineButtonState(); // Initialize straight line button state for the new tab\n updateRopeToolButtonState(); // Initialize rope tool button state for the new tab\n updatePdfTextSelectButtonState(); // Initialize PDF text selection button state for the new tab\n updateBookmarkButtonState(); // Initialize bookmark button state for the new tab\n updateMarkdownButtonState(); // Initialize markdown button state for the new tab\n updateDialButtonState(); // Initialize dial button state for the new tab\n updateFastForwardButtonState(); // Initialize fast forward button state for the new tab\n updateToolButtonStates(); // Initialize tool button states for the new tab\n\n QString tempDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\";\n newCanvas->setSaveFolder(tempDir);\n \n // Load persistent background settings\n BackgroundStyle defaultStyle;\n QColor defaultColor;\n int defaultDensity;\n loadDefaultBackgroundSettings(defaultStyle, defaultColor, defaultDensity);\n \n newCanvas->setBackgroundStyle(defaultStyle);\n newCanvas->setBackgroundColor(defaultColor);\n newCanvas->setBackgroundDensity(defaultDensity);\n newCanvas->setPDFRenderDPI(getPdfDPI());\n \n // Update color button states for the new tab\n updateColorButtonStates();\n}\n void removeTabAt(int index) {\n if (!tabList || !canvasStack) return; // Ensure UI elements exist\n if (index < 0 || index >= canvasStack->count()) return;\n\n // ✅ Remove tab entry\n QListWidgetItem *item = tabList->takeItem(index);\n delete item;\n\n // ✅ Remove and delete the canvas safely\n QWidget *canvasWidget = canvasStack->widget(index); // Get widget before removal\n // ensureTabHasUniqueSaveFolder(currentCanvas()); // Moved to the close button lambda\n\n if (canvasWidget) {\n canvasStack->removeWidget(canvasWidget); // Remove from stack\n // InkCanvas *canvasInstance = qobject_cast(canvasWidget);\n // if (canvasInstance) {\n // QString folderPath = canvasInstance->getSaveFolder();\n // QString tempDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\";\n // if (!folderPath.isEmpty() && folderPath != tempDir && recentNotebooksManager) {\n // recentNotebooksManager->addRecentNotebook(folderPath, canvasInstance); // Moved to close button lambda\n // }\n // }\n delete canvasWidget; // Now delete the widget (and its InkCanvas)\n }\n\n // ✅ Select the previous tab (or first tab if none left)\n if (tabList->count() > 0) {\n int newIndex = qMax(0, index - 1);\n tabList->setCurrentRow(newIndex);\n canvasStack->setCurrentWidget(canvasStack->widget(newIndex));\n }\n\n // QWidget *canvasWidget = canvasStack->widget(index); // Redeclaration - remove this block\n // InkCanvas *canvasInstance = qobject_cast(canvasWidget);\n //\n // if (canvasInstance) {\n // QString folderPath = canvasInstance->getSaveFolder();\n // if (!folderPath.isEmpty() && folderPath != QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\") {\n // // recentNotebooksManager->addRecentNotebook(folderPath, canvasInstance); // Moved to close button lambda\n // }\n // }\n}\n void toggleZoomSlider() {\n if (zoomFrame->isVisible()) {\n zoomFrame->hide();\n return;\n }\n\n // ✅ Set as a standalone pop-up window so it can receive events\n zoomFrame->setWindowFlags(Qt::Popup);\n\n // ✅ Position it right below the button\n QPoint buttonPos = zoomButton->mapToGlobal(QPoint(0, zoomButton->height()));\n zoomFrame->move(buttonPos.x(), buttonPos.y() + 5);\n zoomFrame->show();\n}\n void toggleThicknessSlider() {\n if (thicknessFrame->isVisible()) {\n thicknessFrame->hide();\n return;\n }\n\n // ✅ Set as a standalone pop-up window so it can receive events\n thicknessFrame->setWindowFlags(Qt::Popup);\n\n // ✅ Position it right below the button\n QPoint buttonPos = thicknessButton->mapToGlobal(QPoint(0, thicknessButton->height()));\n thicknessFrame->move(buttonPos.x(), buttonPos.y() + 5);\n\n thicknessFrame->show();\n}\n void toggleFullscreen() {\n if (isFullScreen()) {\n showNormal(); // Exit fullscreen mode\n } else {\n showFullScreen(); // Enter fullscreen mode\n }\n}\n void showJumpToPageDialog() {\n bool ok;\n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1; // ✅ Convert zero-based to one-based\n int newPage = QInputDialog::getInt(this, \"Jump to Page\", \"Enter Page Number:\", \n currentPage, 1, 9999, 1, &ok);\n if (ok) {\n // ✅ Use direction-aware page switching for jump-to-page\n int direction = (newPage > currentPage) ? 1 : (newPage < currentPage) ? -1 : 0;\n if (direction != 0) {\n switchPageWithDirection(newPage, direction);\n } else {\n switchPage(newPage); // Same page, no direction needed\n }\n pageInput->setValue(newPage);\n }\n}\n void goToPreviousPage() {\n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1; // Convert to 1-based\n if (currentPage > 1) {\n int newPage = currentPage - 1;\n switchPageWithDirection(newPage, -1); // -1 indicates backward\n pageInput->setValue(newPage);\n }\n}\n void goToNextPage() {\n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1; // Convert to 1-based\n int newPage = currentPage + 1;\n switchPageWithDirection(newPage, 1); // 1 indicates forward\n pageInput->setValue(newPage);\n}\n void onPageInputChanged(int newPage) {\n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1; // Convert to 1-based\n \n // ✅ Use direction-aware page switching for spinbox\n int direction = (newPage > currentPage) ? 1 : (newPage < currentPage) ? -1 : 0;\n if (direction != 0) {\n switchPageWithDirection(newPage, direction);\n } else {\n switchPage(newPage); // Same page, no direction needed\n }\n}\n void toggleDial() {\n if (!dialContainer) { \n // ✅ Create floating container for the dial\n dialContainer = new QWidget(this);\n dialContainer->setObjectName(\"dialContainer\");\n dialContainer->setFixedSize(140, 140);\n dialContainer->setAttribute(Qt::WA_TranslucentBackground);\n dialContainer->setAttribute(Qt::WA_NoSystemBackground);\n dialContainer->setAttribute(Qt::WA_OpaquePaintEvent);\n dialContainer->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);\n dialContainer->setStyleSheet(\"background: transparent; border-radius: 100px;\"); // ✅ More transparent\n\n // ✅ Create dial\n pageDial = new QDial(dialContainer);\n pageDial->setFixedSize(140, 140);\n pageDial->setMinimum(0);\n pageDial->setMaximum(360);\n pageDial->setWrapping(true); // ✅ Allow full-circle rotation\n \n // Apply theme color immediately when dial is created\n QColor accentColor = getAccentColor();\n pageDial->setStyleSheet(QString(R\"(\n QDial {\n background-color: %1;\n }\n )\").arg(accentColor.name()));\n\n /*\n\n modeDial = new QDial(dialContainer);\n modeDial->setFixedSize(150, 150);\n modeDial->setMinimum(0);\n modeDial->setMaximum(300); // 6 modes, 60° each\n modeDial->setSingleStep(60);\n modeDial->setWrapping(true);\n modeDial->setStyleSheet(\"background:rgb(0, 76, 147);\");\n modeDial->move(25, 25);\n \n */\n \n\n dialColorPreview = new QFrame(dialContainer);\n dialColorPreview->setFixedSize(30, 30);\n dialColorPreview->setStyleSheet(\"border-radius: 15px; border: 1px solid black;\");\n dialColorPreview->move(55, 35); // Center of dial\n\n dialIconView = new QLabel(dialContainer);\n dialIconView->setFixedSize(30, 30);\n dialIconView->setStyleSheet(\"border-radius: 1px; border: 1px solid black;\");\n dialIconView->move(55, 35); // Center of dial\n\n // ✅ Position dial near top-right corner initially\n positionDialContainer();\n\n dialDisplay = new QLabel(dialContainer);\n dialDisplay->setAlignment(Qt::AlignCenter);\n dialDisplay->setFixedSize(80, 80);\n dialDisplay->move(30, 30); // Center position inside the dial\n \n\n int fontId = QFontDatabase::addApplicationFont(\":/resources/fonts/Jersey20-Regular.ttf\");\n // int chnFontId = QFontDatabase::addApplicationFont(\":/resources/fonts/NotoSansSC-Medium.ttf\");\n QStringList fontFamilies = QFontDatabase::applicationFontFamilies(fontId);\n\n if (!fontFamilies.isEmpty()) {\n QFont pixelFont(fontFamilies.at(0), 11);\n dialDisplay->setFont(pixelFont);\n }\n\n dialDisplay->setStyleSheet(\"background-color: black; color: white; font-size: 14px; border-radius: 4px;\");\n\n dialHiddenButton = new QPushButton(dialContainer);\n dialHiddenButton->setFixedSize(80, 80);\n dialHiddenButton->move(30, 30); // Same position as dialDisplay\n dialHiddenButton->setStyleSheet(\"background: transparent; border: none;\"); // ✅ Fully invisible\n dialHiddenButton->setFocusPolicy(Qt::NoFocus); // ✅ Prevents accidental focus issues\n dialHiddenButton->setEnabled(false); // ✅ Disabled by default\n\n // ✅ Connection will be set in changeDialMode() based on current mode\n\n dialColorPreview->raise(); // ✅ Ensure it's on top\n dialIconView->raise();\n // ✅ Connect dial input and release\n // connect(pageDial, &QDial::valueChanged, this, &MainWindow::handleDialInput);\n // connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onDialReleased);\n\n // connect(modeDial, &QDial::valueChanged, this, &MainWindow::handleModeSelection);\n changeDialMode(currentDialMode); // ✅ Set initial mode\n\n // ✅ Enable drag detection\n dialContainer->installEventFilter(this);\n }\n\n // ✅ Ensure that `dialContainer` is always initialized before setting visibility\n if (dialContainer) {\n dialContainer->setVisible(!dialContainer->isVisible());\n }\n\n initializeDialSound(); // ✅ Ensure sound is loaded\n\n // Inside toggleDial():\n \n if (!dialDisplay) {\n dialDisplay = new QLabel(dialContainer);\n }\n updateDialDisplay(); // ✅ Ensure it's updated before showing\n\n if (controllerManager) {\n connect(controllerManager, &SDLControllerManager::buttonHeld, this, &MainWindow::handleButtonHeld);\n connect(controllerManager, &SDLControllerManager::buttonReleased, this, &MainWindow::handleButtonReleased);\n connect(controllerManager, &SDLControllerManager::leftStickAngleChanged, pageDial, &QDial::setValue);\n connect(controllerManager, &SDLControllerManager::leftStickReleased, pageDial, &QDial::sliderReleased);\n connect(controllerManager, &SDLControllerManager::buttonSinglePress, this, &MainWindow::handleControllerButton);\n }\n\n loadButtonMappings(); // ✅ Load button mappings for the controller\n\n // Update button state to reflect dial visibility\n updateDialButtonState();\n}\n void positionDialContainer() {\n if (!dialContainer) return;\n \n // Get window dimensions\n int windowWidth = width();\n int windowHeight = height();\n \n // Get dial dimensions\n int dialWidth = dialContainer->width(); // 140px\n int dialHeight = dialContainer->height(); // 140px\n \n // Calculate toolbar height based on current layout\n int toolbarHeight = isToolbarTwoRows ? 80 : 50; // Approximate heights\n \n // Add tab bar height if visible\n int tabBarHeight = (tabBarContainer && tabBarContainer->isVisible()) ? 38 : 0;\n \n // Define margins from edges\n int rightMargin = 20; // Distance from right edge\n int topMargin = 20; // Distance from top edge (below toolbar and tabs)\n \n // Calculate ideal position (top-right corner with margins)\n int idealX = windowWidth - dialWidth - rightMargin;\n int idealY = toolbarHeight + tabBarHeight + topMargin;\n \n // Ensure dial stays within window bounds with minimum margins\n int minMargin = 10;\n int maxX = windowWidth - dialWidth - minMargin;\n int maxY = windowHeight - dialHeight - minMargin;\n \n // Clamp position to stay within bounds\n int finalX = qBound(minMargin, idealX, maxX);\n int finalY = qBound(toolbarHeight + tabBarHeight + minMargin, idealY, maxY);\n \n // Move the dial to the calculated position\n dialContainer->move(finalX, finalY);\n}\n void handleDialInput(int angle) {\n if (!tracking) {\n startAngle = angle; // ✅ Set initial position\n accumulatedRotation = 0; // ✅ Reset tracking\n tracking = true;\n lastAngle = angle;\n return;\n }\n\n int delta = angle - lastAngle;\n\n // ✅ Handle 360-degree wrapping\n if (delta > 180) delta -= 360; // Example: 350° → 10° should be -20° instead of +340°\n if (delta < -180) delta += 360; // Example: 10° → 350° should be +20° instead of -340°\n\n accumulatedRotation += delta; // ✅ Accumulate movement\n\n // ✅ Detect crossing a 45-degree boundary\n int currentClicks = accumulatedRotation / 45; // Total number of \"clicks\" crossed\n int previousClicks = (accumulatedRotation - delta) / 45; // Previous click count\n\n if (currentClicks != previousClicks) { // ✅ Play sound if a new boundary is crossed\n \n if (dialClickSound) {\n dialClickSound->play();\n \n // ✅ Vibrate controller\n SDL_Joystick *joystick = controllerManager->getJoystick();\n if (joystick) {\n // Note: SDL_JoystickRumble requires SDL 2.0.9+\n // For older versions, this will be a no-op\n #if SDL_VERSION_ATLEAST(2, 0, 9)\n SDL_JoystickRumble(joystick, 0xA000, 0xF000, 10); // Vibrate shortly\n #endif\n }\n \n grossTotalClicks += 1;\n tempClicks = currentClicks;\n updateDialDisplay();\n \n if (isLowResPreviewEnabled()) {\n int previewPage = qBound(1, getCurrentPageForCanvas(currentCanvas()) + currentClicks, 99999);\n currentCanvas()->loadPdfPreviewAsync(previewPage);\n }\n }\n }\n\n lastAngle = angle; // ✅ Store last position\n}\n void onDialReleased() {\n if (!tracking) return; // ✅ Ignore if no tracking\n\n int pagesToAdvance = fastForwardMode ? 8 : 1;\n int totalClicks = accumulatedRotation / 45; // ✅ Convert degrees to pages\n\n /*\n int leftOver = accumulatedRotation % 45; // ✅ Track remaining rotation\n if (leftOver > 22 && totalClicks >= 0) {\n totalClicks += 1; // ✅ Round up if more than halfway\n } \n else if (leftOver <= -22 && totalClicks >= 0) {\n totalClicks -= 1; // ✅ Round down if more than halfway\n }\n */\n \n\n if (totalClicks != 0 || grossTotalClicks != 0) { // ✅ Only switch pages if movement happened\n // Use concurrent autosave for smoother dial operation\n if (currentCanvas()->isEdited()) {\n saveCurrentPageConcurrent();\n }\n\n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1;\n int newPage = qBound(1, currentPage + totalClicks * pagesToAdvance, 99999);\n \n // ✅ Use direction-aware page switching for dial\n int direction = (totalClicks * pagesToAdvance > 0) ? 1 : -1;\n switchPageWithDirection(newPage, direction);\n pageInput->setValue(newPage);\n tempClicks = 0;\n updateDialDisplay(); \n /*\n if (dialClickSound) {\n dialClickSound->play();\n }\n */\n }\n\n accumulatedRotation = 0; // ✅ Reset tracking\n grossTotalClicks = 0;\n tracking = false;\n}\n void initializeDialSound() {\n if (!dialClickSound) {\n dialClickSound = new QSoundEffect(this);\n dialClickSound->setSource(QUrl::fromLocalFile(\":/resources/sounds/dial_click.wav\")); // ✅ Path to the sound file\n dialClickSound->setVolume(0.8); // ✅ Set volume (0.0 - 1.0)\n }\n}\n void changeDialMode(DialMode mode) {\n\n if (!dialContainer) return; // ✅ Ensure dial container exists\n currentDialMode = mode; // ✅ Set new mode\n updateDialDisplay();\n\n // ✅ Enable dialHiddenButton for PanAndPageScroll and ZoomControl modes\n dialHiddenButton->setEnabled(currentDialMode == PanAndPageScroll || currentDialMode == ZoomControl);\n\n // ✅ Disconnect previous slots\n disconnect(pageDial, &QDial::valueChanged, nullptr, nullptr);\n disconnect(pageDial, &QDial::sliderReleased, nullptr, nullptr);\n \n // ✅ Disconnect dialHiddenButton to reconnect with appropriate function\n disconnect(dialHiddenButton, &QPushButton::clicked, nullptr, nullptr);\n \n // ✅ Connect dialHiddenButton to appropriate function based on mode\n if (currentDialMode == PanAndPageScroll) {\n connect(dialHiddenButton, &QPushButton::clicked, this, &MainWindow::toggleControlBar);\n } else if (currentDialMode == ZoomControl) {\n connect(dialHiddenButton, &QPushButton::clicked, this, &MainWindow::cycleZoomLevels);\n }\n\n dialColorPreview->hide();\n dialDisplay->setStyleSheet(\"background-color: black; color: white; font-size: 14px; border-radius: 40px;\");\n\n // ✅ Connect the correct function set for the current mode\n switch (currentDialMode) {\n case PageSwitching:\n connect(pageDial, &QDial::valueChanged, this, &MainWindow::handleDialInput);\n connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onDialReleased);\n break;\n case ZoomControl:\n connect(pageDial, &QDial::valueChanged, this, &MainWindow::handleDialZoom);\n connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onZoomReleased);\n break;\n case ThicknessControl:\n connect(pageDial, &QDial::valueChanged, this, &MainWindow::handleDialThickness);\n connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onThicknessReleased);\n break;\n\n case ToolSwitching:\n connect(pageDial, &QDial::valueChanged, this, &MainWindow::handleToolSelection);\n connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onToolReleased);\n break;\n case PresetSelection:\n connect(pageDial, &QDial::valueChanged, this, &MainWindow::handlePresetSelection);\n connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onPresetReleased);\n break;\n case PanAndPageScroll:\n connect(pageDial, &QDial::valueChanged, this, &MainWindow::handleDialPanScroll);\n connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onPanScrollReleased);\n break;\n \n }\n}\n void handleDialZoom(int angle) {\n if (!tracking) {\n startAngle = angle; \n accumulatedRotation = 0; \n tracking = true;\n lastAngle = angle;\n return;\n }\n\n int delta = angle - lastAngle;\n\n // ✅ Handle 360-degree wrapping\n if (delta > 180) delta -= 360;\n if (delta < -180) delta += 360;\n\n accumulatedRotation += delta;\n\n if (abs(delta) < 4) { \n return; \n }\n\n // ✅ Apply zoom dynamically (instead of waiting for release)\n int oldZoom = zoomSlider->value();\n int newZoom = qBound(10, oldZoom + (delta / 4), 400); \n zoomSlider->setValue(newZoom);\n updateZoom(); // ✅ Ensure zoom updates immediately\n updateDialDisplay(); \n\n lastAngle = angle;\n}\n void handleDialThickness(int angle) {\n if (!tracking) {\n startAngle = angle;\n tracking = true;\n lastAngle = angle;\n return;\n }\n\n int delta = angle - lastAngle;\n if (delta > 180) delta -= 360;\n if (delta < -180) delta += 360;\n\n int thicknessStep = fastForwardMode ? 5 : 1;\n currentCanvas()->setPenThickness(qBound(1.0, currentCanvas()->getPenThickness() + (delta / 10.0) * thicknessStep, 50.0));\n\n updateDialDisplay();\n lastAngle = angle;\n}\n void onZoomReleased() {\n accumulatedRotation = 0;\n tracking = false;\n}\n void onThicknessReleased() {\n accumulatedRotation = 0;\n tracking = false;\n}\n void updateDialDisplay() {\n if (!dialDisplay) return;\n if (!dialColorPreview) return;\n if (!dialIconView) return;\n dialIconView->show();\n qreal dpr = initialDpr;\n QColor currentColor = currentCanvas()->getPenColor();\n switch (currentDialMode) {\n case DialMode::PageSwitching:\n if (fastForwardMode){\n dialDisplay->setText(QString(tr(\"\\n\\nPage\\n%1\").arg(getCurrentPageForCanvas(currentCanvas()) + 1 + tempClicks * 8)));\n }\n else {\n dialDisplay->setText(QString(tr(\"\\n\\nPage\\n%1\").arg(getCurrentPageForCanvas(currentCanvas()) + 1 + tempClicks)));\n }\n dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/bookpage_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n break;\n case DialMode::ThicknessControl:\n {\n QString toolName;\n switch (currentCanvas()->getCurrentTool()) {\n case ToolType::Pen:\n toolName = tr(\"Pen\");\n break;\n case ToolType::Marker:\n toolName = tr(\"Marker\");\n break;\n case ToolType::Eraser:\n toolName = tr(\"Eraser\");\n break;\n }\n dialDisplay->setText(QString(tr(\"\\n\\n%1\\n%2\").arg(toolName).arg(QString::number(currentCanvas()->getPenThickness(), 'f', 1))));\n dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/thickness_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n }\n break;\n case DialMode::ZoomControl:\n dialDisplay->setText(QString(tr(\"\\n\\nZoom\\n%1%\").arg(currentCanvas() ? currentCanvas()->getZoom() * initialDpr : zoomSlider->value() * initialDpr)));\n dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/zoom_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n break;\n \n case DialMode::ToolSwitching:\n // ✅ Convert ToolType to QString for display\n switch (currentCanvas()->getCurrentTool()) {\n case ToolType::Pen:\n dialDisplay->setText(tr(\"\\n\\n\\nPen\"));\n dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/pen_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n break;\n case ToolType::Marker:\n dialDisplay->setText(tr(\"\\n\\n\\nMarker\"));\n dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/marker_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n break;\n case ToolType::Eraser:\n dialDisplay->setText(tr(\"\\n\\n\\nEraser\"));\n dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/eraser_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n break;\n }\n break;\n case PresetSelection:\n dialColorPreview->show();\n dialIconView->hide();\n dialColorPreview->setStyleSheet(QString(\"background-color: %1; border-radius: 15px; border: 1px solid black;\")\n .arg(colorPresets[currentPresetIndex].name()));\n dialDisplay->setText(QString(tr(\"\\n\\nPreset %1\\n#%2\"))\n .arg(currentPresetIndex + 1) // ✅ Display preset index (1-based)\n .arg(colorPresets[currentPresetIndex].name().remove(\"#\"))); // ✅ Display hex color\n // dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/preset_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n break;\n case DialMode::PanAndPageScroll:\n dialIconView->setPixmap(QPixmap(\":/resources/icons/scroll_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n QString fullscreenStatus = controlBarVisible ? tr(\"Etr\") : tr(\"Exit\");\n dialDisplay->setText(QString(tr(\"\\n\\nPage %1\\n%2 FulScr\")).arg(getCurrentPageForCanvas(currentCanvas()) + 1).arg(fullscreenStatus));\n break;\n }\n}\n void handleToolSelection(int angle) {\n static int lastToolIndex = -1; // ✅ Track last tool index\n\n // ✅ Snap to closest fixed 120° step\n int snappedAngle = (angle + 60) / 120 * 120; // Round to nearest 120°\n int toolIndex = snappedAngle / 120; // Convert to tool index (0, 1, 2)\n\n if (toolIndex >= 3) toolIndex = 0; // ✅ Wrap around at 360° → Back to Pen (0)\n\n if (toolIndex != lastToolIndex) { // ✅ Only switch if tool actually changes\n toolSelector->setCurrentIndex(toolIndex); // ✅ Change tool\n lastToolIndex = toolIndex; // ✅ Update last selected tool\n\n // ✅ Play click sound when tool changes\n if (dialClickSound) {\n dialClickSound->play();\n }\n\n SDL_Joystick *joystick = controllerManager->getJoystick();\n\n if (joystick) {\n #if SDL_VERSION_ATLEAST(2, 0, 9)\n SDL_JoystickRumble(joystick, 0xA000, 0xF000, 20); // ✅ Vibrate controller\n #endif\n }\n\n updateToolButtonStates(); // ✅ Update tool button states\n updateDialDisplay(); // ✅ Update dial display]\n }\n}\n void onToolReleased() {\n \n}\n void handlePresetSelection(int angle) {\n static int lastAngle = angle;\n int delta = angle - lastAngle;\n\n // ✅ Handle 360-degree wrapping\n if (delta > 180) delta -= 360;\n if (delta < -180) delta += 360;\n\n if (abs(delta) >= 60) { // ✅ Change preset every 60° (6 presets)\n lastAngle = angle;\n currentPresetIndex = (currentPresetIndex + (delta > 0 ? 1 : -1) + colorPresets.size()) % colorPresets.size();\n \n QColor selectedColor = colorPresets[currentPresetIndex];\n currentCanvas()->setPenColor(selectedColor);\n updateCustomColorButtonStyle(selectedColor);\n updateDialDisplay();\n updateColorButtonStates(); // Update button states when preset is selected\n \n if (dialClickSound) dialClickSound->play(); // ✅ Provide feedback\n SDL_Joystick *joystick = controllerManager->getJoystick();\n if (joystick) {\n #if SDL_VERSION_ATLEAST(2, 0, 9)\n SDL_JoystickRumble(joystick, 0xA000, 0xF000, 25); // Vibrate shortly\n #endif\n }\n }\n}\n void onPresetReleased() {\n accumulatedRotation = 0;\n tracking = false;\n}\n void addColorPreset() {\n QColor currentColor = currentCanvas()->getPenColor();\n\n // ✅ Prevent duplicates\n if (!colorPresets.contains(currentColor)) {\n if (colorPresets.size() >= 6) {\n colorPresets.dequeue(); // ✅ Remove oldest color\n }\n colorPresets.enqueue(currentColor);\n }\n}\n void updateColorPalette() {\n // Clear existing presets\n colorPresets.clear();\n currentPresetIndex = 0;\n \n // Add default pen color (theme-aware)\n colorPresets.enqueue(getDefaultPenColor());\n \n // Add palette colors\n colorPresets.enqueue(getPaletteColor(\"red\"));\n colorPresets.enqueue(getPaletteColor(\"yellow\"));\n colorPresets.enqueue(getPaletteColor(\"blue\"));\n colorPresets.enqueue(getPaletteColor(\"green\"));\n colorPresets.enqueue(QColor(\"#000000\")); // Black (always same)\n colorPresets.enqueue(QColor(\"#FFFFFF\")); // White (always same)\n \n // Only update UI elements if they exist\n if (redButton && blueButton && yellowButton && greenButton) {\n bool darkMode = isDarkMode();\n \n // Update color button icons based on current palette (not theme)\n QString redIconPath = useBrighterPalette ? \":/resources/icons/pen_light_red.png\" : \":/resources/icons/pen_dark_red.png\";\n QString blueIconPath = useBrighterPalette ? \":/resources/icons/pen_light_blue.png\" : \":/resources/icons/pen_dark_blue.png\";\n QString yellowIconPath = useBrighterPalette ? \":/resources/icons/pen_light_yellow.png\" : \":/resources/icons/pen_dark_yellow.png\";\n QString greenIconPath = useBrighterPalette ? \":/resources/icons/pen_light_green.png\" : \":/resources/icons/pen_dark_green.png\";\n \n redButton->setIcon(QIcon(redIconPath));\n blueButton->setIcon(QIcon(blueIconPath));\n yellowButton->setIcon(QIcon(yellowIconPath));\n greenButton->setIcon(QIcon(greenIconPath));\n \n // Update color button states\n updateColorButtonStates();\n }\n}\n QColor getPaletteColor(const QString &colorName) {\n if (useBrighterPalette) {\n // Brighter colors (good for dark backgrounds)\n if (colorName == \"red\") return QColor(\"#FF7755\");\n if (colorName == \"yellow\") return QColor(\"#EECC00\");\n if (colorName == \"blue\") return QColor(\"#66CCFF\");\n if (colorName == \"green\") return QColor(\"#55FF77\");\n } else {\n // Darker colors (good for light backgrounds)\n if (colorName == \"red\") return QColor(\"#AA0000\");\n if (colorName == \"yellow\") return QColor(\"#997700\");\n if (colorName == \"blue\") return QColor(\"#0000AA\");\n if (colorName == \"green\") return QColor(\"#007700\");\n }\n \n // Fallback colors\n if (colorName == \"black\") return QColor(\"#000000\");\n if (colorName == \"white\") return QColor(\"#FFFFFF\");\n \n return QColor(\"#000000\"); // Default fallback\n}\n qreal getDevicePixelRatio() {\n QScreen *screen = QGuiApplication::primaryScreen();\n qreal devicePixelRatio = screen ? screen->devicePixelRatio() : 1.0; // Default to 1.0 if null\n return devicePixelRatio;\n}\n bool isDarkMode() {\n QColor bg = palette().color(QPalette::Window);\n return bg.lightness() < 128; // Lightness scale: 0 (black) - 255 (white)\n}\n QIcon loadThemedIcon(const QString& baseName) {\n QString path = isDarkMode()\n ? QString(\":/resources/icons/%1_reversed.png\").arg(baseName)\n : QString(\":/resources/icons/%1.png\").arg(baseName);\n return QIcon(path);\n}\n QString createButtonStyle(bool darkMode) {\n if (darkMode) {\n // Dark mode: Keep current white highlights (good contrast)\n return R\"(\n QPushButton {\n background: transparent;\n border: none;\n padding: 6px;\n }\n QPushButton:hover {\n background: rgba(255, 255, 255, 50);\n }\n QPushButton:pressed {\n background: rgba(0, 0, 0, 50);\n }\n QPushButton[selected=\"true\"] {\n background: rgba(255, 255, 255, 100);\n border: 2px solid rgba(255, 255, 255, 150);\n padding: 4px;\n border-radius: 4px;\n }\n QPushButton[selected=\"true\"]:hover {\n background: rgba(255, 255, 255, 120);\n }\n QPushButton[selected=\"true\"]:pressed {\n background: rgba(0, 0, 0, 50);\n }\n )\";\n } else {\n // Light mode: Use darker colors for better visibility\n return R\"(\n QPushButton {\n background: transparent;\n border: none;\n padding: 6px;\n }\n QPushButton:hover {\n background: rgba(0, 0, 0, 30);\n }\n QPushButton:pressed {\n background: rgba(0, 0, 0, 60);\n }\n QPushButton[selected=\"true\"] {\n background: rgba(0, 0, 0, 80);\n border: 2px solid rgba(0, 0, 0, 120);\n padding: 4px;\n border-radius: 4px;\n }\n QPushButton[selected=\"true\"]:hover {\n background: rgba(0, 0, 0, 100);\n }\n QPushButton[selected=\"true\"]:pressed {\n background: rgba(0, 0, 0, 140);\n }\n )\";\n }\n}\n void handleDialPanScroll(int angle) {\n if (!tracking) {\n startAngle = angle;\n accumulatedRotation = 0;\n accumulatedRotationAfterLimit = 0;\n tracking = true;\n lastAngle = angle;\n pendingPageFlip = 0;\n return;\n }\n\n int delta = angle - lastAngle;\n\n // Handle 360 wrap\n if (delta > 180) delta -= 360;\n if (delta < -180) delta += 360;\n\n accumulatedRotation += delta;\n\n // Pan scroll\n int panDelta = delta * 4; // Adjust scroll sensitivity here\n int currentPan = panYSlider->value();\n int newPan = currentPan + panDelta;\n\n // Clamp pan slider\n newPan = qBound(panYSlider->minimum(), newPan, panYSlider->maximum());\n panYSlider->setValue(newPan);\n\n // ✅ NEW → if slider reached top/bottom, accumulate AFTER LIMIT\n if (newPan == panYSlider->maximum()) {\n accumulatedRotationAfterLimit += delta;\n\n if (accumulatedRotationAfterLimit >= 120) {\n pendingPageFlip = +1; // Flip next when released\n }\n } \n else if (newPan == panYSlider->minimum()) {\n accumulatedRotationAfterLimit += delta;\n\n if (accumulatedRotationAfterLimit <= -120) {\n pendingPageFlip = -1; // Flip previous when released\n }\n } \n else {\n // Reset after limit accumulator when not at limit\n accumulatedRotationAfterLimit = 0;\n pendingPageFlip = 0;\n }\n\n lastAngle = angle;\n}\n void onPanScrollReleased() {\n // ✅ Perform page flip only when dial released and flip is pending\n if (pendingPageFlip != 0) {\n // Use concurrent saving for smooth dial operation\n if (currentCanvas()->isEdited()) {\n saveCurrentPageConcurrent();\n }\n\n int currentPage = getCurrentPageForCanvas(currentCanvas());\n int newPage = qBound(1, currentPage + pendingPageFlip + 1, 99999);\n \n // ✅ Use direction-aware page switching for pan-and-scroll dial\n switchPageWithDirection(newPage, pendingPageFlip);\n pageInput->setValue(newPage);\n updateDialDisplay();\n\n SDL_Joystick *joystick = controllerManager->getJoystick();\n if (joystick) {\n #if SDL_VERSION_ATLEAST(2, 0, 9)\n SDL_JoystickRumble(joystick, 0xA000, 0xF000, 25); // Vibrate shortly\n #endif\n }\n }\n\n // Reset states\n pendingPageFlip = 0;\n accumulatedRotation = 0;\n accumulatedRotationAfterLimit = 0;\n tracking = false;\n}\n void handleTouchZoomChange(int newZoom) {\n // Update zoom slider without triggering updateZoom again\n zoomSlider->blockSignals(true);\n int oldZoom = zoomSlider->value(); // Get the old zoom value before updating the slider\n zoomSlider->setValue(newZoom);\n zoomSlider->blockSignals(false);\n \n // Show both scrollbars during gesture\n if (panXSlider->maximum() > 0) {\n panXSlider->setVisible(true);\n }\n if (panYSlider->maximum() > 0) {\n panYSlider->setVisible(true);\n }\n scrollbarsVisible = true;\n \n // Update canvas zoom directly\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n // The canvas zoom has already been set by the gesture processing in InkCanvas::event()\n // So we don't need to set it again, just update the last zoom level\n canvas->setLastZoomLevel(newZoom);\n updatePanRange();\n \n // ✅ FIXED: Add thickness adjustment for pinch-to-zoom gestures to maintain visual consistency\n adjustThicknessForZoom(oldZoom, newZoom);\n \n updateDialDisplay();\n }\n}\n void handleTouchPanChange(int panX, int panY) {\n // Clamp values to valid ranges\n panX = qBound(panXSlider->minimum(), panX, panXSlider->maximum());\n panY = qBound(panYSlider->minimum(), panY, panYSlider->maximum());\n \n // Show both scrollbars during gesture\n if (panXSlider->maximum() > 0) {\n panXSlider->setVisible(true);\n }\n if (panYSlider->maximum() > 0) {\n panYSlider->setVisible(true);\n }\n scrollbarsVisible = true;\n \n // Update sliders without triggering their valueChanged signals\n panXSlider->blockSignals(true);\n panYSlider->blockSignals(true);\n panXSlider->setValue(panX);\n panYSlider->setValue(panY);\n panXSlider->blockSignals(false);\n panYSlider->blockSignals(false);\n \n // Update canvas pan directly\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n canvas->setPanX(panX);\n canvas->setPanY(panY);\n canvas->setLastPanX(panX);\n canvas->setLastPanY(panY);\n }\n}\n void handleTouchGestureEnd() {\n // Hide scrollbars immediately when touch gesture ends\n panXSlider->setVisible(false);\n panYSlider->setVisible(false);\n scrollbarsVisible = false;\n}\n void updateColorButtonStates() {\n // Check if there's a current canvas\n if (!currentCanvas()) return;\n \n // Get current pen color\n QColor currentColor = currentCanvas()->getPenColor();\n \n // Determine if we're in dark mode to match the correct colors\n bool darkMode = isDarkMode();\n \n // Reset all color buttons to original style\n redButton->setProperty(\"selected\", false);\n blueButton->setProperty(\"selected\", false);\n yellowButton->setProperty(\"selected\", false);\n greenButton->setProperty(\"selected\", false);\n blackButton->setProperty(\"selected\", false);\n whiteButton->setProperty(\"selected\", false);\n \n // Set the selected property for the matching color button based on current palette\n QColor redColor = getPaletteColor(\"red\");\n QColor blueColor = getPaletteColor(\"blue\");\n QColor yellowColor = getPaletteColor(\"yellow\");\n QColor greenColor = getPaletteColor(\"green\");\n \n if (currentColor == redColor) {\n redButton->setProperty(\"selected\", true);\n } else if (currentColor == blueColor) {\n blueButton->setProperty(\"selected\", true);\n } else if (currentColor == yellowColor) {\n yellowButton->setProperty(\"selected\", true);\n } else if (currentColor == greenColor) {\n greenButton->setProperty(\"selected\", true);\n } else if (currentColor == QColor(\"#000000\")) {\n blackButton->setProperty(\"selected\", true);\n } else if (currentColor == QColor(\"#FFFFFF\")) {\n whiteButton->setProperty(\"selected\", true);\n }\n \n // Force style update\n redButton->style()->unpolish(redButton);\n redButton->style()->polish(redButton);\n blueButton->style()->unpolish(blueButton);\n blueButton->style()->polish(blueButton);\n yellowButton->style()->unpolish(yellowButton);\n yellowButton->style()->polish(yellowButton);\n greenButton->style()->unpolish(greenButton);\n greenButton->style()->polish(greenButton);\n blackButton->style()->unpolish(blackButton);\n blackButton->style()->polish(blackButton);\n whiteButton->style()->unpolish(whiteButton);\n whiteButton->style()->polish(whiteButton);\n}\n void selectColorButton(QPushButton* selectedButton) {\n updateColorButtonStates();\n}\n void updateStraightLineButtonState() {\n // Check if there's a current canvas\n if (!currentCanvas()) return;\n \n // Update the button state to match the canvas straight line mode\n bool isEnabled = currentCanvas()->isStraightLineMode();\n \n // Set visual indicator that the button is active/inactive\n if (straightLineToggleButton) {\n straightLineToggleButton->setProperty(\"selected\", isEnabled);\n \n // Force style update\n straightLineToggleButton->style()->unpolish(straightLineToggleButton);\n straightLineToggleButton->style()->polish(straightLineToggleButton);\n }\n}\n void updateRopeToolButtonState() {\n // Check if there's a current canvas\n if (!currentCanvas()) return;\n\n // Update the button state to match the canvas rope tool mode\n bool isEnabled = currentCanvas()->isRopeToolMode();\n\n // Set visual indicator that the button is active/inactive\n if (ropeToolButton) {\n ropeToolButton->setProperty(\"selected\", isEnabled);\n\n // Force style update\n ropeToolButton->style()->unpolish(ropeToolButton);\n ropeToolButton->style()->polish(ropeToolButton);\n }\n}\n void updateMarkdownButtonState() {\n // Check if there's a current canvas\n if (!currentCanvas()) return;\n\n // Update the button state to match the canvas markdown selection mode\n bool isEnabled = currentCanvas()->isMarkdownSelectionMode();\n\n // Set visual indicator that the button is active/inactive\n if (markdownButton) {\n markdownButton->setProperty(\"selected\", isEnabled);\n\n // Force style update\n markdownButton->style()->unpolish(markdownButton);\n markdownButton->style()->polish(markdownButton);\n }\n}\n void setPenTool() {\n if (!currentCanvas()) return;\n currentCanvas()->setTool(ToolType::Pen);\n updateToolButtonStates();\n updateThicknessSliderForCurrentTool();\n updateDialDisplay();\n}\n void setMarkerTool() {\n if (!currentCanvas()) return;\n currentCanvas()->setTool(ToolType::Marker);\n updateToolButtonStates();\n updateThicknessSliderForCurrentTool();\n updateDialDisplay();\n}\n void setEraserTool() {\n if (!currentCanvas()) return;\n currentCanvas()->setTool(ToolType::Eraser);\n updateToolButtonStates();\n updateThicknessSliderForCurrentTool();\n updateDialDisplay();\n}\n QColor getContrastingTextColor(const QColor &backgroundColor) {\n // Calculate relative luminance using the formula from WCAG 2.0\n double r = backgroundColor.redF();\n double g = backgroundColor.greenF();\n double b = backgroundColor.blueF();\n \n // Gamma correction\n r = (r <= 0.03928) ? r/12.92 : pow((r + 0.055)/1.055, 2.4);\n g = (g <= 0.03928) ? g/12.92 : pow((g + 0.055)/1.055, 2.4);\n b = (b <= 0.03928) ? b/12.92 : pow((b + 0.055)/1.055, 2.4);\n \n // Calculate luminance\n double luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;\n \n // Use white text for darker backgrounds\n return (luminance < 0.5) ? Qt::white : Qt::black;\n}\n void updateCustomColorButtonStyle(const QColor &color) {\n QColor textColor = getContrastingTextColor(color);\n customColorButton->setStyleSheet(QString(\"background-color: %1; color: %2\")\n .arg(color.name())\n .arg(textColor.name()));\n customColorButton->setText(QString(\"%1\").arg(color.name()).toUpper());\n}\n void openRecentNotebooksDialog() {\n RecentNotebooksDialog dialog(this, recentNotebooksManager, this);\n dialog.exec();\n}\n void showPendingTooltip() {\n // This function is now unused since we disabled tablet tracking\n // Tooltips will work through normal mouse hover events instead\n // Keeping the function for potential future use\n}\n void showRopeSelectionMenu(const QPoint &position) {\n // Create context menu for rope tool selection\n QMenu *contextMenu = new QMenu(this);\n contextMenu->setAttribute(Qt::WA_DeleteOnClose);\n \n // Add Copy action\n QAction *copyAction = contextMenu->addAction(tr(\"Copy\"));\n copyAction->setIcon(loadThemedIcon(\"copy\"));\n connect(copyAction, &QAction::triggered, this, [this]() {\n if (currentCanvas()) {\n currentCanvas()->copyRopeSelection();\n }\n });\n \n // Add Delete action\n QAction *deleteAction = contextMenu->addAction(tr(\"Delete\"));\n deleteAction->setIcon(loadThemedIcon(\"trash\"));\n connect(deleteAction, &QAction::triggered, this, [this]() {\n if (currentCanvas()) {\n currentCanvas()->deleteRopeSelection();\n }\n });\n \n // Add Cancel action\n QAction *cancelAction = contextMenu->addAction(tr(\"Cancel\"));\n cancelAction->setIcon(loadThemedIcon(\"cross\"));\n connect(cancelAction, &QAction::triggered, this, [this]() {\n if (currentCanvas()) {\n currentCanvas()->cancelRopeSelection();\n }\n });\n \n // Convert position from canvas coordinates to global coordinates\n QPoint globalPos = currentCanvas()->mapToGlobal(position);\n \n // Show the menu at the specified position\n contextMenu->popup(globalPos);\n}\n void toggleOutlineSidebar() {\n outlineSidebarVisible = !outlineSidebarVisible;\n \n // Hide bookmarks sidebar if it's visible when opening outline\n if (outlineSidebarVisible && bookmarksSidebar && bookmarksSidebar->isVisible()) {\n bookmarksSidebar->setVisible(false);\n bookmarksSidebarVisible = false;\n // Update bookmarks button state\n if (toggleBookmarksButton) {\n toggleBookmarksButton->setProperty(\"selected\", false);\n toggleBookmarksButton->style()->unpolish(toggleBookmarksButton);\n toggleBookmarksButton->style()->polish(toggleBookmarksButton);\n }\n }\n \n outlineSidebar->setVisible(outlineSidebarVisible);\n \n // Update button toggle state\n if (toggleOutlineButton) {\n toggleOutlineButton->setProperty(\"selected\", outlineSidebarVisible);\n toggleOutlineButton->style()->unpolish(toggleOutlineButton);\n toggleOutlineButton->style()->polish(toggleOutlineButton);\n }\n \n // Load PDF outline when showing sidebar for the first time\n if (outlineSidebarVisible) {\n loadPdfOutline();\n }\n}\n void onOutlineItemClicked(QTreeWidgetItem *item, int column) {\n Q_UNUSED(column);\n \n if (!item) return;\n \n // Get the page number stored in the item data\n QVariant pageData = item->data(0, Qt::UserRole);\n if (pageData.isValid()) {\n int pageNumber = pageData.toInt();\n if (pageNumber >= 0) {\n // Switch to the selected page (convert from 0-based to 1-based)\n switchPage(pageNumber + 1);\n pageInput->setValue(pageNumber + 1);\n }\n }\n}\n void loadPdfOutline() {\n if (!outlineTree) return;\n \n outlineTree->clear();\n \n // Get current PDF document\n Poppler::Document* pdfDoc = getPdfDocument();\n if (!pdfDoc) return;\n \n // Get the outline from the PDF document\n QVector outlineItems = pdfDoc->outline();\n \n if (outlineItems.isEmpty()) {\n // If no outline exists, show page numbers as fallback\n int pageCount = pdfDoc->numPages();\n for (int i = 0; i < pageCount; ++i) {\n QTreeWidgetItem* item = new QTreeWidgetItem(outlineTree);\n item->setText(0, QString(tr(\"Page %1\")).arg(i + 1));\n item->setData(0, Qt::UserRole, i); // Store 0-based page index\n }\n } else {\n // Process the actual PDF outline\n for (const Poppler::OutlineItem& outlineItem : outlineItems) {\n addOutlineItem(outlineItem, nullptr);\n }\n }\n \n // Expand the first level by default\n outlineTree->expandToDepth(0);\n}\n void addOutlineItem(const Poppler::OutlineItem& outlineItem, QTreeWidgetItem* parentItem) {\n if (outlineItem.isNull()) return;\n \n QTreeWidgetItem* item;\n if (parentItem) {\n item = new QTreeWidgetItem(parentItem);\n } else {\n item = new QTreeWidgetItem(outlineTree);\n }\n \n // Set the title\n item->setText(0, outlineItem.name());\n \n // Try to get the page number from the destination\n int pageNumber = -1;\n auto destination = outlineItem.destination();\n if (destination) {\n pageNumber = destination->pageNumber();\n }\n \n // Store the page number (1-based) in the item data\n if (pageNumber >= 0) {\n item->setData(0, Qt::UserRole, pageNumber + 1); // Convert to 1-based\n }\n \n // Add child items recursively\n if (outlineItem.hasChildren()) {\n QVector children = outlineItem.children();\n for (const Poppler::OutlineItem& child : children) {\n addOutlineItem(child, item);\n }\n }\n}\n Poppler::Document* getPdfDocument();\n void toggleBookmarksSidebar() {\n if (!bookmarksSidebar) return;\n \n bool isVisible = bookmarksSidebar->isVisible();\n \n // Hide outline sidebar if it's visible\n if (!isVisible && outlineSidebar && outlineSidebar->isVisible()) {\n outlineSidebar->setVisible(false);\n outlineSidebarVisible = false;\n // Update outline button state\n if (toggleOutlineButton) {\n toggleOutlineButton->setProperty(\"selected\", false);\n toggleOutlineButton->style()->unpolish(toggleOutlineButton);\n toggleOutlineButton->style()->polish(toggleOutlineButton);\n }\n }\n \n bookmarksSidebar->setVisible(!isVisible);\n bookmarksSidebarVisible = !isVisible;\n \n // Update button toggle state\n if (toggleBookmarksButton) {\n toggleBookmarksButton->setProperty(\"selected\", bookmarksSidebarVisible);\n toggleBookmarksButton->style()->unpolish(toggleBookmarksButton);\n toggleBookmarksButton->style()->polish(toggleBookmarksButton);\n }\n \n if (bookmarksSidebarVisible) {\n loadBookmarks(); // Refresh bookmarks when opening\n }\n}\n void onBookmarkItemClicked(QTreeWidgetItem *item, int column) {\n Q_UNUSED(column);\n if (!item) return;\n \n // Get the page number from the item data\n bool ok;\n int pageNumber = item->data(0, Qt::UserRole).toInt(&ok);\n if (ok && pageNumber > 0) {\n // Navigate to the bookmarked page\n switchPageWithDirection(pageNumber, (pageNumber > getCurrentPageForCanvas(currentCanvas()) + 1) ? 1 : -1);\n pageInput->setValue(pageNumber);\n }\n}\n void loadBookmarks() {\n if (!bookmarksTree || !currentCanvas()) return;\n \n bookmarksTree->clear();\n \n // Get the current notebook's save folder\n QString saveFolder = currentCanvas()->getSaveFolder();\n if (saveFolder.isEmpty()) return;\n \n QString bookmarksFile = saveFolder + \"/.bookmarks.txt\";\n QFile file(bookmarksFile);\n \n bookmarks.clear();\n \n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n while (!in.atEnd()) {\n QString line = in.readLine().trimmed();\n if (line.isEmpty()) continue;\n \n QStringList parts = line.split('\\t', Qt::KeepEmptyParts);\n if (parts.size() >= 2) {\n bool ok;\n int pageNum = parts[0].toInt(&ok);\n if (ok) {\n QString title = parts[1];\n bookmarks[pageNum] = title;\n }\n }\n }\n file.close();\n }\n \n // Populate the tree widget\n for (auto it = bookmarks.begin(); it != bookmarks.end(); ++it) {\n QTreeWidgetItem *item = new QTreeWidgetItem(bookmarksTree);\n \n // Create a custom widget for each bookmark item\n QWidget *itemWidget = new QWidget();\n QHBoxLayout *itemLayout = new QHBoxLayout(itemWidget);\n itemLayout->setContentsMargins(5, 2, 5, 2);\n itemLayout->setSpacing(5);\n \n // Page number label (fixed width)\n QLabel *pageLabel = new QLabel(QString(tr(\"Page %1\")).arg(it.key()));\n pageLabel->setFixedWidth(60);\n pageLabel->setStyleSheet(\"font-weight: bold; color: #666;\");\n itemLayout->addWidget(pageLabel);\n \n // Editable title (supports Windows handwriting if available)\n QLineEdit *titleEdit = new QLineEdit(it.value());\n titleEdit->setPlaceholderText(\"Enter bookmark title...\");\n titleEdit->setProperty(\"pageNumber\", it.key()); // Store page number for saving\n \n // Enable IME support for multi-language input\n titleEdit->setAttribute(Qt::WA_InputMethodEnabled, true);\n titleEdit->setInputMethodHints(Qt::ImhNone); // Allow all input methods\n titleEdit->installEventFilter(this); // Install event filter for IME handling\n \n // Connect to save when editing is finished\n connect(titleEdit, &QLineEdit::editingFinished, this, [this, titleEdit]() {\n int pageNum = titleEdit->property(\"pageNumber\").toInt();\n QString newTitle = titleEdit->text().trimmed();\n \n if (newTitle.isEmpty()) {\n // Remove bookmark if title is empty\n bookmarks.remove(pageNum);\n } else {\n // Update bookmark title\n bookmarks[pageNum] = newTitle;\n }\n saveBookmarks();\n updateBookmarkButtonState(); // Update button state\n });\n \n itemLayout->addWidget(titleEdit, 1);\n \n // Store page number in item data for navigation\n item->setData(0, Qt::UserRole, it.key());\n \n // Set the custom widget\n bookmarksTree->setItemWidget(item, 0, itemWidget);\n \n // Set item height\n item->setSizeHint(0, QSize(0, 30));\n }\n \n updateBookmarkButtonState(); // Update button state after loading\n}\n void saveBookmarks() {\n if (!currentCanvas()) return;\n \n QString saveFolder = currentCanvas()->getSaveFolder();\n if (saveFolder.isEmpty()) return;\n \n QString bookmarksFile = saveFolder + \"/.bookmarks.txt\";\n QFile file(bookmarksFile);\n \n if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {\n QTextStream out(&file);\n \n // Sort bookmarks by page number\n QList sortedPages = bookmarks.keys();\n std::sort(sortedPages.begin(), sortedPages.end());\n \n for (int pageNum : sortedPages) {\n out << pageNum << '\\t' << bookmarks[pageNum] << '\\n';\n }\n \n file.close();\n }\n}\n void toggleCurrentPageBookmark() {\n if (!currentCanvas()) return;\n \n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1; // Convert to 1-based\n \n if (bookmarks.contains(currentPage)) {\n // Remove bookmark\n bookmarks.remove(currentPage);\n } else {\n // Add bookmark with default title\n QString defaultTitle = QString(tr(\"Bookmark %1\")).arg(currentPage);\n bookmarks[currentPage] = defaultTitle;\n }\n \n saveBookmarks();\n updateBookmarkButtonState();\n \n // Refresh bookmarks view if visible\n if (bookmarksSidebarVisible) {\n loadBookmarks();\n }\n}\n void updateBookmarkButtonState() {\n if (!toggleBookmarkButton || !currentCanvas()) return;\n \n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1; // Convert to 1-based\n bool isBookmarked = bookmarks.contains(currentPage);\n \n toggleBookmarkButton->setProperty(\"selected\", isBookmarked);\n \n // Update tooltip\n if (isBookmarked) {\n toggleBookmarkButton->setToolTip(tr(\"Remove Bookmark\"));\n } else {\n toggleBookmarkButton->setToolTip(tr(\"Add Bookmark\"));\n }\n \n // Force style update\n toggleBookmarkButton->style()->unpolish(toggleBookmarkButton);\n toggleBookmarkButton->style()->polish(toggleBookmarkButton);\n}\n private:\n InkCanvas *canvas;\n QPushButton *benchmarkButton;\n QLabel *benchmarkLabel;\n QTimer *benchmarkTimer;\n bool benchmarking;\n QPushButton *exportNotebookButton;\n QPushButton *importNotebookButton;\n QPushButton *redButton;\n QPushButton *blueButton;\n QPushButton *yellowButton;\n QPushButton *greenButton;\n QPushButton *blackButton;\n QPushButton *whiteButton;\n QLineEdit *customColorInput;\n QPushButton *customColorButton;\n QPushButton *thicknessButton;\n QSlider *thicknessSlider;\n QFrame *thicknessFrame;\n QComboBox *toolSelector;\n QPushButton *penToolButton;\n QPushButton *markerToolButton;\n QPushButton *eraserToolButton;\n QPushButton *deletePageButton;\n QPushButton *selectFolderButton;\n QPushButton *saveButton;\n QPushButton *saveAnnotatedButton;\n QPushButton *fullscreenButton;\n QPushButton *openControlPanelButton;\n QPushButton *openRecentNotebooksButton;\n QPushButton *loadPdfButton;\n QPushButton *clearPdfButton;\n QPushButton *pdfTextSelectButton;\n QPushButton *toggleTabBarButton;\n QMap pageMap;\n QPushButton *backgroundButton;\n QPushButton *straightLineToggleButton;\n QPushButton *ropeToolButton;\n QPushButton *markdownButton;\n QSlider *zoomSlider;\n QPushButton *zoomButton;\n QFrame *zoomFrame;\n QPushButton *dezoomButton;\n QPushButton *zoom50Button;\n QPushButton *zoom200Button;\n QWidget *zoomContainer;\n QLineEdit *zoomInput;\n QScrollBar *panXSlider;\n QScrollBar *panYSlider;\n QListWidget *tabList;\n QStackedWidget *canvasStack;\n QPushButton *addTabButton;\n QWidget *tabBarContainer;\n QWidget *outlineSidebar;\n QTreeWidget *outlineTree;\n QPushButton *toggleOutlineButton;\n bool outlineSidebarVisible = false;\n QWidget *bookmarksSidebar;\n QTreeWidget *bookmarksTree;\n QPushButton *toggleBookmarksButton;\n QPushButton *toggleBookmarkButton;\n QPushButton *touchGesturesButton;\n bool bookmarksSidebarVisible = false;\n QMap bookmarks;\n QPushButton *jumpToPageButton;\n QWidget *dialContainer = nullptr;\n QDial *pageDial = nullptr;\n QDial *modeDial = nullptr;\n QPushButton *dialToggleButton;\n bool fastForwardMode = false;\n QPushButton *fastForwardButton;\n int lastAngle = 0;\n int startAngle = 0;\n bool tracking = false;\n int accumulatedRotation = 0;\n QSoundEffect *dialClickSound = nullptr;\n int grossTotalClicks = 0;\n DialMode currentDialMode = PanAndPageScroll;\n DialMode temporaryDialMode = None;\n QComboBox *dialModeSelector;\n QPushButton *colorPreview;\n QLabel *dialDisplay = nullptr;\n QFrame *dialColorPreview;\n QLabel *dialIconView;\n QFont pixelFont;\n QPushButton *btnPageSwitch;\n QPushButton *btnZoom;\n QPushButton *btnThickness;\n QPushButton *btnTool;\n QPushButton *btnPresets;\n QPushButton *btnPannScroll;\n int tempClicks = 0;\n QPushButton *dialHiddenButton;\n QQueue colorPresets;\n QPushButton *addPresetButton;\n int currentPresetIndex = 0;\n bool useBrighterPalette = false;\n qreal initialDpr = 1.0;\n QWidget *sidebarContainer;\n QWidget *controlBar;\n void setTemporaryDialMode(DialMode mode) {\n if (temporaryDialMode == None) {\n temporaryDialMode = currentDialMode;\n }\n changeDialMode(mode);\n}\n void clearTemporaryDialMode() {\n if (temporaryDialMode != None) {\n changeDialMode(temporaryDialMode);\n temporaryDialMode = None;\n }\n}\n bool controlBarVisible = true;\n void toggleControlBar() {\n // Proper fullscreen toggle: handle both sidebar and control bar\n \n if (controlBarVisible) {\n // Going into fullscreen mode\n \n // First, remember current tab bar state\n sidebarWasVisibleBeforeFullscreen = tabBarContainer->isVisible();\n \n // Hide tab bar if it's visible\n if (tabBarContainer->isVisible()) {\n tabBarContainer->setVisible(false);\n }\n \n // Hide control bar\n controlBarVisible = false;\n controlBar->setVisible(false);\n \n // Hide floating popup widgets when control bar is hidden to prevent stacking\n if (zoomFrame && zoomFrame->isVisible()) zoomFrame->hide();\n if (thicknessFrame && thicknessFrame->isVisible()) thicknessFrame->hide();\n \n // Hide orphaned widgets that are not added to any layout\n if (colorPreview) colorPreview->hide();\n if (thicknessButton) thicknessButton->hide();\n if (jumpToPageButton) jumpToPageButton->hide();\n\n if (toolSelector) toolSelector->hide();\n if (zoomButton) zoomButton->hide();\n if (customColorInput) customColorInput->hide();\n \n // Find and hide local widgets that might be orphaned\n QList comboBoxes = findChildren();\n for (QComboBox* combo : comboBoxes) {\n if (combo->parent() == this && !combo->isVisible()) {\n // Already hidden, keep it hidden\n } else if (combo->parent() == this) {\n // This might be the orphaned dialModeSelector or similar\n combo->hide();\n }\n }\n } else {\n // Coming out of fullscreen mode\n \n // Restore control bar\n controlBarVisible = true;\n controlBar->setVisible(true);\n \n // Restore tab bar to its previous state\n tabBarContainer->setVisible(sidebarWasVisibleBeforeFullscreen);\n \n // Show orphaned widgets when control bar is visible\n // Note: These are kept hidden normally since they're not in the layout\n // Only show them if they were specifically intended to be visible\n }\n \n // Update dial display to reflect new status\n updateDialDisplay();\n \n // Force layout update to recalculate space\n if (auto *canvas = currentCanvas()) {\n QTimer::singleShot(0, this, [this, canvas]() {\n canvas->setMaximumSize(canvas->getCanvasSize());\n });\n }\n}\n void cycleZoomLevels() {\n if (!zoomSlider) return;\n \n int currentZoom = zoomSlider->value();\n int targetZoom;\n \n // Calculate the scaled zoom levels based on initial DPR\n int zoom50 = 50 / initialDpr;\n int zoom100 = 100 / initialDpr;\n int zoom200 = 200 / initialDpr;\n \n // Cycle through 0.5x -> 1x -> 2x -> 0.5x...\n if (currentZoom <= zoom50 + 5) { // Close to 0.5x (with small tolerance)\n targetZoom = zoom100; // Go to 1x\n } else if (currentZoom <= zoom100 + 5) { // Close to 1x\n targetZoom = zoom200; // Go to 2x\n } else { // Any other zoom level or close to 2x\n targetZoom = zoom50; // Go to 0.5x\n }\n \n zoomSlider->setValue(targetZoom);\n updateZoom();\n updateDialDisplay();\n}\n bool sidebarWasVisibleBeforeFullscreen = true;\n int accumulatedRotationAfterLimit = 0;\n int pendingPageFlip = 0;\n QMap buttonHoldMapping;\n QMap buttonPressMapping;\n QMap buttonPressActionMapping;\n QMap keyboardMappings;\n QMap keyboardActionMapping;\n QTimer *tooltipTimer;\n QWidget *lastHoveredWidget;\n QPoint pendingTooltipPos;\n void handleButtonHeld(const QString &buttonName) {\n QString mode = buttonHoldMapping.value(buttonName, \"None\");\n if (mode != \"None\") {\n setTemporaryDialMode(dialModeFromString(mode));\n return;\n }\n}\n void handleButtonReleased(const QString &buttonName) {\n QString mode = buttonHoldMapping.value(buttonName, \"None\");\n if (mode != \"None\") {\n clearTemporaryDialMode();\n }\n}\n void handleControllerButton(const QString &buttonName) { // This is for single press functions\n ControllerAction action = buttonPressActionMapping.value(buttonName, ControllerAction::None);\n\n switch (action) {\n case ControllerAction::ToggleFullscreen:\n fullscreenButton->click();\n break;\n case ControllerAction::ToggleDial:\n toggleDial();\n break;\n case ControllerAction::Zoom50:\n zoom50Button->click();\n break;\n case ControllerAction::ZoomOut:\n dezoomButton->click();\n break;\n case ControllerAction::Zoom200:\n zoom200Button->click();\n break;\n case ControllerAction::AddPreset:\n addPresetButton->click();\n break;\n case ControllerAction::DeletePage:\n deletePageButton->click(); // assuming you have this\n break;\n case ControllerAction::FastForward:\n fastForwardButton->click(); // assuming you have this\n break;\n case ControllerAction::OpenControlPanel:\n openControlPanelButton->click();\n break;\n case ControllerAction::RedColor:\n redButton->click();\n break;\n case ControllerAction::BlueColor:\n blueButton->click();\n break;\n case ControllerAction::YellowColor:\n yellowButton->click();\n break;\n case ControllerAction::GreenColor:\n greenButton->click();\n break;\n case ControllerAction::BlackColor:\n blackButton->click();\n break;\n case ControllerAction::WhiteColor:\n whiteButton->click();\n break;\n case ControllerAction::CustomColor:\n customColorButton->click();\n break;\n case ControllerAction::ToggleSidebar:\n toggleTabBarButton->click();\n break;\n case ControllerAction::Save:\n saveButton->click();\n break;\n case ControllerAction::StraightLineTool:\n straightLineToggleButton->click();\n break;\n case ControllerAction::RopeTool:\n ropeToolButton->click();\n break;\n case ControllerAction::SetPenTool:\n setPenTool();\n break;\n case ControllerAction::SetMarkerTool:\n setMarkerTool();\n break;\n case ControllerAction::SetEraserTool:\n setEraserTool();\n break;\n case ControllerAction::TogglePdfTextSelection:\n pdfTextSelectButton->click();\n break;\n case ControllerAction::ToggleOutline:\n toggleOutlineButton->click();\n break;\n case ControllerAction::ToggleBookmarks:\n toggleBookmarksButton->click();\n break;\n case ControllerAction::AddBookmark:\n toggleBookmarkButton->click();\n break;\n case ControllerAction::ToggleTouchGestures:\n touchGesturesButton->click();\n break;\n default:\n break;\n }\n}\n void handleKeyboardShortcut(const QString &keySequence) {\n ControllerAction action = keyboardActionMapping.value(keySequence, ControllerAction::None);\n \n // Use the same handler as Joy-Con buttons\n switch (action) {\n case ControllerAction::ToggleFullscreen:\n fullscreenButton->click();\n break;\n case ControllerAction::ToggleDial:\n toggleDial();\n break;\n case ControllerAction::Zoom50:\n zoom50Button->click();\n break;\n case ControllerAction::ZoomOut:\n dezoomButton->click();\n break;\n case ControllerAction::Zoom200:\n zoom200Button->click();\n break;\n case ControllerAction::AddPreset:\n addPresetButton->click();\n break;\n case ControllerAction::DeletePage:\n deletePageButton->click();\n break;\n case ControllerAction::FastForward:\n fastForwardButton->click();\n break;\n case ControllerAction::OpenControlPanel:\n openControlPanelButton->click();\n break;\n case ControllerAction::RedColor:\n redButton->click();\n break;\n case ControllerAction::BlueColor:\n blueButton->click();\n break;\n case ControllerAction::YellowColor:\n yellowButton->click();\n break;\n case ControllerAction::GreenColor:\n greenButton->click();\n break;\n case ControllerAction::BlackColor:\n blackButton->click();\n break;\n case ControllerAction::WhiteColor:\n whiteButton->click();\n break;\n case ControllerAction::CustomColor:\n customColorButton->click();\n break;\n case ControllerAction::ToggleSidebar:\n toggleTabBarButton->click();\n break;\n case ControllerAction::Save:\n saveButton->click();\n break;\n case ControllerAction::StraightLineTool:\n straightLineToggleButton->click();\n break;\n case ControllerAction::RopeTool:\n ropeToolButton->click();\n break;\n case ControllerAction::SetPenTool:\n setPenTool();\n break;\n case ControllerAction::SetMarkerTool:\n setMarkerTool();\n break;\n case ControllerAction::SetEraserTool:\n setEraserTool();\n break;\n case ControllerAction::TogglePdfTextSelection:\n pdfTextSelectButton->click();\n break;\n case ControllerAction::ToggleOutline:\n toggleOutlineButton->click();\n break;\n case ControllerAction::ToggleBookmarks:\n toggleBookmarksButton->click();\n break;\n case ControllerAction::AddBookmark:\n toggleBookmarkButton->click();\n break;\n case ControllerAction::ToggleTouchGestures:\n touchGesturesButton->click();\n break;\n default:\n break;\n }\n}\n void saveKeyboardMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.beginGroup(\"KeyboardMappings\");\n for (auto it = keyboardMappings.begin(); it != keyboardMappings.end(); ++it) {\n settings.setValue(it.key(), it.value());\n }\n settings.endGroup();\n}\n void loadKeyboardMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.beginGroup(\"KeyboardMappings\");\n QStringList keys = settings.allKeys();\n \n // List of IME-related shortcuts that should not be intercepted\n QStringList imeShortcuts = {\n \"Ctrl+Space\", // Primary IME toggle\n \"Ctrl+Shift\", // Language switching\n \"Ctrl+Alt\", // IME functions\n \"Shift+Alt\", // Alternative language switching\n \"Alt+Shift\" // Alternative language switching (reversed)\n };\n \n for (const QString &key : keys) {\n // Skip IME-related shortcuts\n if (imeShortcuts.contains(key)) {\n // Remove from settings if it exists\n settings.remove(key);\n continue;\n }\n \n QString value = settings.value(key).toString();\n keyboardMappings[key] = value;\n keyboardActionMapping[key] = stringToAction(value);\n }\n settings.endGroup();\n \n // Save settings to persist the removal of IME shortcuts\n settings.sync();\n}\n void ensureTabHasUniqueSaveFolder(InkCanvas* canvas) {\n if (!canvas) return;\n\n if (canvasStack->count() == 0) return;\n\n QString currentFolder = canvas->getSaveFolder();\n QString tempFolder = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\";\n\n if (currentFolder.isEmpty() || currentFolder == tempFolder) {\n\n QDir sourceDir(tempFolder);\n QStringList pageFiles = sourceDir.entryList(QStringList() << \"*.png\", QDir::Files);\n\n // No pages to save → skip prompting\n if (pageFiles.isEmpty()) {\n return;\n }\n\n QMessageBox::warning(this, tr(\"Unsaved Notebook\"),\n tr(\"This notebook is still using a temporary session folder.\\nPlease select a permanent folder to avoid data loss.\"));\n\n QString selectedFolder = QFileDialog::getExistingDirectory(this, tr(\"Select Save Folder\"));\n if (selectedFolder.isEmpty()) return;\n\n QDir destDir(selectedFolder);\n if (!destDir.exists()) {\n QDir().mkpath(selectedFolder);\n }\n\n // Copy contents from temp to selected folder\n for (const QString &file : sourceDir.entryList(QDir::Files)) {\n QString srcFilePath = tempFolder + \"/\" + file;\n QString dstFilePath = selectedFolder + \"/\" + file;\n\n // If file already exists at destination, remove it to avoid rename failure\n if (QFile::exists(dstFilePath)) {\n QFile::remove(dstFilePath);\n }\n\n QFile::rename(srcFilePath, dstFilePath); // This moves the file\n }\n\n canvas->setSaveFolder(selectedFolder);\n // updateTabLabel(); // No longer needed here, handled by the close button lambda\n }\n\n return;\n}\n RecentNotebooksManager *recentNotebooksManager;\n int pdfRenderDPI = 192;\n void setupUi() {\n \n // Ensure IME is properly enabled for the application\n QInputMethod *inputMethod = QGuiApplication::inputMethod();\n if (inputMethod) {\n inputMethod->show();\n inputMethod->reset();\n }\n \n // Create theme-aware button style\n bool darkMode = isDarkMode();\n QString buttonStyle = createButtonStyle(darkMode);\n\n\n loadPdfButton = new QPushButton(this);\n clearPdfButton = new QPushButton(this);\n loadPdfButton->setFixedSize(26, 30);\n clearPdfButton->setFixedSize(26, 30);\n QIcon pdfIcon(loadThemedIcon(\"pdf\")); // Path to your icon in resources\n QIcon pdfDeleteIcon(loadThemedIcon(\"pdfdelete\")); // Path to your icon in resources\n loadPdfButton->setIcon(pdfIcon);\n clearPdfButton->setIcon(pdfDeleteIcon);\n loadPdfButton->setStyleSheet(buttonStyle);\n clearPdfButton->setStyleSheet(buttonStyle);\n loadPdfButton->setToolTip(tr(\"Load PDF\"));\n clearPdfButton->setToolTip(tr(\"Clear PDF\"));\n connect(loadPdfButton, &QPushButton::clicked, this, &MainWindow::loadPdf);\n connect(clearPdfButton, &QPushButton::clicked, this, &MainWindow::clearPdf);\n\n pdfTextSelectButton = new QPushButton(this);\n pdfTextSelectButton->setFixedSize(26, 30);\n QIcon pdfTextIcon(loadThemedIcon(\"ibeam\"));\n pdfTextSelectButton->setIcon(pdfTextIcon);\n pdfTextSelectButton->setStyleSheet(buttonStyle);\n pdfTextSelectButton->setToolTip(tr(\"Toggle PDF Text Selection\"));\n connect(pdfTextSelectButton, &QPushButton::clicked, this, [this]() {\n if (!currentCanvas()) return;\n \n bool newMode = !currentCanvas()->isPdfTextSelectionEnabled();\n currentCanvas()->setPdfTextSelectionEnabled(newMode);\n updatePdfTextSelectButtonState();\n updateBookmarkButtonState();\n \n // Clear any existing selection when toggling\n if (!newMode) {\n currentCanvas()->clearPdfTextSelection();\n }\n });\n\n exportNotebookButton = new QPushButton(this);\n exportNotebookButton->setFixedSize(26, 30);\n QIcon exportIcon(loadThemedIcon(\"export\")); // Path to your icon in resources\n exportNotebookButton->setIcon(exportIcon);\n exportNotebookButton->setStyleSheet(buttonStyle);\n exportNotebookButton->setToolTip(tr(\"Export Notebook Into .SNPKG File\"));\n importNotebookButton = new QPushButton(this);\n importNotebookButton->setFixedSize(26, 30);\n QIcon importIcon(loadThemedIcon(\"import\")); // Path to your icon in resources\n importNotebookButton->setIcon(importIcon);\n importNotebookButton->setStyleSheet(buttonStyle);\n importNotebookButton->setToolTip(tr(\"Import Notebook From .SNPKG File\"));\n\n connect(exportNotebookButton, &QPushButton::clicked, this, [=]() {\n QString filename = QFileDialog::getSaveFileName(this, tr(\"Export Notebook\"), \"\", \"SpeedyNote Package (*.snpkg)\");\n if (!filename.isEmpty()) {\n if (!filename.endsWith(\".snpkg\")) filename += \".snpkg\";\n currentCanvas()->exportNotebook(filename);\n }\n });\n \n connect(importNotebookButton, &QPushButton::clicked, this, [=]() {\n QString filename = QFileDialog::getOpenFileName(this, tr(\"Import Notebook\"), \"\", \"SpeedyNote Package (*.snpkg)\");\n if (!filename.isEmpty()) {\n currentCanvas()->importNotebook(filename);\n }\n });\n\n benchmarkButton = new QPushButton(this);\n QIcon benchmarkIcon(loadThemedIcon(\"benchmark\")); // Path to your icon in resources\n benchmarkButton->setIcon(benchmarkIcon);\n benchmarkButton->setFixedSize(26, 30); // Make the benchmark button smaller\n benchmarkButton->setStyleSheet(buttonStyle);\n benchmarkButton->setToolTip(tr(\"Toggle Benchmark\"));\n benchmarkLabel = new QLabel(\"PR:N/A\", this);\n benchmarkLabel->setFixedHeight(30); // Make the benchmark bar smaller\n\n toggleTabBarButton = new QPushButton(this);\n toggleTabBarButton->setIcon(loadThemedIcon(\"tabs\")); // You can design separate icons for \"show\" and \"hide\"\n toggleTabBarButton->setToolTip(tr(\"Show/Hide Tab Bar\"));\n toggleTabBarButton->setFixedSize(26, 30);\n toggleTabBarButton->setStyleSheet(buttonStyle);\n toggleTabBarButton->setProperty(\"selected\", true); // Initially visible\n \n // PDF Outline Toggle Button\n toggleOutlineButton = new QPushButton(this);\n toggleOutlineButton->setIcon(loadThemedIcon(\"outline\")); // Icon to be added later\n toggleOutlineButton->setToolTip(tr(\"Show/Hide PDF Outline\"));\n toggleOutlineButton->setFixedSize(26, 30);\n toggleOutlineButton->setStyleSheet(buttonStyle);\n toggleOutlineButton->setProperty(\"selected\", false); // Initially hidden\n \n // Bookmarks Toggle Button\n toggleBookmarksButton = new QPushButton(this);\n toggleBookmarksButton->setIcon(loadThemedIcon(\"bookmark\")); // Using bookpage icon for bookmarks\n toggleBookmarksButton->setToolTip(tr(\"Show/Hide Bookmarks\"));\n toggleBookmarksButton->setFixedSize(26, 30);\n toggleBookmarksButton->setStyleSheet(buttonStyle);\n toggleBookmarksButton->setProperty(\"selected\", false); // Initially hidden\n \n // Add/Remove Bookmark Toggle Button\n toggleBookmarkButton = new QPushButton(this);\n toggleBookmarkButton->setIcon(loadThemedIcon(\"star\"));\n toggleBookmarkButton->setToolTip(tr(\"Add/Remove Bookmark\"));\n toggleBookmarkButton->setFixedSize(26, 30);\n toggleBookmarkButton->setStyleSheet(buttonStyle);\n toggleBookmarkButton->setProperty(\"selected\", false); // For toggle state styling\n\n // Touch Gestures Toggle Button\n touchGesturesButton = new QPushButton(this);\n touchGesturesButton->setIcon(loadThemedIcon(\"hand\")); // Using hand icon for touch/gesture\n touchGesturesButton->setToolTip(tr(\"Toggle Touch Gestures\"));\n touchGesturesButton->setFixedSize(26, 30);\n touchGesturesButton->setStyleSheet(buttonStyle);\n touchGesturesButton->setProperty(\"selected\", touchGesturesEnabled); // For toggle state styling\n\n selectFolderButton = new QPushButton(this);\n selectFolderButton->setFixedSize(26, 30);\n QIcon folderIcon(loadThemedIcon(\"folder\")); // Path to your icon in resources\n selectFolderButton->setIcon(folderIcon);\n selectFolderButton->setStyleSheet(buttonStyle);\n selectFolderButton->setToolTip(tr(\"Select Save Folder\"));\n connect(selectFolderButton, &QPushButton::clicked, this, &MainWindow::selectFolder);\n \n \n saveButton = new QPushButton(this);\n saveButton->setFixedSize(26, 30);\n QIcon saveIcon(loadThemedIcon(\"save\")); // Path to your icon in resources\n saveButton->setIcon(saveIcon);\n saveButton->setStyleSheet(buttonStyle);\n saveButton->setToolTip(tr(\"Save Current Page\"));\n connect(saveButton, &QPushButton::clicked, this, &MainWindow::saveCurrentPage);\n \n saveAnnotatedButton = new QPushButton(this);\n saveAnnotatedButton->setFixedSize(26, 30);\n QIcon saveAnnotatedIcon(loadThemedIcon(\"saveannotated\")); // Path to your icon in resources\n saveAnnotatedButton->setIcon(saveAnnotatedIcon);\n saveAnnotatedButton->setStyleSheet(buttonStyle);\n saveAnnotatedButton->setToolTip(tr(\"Save Page with Background\"));\n connect(saveAnnotatedButton, &QPushButton::clicked, this, &MainWindow::saveAnnotated);\n\n fullscreenButton = new QPushButton(this);\n fullscreenButton->setIcon(loadThemedIcon(\"fullscreen\")); // Load from resources\n fullscreenButton->setFixedSize(26, 30);\n fullscreenButton->setToolTip(tr(\"Toggle Fullscreen\"));\n fullscreenButton->setStyleSheet(buttonStyle);\n\n // ✅ Connect button click to toggleFullscreen() function\n connect(fullscreenButton, &QPushButton::clicked, this, &MainWindow::toggleFullscreen);\n\n // Use the darkMode variable already declared at the beginning of setupUi()\n\n redButton = new QPushButton(this);\n redButton->setFixedSize(18, 30); // Half width\n QString redIconPath = darkMode ? \":/resources/icons/pen_light_red.png\" : \":/resources/icons/pen_dark_red.png\";\n QIcon redIcon(redIconPath);\n redButton->setIcon(redIcon);\n redButton->setStyleSheet(buttonStyle);\n connect(redButton, &QPushButton::clicked, [this]() { \n handleColorButtonClick();\n currentCanvas()->setPenColor(getPaletteColor(\"red\")); \n updateDialDisplay(); \n updateColorButtonStates();\n });\n \n blueButton = new QPushButton(this);\n blueButton->setFixedSize(18, 30); // Half width\n QString blueIconPath = darkMode ? \":/resources/icons/pen_light_blue.png\" : \":/resources/icons/pen_dark_blue.png\";\n QIcon blueIcon(blueIconPath);\n blueButton->setIcon(blueIcon);\n blueButton->setStyleSheet(buttonStyle);\n connect(blueButton, &QPushButton::clicked, [this]() { \n handleColorButtonClick();\n currentCanvas()->setPenColor(getPaletteColor(\"blue\")); \n updateDialDisplay(); \n updateColorButtonStates();\n });\n\n yellowButton = new QPushButton(this);\n yellowButton->setFixedSize(18, 30); // Half width\n QString yellowIconPath = darkMode ? \":/resources/icons/pen_light_yellow.png\" : \":/resources/icons/pen_dark_yellow.png\";\n QIcon yellowIcon(yellowIconPath);\n yellowButton->setIcon(yellowIcon);\n yellowButton->setStyleSheet(buttonStyle);\n connect(yellowButton, &QPushButton::clicked, [this]() { \n handleColorButtonClick();\n currentCanvas()->setPenColor(getPaletteColor(\"yellow\")); \n updateDialDisplay(); \n updateColorButtonStates();\n });\n\n greenButton = new QPushButton(this);\n greenButton->setFixedSize(18, 30); // Half width\n QString greenIconPath = darkMode ? \":/resources/icons/pen_light_green.png\" : \":/resources/icons/pen_dark_green.png\";\n QIcon greenIcon(greenIconPath);\n greenButton->setIcon(greenIcon);\n greenButton->setStyleSheet(buttonStyle);\n connect(greenButton, &QPushButton::clicked, [this]() { \n handleColorButtonClick();\n currentCanvas()->setPenColor(getPaletteColor(\"green\")); \n updateDialDisplay(); \n updateColorButtonStates();\n });\n\n blackButton = new QPushButton(this);\n blackButton->setFixedSize(18, 30); // Half width\n QString blackIconPath = darkMode ? \":/resources/icons/pen_light_black.png\" : \":/resources/icons/pen_dark_black.png\";\n QIcon blackIcon(blackIconPath);\n blackButton->setIcon(blackIcon);\n blackButton->setStyleSheet(buttonStyle);\n connect(blackButton, &QPushButton::clicked, [this]() { \n handleColorButtonClick();\n currentCanvas()->setPenColor(QColor(\"#000000\")); \n updateDialDisplay(); \n updateColorButtonStates();\n });\n\n whiteButton = new QPushButton(this);\n whiteButton->setFixedSize(18, 30); // Half width\n QString whiteIconPath = darkMode ? \":/resources/icons/pen_light_white.png\" : \":/resources/icons/pen_dark_white.png\";\n QIcon whiteIcon(whiteIconPath);\n whiteButton->setIcon(whiteIcon);\n whiteButton->setStyleSheet(buttonStyle);\n connect(whiteButton, &QPushButton::clicked, [this]() { \n handleColorButtonClick();\n currentCanvas()->setPenColor(QColor(\"#FFFFFF\")); \n updateDialDisplay(); \n updateColorButtonStates();\n });\n \n customColorInput = new QLineEdit(this);\n customColorInput->setPlaceholderText(\"Custom HEX\");\n customColorInput->setFixedSize(85, 30);\n \n // Enable IME support for multi-language input\n customColorInput->setAttribute(Qt::WA_InputMethodEnabled, true);\n customColorInput->setInputMethodHints(Qt::ImhNone); // Allow all input methods\n customColorInput->installEventFilter(this); // Install event filter for IME handling\n \n connect(customColorInput, &QLineEdit::returnPressed, this, &MainWindow::applyCustomColor);\n\n \n thicknessButton = new QPushButton(this);\n thicknessButton->setIcon(loadThemedIcon(\"thickness\"));\n thicknessButton->setFixedSize(26, 30);\n thicknessButton->setStyleSheet(buttonStyle);\n connect(thicknessButton, &QPushButton::clicked, this, &MainWindow::toggleThicknessSlider);\n\n thicknessFrame = new QFrame(this);\n thicknessFrame->setFrameShape(QFrame::StyledPanel);\n thicknessFrame->setStyleSheet(R\"(\n background-color: black;\n border: 1px solid black;\n padding: 5px;\n )\");\n thicknessFrame->setVisible(false);\n thicknessFrame->setFixedSize(220, 40); // Adjust width/height as needed\n\n thicknessSlider = new QSlider(Qt::Horizontal, this);\n thicknessSlider->setRange(1, 50);\n thicknessSlider->setValue(5);\n thicknessSlider->setMaximumWidth(200);\n\n\n connect(thicknessSlider, &QSlider::valueChanged, this, &MainWindow::updateThickness);\n\n QVBoxLayout *popupLayoutThickness = new QVBoxLayout();\n popupLayoutThickness->setContentsMargins(10, 5, 10, 5);\n popupLayoutThickness->addWidget(thicknessSlider);\n thicknessFrame->setLayout(popupLayoutThickness);\n\n\n toolSelector = new QComboBox(this);\n toolSelector->addItem(loadThemedIcon(\"pen\"), \"\");\n toolSelector->addItem(loadThemedIcon(\"marker\"), \"\");\n toolSelector->addItem(loadThemedIcon(\"eraser\"), \"\");\n toolSelector->setFixedWidth(43);\n toolSelector->setFixedHeight(30);\n connect(toolSelector, QOverload::of(&QComboBox::currentIndexChanged), this, &MainWindow::changeTool);\n\n // ✅ Individual tool buttons\n penToolButton = new QPushButton(this);\n penToolButton->setFixedSize(26, 30);\n penToolButton->setIcon(loadThemedIcon(\"pen\"));\n penToolButton->setStyleSheet(buttonStyle);\n penToolButton->setToolTip(tr(\"Pen Tool\"));\n connect(penToolButton, &QPushButton::clicked, this, &MainWindow::setPenTool);\n\n markerToolButton = new QPushButton(this);\n markerToolButton->setFixedSize(26, 30);\n markerToolButton->setIcon(loadThemedIcon(\"marker\"));\n markerToolButton->setStyleSheet(buttonStyle);\n markerToolButton->setToolTip(tr(\"Marker Tool\"));\n connect(markerToolButton, &QPushButton::clicked, this, &MainWindow::setMarkerTool);\n\n eraserToolButton = new QPushButton(this);\n eraserToolButton->setFixedSize(26, 30);\n eraserToolButton->setIcon(loadThemedIcon(\"eraser\"));\n eraserToolButton->setStyleSheet(buttonStyle);\n eraserToolButton->setToolTip(tr(\"Eraser Tool\"));\n connect(eraserToolButton, &QPushButton::clicked, this, &MainWindow::setEraserTool);\n\n backgroundButton = new QPushButton(this);\n backgroundButton->setFixedSize(26, 30);\n QIcon bgIcon(loadThemedIcon(\"background\")); // Path to your icon in resources\n backgroundButton->setIcon(bgIcon);\n backgroundButton->setStyleSheet(buttonStyle);\n backgroundButton->setToolTip(tr(\"Set Background Pic\"));\n connect(backgroundButton, &QPushButton::clicked, this, &MainWindow::selectBackground);\n\n // Initialize straight line toggle button\n straightLineToggleButton = new QPushButton(this);\n straightLineToggleButton->setFixedSize(26, 30);\n QIcon straightLineIcon(loadThemedIcon(\"straightLine\")); // Make sure this icon exists or use a different one\n straightLineToggleButton->setIcon(straightLineIcon);\n straightLineToggleButton->setStyleSheet(buttonStyle);\n straightLineToggleButton->setToolTip(tr(\"Toggle Straight Line Mode\"));\n connect(straightLineToggleButton, &QPushButton::clicked, this, [this]() {\n if (!currentCanvas()) return;\n \n // If we're turning on straight line mode, first disable rope tool\n if (!currentCanvas()->isStraightLineMode()) {\n currentCanvas()->setRopeToolMode(false);\n updateRopeToolButtonState();\n }\n \n bool newMode = !currentCanvas()->isStraightLineMode();\n currentCanvas()->setStraightLineMode(newMode);\n updateStraightLineButtonState();\n });\n \n ropeToolButton = new QPushButton(this);\n ropeToolButton->setFixedSize(26, 30);\n QIcon ropeToolIcon(loadThemedIcon(\"rope\")); // Make sure this icon exists\n ropeToolButton->setIcon(ropeToolIcon);\n ropeToolButton->setStyleSheet(buttonStyle);\n ropeToolButton->setToolTip(tr(\"Toggle Rope Tool Mode\"));\n connect(ropeToolButton, &QPushButton::clicked, this, [this]() {\n if (!currentCanvas()) return;\n \n // If we're turning on rope tool mode, first disable straight line\n if (!currentCanvas()->isRopeToolMode()) {\n currentCanvas()->setStraightLineMode(false);\n updateStraightLineButtonState();\n }\n \n bool newMode = !currentCanvas()->isRopeToolMode();\n currentCanvas()->setRopeToolMode(newMode);\n updateRopeToolButtonState();\n });\n \n markdownButton = new QPushButton(this);\n markdownButton->setFixedSize(26, 30);\n QIcon markdownIcon(loadThemedIcon(\"markdown\")); // Using text icon for markdown\n markdownButton->setIcon(markdownIcon);\n markdownButton->setStyleSheet(buttonStyle);\n markdownButton->setToolTip(tr(\"Add Markdown Window\"));\n connect(markdownButton, &QPushButton::clicked, this, [this]() {\n if (!currentCanvas()) return;\n \n // Toggle markdown selection mode\n bool newMode = !currentCanvas()->isMarkdownSelectionMode();\n currentCanvas()->setMarkdownSelectionMode(newMode);\n updateMarkdownButtonState();\n });\n \n deletePageButton = new QPushButton(this);\n deletePageButton->setFixedSize(26, 30);\n QIcon trashIcon(loadThemedIcon(\"trash\")); // Path to your icon in resources\n deletePageButton->setIcon(trashIcon);\n deletePageButton->setStyleSheet(buttonStyle);\n deletePageButton->setToolTip(tr(\"Delete Current Page\"));\n connect(deletePageButton, &QPushButton::clicked, this, &MainWindow::deleteCurrentPage);\n\n zoomButton = new QPushButton(this);\n zoomButton->setIcon(loadThemedIcon(\"zoom\"));\n zoomButton->setFixedSize(26, 30);\n zoomButton->setStyleSheet(buttonStyle);\n connect(zoomButton, &QPushButton::clicked, this, &MainWindow::toggleZoomSlider);\n\n // ✅ Create the floating frame (Initially Hidden)\n zoomFrame = new QFrame(this);\n zoomFrame->setFrameShape(QFrame::StyledPanel);\n zoomFrame->setStyleSheet(R\"(\n background-color: black;\n border: 1px solid black;\n padding: 5px;\n )\");\n zoomFrame->setVisible(false);\n zoomFrame->setFixedSize(440, 40); // Adjust width/height as needed\n\n zoomSlider = new QSlider(Qt::Horizontal, this);\n zoomSlider->setRange(10, 400);\n zoomSlider->setValue(100);\n zoomSlider->setMaximumWidth(405);\n\n connect(zoomSlider, &QSlider::valueChanged, this, &MainWindow::onZoomSliderChanged);\n\n QVBoxLayout *popupLayout = new QVBoxLayout();\n popupLayout->setContentsMargins(10, 5, 10, 5);\n popupLayout->addWidget(zoomSlider);\n zoomFrame->setLayout(popupLayout);\n \n\n zoom50Button = new QPushButton(\"0.5x\", this);\n zoom50Button->setFixedSize(35, 30);\n zoom50Button->setStyleSheet(buttonStyle);\n zoom50Button->setToolTip(tr(\"Set Zoom to 50%\"));\n connect(zoom50Button, &QPushButton::clicked, [this]() { zoomSlider->setValue(50 / initialDpr); updateDialDisplay(); });\n\n dezoomButton = new QPushButton(\"1x\", this);\n dezoomButton->setFixedSize(26, 30);\n dezoomButton->setStyleSheet(buttonStyle);\n dezoomButton->setToolTip(tr(\"Set Zoom to 100%\"));\n connect(dezoomButton, &QPushButton::clicked, [this]() { zoomSlider->setValue(100 / initialDpr); updateDialDisplay(); });\n\n zoom200Button = new QPushButton(\"2x\", this);\n zoom200Button->setFixedSize(31, 30);\n zoom200Button->setStyleSheet(buttonStyle);\n zoom200Button->setToolTip(tr(\"Set Zoom to 200%\"));\n connect(zoom200Button, &QPushButton::clicked, [this]() { zoomSlider->setValue(200 / initialDpr); updateDialDisplay(); });\n\n panXSlider = new QScrollBar(Qt::Horizontal, this);\n panYSlider = new QScrollBar(Qt::Vertical, this);\n panYSlider->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);\n \n // Set scrollbar styling\n QString scrollBarStyle = R\"(\n QScrollBar {\n background: rgba(200, 200, 200, 80);\n border: none;\n margin: 0px;\n }\n QScrollBar:hover {\n background: rgba(200, 200, 200, 120);\n }\n QScrollBar:horizontal {\n height: 16px !important; /* Force narrow height */\n max-height: 16px !important;\n }\n QScrollBar:vertical {\n width: 16px !important; /* Force narrow width */\n max-width: 16px !important;\n }\n QScrollBar::handle {\n background: rgba(100, 100, 100, 150);\n border-radius: 2px;\n min-height: 120px; /* Longer handle for vertical scrollbar */\n min-width: 120px; /* Longer handle for horizontal scrollbar */\n }\n QScrollBar::handle:hover {\n background: rgba(80, 80, 80, 210);\n }\n /* Hide scroll buttons */\n QScrollBar::add-line, \n QScrollBar::sub-line {\n width: 0px;\n height: 0px;\n background: none;\n border: none;\n }\n /* Disable scroll page buttons */\n QScrollBar::add-page, \n QScrollBar::sub-page {\n background: transparent;\n }\n )\";\n \n panXSlider->setStyleSheet(scrollBarStyle);\n panYSlider->setStyleSheet(scrollBarStyle);\n \n // Force fixed dimensions programmatically\n panXSlider->setFixedHeight(16);\n panYSlider->setFixedWidth(16);\n \n // Set up auto-hiding\n panXSlider->setMouseTracking(true);\n panYSlider->setMouseTracking(true);\n panXSlider->installEventFilter(this);\n panYSlider->installEventFilter(this);\n panXSlider->setVisible(false);\n panYSlider->setVisible(false);\n \n // Create timer for auto-hiding\n scrollbarHideTimer = new QTimer(this);\n scrollbarHideTimer->setSingleShot(true);\n scrollbarHideTimer->setInterval(200); // Hide after 0.2 seconds\n connect(scrollbarHideTimer, &QTimer::timeout, this, [this]() {\n panXSlider->setVisible(false);\n panYSlider->setVisible(false);\n scrollbarsVisible = false;\n });\n \n // panXSlider->setFixedHeight(30);\n // panYSlider->setFixedWidth(30);\n\n connect(panXSlider, &QScrollBar::valueChanged, this, &MainWindow::updatePanX);\n \n connect(panYSlider, &QScrollBar::valueChanged, this, &MainWindow::updatePanY);\n\n\n\n\n // 🌟 PDF Outline Sidebar\n outlineSidebar = new QWidget(this);\n outlineSidebar->setFixedWidth(250);\n outlineSidebar->setVisible(false); // Hidden by default\n \n QVBoxLayout *outlineLayout = new QVBoxLayout(outlineSidebar);\n outlineLayout->setContentsMargins(5, 5, 5, 5);\n \n QLabel *outlineLabel = new QLabel(tr(\"PDF Outline\"), outlineSidebar);\n outlineLabel->setStyleSheet(\"font-weight: bold; padding: 5px;\");\n outlineLayout->addWidget(outlineLabel);\n \n outlineTree = new QTreeWidget(outlineSidebar);\n outlineTree->setHeaderHidden(true);\n outlineTree->setRootIsDecorated(true);\n outlineTree->setIndentation(15);\n outlineLayout->addWidget(outlineTree);\n \n // Connect outline tree item clicks\n connect(outlineTree, &QTreeWidget::itemClicked, this, &MainWindow::onOutlineItemClicked);\n \n // 🌟 Bookmarks Sidebar\n bookmarksSidebar = new QWidget(this);\n bookmarksSidebar->setFixedWidth(250);\n bookmarksSidebar->setVisible(false); // Hidden by default\n \n QVBoxLayout *bookmarksLayout = new QVBoxLayout(bookmarksSidebar);\n bookmarksLayout->setContentsMargins(5, 5, 5, 5);\n \n QLabel *bookmarksLabel = new QLabel(tr(\"Bookmarks\"), bookmarksSidebar);\n bookmarksLabel->setStyleSheet(\"font-weight: bold; padding: 5px;\");\n bookmarksLayout->addWidget(bookmarksLabel);\n \n bookmarksTree = new QTreeWidget(bookmarksSidebar);\n bookmarksTree->setHeaderHidden(true);\n bookmarksTree->setRootIsDecorated(false);\n bookmarksTree->setIndentation(0);\n bookmarksLayout->addWidget(bookmarksTree);\n \n // Connect bookmarks tree item clicks\n connect(bookmarksTree, &QTreeWidget::itemClicked, this, &MainWindow::onBookmarkItemClicked);\n\n // 🌟 Horizontal Tab Bar (like modern web browsers)\n tabList = new QListWidget(this);\n tabList->setFlow(QListView::LeftToRight); // Make it horizontal\n tabList->setFixedHeight(32); // Increased to accommodate scrollbar below tabs\n tabList->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);\n tabList->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n tabList->setSelectionMode(QAbstractItemView::SingleSelection);\n\n // Style the tab bar like a modern browser with transparent scrollbar\n tabList->setStyleSheet(R\"(\n QListWidget {\n background-color: rgba(240, 240, 240, 255);\n border: none;\n border-bottom: 1px solid rgba(200, 200, 200, 255);\n outline: none;\n }\n QListWidget::item {\n background-color: rgba(220, 220, 220, 255);\n border: 1px solid rgba(180, 180, 180, 255);\n border-bottom: none;\n margin-right: 1px;\n margin-top: 2px;\n padding: 0px;\n min-width: 80px;\n max-width: 120px;\n }\n QListWidget::item:selected {\n background-color: white;\n border: 1px solid rgba(180, 180, 180, 255);\n border-bottom: 1px solid white;\n margin-top: 1px;\n }\n QListWidget::item:hover:!selected {\n background-color: rgba(230, 230, 230, 255);\n }\n QScrollBar:horizontal {\n background: rgba(240, 240, 240, 255);\n height: 8px;\n border: none;\n margin: 0px;\n border-top: 1px solid rgba(200, 200, 200, 255);\n }\n QScrollBar::handle:horizontal {\n background: rgba(150, 150, 150, 120);\n border-radius: 4px;\n min-width: 20px;\n margin: 1px;\n }\n QScrollBar::handle:horizontal:hover {\n background: rgba(120, 120, 120, 200);\n }\n QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal {\n width: 0px;\n height: 0px;\n background: none;\n border: none;\n }\n QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {\n background: transparent;\n }\n )\");\n\n // 🌟 Add Button for New Tab (styled like browser + button)\n addTabButton = new QPushButton(this);\n QIcon addTab(loadThemedIcon(\"addtab\")); // Path to your icon in resources\n addTabButton->setIcon(addTab);\n addTabButton->setFixedSize(30, 30); // Even smaller to match thinner layout\n addTabButton->setStyleSheet(R\"(\n QPushButton {\n background-color: rgba(220, 220, 220, 255);\n border: 1px solid rgba(180, 180, 180, 255);\n border-radius: 15px;\n margin: 2px;\n }\n QPushButton:hover {\n background-color: rgba(200, 200, 200, 255);\n }\n QPushButton:pressed {\n background-color: rgba(180, 180, 180, 255);\n }\n )\");\n addTabButton->setToolTip(tr(\"Add New Tab\"));\n connect(addTabButton, &QPushButton::clicked, this, &MainWindow::addNewTab);\n\n if (!canvasStack) {\n canvasStack = new QStackedWidget(this);\n }\n\n connect(tabList, &QListWidget::currentRowChanged, this, &MainWindow::switchTab);\n\n // Create horizontal tab container\n tabBarContainer = new QWidget(this);\n tabBarContainer->setObjectName(\"tabBarContainer\");\n tabBarContainer->setFixedHeight(38); // Increased to accommodate scrollbar below tabs\n \n QHBoxLayout *tabBarLayout = new QHBoxLayout(tabBarContainer);\n tabBarLayout->setContentsMargins(5, 5, 5, 5);\n tabBarLayout->setSpacing(5);\n tabBarLayout->addWidget(tabList, 1); // Tab list takes most space\n tabBarLayout->addWidget(addTabButton, 0); // Add button stays at the end\n\n connect(toggleTabBarButton, &QPushButton::clicked, this, [=]() {\n bool isVisible = tabBarContainer->isVisible();\n tabBarContainer->setVisible(!isVisible);\n \n // Update button toggle state\n toggleTabBarButton->setProperty(\"selected\", !isVisible);\n toggleTabBarButton->style()->unpolish(toggleTabBarButton);\n toggleTabBarButton->style()->polish(toggleTabBarButton);\n\n QTimer::singleShot(0, this, [this]() {\n if (auto *canvas = currentCanvas()) {\n canvas->setMaximumSize(canvas->getCanvasSize());\n }\n });\n });\n \n connect(toggleOutlineButton, &QPushButton::clicked, this, &MainWindow::toggleOutlineSidebar);\n connect(toggleBookmarksButton, &QPushButton::clicked, this, &MainWindow::toggleBookmarksSidebar);\n connect(toggleBookmarkButton, &QPushButton::clicked, this, &MainWindow::toggleCurrentPageBookmark);\n connect(touchGesturesButton, &QPushButton::clicked, this, [this]() {\n setTouchGesturesEnabled(!touchGesturesEnabled);\n touchGesturesButton->setProperty(\"selected\", touchGesturesEnabled);\n touchGesturesButton->style()->unpolish(touchGesturesButton);\n touchGesturesButton->style()->polish(touchGesturesButton);\n });\n\n \n\n\n // Previous page button\n prevPageButton = new QPushButton(this);\n prevPageButton->setFixedSize(26, 30);\n prevPageButton->setText(\"◀\");\n prevPageButton->setStyleSheet(buttonStyle);\n prevPageButton->setToolTip(tr(\"Previous Page\"));\n connect(prevPageButton, &QPushButton::clicked, this, &MainWindow::goToPreviousPage);\n\n pageInput = new QSpinBox(this);\n pageInput->setFixedSize(42, 30);\n pageInput->setMinimum(1);\n pageInput->setMaximum(9999);\n pageInput->setValue(1);\n pageInput->setMaximumWidth(100);\n connect(pageInput, QOverload::of(&QSpinBox::valueChanged), this, &MainWindow::onPageInputChanged);\n\n // Next page button\n nextPageButton = new QPushButton(this);\n nextPageButton->setFixedSize(26, 30);\n nextPageButton->setText(\"▶\");\n nextPageButton->setStyleSheet(buttonStyle);\n nextPageButton->setToolTip(tr(\"Next Page\"));\n connect(nextPageButton, &QPushButton::clicked, this, &MainWindow::goToNextPage);\n\n jumpToPageButton = new QPushButton(this);\n // QIcon jumpIcon(\":/resources/icons/bookpage.png\"); // Path to your icon in resources\n jumpToPageButton->setFixedSize(26, 30);\n jumpToPageButton->setStyleSheet(buttonStyle);\n jumpToPageButton->setIcon(loadThemedIcon(\"bookpage\"));\n connect(jumpToPageButton, &QPushButton::clicked, this, &MainWindow::showJumpToPageDialog);\n\n // ✅ Dial Toggle Button\n dialToggleButton = new QPushButton(this);\n dialToggleButton->setIcon(loadThemedIcon(\"dial\")); // Icon for dial\n dialToggleButton->setFixedSize(26, 30);\n dialToggleButton->setToolTip(tr(\"Toggle Magic Dial\"));\n dialToggleButton->setStyleSheet(buttonStyle);\n\n // ✅ Connect to toggle function\n connect(dialToggleButton, &QPushButton::clicked, this, &MainWindow::toggleDial);\n\n // toggleDial();\n\n \n\n fastForwardButton = new QPushButton(this);\n fastForwardButton->setFixedSize(26, 30);\n // QIcon ffIcon(\":/resources/icons/fastforward.png\"); // Path to your icon in resources\n fastForwardButton->setIcon(loadThemedIcon(\"fastforward\"));\n fastForwardButton->setToolTip(tr(\"Toggle Fast Forward 8x\"));\n fastForwardButton->setStyleSheet(buttonStyle);\n\n // ✅ Toggle fast-forward mode\n connect(fastForwardButton, &QPushButton::clicked, [this]() {\n fastForwardMode = !fastForwardMode;\n updateFastForwardButtonState();\n });\n\n QComboBox *dialModeSelector = new QComboBox(this);\n dialModeSelector->addItem(\"Page Switch\", PageSwitching);\n dialModeSelector->addItem(\"Zoom\", ZoomControl);\n dialModeSelector->addItem(\"Thickness\", ThicknessControl);\n\n dialModeSelector->addItem(\"Tool Switch\", ToolSwitching);\n dialModeSelector->setFixedWidth(120);\n\n connect(dialModeSelector, QOverload::of(&QComboBox::currentIndexChanged), this,\n [this](int index) { changeDialMode(static_cast(index)); });\n\n\n\n colorPreview = new QPushButton(this);\n colorPreview->setFixedSize(26, 30);\n colorPreview->setStyleSheet(\"border-radius: 15px; border: 1px solid gray;\");\n colorPreview->setEnabled(false); // ✅ Prevents it from being clicked\n\n btnPageSwitch = new QPushButton(loadThemedIcon(\"bookpage\"), \"\", this);\n btnPageSwitch->setStyleSheet(buttonStyle);\n btnPageSwitch->setFixedSize(26, 30);\n btnPageSwitch->setToolTip(tr(\"Set Dial Mode to Page Switching\"));\n btnZoom = new QPushButton(loadThemedIcon(\"zoom\"), \"\", this);\n btnZoom->setStyleSheet(buttonStyle);\n btnZoom->setFixedSize(26, 30);\n btnZoom->setToolTip(tr(\"Set Dial Mode to Zoom Ctrl\"));\n btnThickness = new QPushButton(loadThemedIcon(\"thickness\"), \"\", this);\n btnThickness->setStyleSheet(buttonStyle);\n btnThickness->setFixedSize(26, 30);\n btnThickness->setToolTip(tr(\"Set Dial Mode to Pen Tip Thickness Ctrl\"));\n\n btnTool = new QPushButton(loadThemedIcon(\"pen\"), \"\", this);\n btnTool->setStyleSheet(buttonStyle);\n btnTool->setFixedSize(26, 30);\n btnTool->setToolTip(tr(\"Set Dial Mode to Tool Switching\"));\n btnPresets = new QPushButton(loadThemedIcon(\"preset\"), \"\", this);\n btnPresets->setStyleSheet(buttonStyle);\n btnPresets->setFixedSize(26, 30);\n btnPresets->setToolTip(tr(\"Set Dial Mode to Color Preset Selection\"));\n btnPannScroll = new QPushButton(loadThemedIcon(\"scroll\"), \"\", this);\n btnPannScroll->setStyleSheet(buttonStyle);\n btnPannScroll->setFixedSize(26, 30);\n btnPannScroll->setToolTip(tr(\"Slide and turn pages with the dial\"));\n\n connect(btnPageSwitch, &QPushButton::clicked, this, [this]() { changeDialMode(PageSwitching); });\n connect(btnZoom, &QPushButton::clicked, this, [this]() { changeDialMode(ZoomControl); });\n connect(btnThickness, &QPushButton::clicked, this, [this]() { changeDialMode(ThicknessControl); });\n\n connect(btnTool, &QPushButton::clicked, this, [this]() { changeDialMode(ToolSwitching); });\n connect(btnPresets, &QPushButton::clicked, this, [this]() { changeDialMode(PresetSelection); }); \n connect(btnPannScroll, &QPushButton::clicked, this, [this]() { changeDialMode(PanAndPageScroll); });\n\n\n // ✅ Initialize color presets based on palette mode (will be updated after UI setup)\n colorPresets.enqueue(getDefaultPenColor());\n colorPresets.enqueue(QColor(\"#AA0000\")); // Temporary - will be updated later\n colorPresets.enqueue(QColor(\"#997700\"));\n colorPresets.enqueue(QColor(\"#0000AA\"));\n colorPresets.enqueue(QColor(\"#007700\"));\n colorPresets.enqueue(QColor(\"#000000\"));\n colorPresets.enqueue(QColor(\"#FFFFFF\"));\n\n // ✅ Button to add current color to presets\n addPresetButton = new QPushButton(loadThemedIcon(\"savepreset\"), \"\", this);\n addPresetButton->setStyleSheet(buttonStyle);\n addPresetButton->setToolTip(tr(\"Add Current Color to Presets\"));\n addPresetButton->setFixedSize(26, 30);\n connect(addPresetButton, &QPushButton::clicked, this, &MainWindow::addColorPreset);\n\n\n\n\n openControlPanelButton = new QPushButton(this);\n openControlPanelButton->setIcon(loadThemedIcon(\"settings\")); // Replace with your actual settings icon\n openControlPanelButton->setStyleSheet(buttonStyle);\n openControlPanelButton->setToolTip(tr(\"Open Control Panel\"));\n openControlPanelButton->setFixedSize(26, 30); // Adjust to match your other buttons\n\n connect(openControlPanelButton, &QPushButton::clicked, this, [=]() {\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n ControlPanelDialog dialog(this, canvas, this);\n dialog.exec(); // Modal\n }\n });\n\n openRecentNotebooksButton = new QPushButton(this); // Create button\n openRecentNotebooksButton->setIcon(loadThemedIcon(\"recent\")); // Replace with actual icon if available\n openRecentNotebooksButton->setStyleSheet(buttonStyle);\n openRecentNotebooksButton->setToolTip(tr(\"Open Recent Notebooks\"));\n openRecentNotebooksButton->setFixedSize(26, 30);\n connect(openRecentNotebooksButton, &QPushButton::clicked, this, &MainWindow::openRecentNotebooksDialog);\n\n customColorButton = new QPushButton(this);\n customColorButton->setFixedSize(62, 30);\n QColor initialColor = getDefaultPenColor(); // Theme-aware default color\n customColorButton->setText(initialColor.name().toUpper());\n\n if (currentCanvas()) {\n initialColor = currentCanvas()->getPenColor();\n }\n\n updateCustomColorButtonStyle(initialColor);\n\n QTimer::singleShot(0, this, [=]() {\n connect(customColorButton, &QPushButton::clicked, this, [=]() {\n if (!currentCanvas()) return;\n \n handleColorButtonClick();\n \n // Get the current custom color from the button text\n QString buttonText = customColorButton->text();\n QColor customColor(buttonText);\n \n // Check if the custom color is already the current pen color\n if (currentCanvas()->getPenColor() == customColor) {\n // Second click - show color picker dialog\n QColor chosen = QColorDialog::getColor(currentCanvas()->getPenColor(), this, \"Select Pen Color\");\n if (chosen.isValid()) {\n currentCanvas()->setPenColor(chosen);\n updateCustomColorButtonStyle(chosen);\n updateDialDisplay();\n updateColorButtonStates();\n }\n } else {\n // First click - apply the custom color\n currentCanvas()->setPenColor(customColor);\n updateDialDisplay();\n updateColorButtonStates();\n }\n });\n });\n\n QHBoxLayout *controlLayout = new QHBoxLayout;\n \n controlLayout->addWidget(toggleOutlineButton);\n controlLayout->addWidget(toggleBookmarksButton);\n controlLayout->addWidget(toggleBookmarkButton);\n controlLayout->addWidget(touchGesturesButton);\n controlLayout->addWidget(toggleTabBarButton);\n controlLayout->addWidget(selectFolderButton);\n\n controlLayout->addWidget(exportNotebookButton);\n controlLayout->addWidget(importNotebookButton);\n controlLayout->addWidget(loadPdfButton);\n controlLayout->addWidget(clearPdfButton);\n controlLayout->addWidget(pdfTextSelectButton);\n controlLayout->addWidget(backgroundButton);\n controlLayout->addWidget(saveButton);\n controlLayout->addWidget(saveAnnotatedButton);\n controlLayout->addWidget(openControlPanelButton);\n controlLayout->addWidget(openRecentNotebooksButton); // Add button to layout\n controlLayout->addWidget(redButton);\n controlLayout->addWidget(blueButton);\n controlLayout->addWidget(yellowButton);\n controlLayout->addWidget(greenButton);\n controlLayout->addWidget(blackButton);\n controlLayout->addWidget(whiteButton);\n controlLayout->addWidget(customColorButton);\n controlLayout->addWidget(straightLineToggleButton);\n controlLayout->addWidget(ropeToolButton); // Add rope tool button to layout\n controlLayout->addWidget(markdownButton); // Add markdown button to layout\n // controlLayout->addWidget(colorPreview);\n // controlLayout->addWidget(thicknessButton);\n // controlLayout->addWidget(jumpToPageButton);\n controlLayout->addWidget(dialToggleButton);\n controlLayout->addWidget(fastForwardButton);\n // controlLayout->addWidget(channelSelector);\n controlLayout->addWidget(btnPageSwitch);\n controlLayout->addWidget(btnPannScroll);\n controlLayout->addWidget(btnZoom);\n controlLayout->addWidget(btnThickness);\n\n controlLayout->addWidget(btnTool);\n controlLayout->addWidget(btnPresets);\n controlLayout->addWidget(addPresetButton);\n // controlLayout->addWidget(dialModeSelector);\n // controlLayout->addStretch();\n \n // controlLayout->addWidget(toolSelector);\n controlLayout->addWidget(fullscreenButton);\n // controlLayout->addWidget(zoomButton);\n controlLayout->addWidget(zoom50Button);\n controlLayout->addWidget(dezoomButton);\n controlLayout->addWidget(zoom200Button);\n controlLayout->addStretch();\n \n \n controlLayout->addWidget(prevPageButton);\n controlLayout->addWidget(pageInput);\n controlLayout->addWidget(nextPageButton);\n controlLayout->addWidget(benchmarkButton);\n controlLayout->addWidget(benchmarkLabel);\n controlLayout->addWidget(deletePageButton);\n \n \n \n controlBar = new QWidget; // Use member variable instead of local\n controlBar->setObjectName(\"controlBar\");\n // controlBar->setLayout(controlLayout); // Commented out - responsive layout will handle this\n controlBar->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);\n\n // Theme will be applied later in loadUserSettings -> updateTheme()\n controlBar->setStyleSheet(\"\");\n\n \n \n\n canvasStack = new QStackedWidget();\n canvasStack->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);\n\n // Create a container for the canvas and scrollbars with relative positioning\n QWidget *canvasContainer = new QWidget;\n QVBoxLayout *canvasLayout = new QVBoxLayout(canvasContainer);\n canvasLayout->setContentsMargins(0, 0, 0, 0);\n canvasLayout->addWidget(canvasStack);\n\n // Enable context menu for the workaround\n canvasContainer->setContextMenuPolicy(Qt::CustomContextMenu);\n \n // Set up the scrollbars to overlay the canvas\n panXSlider->setParent(canvasContainer);\n panYSlider->setParent(canvasContainer);\n \n // Raise scrollbars to ensure they're visible above the canvas\n panXSlider->raise();\n panYSlider->raise();\n \n // Handle scrollbar intersection\n connect(canvasContainer, &QWidget::customContextMenuRequested, this, [this]() {\n // This connection is just to make sure the container exists\n // and can receive signals - a workaround for some Qt versions\n });\n \n // Position the scrollbars at the bottom and right edges\n canvasContainer->installEventFilter(this);\n \n // Update scrollbar positions initially\n QTimer::singleShot(0, this, [this, canvasContainer]() {\n updateScrollbarPositions();\n });\n\n // Main layout: toolbar -> tab bar -> canvas (vertical stack)\n QWidget *container = new QWidget;\n container->setObjectName(\"container\");\n QVBoxLayout *mainLayout = new QVBoxLayout(container);\n mainLayout->setContentsMargins(0, 0, 0, 0); // ✅ Remove extra margins\n mainLayout->setSpacing(0); // ✅ Remove spacing between components\n \n // Add components in vertical order\n mainLayout->addWidget(controlBar); // Toolbar at top\n mainLayout->addWidget(tabBarContainer); // Tab bar below toolbar\n \n // Content area with sidebars and canvas\n QHBoxLayout *contentLayout = new QHBoxLayout;\n contentLayout->setContentsMargins(0, 0, 0, 0);\n contentLayout->setSpacing(0);\n contentLayout->addWidget(outlineSidebar, 0); // Fixed width outline sidebar\n contentLayout->addWidget(bookmarksSidebar, 0); // Fixed width bookmarks sidebar\n contentLayout->addWidget(canvasContainer, 1); // Canvas takes remaining space\n \n QWidget *contentWidget = new QWidget;\n contentWidget->setLayout(contentLayout);\n mainLayout->addWidget(contentWidget, 1);\n\n setCentralWidget(container);\n\n benchmarkTimer = new QTimer(this);\n connect(benchmarkButton, &QPushButton::clicked, this, &MainWindow::toggleBenchmark);\n connect(benchmarkTimer, &QTimer::timeout, this, &MainWindow::updateBenchmarkDisplay);\n\n QString tempDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\";\n QDir dir(tempDir);\n\n // Remove all contents (but keep the directory itself)\n if (dir.exists()) {\n dir.removeRecursively(); // Careful: this wipes everything inside\n }\n QDir().mkpath(tempDir); // Recreate clean directory\n\n addNewTab();\n\n // Initialize responsive toolbar layout\n createSingleRowLayout(); // Start with single row layout\n \n // Now that all UI components are created, update the color palette\n updateColorPalette();\n\n}\n void loadUserSettings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n\n // Load low-res toggle\n lowResPreviewEnabled = settings.value(\"lowResPreviewEnabled\", true).toBool();\n setLowResPreviewEnabled(lowResPreviewEnabled);\n\n \n zoomButtonsVisible = settings.value(\"zoomButtonsVisible\", true).toBool();\n setZoomButtonsVisible(zoomButtonsVisible);\n\n scrollOnTopEnabled = settings.value(\"scrollOnTopEnabled\", true).toBool();\n setScrollOnTopEnabled(scrollOnTopEnabled);\n\n touchGesturesEnabled = settings.value(\"touchGesturesEnabled\", true).toBool();\n setTouchGesturesEnabled(touchGesturesEnabled);\n \n // Update button visual state to match loaded setting\n touchGesturesButton->setProperty(\"selected\", touchGesturesEnabled);\n touchGesturesButton->style()->unpolish(touchGesturesButton);\n touchGesturesButton->style()->polish(touchGesturesButton);\n \n // Initialize default background settings if they don't exist\n if (!settings.contains(\"defaultBackgroundStyle\")) {\n saveDefaultBackgroundSettings(BackgroundStyle::Grid, Qt::white, 30);\n }\n \n // Load keyboard mappings\n loadKeyboardMappings();\n \n // Load theme settings\n loadThemeSettings();\n}\n bool scrollbarsVisible = false;\n QTimer *scrollbarHideTimer = nullptr;\n bool eventFilter(QObject *obj, QEvent *event) override {\n static bool dragging = false;\n static QPoint lastMousePos;\n static QTimer *longPressTimer = nullptr;\n\n // Handle IME focus events for text input widgets\n QLineEdit *lineEdit = qobject_cast(obj);\n if (lineEdit) {\n if (event->type() == QEvent::FocusIn) {\n // Ensure IME is enabled when text field gets focus\n lineEdit->setAttribute(Qt::WA_InputMethodEnabled, true);\n QInputMethod *inputMethod = QGuiApplication::inputMethod();\n if (inputMethod) {\n inputMethod->show();\n }\n }\n else if (event->type() == QEvent::FocusOut) {\n // Keep IME available but reset state\n QInputMethod *inputMethod = QGuiApplication::inputMethod();\n if (inputMethod) {\n inputMethod->reset();\n }\n }\n }\n\n // Handle resize events for canvas container\n QWidget *container = canvasStack ? canvasStack->parentWidget() : nullptr;\n if (obj == container && event->type() == QEvent::Resize) {\n updateScrollbarPositions();\n return false; // Let the event propagate\n }\n\n // Handle scrollbar visibility\n if (obj == panXSlider || obj == panYSlider) {\n if (event->type() == QEvent::Enter) {\n // Mouse entered scrollbar area\n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n return false;\n } \n else if (event->type() == QEvent::Leave) {\n // Mouse left scrollbar area - start timer to hide\n if (!scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->start();\n }\n return false;\n }\n }\n\n // Check if this is a canvas event for scrollbar handling\n InkCanvas* canvas = qobject_cast(obj);\n if (canvas) {\n // Handle mouse movement for scrollbar visibility\n if (event->type() == QEvent::MouseMove) {\n QMouseEvent* mouseEvent = static_cast(event);\n handleEdgeProximity(canvas, mouseEvent->pos());\n }\n // Handle tablet events for stylus hover (safely)\n else if (event->type() == QEvent::TabletMove) {\n try {\n QTabletEvent* tabletEvent = static_cast(event);\n handleEdgeProximity(canvas, tabletEvent->position().toPoint());\n } catch (...) {\n // Ignore tablet event errors to prevent crashes\n }\n }\n // Handle mouse button press events for forward/backward navigation\n else if (event->type() == QEvent::MouseButtonPress) {\n QMouseEvent* mouseEvent = static_cast(event);\n \n // Mouse button 4 (Back button) - Previous page\n if (mouseEvent->button() == Qt::BackButton) {\n if (prevPageButton) {\n prevPageButton->click();\n }\n return true; // Consume the event\n }\n // Mouse button 5 (Forward button) - Next page\n else if (mouseEvent->button() == Qt::ForwardButton) {\n if (nextPageButton) {\n nextPageButton->click();\n }\n return true; // Consume the event\n }\n }\n // Handle wheel events for scrolling\n else if (event->type() == QEvent::Wheel) {\n QWheelEvent* wheelEvent = static_cast(event);\n \n // Check if we need scrolling\n bool needHorizontalScroll = panXSlider->maximum() > 0;\n bool needVerticalScroll = panYSlider->maximum() > 0;\n \n // Handle vertical scrolling (Y axis)\n if (wheelEvent->angleDelta().y() != 0 && needVerticalScroll) {\n // Calculate scroll amount (negative because wheel up should scroll up)\n int scrollDelta = -wheelEvent->angleDelta().y() / 8; // Convert from 1/8 degree units\n scrollDelta = scrollDelta / 15; // Convert to steps (typical wheel step is 15 degrees)\n \n // Much faster base scroll speed - aim for ~3-5 scrolls to reach bottom\n int baseScrollAmount = panYSlider->maximum() / 8; // 1/8 of total range per scroll\n scrollDelta = scrollDelta * qMax(baseScrollAmount, 50); // Minimum 50 units per scroll\n \n // Apply the scroll\n int currentPan = panYSlider->value();\n int newPan = qBound(panYSlider->minimum(), currentPan + scrollDelta, panYSlider->maximum());\n panYSlider->setValue(newPan);\n \n // Show scrollbar temporarily\n panYSlider->setVisible(true);\n scrollbarsVisible = true;\n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n scrollbarHideTimer->start();\n \n // Consume the event\n return true;\n }\n \n // Handle horizontal scrolling (X axis) - for completeness\n if (wheelEvent->angleDelta().x() != 0 && needHorizontalScroll) {\n // Calculate scroll amount\n int scrollDelta = wheelEvent->angleDelta().x() / 8; // Convert from 1/8 degree units\n scrollDelta = scrollDelta / 15; // Convert to steps\n \n // Much faster base scroll speed - same logic as vertical\n int baseScrollAmount = panXSlider->maximum() / 8; // 1/8 of total range per scroll\n scrollDelta = scrollDelta * qMax(baseScrollAmount, 50); // Minimum 50 units per scroll\n \n // Apply the scroll\n int currentPan = panXSlider->value();\n int newPan = qBound(panXSlider->minimum(), currentPan + scrollDelta, panXSlider->maximum());\n panXSlider->setValue(newPan);\n \n // Show scrollbar temporarily\n panXSlider->setVisible(true);\n scrollbarsVisible = true;\n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n scrollbarHideTimer->start();\n \n // Consume the event\n return true;\n }\n \n // If no scrolling was needed, let the event propagate\n return false;\n }\n }\n\n // Handle dial container drag events\n if (obj == dialContainer) {\n if (event->type() == QEvent::MouseButtonPress) {\n QMouseEvent *mouseEvent = static_cast(event);\n lastMousePos = mouseEvent->globalPos();\n dragging = false;\n\n if (!longPressTimer) {\n longPressTimer = new QTimer(this);\n longPressTimer->setSingleShot(true);\n connect(longPressTimer, &QTimer::timeout, [this]() {\n dragging = true; // ✅ Allow movement after long press\n });\n }\n longPressTimer->start(1500); // ✅ Start long press timer (500ms)\n return true;\n }\n\n if (event->type() == QEvent::MouseMove && dragging) {\n QMouseEvent *mouseEvent = static_cast(event);\n QPoint delta = mouseEvent->globalPos() - lastMousePos;\n dialContainer->move(dialContainer->pos() + delta);\n lastMousePos = mouseEvent->globalPos();\n return true;\n }\n\n if (event->type() == QEvent::MouseButtonRelease) {\n if (longPressTimer) longPressTimer->stop();\n dragging = false; // ✅ Stop dragging on release\n return true;\n }\n }\n\n return QObject::eventFilter(obj, event);\n}\n void updateScrollbarPositions() {\n QWidget *container = canvasStack->parentWidget();\n if (!container || !panXSlider || !panYSlider) return;\n \n // Add small margins for better visibility\n const int margin = 3;\n \n // Get scrollbar dimensions\n const int scrollbarWidth = panYSlider->width();\n const int scrollbarHeight = panXSlider->height();\n \n // Calculate sizes based on container\n int containerWidth = container->width();\n int containerHeight = container->height();\n \n // Leave a bit of space for the corner\n int cornerOffset = 15;\n \n // Position horizontal scrollbar at top\n panXSlider->setGeometry(\n cornerOffset + margin, // Leave space at left corner\n margin,\n containerWidth - cornerOffset - margin*2, // Full width minus corner and right margin\n scrollbarHeight\n );\n \n // Position vertical scrollbar at left\n panYSlider->setGeometry(\n margin,\n cornerOffset + margin, // Leave space at top corner\n scrollbarWidth,\n containerHeight - cornerOffset - margin*2 // Full height minus corner and bottom margin\n );\n}\n void handleEdgeProximity(InkCanvas* canvas, const QPoint& pos) {\n if (!canvas) return;\n \n // Get canvas dimensions\n int canvasWidth = canvas->width();\n int canvasHeight = canvas->height();\n \n // Edge detection zones - show scrollbars when pointer is within 50px of edges\n bool nearLeftEdge = pos.x() < 25; // For vertical scrollbar\n bool nearTopEdge = pos.y() < 25; // For horizontal scrollbar - entire top edge\n \n // Only show scrollbars if canvas is larger than viewport\n bool needHorizontalScroll = panXSlider->maximum() > 0;\n bool needVerticalScroll = panYSlider->maximum() > 0;\n \n // Show/hide scrollbars based on pointer position\n if (nearLeftEdge && needVerticalScroll) {\n panYSlider->setVisible(true);\n scrollbarsVisible = true;\n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n scrollbarHideTimer->start();\n }\n \n if (nearTopEdge && needHorizontalScroll) {\n panXSlider->setVisible(true);\n scrollbarsVisible = true;\n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n scrollbarHideTimer->start();\n }\n}\n bool isToolbarTwoRows = false;\n QVBoxLayout *controlLayoutVertical = nullptr;\n QHBoxLayout *controlLayoutSingle = nullptr;\n QHBoxLayout *controlLayoutFirstRow = nullptr;\n QHBoxLayout *controlLayoutSecondRow = nullptr;\n void updateToolbarLayout() {\n // Calculate scaled width using device pixel ratio\n QScreen *screen = QGuiApplication::primaryScreen();\n // qreal dpr = screen ? screen->devicePixelRatio() : 1.0;\n int scaledWidth = width();\n \n // Dynamic threshold based on zoom button visibility\n int threshold = areZoomButtonsVisible() ? 1548 : 1438;\n \n // Debug output to understand what's happening\n // qDebug() << \"Window width:\" << scaledWidth << \"Threshold:\" << threshold << \"Zoom buttons visible:\" << areZoomButtonsVisible();\n \n bool shouldBeTwoRows = scaledWidth <= threshold;\n \n // qDebug() << \"Should be two rows:\" << shouldBeTwoRows << \"Currently is two rows:\" << isToolbarTwoRows;\n \n if (shouldBeTwoRows != isToolbarTwoRows) {\n isToolbarTwoRows = shouldBeTwoRows;\n \n // qDebug() << \"Switching to\" << (isToolbarTwoRows ? \"two rows\" : \"single row\");\n \n if (isToolbarTwoRows) {\n createTwoRowLayout();\n } else {\n createSingleRowLayout();\n }\n }\n}\n void createSingleRowLayout() {\n // Delete separator line if it exists (from previous 2-row layout)\n if (separatorLine) {\n delete separatorLine;\n separatorLine = nullptr;\n }\n \n // Create new single row layout first\n QHBoxLayout *newLayout = new QHBoxLayout;\n \n // Add all widgets to single row (same order as before)\n newLayout->addWidget(toggleTabBarButton);\n newLayout->addWidget(toggleOutlineButton);\n newLayout->addWidget(toggleBookmarksButton);\n newLayout->addWidget(toggleBookmarkButton);\n newLayout->addWidget(touchGesturesButton);\n newLayout->addWidget(selectFolderButton);\n newLayout->addWidget(exportNotebookButton);\n newLayout->addWidget(importNotebookButton);\n newLayout->addWidget(loadPdfButton);\n newLayout->addWidget(clearPdfButton);\n newLayout->addWidget(pdfTextSelectButton);\n newLayout->addWidget(backgroundButton);\n newLayout->addWidget(saveButton);\n newLayout->addWidget(saveAnnotatedButton);\n newLayout->addWidget(openControlPanelButton);\n newLayout->addWidget(openRecentNotebooksButton);\n newLayout->addWidget(redButton);\n newLayout->addWidget(blueButton);\n newLayout->addWidget(yellowButton);\n newLayout->addWidget(greenButton);\n newLayout->addWidget(blackButton);\n newLayout->addWidget(whiteButton);\n newLayout->addWidget(customColorButton);\n newLayout->addWidget(penToolButton);\n newLayout->addWidget(markerToolButton);\n newLayout->addWidget(eraserToolButton);\n newLayout->addWidget(straightLineToggleButton);\n newLayout->addWidget(ropeToolButton);\n newLayout->addWidget(markdownButton);\n newLayout->addWidget(dialToggleButton);\n newLayout->addWidget(fastForwardButton);\n newLayout->addWidget(btnPageSwitch);\n newLayout->addWidget(btnPannScroll);\n newLayout->addWidget(btnZoom);\n newLayout->addWidget(btnThickness);\n\n newLayout->addWidget(btnTool);\n newLayout->addWidget(btnPresets);\n newLayout->addWidget(addPresetButton);\n newLayout->addWidget(fullscreenButton);\n \n // Only add zoom buttons if they're visible\n if (areZoomButtonsVisible()) {\n newLayout->addWidget(zoom50Button);\n newLayout->addWidget(dezoomButton);\n newLayout->addWidget(zoom200Button);\n }\n \n newLayout->addStretch();\n newLayout->addWidget(prevPageButton);\n newLayout->addWidget(pageInput);\n newLayout->addWidget(nextPageButton);\n newLayout->addWidget(benchmarkButton);\n newLayout->addWidget(benchmarkLabel);\n newLayout->addWidget(deletePageButton);\n \n // Safely replace the layout\n QLayout* oldLayout = controlBar->layout();\n if (oldLayout) {\n // Remove all items from old layout (but don't delete widgets)\n QLayoutItem* item;\n while ((item = oldLayout->takeAt(0)) != nullptr) {\n // Just removing, not deleting widgets\n }\n delete oldLayout;\n }\n \n // Set the new layout\n controlBar->setLayout(newLayout);\n controlLayoutSingle = newLayout;\n \n // Clean up other layout pointers\n controlLayoutVertical = nullptr;\n controlLayoutFirstRow = nullptr;\n controlLayoutSecondRow = nullptr;\n \n // Update pan range after layout change\n updatePanRange();\n}\n void createTwoRowLayout() {\n // Create new layouts first\n QVBoxLayout *newVerticalLayout = new QVBoxLayout;\n QHBoxLayout *newFirstRowLayout = new QHBoxLayout;\n QHBoxLayout *newSecondRowLayout = new QHBoxLayout;\n \n // Add comfortable spacing and margins for 2-row layout\n newFirstRowLayout->setContentsMargins(8, 8, 8, 6); // More generous margins\n newFirstRowLayout->setSpacing(3); // Add spacing between buttons for less cramped feel\n newSecondRowLayout->setContentsMargins(8, 6, 8, 8); // More generous margins\n newSecondRowLayout->setSpacing(3); // Add spacing between buttons for less cramped feel\n \n // First row: up to customColorButton\n newFirstRowLayout->addWidget(toggleTabBarButton);\n newFirstRowLayout->addWidget(toggleOutlineButton);\n newFirstRowLayout->addWidget(toggleBookmarksButton);\n newFirstRowLayout->addWidget(toggleBookmarkButton);\n newFirstRowLayout->addWidget(touchGesturesButton);\n newFirstRowLayout->addWidget(selectFolderButton);\n newFirstRowLayout->addWidget(exportNotebookButton);\n newFirstRowLayout->addWidget(importNotebookButton);\n newFirstRowLayout->addWidget(loadPdfButton);\n newFirstRowLayout->addWidget(clearPdfButton);\n newFirstRowLayout->addWidget(pdfTextSelectButton);\n newFirstRowLayout->addWidget(backgroundButton);\n newFirstRowLayout->addWidget(saveButton);\n newFirstRowLayout->addWidget(saveAnnotatedButton);\n newFirstRowLayout->addWidget(openControlPanelButton);\n newFirstRowLayout->addWidget(openRecentNotebooksButton);\n newFirstRowLayout->addWidget(redButton);\n newFirstRowLayout->addWidget(blueButton);\n newFirstRowLayout->addWidget(yellowButton);\n newFirstRowLayout->addWidget(greenButton);\n newFirstRowLayout->addWidget(blackButton);\n newFirstRowLayout->addWidget(whiteButton);\n newFirstRowLayout->addWidget(customColorButton);\n newFirstRowLayout->addWidget(penToolButton);\n newFirstRowLayout->addWidget(markerToolButton);\n newFirstRowLayout->addWidget(eraserToolButton);\n newFirstRowLayout->addStretch();\n \n // Create a separator line\n if (!separatorLine) {\n separatorLine = new QFrame();\n separatorLine->setFrameShape(QFrame::HLine);\n separatorLine->setFrameShadow(QFrame::Sunken);\n separatorLine->setLineWidth(1);\n separatorLine->setStyleSheet(\"QFrame { color: rgba(255, 255, 255, 255); }\");\n }\n \n // Second row: everything after customColorButton\n newSecondRowLayout->addWidget(straightLineToggleButton);\n newSecondRowLayout->addWidget(ropeToolButton);\n newSecondRowLayout->addWidget(markdownButton);\n newSecondRowLayout->addWidget(dialToggleButton);\n newSecondRowLayout->addWidget(fastForwardButton);\n newSecondRowLayout->addWidget(btnPageSwitch);\n newSecondRowLayout->addWidget(btnPannScroll);\n newSecondRowLayout->addWidget(btnZoom);\n newSecondRowLayout->addWidget(btnThickness);\n\n newSecondRowLayout->addWidget(btnTool);\n newSecondRowLayout->addWidget(btnPresets);\n newSecondRowLayout->addWidget(addPresetButton);\n newSecondRowLayout->addWidget(fullscreenButton);\n \n // Only add zoom buttons if they're visible\n if (areZoomButtonsVisible()) {\n newSecondRowLayout->addWidget(zoom50Button);\n newSecondRowLayout->addWidget(dezoomButton);\n newSecondRowLayout->addWidget(zoom200Button);\n }\n \n newSecondRowLayout->addStretch();\n newSecondRowLayout->addWidget(prevPageButton);\n newSecondRowLayout->addWidget(pageInput);\n newSecondRowLayout->addWidget(nextPageButton);\n newSecondRowLayout->addWidget(benchmarkButton);\n newSecondRowLayout->addWidget(benchmarkLabel);\n newSecondRowLayout->addWidget(deletePageButton);\n \n // Add layouts to vertical layout with separator\n newVerticalLayout->addLayout(newFirstRowLayout);\n newVerticalLayout->addWidget(separatorLine);\n newVerticalLayout->addLayout(newSecondRowLayout);\n newVerticalLayout->setContentsMargins(0, 0, 0, 0);\n newVerticalLayout->setSpacing(0); // No spacing since we have our own separator\n \n // Safely replace the layout\n QLayout* oldLayout = controlBar->layout();\n if (oldLayout) {\n // Remove all items from old layout (but don't delete widgets)\n QLayoutItem* item;\n while ((item = oldLayout->takeAt(0)) != nullptr) {\n // Just removing, not deleting widgets\n }\n delete oldLayout;\n }\n \n // Set the new layout\n controlBar->setLayout(newVerticalLayout);\n controlLayoutVertical = newVerticalLayout;\n controlLayoutFirstRow = newFirstRowLayout;\n controlLayoutSecondRow = newSecondRowLayout;\n \n // Clean up other layout pointer\n controlLayoutSingle = nullptr;\n \n // Update pan range after layout change\n updatePanRange();\n}\n QString elideTabText(const QString &text, int maxWidth) {\n // Create a font metrics object using the default font\n QFontMetrics fontMetrics(QApplication::font());\n \n // Elide the text from the right (showing the beginning)\n return fontMetrics.elidedText(text, Qt::ElideRight, maxWidth);\n}\n QTimer *layoutUpdateTimer = nullptr;\n QFrame *separatorLine = nullptr;\n protected:\n void resizeEvent(QResizeEvent *event) override {\n QMainWindow::resizeEvent(event);\n \n // Use a timer to delay layout updates during resize to prevent excessive switching\n if (!layoutUpdateTimer) {\n layoutUpdateTimer = new QTimer(this);\n layoutUpdateTimer->setSingleShot(true);\n connect(layoutUpdateTimer, &QTimer::timeout, this, [this]() {\n updateToolbarLayout();\n // Also reposition dial after resize finishes\n if (dialContainer && dialContainer->isVisible()) {\n positionDialContainer();\n }\n });\n }\n \n layoutUpdateTimer->stop();\n layoutUpdateTimer->start(100); // Wait 100ms after resize stops\n}\n void keyPressEvent(QKeyEvent *event) override {\n // Don't intercept keyboard events when text input widgets have focus\n // This prevents conflicts with Windows TextInputFramework\n QWidget *focusWidget = QApplication::focusWidget();\n if (focusWidget) {\n bool isTextInputWidget = qobject_cast(focusWidget) || \n qobject_cast(focusWidget) || \n qobject_cast(focusWidget) ||\n qobject_cast(focusWidget) ||\n qobject_cast(focusWidget);\n \n if (isTextInputWidget) {\n // Let text input widgets handle their own keyboard events\n QMainWindow::keyPressEvent(event);\n return;\n }\n }\n \n // Don't intercept IME-related keyboard shortcuts\n // These are reserved for Windows Input Method Editor\n if (event->modifiers() & Qt::ControlModifier) {\n if (event->key() == Qt::Key_Space || // Ctrl+Space (IME toggle)\n event->key() == Qt::Key_Shift || // Ctrl+Shift (language switch)\n event->key() == Qt::Key_Alt) { // Ctrl+Alt (IME functions)\n // Let Windows handle IME shortcuts\n QMainWindow::keyPressEvent(event);\n return;\n }\n }\n \n // Don't intercept Shift+Alt (another common IME shortcut)\n if ((event->modifiers() & Qt::ShiftModifier) && (event->modifiers() & Qt::AltModifier)) {\n QMainWindow::keyPressEvent(event);\n return;\n }\n \n // Build key sequence string\n QStringList modifiers;\n \n if (event->modifiers() & Qt::ControlModifier) modifiers << \"Ctrl\";\n if (event->modifiers() & Qt::ShiftModifier) modifiers << \"Shift\";\n if (event->modifiers() & Qt::AltModifier) modifiers << \"Alt\";\n if (event->modifiers() & Qt::MetaModifier) modifiers << \"Meta\";\n \n QString keyString = QKeySequence(event->key()).toString();\n \n QString fullSequence;\n if (!modifiers.isEmpty()) {\n fullSequence = modifiers.join(\"+\") + \"+\" + keyString;\n } else {\n fullSequence = keyString;\n }\n \n // Check if this sequence is mapped\n if (keyboardMappings.contains(fullSequence)) {\n handleKeyboardShortcut(fullSequence);\n event->accept();\n return;\n }\n \n // If not handled, pass to parent\n QMainWindow::keyPressEvent(event);\n}\n void tabletEvent(QTabletEvent *event) override {\n // Since tablet tracking is disabled to prevent crashes, we now only handle\n // basic tablet events that come through when stylus is touching the surface\n if (!event) {\n return;\n }\n \n // Just pass tablet events to parent safely without custom hover handling\n // (hover tooltips will work through normal mouse events instead)\n try {\n QMainWindow::tabletEvent(event);\n } catch (...) {\n // Catch any exceptions and just accept the event\n event->accept();\n }\n}\n void inputMethodEvent(QInputMethodEvent *event) override {\n // Forward IME events to the focused widget\n QWidget *focusWidget = QApplication::focusWidget();\n if (focusWidget && focusWidget != this) {\n QApplication::sendEvent(focusWidget, event);\n event->accept();\n return;\n }\n \n // Default handling\n QMainWindow::inputMethodEvent(event);\n}\n QVariant inputMethodQuery(Qt::InputMethodQuery query) const override {\n // Forward IME queries to the focused widget\n QWidget *focusWidget = QApplication::focusWidget();\n if (focusWidget && focusWidget != this) {\n return focusWidget->inputMethodQuery(query);\n }\n \n // Default handling\n return QMainWindow::inputMethodQuery(query);\n}\n};"], ["/SpeedyNote/source/InkCanvas.h", "class MarkdownWindowManager {\n Q_OBJECT\n\nsignals:\n void zoomChanged(int newZoom);\n void panChanged(int panX, int panY);\n void touchGestureEnded();\n void ropeSelectionCompleted(const QPoint &position);\n void pdfLinkClicked(int targetPage);\n void pdfTextSelected(const QString &text);\n void pdfLoaded();\n void markdownSelectionModeChanged(bool enabled);\n public:\n explicit InkCanvas(QWidget *parent = nullptr) { \n \n // Set theme-aware default pen color\n MainWindow *mainWindow = qobject_cast(parent);\n if (mainWindow) {\n penColor = mainWindow->getDefaultPenColor();\n } \n setAttribute(Qt::WA_StaticContents);\n setTabletTracking(true);\n setAttribute(Qt::WA_AcceptTouchEvents); // Enable touch events\n\n // Enable immediate updates for smoother animation\n setAttribute(Qt::WA_OpaquePaintEvent);\n setAttribute(Qt::WA_NoSystemBackground);\n \n // Detect screen resolution and set canvas size\n QScreen *screen = QGuiApplication::primaryScreen();\n if (screen) {\n QSize logicalSize = screen->availableGeometry().size() * 0.89;\n setMaximumSize(logicalSize); // Optional\n setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);\n } else {\n setFixedSize(1920, 1080); // Fallback size\n }\n \n initializeBuffer();\n QCache pdfCache(10);\n pdfCache.setMaxCost(10); // ✅ Ensures the cache holds at most 5 pages\n // No need to set auto-delete, QCache will handle deletion automatically\n \n // Initialize PDF text selection throttling timer (60 FPS = ~16.67ms)\n pdfTextSelectionTimer = new QTimer(this);\n pdfTextSelectionTimer->setSingleShot(true);\n pdfTextSelectionTimer->setInterval(16); // ~60 FPS\n connect(pdfTextSelectionTimer, &QTimer::timeout, this, &InkCanvas::processPendingTextSelection);\n \n // Initialize PDF cache timer (will be created on-demand)\n pdfCacheTimer = nullptr;\n currentCachedPage = -1;\n \n // Initialize note page cache system\n noteCache.setMaxCost(15); // Cache up to 15 note pages (more than PDF since they're smaller)\n noteCacheTimer = nullptr;\n currentCachedNotePage = -1;\n \n // Initialize markdown manager\n markdownManager = new MarkdownWindowManager(this, this);\n \n // Connect pan/zoom signals to update markdown window positions\n connect(this, &InkCanvas::panChanged, markdownManager, &MarkdownWindowManager::updateAllWindowPositions);\n connect(this, &InkCanvas::zoomChanged, markdownManager, &MarkdownWindowManager::updateAllWindowPositions);\n}\n virtual ~InkCanvas() {\n // Cleanup if needed\n}\n void startBenchmark() {\n benchmarking = true;\n processedTimestamps.clear();\n benchmarkTimer.start();\n}\n void stopBenchmark() {\n benchmarking = false;\n}\n int getProcessedRate() {\n qint64 now = benchmarkTimer.elapsed();\n while (!processedTimestamps.empty() && now - processedTimestamps.front() > 1000) {\n processedTimestamps.pop_front();\n }\n return static_cast(processedTimestamps.size());\n}\n void setPenColor(const QColor &color) {\n penColor = color;\n}\n void setPenThickness(qreal thickness) {\n // Set thickness for the current tool\n switch (currentTool) {\n case ToolType::Pen:\n penToolThickness = thickness;\n break;\n case ToolType::Marker:\n markerToolThickness = thickness;\n break;\n case ToolType::Eraser:\n eraserToolThickness = thickness;\n break;\n }\n \n // Update the current thickness for efficient drawing\n penThickness = thickness;\n}\n void adjustAllToolThicknesses(qreal zoomRatio) {\n // Adjust thickness for all tools to maintain visual consistency\n penToolThickness *= zoomRatio;\n markerToolThickness *= zoomRatio;\n eraserToolThickness *= zoomRatio;\n \n // Update the current thickness based on the current tool\n switch (currentTool) {\n case ToolType::Pen:\n penThickness = penToolThickness;\n break;\n case ToolType::Marker:\n penThickness = markerToolThickness;\n break;\n case ToolType::Eraser:\n penThickness = eraserToolThickness;\n break;\n }\n}\n void setTool(ToolType tool) {\n currentTool = tool;\n \n // Switch to the thickness for the new tool\n switch (currentTool) {\n case ToolType::Pen:\n penThickness = penToolThickness;\n break;\n case ToolType::Marker:\n penThickness = markerToolThickness;\n break;\n case ToolType::Eraser:\n penThickness = eraserToolThickness;\n break;\n }\n}\n void setSaveFolder(const QString &folderPath) {\n saveFolder = folderPath;\n clearPdfNoDelete(); \n\n if (!saveFolder.isEmpty()) {\n QDir().mkpath(saveFolder);\n loadNotebookId(); // ✅ Load notebook ID when save folder is set\n }\n\n QString bgMetaFile = saveFolder + \"/.background_config.txt\"; // This metadata is for background styles, not to be confused with pdf directories. \n if (QFile::exists(bgMetaFile)) {\n QFile file(bgMetaFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n while (!in.atEnd()) {\n QString line = in.readLine().trimmed();\n if (line.startsWith(\"style=\")) {\n QString val = line.mid(6);\n if (val == \"Grid\") backgroundStyle = BackgroundStyle::Grid;\n else if (val == \"Lines\") backgroundStyle = BackgroundStyle::Lines;\n else backgroundStyle = BackgroundStyle::None;\n } else if (line.startsWith(\"color=\")) {\n backgroundColor = QColor(line.mid(6));\n } else if (line.startsWith(\"density=\")) {\n backgroundDensity = line.mid(8).toInt();\n }\n }\n file.close();\n }\n }\n\n // ✅ Check if the folder has a saved PDF path\n QString metadataFile = saveFolder + \"/.pdf_path.txt\";\n if (!QFile::exists(metadataFile)) {\n return;\n }\n\n\n QFile file(metadataFile);\n if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n return;\n }\n\n QTextStream in(&file);\n QString storedPdfPath = in.readLine().trimmed();\n file.close();\n\n if (storedPdfPath.isEmpty()) {\n return;\n }\n\n\n // ✅ Ensure the stored PDF file still exists before loading\n if (!QFile::exists(storedPdfPath)) {\n return;\n }\n loadPdf(storedPdfPath);\n}\n void saveToFile(int pageNumber) {\n if (saveFolder.isEmpty()) {\n return;\n }\n QString filePath = saveFolder + QString(\"/%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n\n // ✅ If no file exists and the buffer is empty, do nothing\n \n if (!edited) {\n return;\n }\n\n QImage image(buffer.size(), QImage::Format_ARGB32);\n image.fill(Qt::transparent);\n QPainter painter(&image);\n painter.drawPixmap(0, 0, buffer);\n image.save(filePath, \"PNG\");\n edited = false;\n \n // Save markdown windows for this page\n if (markdownManager) {\n markdownManager->saveWindowsForPage(pageNumber);\n }\n \n // Update note cache with the saved buffer\n noteCache.insert(pageNumber, new QPixmap(buffer));\n}\n void saveCurrentPage() {\n MainWindow *mainWin = qobject_cast(parentWidget()); // ✅ Get main window\n if (!mainWin) return;\n \n int currentPage = mainWin->getCurrentPageForCanvas(this); // ✅ Get correct page\n saveToFile(currentPage);\n}\n void loadPage(int pageNumber) {\n if (saveFolder.isEmpty()) return;\n\n // Hide any markdown windows from the previous page BEFORE loading the new page content.\n // This ensures the correct repaint area and stops the transparency timer.\n if (markdownManager) {\n markdownManager->hideAllWindows();\n }\n\n // Update current note page tracker\n currentCachedNotePage = pageNumber;\n\n // Check if note page is already cached\n bool loadedFromCache = false;\n if (noteCache.contains(pageNumber)) {\n // Use cached note page immediately\n buffer = *noteCache.object(pageNumber);\n loadedFromCache = true;\n } else {\n // Load note page from disk and cache it\n loadNotePageToCache(pageNumber);\n \n // Use the newly cached page or initialize buffer if loading failed\n if (noteCache.contains(pageNumber)) {\n buffer = *noteCache.object(pageNumber);\n loadedFromCache = true;\n } else {\n initializeBuffer(); // Clear the canvas if no file exists\n loadedFromCache = false;\n }\n }\n \n // Reset edited state when loading a new page\n edited = false;\n \n // Handle background image loading (PDF or custom background)\n if (isPdfLoaded && pdfDocument && pageNumber >= 0 && pageNumber < pdfDocument->numPages()) {\n // Use PDF as background (should already be cached by loadPdfPage)\n if (pdfCache.contains(pageNumber)) {\n backgroundImage = *pdfCache.object(pageNumber);\n \n // Resize canvas buffer to match PDF page size if needed\n if (backgroundImage.size() != buffer.size()) {\n QPixmap newBuffer(backgroundImage.size());\n newBuffer.fill(Qt::transparent);\n\n // Copy existing drawings\n QPainter painter(&newBuffer);\n painter.drawPixmap(0, 0, buffer);\n\n buffer = newBuffer;\n // Don't constrain widget size - let it expand to fill available space\n // The paintEvent will center the PDF content within the widget\n \n // Update cache with resized buffer\n noteCache.insert(pageNumber, new QPixmap(buffer));\n }\n }\n } else {\n // Handle custom background images\n QString bgFileName = saveFolder + QString(\"/bg_%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n QString metadataFile = saveFolder + QString(\"/.%1_bgsize_%2.txt\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n\n int bgWidth = 0, bgHeight = 0;\n if (QFile::exists(metadataFile)) {\n QFile file(metadataFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n in >> bgWidth >> bgHeight;\n file.close();\n }\n }\n\n if (QFile::exists(bgFileName)) {\n QImage bgImage(bgFileName);\n backgroundImage = QPixmap::fromImage(bgImage);\n\n // Resize canvas **only if background resolution is different**\n if (bgWidth > 0 && bgHeight > 0 && (bgWidth != width() || bgHeight != height())) {\n // Create a new buffer\n QPixmap newBuffer(bgWidth, bgHeight);\n newBuffer.fill(Qt::transparent);\n\n // Copy existing drawings to the new buffer\n QPainter painter(&newBuffer);\n painter.drawPixmap(0, 0, buffer);\n\n // Assign the new buffer\n buffer = newBuffer;\n setMaximumSize(bgWidth, bgHeight);\n \n // Update cache with resized buffer\n noteCache.insert(pageNumber, new QPixmap(buffer));\n }\n } else {\n backgroundImage = QPixmap(); // No background for this page\n // Only apply device pixel ratio fix if buffer was NOT loaded from cache\n // This prevents resizing cached buffers that might already be correctly sized\n if (!loadedFromCache) {\n QScreen *screen = QGuiApplication::primaryScreen();\n qreal dpr = screen ? screen->devicePixelRatio() : 1.0;\n QSize logicalSize = screen ? screen->size() : QSize(1440, 900);\n QSize expectedPixelSize = logicalSize * dpr;\n \n if (buffer.size() != expectedPixelSize) {\n // Buffer is wrong size, need to resize it properly\n QPixmap newBuffer(expectedPixelSize);\n newBuffer.fill(Qt::transparent);\n \n // Copy existing drawings if buffer was smaller\n if (!buffer.isNull()) {\n QPainter painter(&newBuffer);\n painter.drawPixmap(0, 0, buffer);\n }\n \n buffer = newBuffer;\n setMaximumSize(expectedPixelSize);\n }\n }\n }\n }\n\n // Cache adjacent note pages after delay for faster navigation\n checkAndCacheAdjacentNotePages(pageNumber);\n\n update();\n adjustSize(); // Force the widget to update its size\n parentWidget()->update();\n \n // Load markdown windows AFTER canvas is fully rendered and sized\n // Use a single-shot timer to ensure the canvas is fully updated\n QTimer::singleShot(0, this, [this, pageNumber]() {\n if (markdownManager) {\n markdownManager->loadWindowsForPage(pageNumber);\n }\n });\n}\n void deletePage(int pageNumber) {\n if (saveFolder.isEmpty()) {\n return;\n }\n QString fileName = saveFolder + QString(\"/%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n QString bgFileName = saveFolder + QString(\"/bg_%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n QString metadataFileName = saveFolder + QString(\"/.%1_bgsize_%2.txt\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n \n #ifdef Q_OS_WIN\n // Remove hidden attribute before deleting in Windows\n SetFileAttributesW(reinterpret_cast(metadataFileName.utf16()), FILE_ATTRIBUTE_NORMAL);\n #endif\n \n QFile::remove(fileName);\n QFile::remove(bgFileName);\n QFile::remove(metadataFileName);\n\n // Remove deleted page from note cache\n noteCache.remove(pageNumber);\n\n // Delete markdown windows for this page\n if (markdownManager) {\n markdownManager->deleteWindowsForPage(pageNumber);\n }\n\n if (pdfDocument){\n loadPdfPage(pageNumber);\n }\n else{\n loadPage(pageNumber);\n }\n\n}\n void setBackground(const QString &filePath, int pageNumber) {\n if (saveFolder.isEmpty()) {\n return; // No save folder set\n }\n\n // Construct full path inside save folder\n QString bgFileName = saveFolder + QString(\"/bg_%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n\n // Copy the file to the save folder\n QFile::copy(filePath, bgFileName);\n\n // Load the background image\n QImage bgImage(bgFileName);\n\n if (!bgImage.isNull()) {\n // Save background resolution in metadata file\n QString metadataFile = saveFolder + QString(\"/.%1_bgsize_%2.txt\")\n .arg(notebookId)\n .arg(pageNumber, 5, 10, QChar('0'));\n QFile file(metadataFile);\n if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {\n QTextStream out(&file);\n out << bgImage.width() << \" \" << bgImage.height();\n file.close();\n }\n\n #ifdef Q_OS_WIN\n // Set hidden attribute for metadata on Windows\n SetFileAttributesW(reinterpret_cast(metadataFile.utf16()), FILE_ATTRIBUTE_HIDDEN);\n #endif \n\n // Only resize if the background size is different\n if (bgImage.width() != width() || bgImage.height() != height()) {\n // Create a new buffer with the new size\n QPixmap newBuffer(bgImage.width(), bgImage.height());\n newBuffer.fill(Qt::transparent);\n\n // Copy existing drawings\n QPainter painter(&newBuffer);\n painter.drawPixmap(0, 0, buffer);\n\n // Assign new buffer and update canvas size\n buffer = newBuffer;\n setMaximumSize(bgImage.width(), bgImage.height());\n }\n\n backgroundImage = QPixmap::fromImage(bgImage);\n \n update();\n adjustSize();\n parentWidget()->update();\n }\n\n update(); // Refresh canvas\n}\n void saveAnnotated(int pageNumber) {\n if (saveFolder.isEmpty()) return;\n\n QString filePath = saveFolder + QString(\"/annotated_%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n\n // Use the buffer size to ensure correct resolution\n QImage image(buffer.size(), QImage::Format_ARGB32);\n image.fill(Qt::transparent);\n QPainter painter(&image);\n \n if (!backgroundImage.isNull()) {\n painter.drawPixmap(0, 0, backgroundImage.scaled(buffer.size(), Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation));\n }\n \n painter.drawPixmap(0, 0, buffer);\n image.save(filePath, \"PNG\");\n}\n void setZoom(int zoomLevel) {\n int newZoom = qMax(10, qMin(zoomLevel, 400)); // Limit zoom to 10%-400%\n if (zoomFactor != newZoom) {\n zoomFactor = newZoom;\n internalZoomFactor = zoomFactor; // Sync internal zoom\n update();\n emit zoomChanged(zoomFactor);\n }\n}\n int getZoom() const {\n return zoomFactor;\n}\n void updatePanOffsets(int xOffset, int yOffset) {\n panOffsetX = xOffset;\n panOffsetY = yOffset;\n update();\n}\n int getPanOffsetX() const {\n return panOffsetX;\n}\n int getPanOffsetY() const {\n return panOffsetY;\n}\n void setPanX(int xOffset) {\n if (panOffsetX != value) {\n panOffsetX = value;\n update();\n emit panChanged(panOffsetX, panOffsetY);\n }\n}\n void setPanY(int yOffset) {\n if (panOffsetY != value) {\n panOffsetY = value;\n update();\n emit panChanged(panOffsetX, panOffsetY);\n }\n}\n void loadPdf(const QString &pdfPath) {\n pdfDocument = Poppler::Document::load(pdfPath);\n if (pdfDocument && !pdfDocument->isLocked()) {\n // Enable anti-aliasing rendering hints for better text quality\n pdfDocument->setRenderHint(Poppler::Document::Antialiasing, true);\n pdfDocument->setRenderHint(Poppler::Document::TextAntialiasing, true);\n pdfDocument->setRenderHint(Poppler::Document::TextHinting, true);\n pdfDocument->setRenderHint(Poppler::Document::TextSlightHinting, true);\n \n totalPdfPages = pdfDocument->numPages();\n isPdfLoaded = true;\n totalPdfPages = pdfDocument->numPages();\n loadPdfPage(0); // Load first page\n // ✅ Save the PDF path in the metadata file\n if (!saveFolder.isEmpty()) {\n QString metadataFile = saveFolder + \"/.pdf_path.txt\";\n QFile file(metadataFile);\n if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {\n QTextStream out(&file);\n out << pdfPath; // Store the absolute path of the PDF\n file.close();\n }\n }\n // Emit signal that PDF was loaded\n emit pdfLoaded();\n }\n}\n void loadPdfPage(int pageNumber) {\n if (!pdfDocument) return;\n\n // Update current page tracker\n currentCachedPage = pageNumber;\n\n // Check if target page is already cached\n if (pdfCache.contains(pageNumber)) {\n // Display the cached page immediately\n backgroundImage = *pdfCache.object(pageNumber);\n loadPage(pageNumber); // Load annotations\n loadPdfTextBoxes(pageNumber); // Load text boxes for PDF text selection\n update();\n \n // Check and cache adjacent pages after delay\n checkAndCacheAdjacentPages(pageNumber);\n return;\n }\n\n // Target page not in cache - render it immediately\n renderPdfPageToCache(pageNumber);\n \n // Display the newly rendered page\n if (pdfCache.contains(pageNumber)) {\n backgroundImage = *pdfCache.object(pageNumber);\n } else {\n backgroundImage = QPixmap(); // Clear background if rendering failed\n }\n \n loadPage(pageNumber); // Load existing canvas annotations\n loadPdfTextBoxes(pageNumber); // Load text boxes for PDF text selection\n update();\n \n // Cache adjacent pages after delay\n checkAndCacheAdjacentPages(pageNumber);\n}\n bool isPdfLoadedFunc() const {\n return isPdfLoaded;\n}\n int getTotalPdfPages() const {\n return totalPdfPages;\n}\n Poppler::Document* getPdfDocument() const;\n void clearPdf() {\n pdfDocument.reset();\n pdfDocument = nullptr;\n isPdfLoaded = false;\n totalPdfPages = 0;\n pdfCache.clear();\n \n // Reset cache system state\n currentCachedPage = -1;\n if (pdfCacheTimer && pdfCacheTimer->isActive()) {\n pdfCacheTimer->stop();\n }\n \n // Cancel and clean up any active PDF watchers\n for (QFutureWatcher* watcher : activePdfWatchers) {\n if (watcher && !watcher->isFinished()) {\n watcher->cancel();\n }\n watcher->deleteLater();\n }\n activePdfWatchers.clear();\n\n // ✅ Remove the PDF path file when clearing the PDF\n if (!saveFolder.isEmpty()) {\n QString metadataFile = saveFolder + \"/.pdf_path.txt\";\n QFile::remove(metadataFile);\n }\n}\n void clearPdfNoDelete() {\n pdfDocument.reset();\n pdfDocument = nullptr;\n isPdfLoaded = false;\n totalPdfPages = 0;\n pdfCache.clear();\n \n // Reset cache system state\n currentCachedPage = -1;\n if (pdfCacheTimer && pdfCacheTimer->isActive()) {\n pdfCacheTimer->stop();\n }\n \n // Cancel and clean up any active PDF watchers\n for (QFutureWatcher* watcher : activePdfWatchers) {\n if (watcher && !watcher->isFinished()) {\n watcher->cancel();\n }\n watcher->deleteLater();\n }\n activePdfWatchers.clear();\n}\n QString getSaveFolder() const {\n return saveFolder;\n}\n QColor getPenColor() {\n return penColor;\n}\n qreal getPenThickness() {\n return penThickness;\n}\n ToolType getCurrentTool() {\n return currentTool;\n}\n void loadPdfPreviewAsync(int pageNumber) {\n if (!pdfDocument || pageNumber < 0 || pageNumber >= pdfDocument->numPages()) return;\n\n QFutureWatcher *watcher = new QFutureWatcher(this);\n\n connect(watcher, &QFutureWatcher::finished, this, [this, watcher]() {\n QPixmap result = watcher->result();\n if (!result.isNull()) {\n backgroundImage = result;\n update(); // trigger repaint\n }\n watcher->deleteLater(); // Clean up\n });\n\n QFuture future = QtConcurrent::run([=]() -> QPixmap {\n std::unique_ptr page(pdfDocument->page(pageNumber));\n if (!page) return QPixmap();\n\n // Render with document-level anti-aliasing settings\n QImage pdfImage = page->renderToImage(96, 96);\n if (pdfImage.isNull()) return QPixmap();\n\n QImage upscaled = pdfImage.scaled(pdfImage.width() * (pdfRenderDPI / 96),\n pdfImage.height() * (pdfRenderDPI / 96),\n Qt::KeepAspectRatio,\n Qt::SmoothTransformation);\n\n return QPixmap::fromImage(upscaled);\n });\n\n watcher->setFuture(future);\n}\n void setBackgroundStyle(BackgroundStyle style) {\n backgroundStyle = style;\n update(); // Trigger repaint\n}\n void setBackgroundColor(const QColor &color) {\n backgroundColor = color;\n update();\n}\n void setBackgroundDensity(int density) {\n backgroundDensity = density;\n update();\n}\n void saveBackgroundMetadata() {\n if (saveFolder.isEmpty()) return;\n\n QString bgMetaFile = saveFolder + \"/.background_config.txt\";\n QFile file(bgMetaFile);\n if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {\n QTextStream out(&file);\n QString styleStr = \"None\";\n if (backgroundStyle == BackgroundStyle::Grid) styleStr = \"Grid\";\n else if (backgroundStyle == BackgroundStyle::Lines) styleStr = \"Lines\";\n\n out << \"style=\" << styleStr << \"\\n\";\n out << \"color=\" << backgroundColor.name().toUpper() << \"\\n\";\n out << \"density=\" << backgroundDensity << \"\\n\";\n file.close();\n }\n}\n void exportNotebook(const QString &destinationFile) {\n if (destinationFile.isEmpty()) {\n QMessageBox::warning(nullptr, tr(\"Export Error\"), tr(\"No export file specified.\"));\n return;\n }\n\n if (saveFolder.isEmpty()) {\n QMessageBox::warning(nullptr, tr(\"Export Error\"), tr(\"No notebook loaded (saveFolder is empty)\"));\n return;\n }\n\n QStringList files;\n\n // Collect all files from saveFolder\n QDir dir(saveFolder);\n QDirIterator it(saveFolder, QDir::Files, QDirIterator::Subdirectories);\n while (it.hasNext()) {\n QString filePath = it.next();\n QString relativePath = dir.relativeFilePath(filePath);\n files << relativePath;\n }\n\n if (files.isEmpty()) {\n QMessageBox::warning(nullptr, tr(\"Export Error\"), tr(\"No files found to export.\"));\n return;\n }\n\n // Generate temporary file list\n QString tempFileList = saveFolder + \"/filelist.txt\";\n QFile listFile(tempFileList);\n if (listFile.open(QIODevice::WriteOnly | QIODevice::Text)) {\n QTextStream out(&listFile);\n for (const QString &file : files) {\n out << file << \"\\n\";\n }\n listFile.close();\n } else {\n QMessageBox::warning(nullptr, tr(\"Export Error\"), tr(\"Failed to create temporary file list.\"));\n return;\n }\n\n#ifdef _WIN32\n QString tarExe = QCoreApplication::applicationDirPath() + \"/bsdtar.exe\";\n#else\n QString tarExe = \"tar\";\n#endif\n\n QStringList args;\n args << \"-cf\" << QDir::toNativeSeparators(destinationFile);\n\n for (const QString &file : files) {\n args << QDir::toNativeSeparators(file);\n }\n\n QProcess process;\n process.setWorkingDirectory(saveFolder);\n\n process.start(tarExe, args);\n if (!process.waitForFinished()) {\n QMessageBox::warning(nullptr, tr(\"Export Error\"), tr(\"Tar process failed to finish.\"));\n QFile::remove(tempFileList);\n return;\n }\n\n QFile::remove(tempFileList);\n\n if (process.exitStatus() != QProcess::NormalExit || process.exitCode() != 0) {\n QMessageBox::warning(nullptr, tr(\"Export Error\"), tr(\"Tar process failed.\"));\n return;\n }\n\n QMessageBox::information(nullptr, tr(\"Export\"), tr(\"Notebook exported successfully.\"));\n}\n void importNotebook(const QString &packageFile) {\n\n // Ask user for destination working folder\n QString destFolder = QFileDialog::getExistingDirectory(nullptr, tr(\"Select Destination Folder for Imported Notebook\"));\n\n if (destFolder.isEmpty()) {\n QMessageBox::warning(nullptr, tr(\"Import Canceled\"), tr(\"No destination folder selected.\"));\n return;\n }\n\n // Check if destination folder is empty (optional, good practice)\n QDir destDir(destFolder);\n if (!destDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot).isEmpty()) {\n QMessageBox::StandardButton reply = QMessageBox::question(nullptr, tr(\"Destination Not Empty\"),\n tr(\"The selected folder is not empty. Files may be overwritten. Continue?\"),\n QMessageBox::Yes | QMessageBox::No);\n if (reply != QMessageBox::Yes) {\n return;\n }\n }\n\n#ifdef _WIN32\n QString tarExe = QCoreApplication::applicationDirPath() + \"/bsdtar.exe\";\n#else\n QString tarExe = \"tar\";\n#endif\n\n // Extract package\n QStringList args;\n args << \"-xf\" << packageFile;\n\n QProcess process;\n process.setWorkingDirectory(destFolder);\n process.start(tarExe, args);\n process.waitForFinished();\n\n // Switch notebook folder\n setSaveFolder(destFolder);\n loadPage(0);\n\n QMessageBox::information(nullptr, tr(\"Import Complete\"), tr(\"Notebook imported successfully.\"));\n}\n void importNotebookTo(const QString &packageFile, const QString &destFolder) {\n\n #ifdef _WIN32\n QString tarExe = QCoreApplication::applicationDirPath() + \"/bsdtar.exe\";\n #else\n QString tarExe = \"tar\";\n #endif\n \n QStringList args;\n args << \"-xf\" << packageFile;\n \n QProcess process;\n process.setWorkingDirectory(destFolder);\n process.start(tarExe, args);\n process.waitForFinished();\n \n setSaveFolder(destFolder);\n loadNotebookId();\n loadPage(0);\n\n QMessageBox::information(nullptr, tr(\"Import\"), tr(\"Notebook imported successfully.\"));\n }\n void deleteRopeSelection() {\n if (!selectionBuffer.isNull() && !selectionRect.isEmpty()) {\n // If the selection area hasn't been cleared from the buffer yet, clear it now for deletion\n if (!selectionAreaCleared && !selectionMaskPath.isEmpty()) {\n QPainter painter(&buffer);\n painter.setCompositionMode(QPainter::CompositionMode_Clear);\n painter.fillPath(selectionMaskPath, Qt::transparent);\n painter.end();\n }\n \n // Clear the selection state\n selectionBuffer = QPixmap();\n selectionRect = QRect();\n exactSelectionRectF = QRectF();\n movingSelection = false;\n selectingWithRope = false;\n selectionJustCopied = false;\n selectionAreaCleared = false;\n selectionMaskPath = QPainterPath();\n selectionBufferRect = QRectF();\n \n // Mark as edited since we deleted content\n if (!edited) {\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n \n // Update the entire canvas to remove selection visuals\n update();\n }\n}\n void cancelRopeSelection() {\n if (!selectionBuffer.isNull() && !selectionRect.isEmpty()) {\n // Paste the selection back to its current location (where user moved it)\n QPainter painter(&buffer);\n // Explicitly set composition mode to draw on top of existing content\n painter.setCompositionMode(QPainter::CompositionMode_SourceOver);\n // Use the current selection position\n QPointF currentTopLeft = exactSelectionRectF.isEmpty() ? selectionRect.topLeft() : exactSelectionRectF.topLeft();\n QPointF bufferDest = mapLogicalWidgetToPhysicalBuffer(currentTopLeft);\n painter.drawPixmap(bufferDest.toPoint(), selectionBuffer);\n painter.end();\n \n // Store selection buffer size for update calculation before clearing it\n QSize selectionSize = selectionBuffer.size();\n QRect updateRect = QRect(currentTopLeft.toPoint(), selectionSize);\n \n // Clear the selection state\n selectionBuffer = QPixmap();\n selectionRect = QRect();\n exactSelectionRectF = QRectF();\n movingSelection = false;\n selectingWithRope = false;\n selectionJustCopied = false;\n selectionAreaCleared = false;\n selectionMaskPath = QPainterPath();\n selectionBufferRect = QRectF();\n \n // Update the restored area\n update(updateRect.adjusted(-5, -5, 5, 5));\n }\n}\n void copyRopeSelection() {\n if (!selectionBuffer.isNull() && !selectionRect.isEmpty()) {\n // Get current selection position\n QPointF currentTopLeft = exactSelectionRectF.isEmpty() ? selectionRect.topLeft() : exactSelectionRectF.topLeft();\n \n // Calculate new position (right next to the original), but ensure it stays within canvas bounds\n QPointF newTopLeft = currentTopLeft + QPointF(selectionRect.width() + 5, 0); // 5 pixels gap\n \n // Check if the new position would extend beyond buffer boundaries and adjust if needed\n QPointF currentBufferDest = mapLogicalWidgetToPhysicalBuffer(currentTopLeft);\n QPointF newBufferDest = mapLogicalWidgetToPhysicalBuffer(newTopLeft);\n \n // Ensure the copy stays within buffer bounds\n if (newBufferDest.x() + selectionBuffer.width() > buffer.width()) {\n // If it would extend beyond right edge, place it to the left of the original\n newTopLeft = currentTopLeft - QPointF(selectionRect.width() + 5, 0);\n newBufferDest = mapLogicalWidgetToPhysicalBuffer(newTopLeft);\n \n // If it still doesn't fit on the left, place it below the original\n if (newBufferDest.x() < 0) {\n newTopLeft = currentTopLeft + QPointF(0, selectionRect.height() + 5);\n newBufferDest = mapLogicalWidgetToPhysicalBuffer(newTopLeft);\n \n // If it doesn't fit below either, place it above\n if (newBufferDest.y() + selectionBuffer.height() > buffer.height()) {\n newTopLeft = currentTopLeft - QPointF(0, selectionRect.height() + 5);\n newBufferDest = mapLogicalWidgetToPhysicalBuffer(newTopLeft);\n \n // If none of the positions work, just offset slightly and let it extend\n if (newBufferDest.y() < 0) {\n newTopLeft = currentTopLeft + QPointF(10, 10);\n newBufferDest = mapLogicalWidgetToPhysicalBuffer(newTopLeft);\n }\n }\n }\n }\n if (newBufferDest.y() + selectionBuffer.height() > buffer.height()) {\n // If it would extend beyond bottom edge, place it above the original\n newTopLeft = currentTopLeft - QPointF(0, selectionRect.height() + 5);\n newBufferDest = mapLogicalWidgetToPhysicalBuffer(newTopLeft);\n }\n \n // First, paste the selection back to its current location to restore the original\n QPainter painter(&buffer);\n // Explicitly set composition mode to draw on top of existing content\n painter.setCompositionMode(QPainter::CompositionMode_SourceOver);\n painter.drawPixmap(currentBufferDest.toPoint(), selectionBuffer);\n \n // Then, paste the copy to the new location\n // We need to handle the case where the copy extends beyond buffer boundaries\n QRect targetRect(newBufferDest.toPoint(), selectionBuffer.size());\n QRect bufferBounds(0, 0, buffer.width(), buffer.height());\n QRect clippedRect = targetRect.intersected(bufferBounds);\n \n if (!clippedRect.isEmpty()) {\n // Calculate which part of the selectionBuffer to draw\n QRect sourceRect = QRect(\n clippedRect.x() - targetRect.x(),\n clippedRect.y() - targetRect.y(),\n clippedRect.width(),\n clippedRect.height()\n );\n \n painter.drawPixmap(clippedRect, selectionBuffer, sourceRect);\n }\n \n // For the selection buffer, we keep the FULL content, even if parts extend beyond canvas\n // This way when the user drags it back, the full content is preserved\n QPixmap newSelectionBuffer = selectionBuffer; // Keep the full original content\n \n // DON'T clear the copied area immediately - leave both original and copy on the canvas\n // The copy will only be cleared when the user actually starts moving the selection\n // This way, if the user cancels without moving, both original and copy remain permanently\n painter.end();\n \n // Update the selection buffer and position\n selectionBuffer = newSelectionBuffer;\n selectionRect = QRect(newTopLeft.toPoint(), selectionRect.size());\n exactSelectionRectF = QRectF(newTopLeft, selectionRect.size());\n selectionJustCopied = true; // Mark that this selection was just copied\n \n // Mark as edited since we added content\n if (!edited) {\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n \n // Update the entire affected area (original + copy + gap)\n QRect updateArea = QRect(currentTopLeft.toPoint(), selectionRect.size())\n .united(selectionRect)\n .adjusted(-10, -10, 10, 10);\n update(updateArea);\n }\n}\n void setMarkdownSelectionMode(bool enabled) {\n markdownSelectionMode = enabled;\n \n if (markdownManager) {\n markdownManager->setSelectionMode(enabled);\n }\n \n if (!enabled) {\n markdownSelecting = false;\n }\n \n // Update cursor\n setCursor(enabled ? Qt::CrossCursor : Qt::ArrowCursor);\n \n // Notify signal\n emit markdownSelectionModeChanged(enabled);\n}\n bool isMarkdownSelectionMode() const {\n return markdownSelectionMode;\n}\n void clearPdfTextSelection() {\n // Clear selection state\n selectedTextBoxes.clear();\n pdfTextSelecting = false;\n \n // Cancel any pending throttled updates\n if (pdfTextSelectionTimer && pdfTextSelectionTimer->isActive()) {\n pdfTextSelectionTimer->stop();\n }\n hasPendingSelection = false;\n \n // Refresh display\n update();\n}\n QString getSelectedPdfText() const {\n if (selectedTextBoxes.isEmpty()) {\n return QString();\n }\n \n // Pre-allocate string with estimated size for efficiency\n QString selectedText;\n selectedText.reserve(selectedTextBoxes.size() * 20); // Estimate ~20 chars per text box\n \n // Build text with space separators\n for (const Poppler::TextBox* textBox : selectedTextBoxes) {\n if (textBox && !textBox->text().isEmpty()) {\n if (!selectedText.isEmpty()) {\n selectedText += \" \";\n }\n selectedText += textBox->text();\n }\n }\n \n return selectedText;\n}\n QPointF mapWidgetToCanvas(const QPointF &widgetPoint) const {\n QPointF topLeft = mapWidgetToCanvas(widgetRect.topLeft());\n QPointF bottomRight = mapWidgetToCanvas(widgetRect.bottomRight());\n \n return QRect(topLeft.toPoint(), bottomRight.toPoint());\n}\n QPointF mapCanvasToWidget(const QPointF &canvasPoint) const {\n QPointF topLeft = mapCanvasToWidget(canvasRect.topLeft());\n QPointF bottomRight = mapCanvasToWidget(canvasRect.bottomRight());\n \n return QRect(topLeft.toPoint(), bottomRight.toPoint());\n}\n QRect mapWidgetToCanvas(const QRect &widgetRect) const {\n QPointF topLeft = mapWidgetToCanvas(widgetRect.topLeft());\n QPointF bottomRight = mapWidgetToCanvas(widgetRect.bottomRight());\n \n return QRect(topLeft.toPoint(), bottomRight.toPoint());\n}\n QRect mapCanvasToWidget(const QRect &canvasRect) const {\n QPointF topLeft = mapCanvasToWidget(canvasRect.topLeft());\n QPointF bottomRight = mapCanvasToWidget(canvasRect.bottomRight());\n \n return QRect(topLeft.toPoint(), bottomRight.toPoint());\n}\n protected:\n void paintEvent(QPaintEvent *event) override {\n QPainter painter(this);\n \n // Save the painter state before transformations\n painter.save();\n \n // Calculate the scaled canvas size\n qreal scaledCanvasWidth = buffer.width() * (internalZoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (internalZoomFactor / 100.0);\n \n // Calculate centering offsets\n qreal centerOffsetX = 0;\n qreal centerOffsetY = 0;\n \n // Center horizontally if canvas is smaller than widget\n if (scaledCanvasWidth < width()) {\n centerOffsetX = (width() - scaledCanvasWidth) / 2.0;\n }\n \n // Center vertically if canvas is smaller than widget\n if (scaledCanvasHeight < height()) {\n centerOffsetY = (height() - scaledCanvasHeight) / 2.0;\n }\n \n // Apply centering offset first\n painter.translate(centerOffsetX, centerOffsetY);\n \n // Use internal zoom factor for smoother animation\n painter.scale(internalZoomFactor / 100.0, internalZoomFactor / 100.0);\n\n // Pan offset needs to be reversed because painter works in transformed coordinates\n painter.translate(-panOffsetX, -panOffsetY);\n\n // Set clipping rectangle to canvas bounds to prevent painting outside\n painter.setClipRect(0, 0, buffer.width(), buffer.height());\n\n // 🟨 Notebook-style background rendering\n if (backgroundImage.isNull()) {\n painter.save();\n \n // Always apply background color regardless of style\n painter.fillRect(QRectF(0, 0, buffer.width(), buffer.height()), backgroundColor);\n\n // Only draw grid/lines if not \"None\" style\n if (backgroundStyle != BackgroundStyle::None) {\n QPen linePen(QColor(100, 100, 100, 100)); // Subtle gray lines\n linePen.setWidthF(1.0);\n painter.setPen(linePen);\n\n qreal scaledDensity = backgroundDensity;\n\n if (devicePixelRatioF() > 1.0)\n scaledDensity *= devicePixelRatioF(); // Optional DPI handling\n\n if (backgroundStyle == BackgroundStyle::Lines || backgroundStyle == BackgroundStyle::Grid) {\n for (int y = 0; y < buffer.height(); y += scaledDensity)\n painter.drawLine(0, y, buffer.width(), y);\n }\n if (backgroundStyle == BackgroundStyle::Grid) {\n for (int x = 0; x < buffer.width(); x += scaledDensity)\n painter.drawLine(x, 0, x, buffer.height());\n }\n }\n\n painter.restore();\n }\n\n // ✅ Draw loaded image or PDF background if available\n if (!backgroundImage.isNull()) {\n painter.drawPixmap(0, 0, backgroundImage);\n }\n\n // ✅ Draw user's strokes from the buffer (transparent overlay)\n painter.drawPixmap(0, 0, buffer);\n \n // Draw straight line preview if in straight line mode and drawing\n // Skip preview for eraser tool\n if (straightLineMode && drawing && currentTool != ToolType::Eraser) {\n // Save the current state before applying the eraser mode\n painter.save();\n \n // Store current pressure - ensure minimum is 0.5 for consistent preview\n qreal pressure = qMax(0.5, painter.device()->devicePixelRatioF() > 1.0 ? 0.8 : 1.0);\n \n // Set up the pen based on tool type\n if (currentTool == ToolType::Marker) {\n qreal thickness = penThickness * 8.0;\n QColor markerColor = penColor;\n // Increase alpha for better visibility in straight line mode\n // Using a higher value (80) instead of the regular 4 to compensate for single-pass drawing\n markerColor.setAlpha(80);\n QPen pen(markerColor, thickness, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);\n painter.setPen(pen);\n } else { // Default Pen\n // Match the exact same thickness calculation as in drawStroke\n qreal scaledThickness = penThickness * pressure;\n QPen pen(penColor, scaledThickness, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);\n painter.setPen(pen);\n }\n \n // Use the same coordinate transformation logic as in drawStroke\n // to ensure the preview line appears at the exact same position\n QPointF bufferStart, bufferEnd;\n \n // Convert screen coordinates to buffer coordinates using the same calculations as drawStroke\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n QPointF adjustedStart = straightLineStartPoint - QPointF(centerOffsetX, centerOffsetY);\n QPointF adjustedEnd = lastPoint - QPointF(centerOffsetX, centerOffsetY);\n \n bufferStart = (adjustedStart / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n bufferEnd = (adjustedEnd / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n \n // Draw the preview line using the same coordinates that will be used for the final line\n painter.drawLine(bufferStart, bufferEnd);\n \n // Restore the original painter state\n painter.restore();\n }\n\n // Draw selection rectangle if in rope tool mode and selecting, moving, or has a selection\n if (ropeToolMode && (selectingWithRope || movingSelection || (!selectionBuffer.isNull() && !selectionRect.isEmpty()))) {\n painter.save(); // Save painter state for overlays\n painter.resetTransform(); // Reset transform to draw directly in logical widget coordinates\n \n if (selectingWithRope && !lassoPathPoints.isEmpty()) {\n QPen selectionPen(Qt::DashLine);\n selectionPen.setColor(Qt::blue);\n selectionPen.setWidthF(1.5); // Width in logical pixels\n painter.setPen(selectionPen);\n painter.drawPolygon(lassoPathPoints); // lassoPathPoints are logical widget coordinates\n } else if (!selectionBuffer.isNull() && !selectionRect.isEmpty()) {\n // selectionRect is in logical widget coordinates.\n // selectionBuffer is in buffer coordinates, we need to handle scaling correctly\n QPixmap scaledBuffer = selectionBuffer;\n \n // Calculate the current zoom factor\n qreal currentZoom = internalZoomFactor / 100.0;\n \n // Scale the selection buffer to match the current zoom level\n if (currentZoom != 1.0) {\n QSize scaledSize = QSize(\n qRound(scaledBuffer.width() * currentZoom),\n qRound(scaledBuffer.height() * currentZoom)\n );\n scaledBuffer = scaledBuffer.scaled(scaledSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);\n }\n \n // Draw it at the logical position\n // Use exactSelectionRectF for smoother movement if available\n QPointF topLeft = exactSelectionRectF.isEmpty() ? selectionRect.topLeft() : exactSelectionRectF.topLeft();\n painter.drawPixmap(topLeft, scaledBuffer);\n\n QPen selectionBorderPen(Qt::DashLine);\n selectionBorderPen.setColor(Qt::darkCyan);\n selectionBorderPen.setWidthF(1.5); // Width in logical pixels\n painter.setPen(selectionBorderPen);\n \n // Use exactSelectionRectF for drawing the selection border if available\n if (!exactSelectionRectF.isEmpty()) {\n painter.drawRect(exactSelectionRectF);\n } else {\n painter.drawRect(selectionRect);\n }\n }\n painter.restore(); // Restore painter state to what it was for drawing the main buffer\n }\n \n\n \n\n \n // Restore the painter state\n painter.restore();\n \n // Fill the area outside the canvas with the widget's background color\n QRect widgetRect = rect();\n QRectF canvasRect(\n centerOffsetX - panOffsetX * (internalZoomFactor / 100.0),\n centerOffsetY - panOffsetY * (internalZoomFactor / 100.0),\n buffer.width() * (internalZoomFactor / 100.0),\n buffer.height() * (internalZoomFactor / 100.0)\n );\n \n // Create regions for areas outside the canvas\n QRegion outsideRegion(widgetRect);\n outsideRegion -= QRegion(canvasRect.toRect());\n \n // Fill the outside region with the background color\n painter.setClipRegion(outsideRegion);\n painter.fillRect(widgetRect, palette().window().color());\n \n // Reset clipping for overlay elements that should appear on top\n painter.setClipping(false);\n \n // Draw markdown selection overlay\n if (markdownSelectionMode && markdownSelecting) {\n painter.save();\n QPen selectionPen(Qt::DashLine);\n selectionPen.setColor(Qt::green);\n selectionPen.setWidthF(2.0);\n painter.setPen(selectionPen);\n \n QBrush selectionBrush(QColor(0, 255, 0, 30)); // Semi-transparent green\n painter.setBrush(selectionBrush);\n \n QRect selectionRect = QRect(markdownSelectionStart, markdownSelectionEnd).normalized();\n painter.drawRect(selectionRect);\n painter.restore();\n }\n \n // Draw PDF text selection overlay on top of everything\n if (pdfTextSelectionEnabled && isPdfLoaded) {\n painter.save(); // Save painter state for PDF text overlay\n painter.resetTransform(); // Reset transform to draw directly in logical widget coordinates\n \n // Draw selection rectangle if actively selecting\n if (pdfTextSelecting) {\n QPen selectionPen(Qt::DashLine);\n selectionPen.setColor(QColor(0, 120, 215)); // Blue selection rectangle\n selectionPen.setWidthF(2.0); // Make it more visible\n painter.setPen(selectionPen);\n \n QBrush selectionBrush(QColor(0, 120, 215, 30)); // Semi-transparent blue fill\n painter.setBrush(selectionBrush);\n \n QRectF selectionRect(pdfSelectionStart, pdfSelectionEnd);\n selectionRect = selectionRect.normalized();\n painter.drawRect(selectionRect);\n }\n \n // Draw highlights for selected text boxes\n if (!selectedTextBoxes.isEmpty()) {\n QColor highlightColor = QColor(255, 255, 0, 100); // Semi-transparent yellow\n painter.setBrush(highlightColor);\n painter.setPen(Qt::NoPen);\n \n // Draw highlight rectangles for selected text boxes\n for (const Poppler::TextBox* textBox : selectedTextBoxes) {\n if (textBox) {\n // Convert PDF coordinates to widget coordinates\n QRectF pdfRect = textBox->boundingBox();\n QPointF topLeft = mapPdfToWidgetCoordinates(pdfRect.topLeft());\n QPointF bottomRight = mapPdfToWidgetCoordinates(pdfRect.bottomRight());\n QRectF widgetRect(topLeft, bottomRight);\n widgetRect = widgetRect.normalized();\n \n painter.drawRect(widgetRect);\n }\n }\n }\n \n painter.restore(); // Restore painter state\n }\n}\n void tabletEvent(QTabletEvent *event) override {\n // ✅ PRIORITY: Handle PDF text selection with stylus when enabled\n // This redirects stylus input to text selection instead of drawing\n if (pdfTextSelectionEnabled && isPdfLoaded) {\n if (event->type() == QEvent::TabletPress) {\n pdfTextSelecting = true;\n pdfSelectionStart = event->position();\n pdfSelectionEnd = pdfSelectionStart;\n \n // Clear any existing selected text boxes without resetting pdfTextSelecting\n selectedTextBoxes.clear();\n \n setCursor(Qt::IBeamCursor); // Ensure cursor is correct\n update(); // Refresh display\n event->accept();\n return;\n } else if (event->type() == QEvent::TabletMove && pdfTextSelecting) {\n pdfSelectionEnd = event->position();\n \n // Store pending selection for throttled processing (60 FPS throttling)\n pendingSelectionStart = pdfSelectionStart;\n pendingSelectionEnd = pdfSelectionEnd;\n hasPendingSelection = true;\n \n // Start timer if not already running (throttled to 60 FPS)\n if (!pdfTextSelectionTimer->isActive()) {\n pdfTextSelectionTimer->start();\n }\n \n // NOTE: No direct update() call here - let the timer handle updates at 60 FPS\n event->accept();\n return;\n } else if (event->type() == QEvent::TabletRelease && pdfTextSelecting) {\n pdfSelectionEnd = event->position();\n \n // Process any pending selection immediately on release\n if (pdfTextSelectionTimer && pdfTextSelectionTimer->isActive()) {\n pdfTextSelectionTimer->stop();\n if (hasPendingSelection) {\n updatePdfTextSelection(pendingSelectionStart, pendingSelectionEnd);\n hasPendingSelection = false;\n }\n } else {\n // Update selection with final position\n updatePdfTextSelection(pdfSelectionStart, pdfSelectionEnd);\n }\n \n pdfTextSelecting = false;\n \n // Check for link clicks if no text was selected\n QString selectedText = getSelectedPdfText();\n if (selectedText.isEmpty()) {\n handlePdfLinkClick(event->position());\n } else {\n // Show context menu for text selection\n QPoint globalPos = mapToGlobal(event->position().toPoint());\n showPdfTextSelectionMenu(globalPos);\n }\n \n event->accept();\n return;\n }\n }\n \n // ✅ NORMAL STYLUS BEHAVIOR: Only reached when PDF text selection is OFF\n // Hardware eraser detection\n static bool hardwareEraserActive = false;\n bool wasUsingHardwareEraser = false;\n \n // Track hardware eraser state\n if (event->pointerType() == QPointingDevice::PointerType::Eraser) {\n // Hardware eraser is being used\n wasUsingHardwareEraser = true;\n \n if (event->type() == QEvent::TabletPress) {\n // Start of eraser stroke - save current tool and switch to eraser\n hardwareEraserActive = true;\n previousTool = currentTool;\n currentTool = ToolType::Eraser;\n }\n }\n \n // Maintain hardware eraser state across move events\n if (hardwareEraserActive && event->type() != QEvent::TabletRelease) {\n wasUsingHardwareEraser = true;\n }\n\n // Determine if we're in eraser mode (either hardware eraser or tool set to eraser)\n bool isErasing = (currentTool == ToolType::Eraser);\n\n if (event->type() == QEvent::TabletPress) {\n drawing = true;\n lastPoint = event->posF(); // Logical widget coordinates\n if (straightLineMode) {\n straightLineStartPoint = lastPoint;\n }\n if (ropeToolMode) {\n if (!selectionBuffer.isNull() && selectionRect.contains(lastPoint.toPoint())) {\n // Start moving an existing selection (or continue if already moving)\n movingSelection = true;\n selectingWithRope = false;\n lastMovePoint = lastPoint;\n // Initialize the exact floating-point rect if it's empty\n if (exactSelectionRectF.isEmpty()) {\n exactSelectionRectF = QRectF(selectionRect);\n }\n \n // If this selection was just copied, clear the area now that user is moving it\n if (selectionJustCopied) {\n QPainter painter(&buffer);\n painter.setCompositionMode(QPainter::CompositionMode_Clear);\n QPointF bufferDest = mapLogicalWidgetToPhysicalBuffer(selectionRect.topLeft());\n QRect clearRect(bufferDest.toPoint(), selectionBuffer.size());\n // Only clear the part that's within buffer bounds\n QRect bufferBounds(0, 0, buffer.width(), buffer.height());\n QRect clippedClearRect = clearRect.intersected(bufferBounds);\n if (!clippedClearRect.isEmpty()) {\n painter.fillRect(clippedClearRect, Qt::transparent);\n }\n painter.end();\n selectionJustCopied = false; // Clear the flag\n }\n \n // If the selection area hasn't been cleared from the buffer yet, clear it now\n if (!selectionAreaCleared && !selectionMaskPath.isEmpty()) {\n QPainter painter(&buffer);\n painter.setCompositionMode(QPainter::CompositionMode_Clear);\n painter.fillPath(selectionMaskPath, Qt::transparent);\n painter.end();\n selectionAreaCleared = true;\n }\n // selectionBuffer already has the content.\n // The original area in 'buffer' was already cleared when selection was made.\n } else {\n // Start a new selection or cancel existing one\n if (!selectionBuffer.isNull()) { // If there's an active selection, a tap outside cancels it\n selectionBuffer = QPixmap();\n selectionRect = QRect();\n lassoPathPoints.clear();\n movingSelection = false;\n selectingWithRope = false;\n selectionJustCopied = false;\n selectionAreaCleared = false;\n selectionMaskPath = QPainterPath();\n selectionBufferRect = QRectF();\n update(); // Full update to remove old selection visuals\n drawing = false; // Consumed this press for cancel\n return;\n }\n selectingWithRope = true;\n movingSelection = false;\n selectionJustCopied = false;\n selectionAreaCleared = false;\n selectionMaskPath = QPainterPath();\n selectionBufferRect = QRectF();\n lassoPathPoints.clear();\n lassoPathPoints << lastPoint; // Start the lasso path\n selectionRect = QRect();\n selectionBuffer = QPixmap();\n }\n }\n } else if (event->type() == QEvent::TabletMove && drawing) {\n if (ropeToolMode) {\n if (selectingWithRope) {\n QRectF oldPreviewBoundingRect = lassoPathPoints.boundingRect();\n lassoPathPoints << event->posF();\n lastPoint = event->posF();\n QRectF newPreviewBoundingRect = lassoPathPoints.boundingRect();\n // Update the area of the selection rectangle preview (logical widget coordinates)\n update(oldPreviewBoundingRect.united(newPreviewBoundingRect).toRect().adjusted(-5,-5,5,5));\n } else if (movingSelection) {\n QPointF delta = event->posF() - lastMovePoint; // Delta in logical widget coordinates\n QRect oldWidgetSelectionRect = selectionRect;\n \n // Update the exact floating-point rectangle first\n exactSelectionRectF.translate(delta);\n \n // Convert back to integer rect, but only when the position actually changes\n QRect newRect = exactSelectionRectF.toRect();\n if (newRect != selectionRect) {\n selectionRect = newRect;\n // Update the combined area of the old and new selection positions (logical widget coordinates)\n update(oldWidgetSelectionRect.united(selectionRect).adjusted(-2,-2,2,2));\n } else {\n // Even if the integer position didn't change, we still need to update\n // to make movement feel smoother, especially with slow movements\n update(selectionRect.adjusted(-2,-2,2,2));\n }\n \n lastMovePoint = event->posF();\n if (!edited){\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n }\n } else if (straightLineMode && !isErasing) {\n // For straight line mode with non-eraser tools, just update the last position\n // and trigger a repaint of only the affected area for preview\n static QElapsedTimer updateTimer;\n static bool timerInitialized = false;\n \n if (!timerInitialized) {\n updateTimer.start();\n timerInitialized = true;\n }\n \n // Throttle updates based on time for high CPU usage tools\n bool shouldUpdate = true;\n \n // Apply throttling for marker which can be CPU intensive\n if (currentTool == ToolType::Marker) {\n shouldUpdate = updateTimer.elapsed() > 16; // Only update every 16ms (approx 60fps)\n }\n \n if (shouldUpdate) {\n QPointF oldLastPoint = lastPoint;\n lastPoint = event->posF();\n \n // Calculate affected rectangle that needs updating\n QRectF updateRect = calculatePreviewRect(straightLineStartPoint, oldLastPoint, lastPoint);\n update(updateRect.toRect());\n \n // Reset timer\n updateTimer.restart();\n } else {\n // Just update the last point without redrawing\n lastPoint = event->posF();\n }\n } else if (straightLineMode && isErasing) {\n // For eraser in straight line mode, continuously erase from start to current point\n // This gives immediate visual feedback and smoother erasing experience\n \n // Store current point\n QPointF currentPoint = event->posF();\n \n // Clear previous stroke by redrawing with transparency\n QRectF updateRect = QRectF(straightLineStartPoint, lastPoint).normalized().adjusted(-20, -20, 20, 20);\n update(updateRect.toRect());\n \n // Erase from start point to current position\n eraseStroke(straightLineStartPoint, currentPoint, event->pressure());\n \n // Update last point\n lastPoint = currentPoint;\n \n // Only track benchmarking when enabled\n if (benchmarking) {\n processedTimestamps.push_back(benchmarkTimer.elapsed());\n }\n } else {\n // Normal drawing mode OR eraser regardless of straight line mode\n if (isErasing) {\n eraseStroke(lastPoint, event->posF(), event->pressure());\n } else {\n drawStroke(lastPoint, event->posF(), event->pressure());\n }\n lastPoint = event->posF();\n \n // Only track benchmarking when enabled\n if (benchmarking) {\n processedTimestamps.push_back(benchmarkTimer.elapsed());\n }\n }\n } else if (event->type() == QEvent::TabletRelease) {\n if (straightLineMode && !isErasing) {\n // Draw the final line on release with the current pressure\n qreal pressure = event->pressure();\n \n // Always use at least a minimum pressure\n pressure = qMax(pressure, 0.5);\n \n drawStroke(straightLineStartPoint, event->posF(), pressure);\n \n // Only track benchmarking when enabled\n if (benchmarking) {\n processedTimestamps.push_back(benchmarkTimer.elapsed());\n }\n \n // Force repaint to clear the preview line\n update();\n if (!edited){\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n } else if (straightLineMode && isErasing) {\n // For erasing in straight line mode, most of the work is done during movement\n // Just ensure one final erasing pass from start to end point\n qreal pressure = qMax(event->pressure(), 0.5);\n \n // Final pass to ensure the entire line is erased\n eraseStroke(straightLineStartPoint, event->posF(), pressure);\n \n // Force update to clear any remaining artifacts\n update();\n if (!edited){\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n }\n \n drawing = false;\n \n // Reset tool state if we were using the hardware eraser\n if (wasUsingHardwareEraser) {\n currentTool = previousTool;\n hardwareEraserActive = false; // Reset hardware eraser tracking\n }\n\n if (ropeToolMode) {\n if (selectingWithRope) {\n if (lassoPathPoints.size() > 2) { // Need at least 3 points for a polygon\n lassoPathPoints << lassoPathPoints.first(); // Close the polygon\n \n if (!lassoPathPoints.boundingRect().isEmpty()) {\n // 1. Create a QPolygonF in buffer coordinates using proper transformation\n QPolygonF bufferLassoPath;\n for (const QPointF& p_widget_logical : qAsConst(lassoPathPoints)) {\n bufferLassoPath << mapLogicalWidgetToPhysicalBuffer(p_widget_logical);\n }\n\n // 2. Get the bounding box of this path on the buffer\n QRectF bufferPathBoundingRect = bufferLassoPath.boundingRect();\n\n // 3. Copy that part of the main buffer\n QPixmap originalPiece = buffer.copy(bufferPathBoundingRect.toRect());\n\n // 4. Create the selectionBuffer (same size as originalPiece) and fill transparent\n selectionBuffer = QPixmap(originalPiece.size());\n selectionBuffer.fill(Qt::transparent);\n \n // 5. Create a mask from the lasso path\n QPainterPath maskPath;\n // The lasso path for the mask needs to be relative to originalPiece.topLeft()\n maskPath.addPolygon(bufferLassoPath.translated(-bufferPathBoundingRect.topLeft()));\n \n // 6. Paint the originalPiece onto selectionBuffer, using the mask\n QPainter selectionPainter(&selectionBuffer);\n selectionPainter.setClipPath(maskPath);\n selectionPainter.drawPixmap(0,0, originalPiece);\n selectionPainter.end();\n\n // 7. DON'T clear the selected area from the main buffer yet\n // The area will only be cleared when the user actually starts moving the selection\n // This way, if the user cancels without moving, the original content remains\n selectionAreaCleared = false;\n \n // Store the mask path and buffer rect for later clearing when movement starts\n selectionMaskPath = maskPath.translated(bufferPathBoundingRect.topLeft());\n selectionBufferRect = bufferPathBoundingRect;\n \n // 8. Calculate the correct selectionRect in logical widget coordinates\n QRectF logicalSelectionRect = mapRectBufferToWidgetLogical(bufferPathBoundingRect);\n selectionRect = logicalSelectionRect.toRect();\n exactSelectionRectF = logicalSelectionRect;\n \n // Update the area of the selection on screen\n update(logicalSelectionRect.adjusted(-2,-2,2,2).toRect());\n \n // Emit signal for context menu at the center of the selection with a delay\n // This allows the user to immediately start moving the selection if desired\n QPoint menuPosition = selectionRect.center();\n QTimer::singleShot(500, this, [this, menuPosition]() {\n // Only show menu if selection still exists and hasn't been moved\n if (!selectionBuffer.isNull() && !selectionRect.isEmpty() && !movingSelection) {\n emit ropeSelectionCompleted(menuPosition);\n }\n });\n }\n }\n lassoPathPoints.clear(); // Ready for next selection, or move\n selectingWithRope = false;\n // Now, if the user presses inside selectionRect, movingSelection will become true.\n } else if (movingSelection) {\n if (!selectionBuffer.isNull() && !selectionRect.isEmpty()) {\n QPainter painter(&buffer);\n // Explicitly set composition mode to draw on top of existing content\n painter.setCompositionMode(QPainter::CompositionMode_SourceOver);\n // Use exact floating-point position if available for more precise placement\n QPointF topLeft = exactSelectionRectF.isEmpty() ? selectionRect.topLeft() : exactSelectionRectF.topLeft();\n // Use proper coordinate transformation to get buffer coordinates\n QPointF bufferDest = mapLogicalWidgetToPhysicalBuffer(topLeft);\n painter.drawPixmap(bufferDest.toPoint(), selectionBuffer);\n painter.end();\n \n // Update the pasted area\n QRectF bufferPasteRect(bufferDest, selectionBuffer.size());\n update(mapRectBufferToWidgetLogical(bufferPasteRect).adjusted(-2,-2,2,2));\n \n // Clear selection after pasting, making it permanent\n selectionBuffer = QPixmap();\n selectionRect = QRect();\n exactSelectionRectF = QRectF();\n movingSelection = false;\n selectionJustCopied = false;\n selectionAreaCleared = false;\n selectionMaskPath = QPainterPath();\n selectionBufferRect = QRectF();\n }\n }\n }\n \n\n }\n event->accept();\n}\n void mousePressEvent(QMouseEvent *event) override {\n // Handle markdown selection when enabled\n if (markdownSelectionMode && event->button() == Qt::LeftButton) {\n markdownSelecting = true;\n markdownSelectionStart = event->pos();\n markdownSelectionEnd = markdownSelectionStart;\n event->accept();\n return;\n }\n \n // Handle PDF text selection when enabled (mouse/touch fallback - stylus handled in tabletEvent)\n if (pdfTextSelectionEnabled && isPdfLoaded) {\n if (event->button() == Qt::LeftButton) {\n pdfTextSelecting = true;\n pdfSelectionStart = event->position();\n pdfSelectionEnd = pdfSelectionStart;\n \n // Clear any existing selected text boxes without resetting pdfTextSelecting\n selectedTextBoxes.clear();\n \n setCursor(Qt::IBeamCursor); // Ensure cursor is correct\n update(); // Refresh display\n event->accept();\n return;\n }\n }\n \n // Ignore mouse/touch input on canvas for drawing (drawing only works with tablet/stylus)\n event->ignore();\n}\n void mouseMoveEvent(QMouseEvent *event) override {\n // Handle markdown selection when enabled\n if (markdownSelectionMode && markdownSelecting) {\n markdownSelectionEnd = event->pos();\n update(); // Refresh to show selection rectangle\n event->accept();\n return;\n }\n \n // Handle PDF text selection when enabled (mouse/touch fallback - stylus handled in tabletEvent)\n if (pdfTextSelectionEnabled && isPdfLoaded && pdfTextSelecting) {\n pdfSelectionEnd = event->position();\n \n // Store pending selection for throttled processing\n pendingSelectionStart = pdfSelectionStart;\n pendingSelectionEnd = pdfSelectionEnd;\n hasPendingSelection = true;\n \n // Start timer if not already running (throttled to 60 FPS)\n if (!pdfTextSelectionTimer->isActive()) {\n pdfTextSelectionTimer->start();\n }\n \n event->accept();\n return;\n }\n \n // Update cursor based on mode when not actively selecting\n if (pdfTextSelectionEnabled && isPdfLoaded && !pdfTextSelecting) {\n setCursor(Qt::IBeamCursor);\n }\n \n event->ignore();\n}\n void mouseReleaseEvent(QMouseEvent *event) override {\n // Handle markdown selection when enabled\n if (markdownSelectionMode && markdownSelecting && event->button() == Qt::LeftButton) {\n markdownSelecting = false;\n \n // Create markdown window if selection is valid\n QRect selectionRect = QRect(markdownSelectionStart, markdownSelectionEnd).normalized();\n if (selectionRect.width() > 50 && selectionRect.height() > 50 && markdownManager) {\n markdownManager->createMarkdownWindow(selectionRect);\n }\n \n // Exit selection mode\n setMarkdownSelectionMode(false);\n \n // Force screen update to clear the green selection overlay\n update();\n \n event->accept();\n return;\n }\n \n // Handle PDF text selection when enabled (mouse/touch fallback - stylus handled in tabletEvent)\n if (pdfTextSelectionEnabled && isPdfLoaded && pdfTextSelecting) {\n if (event->button() == Qt::LeftButton) {\n pdfSelectionEnd = event->position();\n \n // Process any pending selection immediately on release\n if (pdfTextSelectionTimer && pdfTextSelectionTimer->isActive()) {\n pdfTextSelectionTimer->stop();\n if (hasPendingSelection) {\n updatePdfTextSelection(pendingSelectionStart, pendingSelectionEnd);\n hasPendingSelection = false;\n }\n } else {\n // Update selection with final position\n updatePdfTextSelection(pdfSelectionStart, pdfSelectionEnd);\n }\n \n pdfTextSelecting = false;\n \n // Check for link clicks if no text was selected\n QString selectedText = getSelectedPdfText();\n if (selectedText.isEmpty()) {\n handlePdfLinkClick(event->position());\n } else {\n // Show context menu for text selection\n QPoint globalPos = mapToGlobal(event->position().toPoint());\n showPdfTextSelectionMenu(globalPos);\n }\n \n event->accept();\n return;\n }\n }\n \n\n \n event->ignore();\n}\n void resizeEvent(QResizeEvent *event) override {\n // Don't resize the buffer when the widget resizes\n // The buffer size should be determined by the PDF/document content, not the widget size\n // The paintEvent will handle centering the buffer content within the widget\n \n QWidget::resizeEvent(event);\n}\n bool event(QEvent *event) override {\n if (!touchGesturesEnabled) {\n return QWidget::event(event);\n }\n\n if (event->type() == QEvent::TouchBegin || \n event->type() == QEvent::TouchUpdate || \n event->type() == QEvent::TouchEnd) {\n \n QTouchEvent *touchEvent = static_cast(event);\n const QList touchPoints = touchEvent->points();\n \n activeTouchPoints = touchPoints.count();\n\n if (activeTouchPoints == 1) {\n // Single finger pan\n const QTouchEvent::TouchPoint &touchPoint = touchPoints.first();\n \n if (event->type() == QEvent::TouchBegin) {\n isPanning = true;\n lastTouchPos = touchPoint.position();\n } else if (event->type() == QEvent::TouchUpdate && isPanning) {\n QPointF delta = touchPoint.position() - lastTouchPos;\n \n // Make panning more responsive by using floating-point calculations\n qreal scaledDeltaX = delta.x() / (internalZoomFactor / 100.0);\n qreal scaledDeltaY = delta.y() / (internalZoomFactor / 100.0);\n \n // Calculate new pan positions with sub-pixel precision\n qreal newPanX = panOffsetX - scaledDeltaX;\n qreal newPanY = panOffsetY - scaledDeltaY;\n \n // Clamp pan values when canvas is smaller than viewport\n qreal scaledCanvasWidth = buffer.width() * (internalZoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (internalZoomFactor / 100.0);\n \n // If canvas is smaller than widget, lock pan to 0 (centered)\n if (scaledCanvasWidth < width()) {\n newPanX = 0;\n }\n if (scaledCanvasHeight < height()) {\n newPanY = 0;\n }\n \n // Emit signal with integer values for compatibility\n emit panChanged(qRound(newPanX), qRound(newPanY));\n \n lastTouchPos = touchPoint.position();\n }\n } else if (activeTouchPoints == 2) {\n // Two finger pinch zoom\n isPanning = false;\n \n const QTouchEvent::TouchPoint &touch1 = touchPoints[0];\n const QTouchEvent::TouchPoint &touch2 = touchPoints[1];\n \n // Calculate distance between touch points with higher precision\n qreal currentDist = QLineF(touch1.position(), touch2.position()).length();\n qreal startDist = QLineF(touch1.pressPosition(), touch2.pressPosition()).length();\n \n if (event->type() == QEvent::TouchBegin) {\n lastPinchScale = 1.0;\n // Store the starting internal zoom\n internalZoomFactor = zoomFactor;\n } else if (event->type() == QEvent::TouchUpdate && startDist > 0) {\n qreal scale = currentDist / startDist;\n \n // Use exponential scaling for more natural feel\n qreal scaleChange = scale / lastPinchScale;\n \n // Apply scale with higher sensitivity\n internalZoomFactor *= scaleChange;\n internalZoomFactor = qBound(10.0, internalZoomFactor, 400.0);\n \n // Calculate zoom center (midpoint between two fingers)\n QPointF center = (touch1.position() + touch2.position()) / 2.0;\n \n // Account for centering offset\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n // Adjust center point for centering offset\n QPointF adjustedCenter = center - QPointF(centerOffsetX, centerOffsetY);\n \n // Always update zoom for smooth animation\n int newZoom = qRound(internalZoomFactor);\n \n // Calculate pan adjustment to keep the zoom centered at pinch point\n QPointF bufferCenter = adjustedCenter / (zoomFactor / 100.0) + QPointF(panOffsetX, panOffsetY);\n \n // Update zoom factor before emitting\n qreal oldZoomFactor = zoomFactor;\n zoomFactor = newZoom;\n \n // Emit zoom change even for small changes\n emit zoomChanged(newZoom);\n \n // Adjust pan to keep center point fixed with sub-pixel precision\n qreal newPanX = bufferCenter.x() - adjustedCenter.x() / (internalZoomFactor / 100.0);\n qreal newPanY = bufferCenter.y() - adjustedCenter.y() / (internalZoomFactor / 100.0);\n \n // After zoom, check if we need to center\n qreal newScaledCanvasWidth = buffer.width() * (internalZoomFactor / 100.0);\n qreal newScaledCanvasHeight = buffer.height() * (internalZoomFactor / 100.0);\n \n if (newScaledCanvasWidth < width()) {\n newPanX = 0;\n }\n if (newScaledCanvasHeight < height()) {\n newPanY = 0;\n }\n \n emit panChanged(qRound(newPanX), qRound(newPanY));\n \n lastPinchScale = scale;\n \n // Request update only for visible area\n update();\n }\n } else {\n // More than 2 fingers - ignore\n isPanning = false;\n }\n \n if (event->type() == QEvent::TouchEnd) {\n isPanning = false;\n lastPinchScale = 1.0;\n activeTouchPoints = 0;\n // Sync internal zoom with actual zoom\n internalZoomFactor = zoomFactor;\n \n // Emit signal that touch gesture has ended\n emit touchGestureEnded();\n }\n \n event->accept();\n return true;\n }\n \n return QWidget::event(event);\n}\n private:\n QPointF mapLogicalWidgetToPhysicalBuffer(const QPointF& logicalWidgetPoint) {\n // Use the same coordinate transformation logic as drawStroke for consistency\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n // Convert widget position to buffer position, accounting for centering\n QPointF adjustedPoint = logicalWidgetPoint - QPointF(centerOffsetX, centerOffsetY);\n QPointF bufferPoint = (adjustedPoint / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n \n return bufferPoint;\n}\n QRect mapRectBufferToWidgetLogical(const QRectF& physicalBufferRect) {\n // Use the same coordinate transformation logic as drawStroke for consistency\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n // Convert buffer coordinates back to widget coordinates\n QRectF widgetRect = QRectF(\n (physicalBufferRect.topLeft() - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY),\n physicalBufferRect.size() * (zoomFactor / 100.0)\n );\n \n return widgetRect.toRect();\n}\n QPixmap buffer;\n QImage background;\n QPointF lastPoint;\n QPointF straightLineStartPoint;\n bool drawing;\n QColor penColor;\n qreal penThickness;\n ToolType currentTool;\n ToolType previousTool;\n qreal penToolThickness = 5.0;\n qreal markerToolThickness = 5.0;\n qreal eraserToolThickness = 5.0;\n QString saveFolder;\n QPixmap backgroundImage;\n bool straightLineMode = false;\n bool ropeToolMode = false;\n QPixmap selectionBuffer;\n QRect selectionRect;\n QRectF exactSelectionRectF;\n QPolygonF lassoPathPoints;\n bool selectingWithRope = false;\n bool movingSelection = false;\n bool selectionJustCopied = false;\n bool selectionAreaCleared = false;\n QPainterPath selectionMaskPath;\n QRectF selectionBufferRect;\n QPointF lastMovePoint;\n int zoomFactor;\n int panOffsetX;\n int panOffsetY;\n qreal internalZoomFactor = 100.0;\n void initializeBuffer() {\n QScreen *screen = QGuiApplication::primaryScreen();\n qreal dpr = screen ? screen->devicePixelRatio() : 1.0;\n\n // Get logical screen size\n QSize logicalSize = screen ? screen->size() : QSize(1440, 900);\n QSize pixelSize = logicalSize * dpr;\n\n buffer = QPixmap(pixelSize);\n buffer.fill(Qt::transparent);\n\n setMaximumSize(pixelSize); // 🔥 KEY LINE to make full canvas drawable\n}\n void drawStroke(const QPointF &start, const QPointF &end, qreal pressure) {\n if (buffer.isNull()) {\n initializeBuffer();\n }\n\n if (!edited){\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n\n QPainter painter(&buffer);\n painter.setRenderHint(QPainter::Antialiasing);\n\n qreal thickness = penThickness;\n\n qreal updatePadding = (currentTool == ToolType::Marker) ? thickness * 4.0 : 10;\n\n if (currentTool == ToolType::Marker) {\n thickness *= 8.0;\n QColor markerColor = penColor;\n // Adjust alpha based on whether we're in straight line mode\n if (straightLineMode) {\n // For straight line mode, use higher alpha to make it more visible\n markerColor.setAlpha(40);\n } else {\n // For regular drawing, use lower alpha for the usual marker effect\n markerColor.setAlpha(4);\n }\n QPen pen(markerColor, thickness, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);\n painter.setPen(pen);\n } else { // Default Pen\n qreal scaledThickness = thickness * pressure; // **Linear pressure scaling**\n QPen pen(penColor, scaledThickness, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);\n painter.setPen(pen);\n }\n\n // Calculate centering offsets\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n // Convert screen position to buffer position, accounting for centering\n QPointF adjustedStart = start - QPointF(centerOffsetX, centerOffsetY);\n QPointF adjustedEnd = end - QPointF(centerOffsetX, centerOffsetY);\n \n QPointF bufferStart = (adjustedStart / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n QPointF bufferEnd = (adjustedEnd / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n\n painter.drawLine(bufferStart, bufferEnd);\n\n QRectF updateRect = QRectF(bufferStart, bufferEnd)\n .normalized()\n .adjusted(-updatePadding, -updatePadding, updatePadding, updatePadding);\n\n QRect scaledUpdateRect = QRect(\n ((updateRect.topLeft() - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY)).toPoint(),\n ((updateRect.bottomRight() - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY)).toPoint()\n );\n update(scaledUpdateRect);\n}\n void eraseStroke(const QPointF &start, const QPointF &end, qreal pressure) {\n if (buffer.isNull()) {\n initializeBuffer();\n }\n\n if (!edited){\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n\n QPainter painter(&buffer);\n painter.setCompositionMode(QPainter::CompositionMode_Clear);\n\n qreal eraserThickness = penThickness * 6.0;\n QPen eraserPen(Qt::transparent, eraserThickness, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);\n painter.setPen(eraserPen);\n\n // Calculate centering offsets\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n // Convert screen position to buffer position, accounting for centering\n QPointF adjustedStart = start - QPointF(centerOffsetX, centerOffsetY);\n QPointF adjustedEnd = end - QPointF(centerOffsetX, centerOffsetY);\n \n QPointF bufferStart = (adjustedStart / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n QPointF bufferEnd = (adjustedEnd / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n\n painter.drawLine(bufferStart, bufferEnd);\n\n qreal updatePadding = eraserThickness / 2.0 + 5.0; // Half the eraser thickness plus some extra padding\n QRectF updateRect = QRectF(bufferStart, bufferEnd)\n .normalized()\n .adjusted(-updatePadding, -updatePadding, updatePadding, updatePadding);\n\n QRect scaledUpdateRect = QRect(\n ((updateRect.topLeft() - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY)).toPoint(),\n ((updateRect.bottomRight() - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY)).toPoint()\n );\n update(scaledUpdateRect);\n}\n QRectF calculatePreviewRect(const QPointF &start, const QPointF &oldEnd, const QPointF &newEnd) {\n // Calculate centering offsets - use the same calculation as in paintEvent\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n // Calculate the buffer coordinates for our points (same as in drawStroke)\n QPointF adjustedStart = start - QPointF(centerOffsetX, centerOffsetY);\n QPointF adjustedOldEnd = oldEnd - QPointF(centerOffsetX, centerOffsetY);\n QPointF adjustedNewEnd = newEnd - QPointF(centerOffsetX, centerOffsetY);\n \n QPointF bufferStart = (adjustedStart / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n QPointF bufferOldEnd = (adjustedOldEnd / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n QPointF bufferNewEnd = (adjustedNewEnd / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n \n // Now convert from buffer coordinates to screen coordinates\n QPointF screenStart = (bufferStart - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY);\n QPointF screenOldEnd = (bufferOldEnd - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY);\n QPointF screenNewEnd = (bufferNewEnd - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY);\n \n // Create rectangles for both the old and new lines\n QRectF oldLineRect = QRectF(screenStart, screenOldEnd).normalized();\n QRectF newLineRect = QRectF(screenStart, screenNewEnd).normalized();\n \n // Calculate padding based on pen thickness and device pixel ratio\n qreal dpr = devicePixelRatioF();\n qreal padding;\n \n if (currentTool == ToolType::Eraser) {\n padding = penThickness * 6.0 * dpr;\n } else if (currentTool == ToolType::Marker) {\n padding = penThickness * 8.0 * dpr;\n } else {\n padding = penThickness * dpr;\n }\n \n // Ensure minimum padding\n padding = qMax(padding, 15.0);\n \n // Combine rectangles with appropriate padding\n QRectF combinedRect = oldLineRect.united(newLineRect);\n return combinedRect.adjusted(-padding, -padding, padding, padding);\n}\n QCache pdfCache;\n std::unique_ptr pdfDocument;\n int currentPdfPage;\n bool isPdfLoaded = false;\n int totalPdfPages = 0;\n int lastActivePage = 0;\n int lastZoomLevel = 100;\n int lastPanX = 0;\n int lastPanY = 0;\n bool edited = false;\n bool benchmarking;\n std::deque processedTimestamps;\n QElapsedTimer benchmarkTimer;\n QString notebookId;\n void loadNotebookId() {\n QString idFile = saveFolder + \"/.notebook_id.txt\";\n if (QFile::exists(idFile)) {\n QFile file(idFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n notebookId = in.readLine().trimmed();\n }\n } else {\n // No ID file → create new random ID\n notebookId = QUuid::createUuid().toString(QUuid::WithoutBraces).replace(\"-\", \"\");\n saveNotebookId();\n }\n}\n void saveNotebookId() {\n QString idFile = saveFolder + \"/.notebook_id.txt\";\n QFile file(idFile);\n if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {\n QTextStream out(&file);\n out << notebookId;\n }\n}\n int pdfRenderDPI = 192;\n bool touchGesturesEnabled = false;\n QPointF lastTouchPos;\n qreal lastPinchScale = 1.0;\n bool isPanning = false;\n int activeTouchPoints = 0;\n BackgroundStyle backgroundStyle = BackgroundStyle::None;\n QColor backgroundColor = Qt::white;\n int backgroundDensity = 40;\n bool pdfTextSelectionEnabled = false;\n bool pdfTextSelecting = false;\n QPointF pdfSelectionStart;\n QPointF pdfSelectionEnd;\n QList currentPdfTextBoxes;\n QList selectedTextBoxes;\n std::unique_ptr currentPdfPageForText;\n QTimer* pdfTextSelectionTimer = nullptr;\n QPointF pendingSelectionStart;\n QPointF pendingSelectionEnd;\n bool hasPendingSelection = false;\n QTimer* pdfCacheTimer = nullptr;\n int currentCachedPage = -1;\n int pendingCacheTargetPage = -1;\n QList*> activePdfWatchers;\n QCache noteCache;\n QTimer* noteCacheTimer = nullptr;\n int currentCachedNotePage = -1;\n int pendingNoteCacheTargetPage = -1;\n QList*> activeNoteWatchers;\n MarkdownWindowManager* markdownManager = nullptr;\n bool markdownSelectionMode = false;\n QPoint markdownSelectionStart;\n QPoint markdownSelectionEnd;\n bool markdownSelecting = false;\n void loadPdfTextBoxes(int pageNumber) {\n // Clear existing text boxes\n qDeleteAll(currentPdfTextBoxes);\n currentPdfTextBoxes.clear();\n \n if (!pdfDocument || pageNumber < 0 || pageNumber >= pdfDocument->numPages()) {\n return;\n }\n \n // Get the page for text operations\n currentPdfPageForText = std::unique_ptr(pdfDocument->page(pageNumber));\n if (!currentPdfPageForText) {\n return;\n }\n \n // Load text boxes for the page\n auto textBoxVector = currentPdfPageForText->textList();\n currentPdfTextBoxes.clear();\n for (auto& textBox : textBoxVector) {\n currentPdfTextBoxes.append(textBox.release()); // Transfer ownership to QList\n }\n}\n QPointF mapWidgetToPdfCoordinates(const QPointF &widgetPoint) {\n if (!currentPdfPageForText || backgroundImage.isNull()) {\n return QPointF();\n }\n \n // Use the same zoom factor as in paintEvent (internalZoomFactor for smooth animations)\n qreal zoom = internalZoomFactor / 100.0;\n \n // Calculate the scaled canvas size (same as in paintEvent)\n qreal scaledCanvasWidth = buffer.width() * zoom;\n qreal scaledCanvasHeight = buffer.height() * zoom;\n \n // Calculate centering offsets (same as in paintEvent)\n qreal centerOffsetX = 0;\n qreal centerOffsetY = 0;\n \n // Center horizontally if canvas is smaller than widget\n if (scaledCanvasWidth < width()) {\n centerOffsetX = (width() - scaledCanvasWidth) / 2.0;\n }\n \n // Center vertically if canvas is smaller than widget\n if (scaledCanvasHeight < height()) {\n centerOffsetY = (height() - scaledCanvasHeight) / 2.0;\n }\n \n // Reverse the transformations applied in paintEvent\n QPointF adjustedPoint = widgetPoint;\n adjustedPoint -= QPointF(centerOffsetX, centerOffsetY);\n adjustedPoint /= zoom;\n adjustedPoint += QPointF(panOffsetX, panOffsetY);\n \n // Convert to PDF coordinates\n // Since Poppler renders the PDF in Qt coordinate system (top-left origin),\n // we don't need to flip the Y coordinate\n QSizeF pdfPageSize = currentPdfPageForText->pageSizeF();\n QSizeF imageSize = backgroundImage.size();\n \n // Scale from image coordinates to PDF coordinates\n qreal scaleX = pdfPageSize.width() / imageSize.width();\n qreal scaleY = pdfPageSize.height() / imageSize.height();\n \n QPointF pdfPoint;\n pdfPoint.setX(adjustedPoint.x() * scaleX);\n pdfPoint.setY(adjustedPoint.y() * scaleY); // No Y-axis flipping needed\n \n return pdfPoint;\n}\n QPointF mapPdfToWidgetCoordinates(const QPointF &pdfPoint) {\n if (!currentPdfPageForText || backgroundImage.isNull()) {\n return QPointF();\n }\n \n // Convert from PDF coordinates to image coordinates\n QSizeF pdfPageSize = currentPdfPageForText->pageSizeF();\n QSizeF imageSize = backgroundImage.size();\n \n // Scale from PDF coordinates to image coordinates\n qreal scaleX = imageSize.width() / pdfPageSize.width();\n qreal scaleY = imageSize.height() / pdfPageSize.height();\n \n QPointF imagePoint;\n imagePoint.setX(pdfPoint.x() * scaleX);\n imagePoint.setY(pdfPoint.y() * scaleY); // No Y-axis flipping needed\n \n // Use the same zoom factor as in paintEvent (internalZoomFactor for smooth animations)\n qreal zoom = internalZoomFactor / 100.0;\n \n // Apply the same transformations as in paintEvent\n QPointF widgetPoint = imagePoint;\n widgetPoint -= QPointF(panOffsetX, panOffsetY);\n widgetPoint *= zoom;\n \n // Calculate the scaled canvas size (same as in paintEvent)\n qreal scaledCanvasWidth = buffer.width() * zoom;\n qreal scaledCanvasHeight = buffer.height() * zoom;\n \n // Calculate centering offsets (same as in paintEvent)\n qreal centerOffsetX = 0;\n qreal centerOffsetY = 0;\n \n // Center horizontally if canvas is smaller than widget\n if (scaledCanvasWidth < width()) {\n centerOffsetX = (width() - scaledCanvasWidth) / 2.0;\n }\n \n // Center vertically if canvas is smaller than widget\n if (scaledCanvasHeight < height()) {\n centerOffsetY = (height() - scaledCanvasHeight) / 2.0;\n }\n \n widgetPoint += QPointF(centerOffsetX, centerOffsetY);\n \n return widgetPoint;\n}\n void updatePdfTextSelection(const QPointF &start, const QPointF &end) {\n // Early return if PDF is not loaded or no text boxes available\n if (!isPdfLoaded || currentPdfTextBoxes.isEmpty()) {\n return;\n }\n \n // Clear previous selection efficiently\n selectedTextBoxes.clear();\n \n // Create normalized selection rectangle in widget coordinates\n QRectF widgetSelectionRect(start, end);\n widgetSelectionRect = widgetSelectionRect.normalized();\n \n // Convert to PDF coordinate space\n QPointF pdfTopLeft = mapWidgetToPdfCoordinates(widgetSelectionRect.topLeft());\n QPointF pdfBottomRight = mapWidgetToPdfCoordinates(widgetSelectionRect.bottomRight());\n QRectF pdfSelectionRect(pdfTopLeft, pdfBottomRight);\n pdfSelectionRect = pdfSelectionRect.normalized();\n \n // Reserve space for efficiency if we expect many selections\n selectedTextBoxes.reserve(qMin(currentPdfTextBoxes.size(), 50));\n \n // Find intersecting text boxes with optimized loop\n for (const Poppler::TextBox* textBox : currentPdfTextBoxes) {\n if (textBox && textBox->boundingBox().intersects(pdfSelectionRect)) {\n selectedTextBoxes.append(const_cast(textBox));\n }\n }\n \n // Only emit signal and update if we have selected text\n if (!selectedTextBoxes.isEmpty()) {\n QString selectedText = getSelectedPdfText();\n if (!selectedText.isEmpty()) {\n emit pdfTextSelected(selectedText);\n }\n }\n \n // Trigger repaint to show selection\n update();\n}\n void handlePdfLinkClick(const QPointF &clickPoint) {\n if (!isPdfLoaded || !currentPdfPageForText) {\n return;\n }\n \n // Convert widget coordinates to PDF coordinates\n QPointF pdfPoint = mapWidgetToPdfCoordinates(position);\n \n // Get PDF page size for reference\n QSizeF pdfPageSize = currentPdfPageForText->pageSizeF();\n \n // Convert to normalized coordinates (0.0 to 1.0) to match Poppler's link coordinate system\n QPointF normalizedPoint(pdfPoint.x() / pdfPageSize.width(), pdfPoint.y() / pdfPageSize.height());\n \n // Get links for the current page\n auto links = currentPdfPageForText->links();\n \n for (const auto& link : links) {\n QRectF linkArea = link->linkArea();\n \n // Normalize the rectangle to handle negative width/height\n QRectF normalizedLinkArea = linkArea.normalized();\n \n // Check if the normalized rectangle contains the normalized point\n if (normalizedLinkArea.contains(normalizedPoint)) {\n // Handle different types of links\n if (link->linkType() == Poppler::Link::Goto) {\n Poppler::LinkGoto* gotoLink = static_cast(link.get());\n if (gotoLink && gotoLink->destination().pageNumber() >= 0) {\n int targetPage = gotoLink->destination().pageNumber() - 1; // Convert to 0-based\n emit pdfLinkClicked(targetPage);\n return;\n }\n }\n // Add other link types as needed (URI, etc.)\n }\n }\n}\n void showPdfTextSelectionMenu(const QPoint &position) {\n QString selectedText = getSelectedPdfText();\n if (selectedText.isEmpty()) {\n return; // No text selected, don't show menu\n }\n \n // Create context menu\n QMenu *contextMenu = new QMenu(this);\n contextMenu->setAttribute(Qt::WA_DeleteOnClose);\n \n // Add Copy action\n QAction *copyAction = contextMenu->addAction(tr(\"Copy\"));\n copyAction->setIcon(QIcon(\":/resources/icons/copy.png\")); // You may need to add this icon\n connect(copyAction, &QAction::triggered, this, [selectedText]() {\n QClipboard *clipboard = QGuiApplication::clipboard();\n clipboard->setText(selectedText);\n });\n \n // Add separator\n contextMenu->addSeparator();\n \n // Add Cancel action\n QAction *cancelAction = contextMenu->addAction(tr(\"Cancel\"));\n cancelAction->setIcon(QIcon(\":/resources/icons/cross.png\"));\n connect(cancelAction, &QAction::triggered, this, [this]() {\n clearPdfTextSelection();\n });\n \n // Show the menu at the specified position\n contextMenu->popup(position);\n}\n QList getTextBoxesInSelection(const QPointF &start, const QPointF &end) {\n QList selectedBoxes;\n \n if (!currentPdfPageForText) {\n // qDebug() << \"PDF text selection: No current page for text\";\n return selectedBoxes;\n }\n \n // Convert widget coordinates to PDF coordinates\n QPointF pdfStart = mapWidgetToPdfCoordinates(start);\n QPointF pdfEnd = mapWidgetToPdfCoordinates(end);\n \n // qDebug() << \"PDF text selection: Widget coords\" << start << \"to\" << end;\n // qDebug() << \"PDF text selection: PDF coords\" << pdfStart << \"to\" << pdfEnd;\n \n // Create selection rectangle in PDF coordinates\n QRectF selectionRect(pdfStart, pdfEnd);\n selectionRect = selectionRect.normalized();\n \n // qDebug() << \"PDF text selection: Selection rect in PDF coords:\" << selectionRect;\n \n // Find text boxes that intersect with the selection\n int intersectionCount = 0;\n for (Poppler::TextBox* textBox : currentPdfTextBoxes) {\n if (textBox) {\n QRectF textBoxRect = textBox->boundingBox();\n bool intersects = textBoxRect.intersects(selectionRect);\n \n if (intersects) {\n selectedBoxes.append(textBox);\n intersectionCount++;\n // qDebug() << \"PDF text selection: Text box intersects:\" << textBox->text() \n // << \"at\" << textBoxRect;\n }\n }\n }\n \n // qDebug() << \"PDF text selection: Found\" << intersectionCount << \"intersecting text boxes\";\n \n return selectedBoxes;\n}\n void renderPdfPageToCache(int pageNumber) {\n if (!pdfDocument || !isValidPageNumber(pageNumber)) {\n return;\n }\n \n // Check if already cached\n if (pdfCache.contains(pageNumber)) {\n return;\n }\n \n // Ensure the cache holds only 10 pages max\n if (pdfCache.count() >= 10) {\n auto oldestKey = pdfCache.keys().first();\n pdfCache.remove(oldestKey);\n }\n \n // Render the page and store it in the cache\n std::unique_ptr page(pdfDocument->page(pageNumber));\n if (page) {\n // Render with document-level anti-aliasing settings\n QImage pdfImage = page->renderToImage(pdfRenderDPI, pdfRenderDPI);\n if (!pdfImage.isNull()) {\n QPixmap cachedPixmap = QPixmap::fromImage(pdfImage);\n pdfCache.insert(pageNumber, new QPixmap(cachedPixmap));\n }\n }\n}\n void checkAndCacheAdjacentPages(int targetPage) {\n if (!pdfDocument || !isValidPageNumber(targetPage)) {\n return;\n }\n \n // Calculate adjacent pages\n int prevPage = targetPage - 1;\n int nextPage = targetPage + 1;\n \n // Check what needs to be cached\n bool needPrevPage = isValidPageNumber(prevPage) && !pdfCache.contains(prevPage);\n bool needCurrentPage = !pdfCache.contains(targetPage);\n bool needNextPage = isValidPageNumber(nextPage) && !pdfCache.contains(nextPage);\n \n // If all pages are cached, nothing to do\n if (!needPrevPage && !needCurrentPage && !needNextPage) {\n return;\n }\n \n // Stop any existing timer\n if (pdfCacheTimer && pdfCacheTimer->isActive()) {\n pdfCacheTimer->stop();\n }\n \n // Create timer if it doesn't exist\n if (!pdfCacheTimer) {\n pdfCacheTimer = new QTimer(this);\n pdfCacheTimer->setSingleShot(true);\n connect(pdfCacheTimer, &QTimer::timeout, this, &InkCanvas::cacheAdjacentPages);\n }\n \n // Store the target page for validation when timer fires\n pendingCacheTargetPage = targetPage;\n \n // Start 1-second delay timer\n pdfCacheTimer->start(1000);\n}\n bool isValidPageNumber(int pageNumber) const {\n return (pageNumber >= 0 && pageNumber < totalPdfPages);\n}\n void loadNotePageToCache(int pageNumber) {\n // Check if already cached\n if (noteCache.contains(pageNumber)) {\n return;\n }\n \n QString filePath = getNotePageFilePath(pageNumber);\n if (filePath.isEmpty()) {\n return;\n }\n \n // Ensure the cache doesn't exceed its limit\n if (noteCache.count() >= 15) {\n // QCache will automatically remove least recently used items\n // but we can be explicit about it\n auto keys = noteCache.keys();\n if (!keys.isEmpty()) {\n noteCache.remove(keys.first());\n }\n }\n \n // Load note page from disk if it exists\n if (QFile::exists(filePath)) {\n QPixmap notePixmap;\n if (notePixmap.load(filePath)) {\n noteCache.insert(pageNumber, new QPixmap(notePixmap));\n }\n }\n // If file doesn't exist, we don't cache anything - loadPage will handle initialization\n}\n void checkAndCacheAdjacentNotePages(int targetPage) {\n if (saveFolder.isEmpty()) {\n return;\n }\n \n // Calculate adjacent pages\n int prevPage = targetPage - 1;\n int nextPage = targetPage + 1;\n \n // Check what needs to be cached (we don't have a max page limit for notes)\n bool needPrevPage = (prevPage >= 0) && !noteCache.contains(prevPage);\n bool needCurrentPage = !noteCache.contains(targetPage);\n bool needNextPage = !noteCache.contains(nextPage); // No upper limit check for notes\n \n // If all nearby pages are cached, nothing to do\n if (!needPrevPage && !needCurrentPage && !needNextPage) {\n return;\n }\n \n // Stop any existing timer\n if (noteCacheTimer && noteCacheTimer->isActive()) {\n noteCacheTimer->stop();\n }\n \n // Create timer if it doesn't exist\n if (!noteCacheTimer) {\n noteCacheTimer = new QTimer(this);\n noteCacheTimer->setSingleShot(true);\n connect(noteCacheTimer, &QTimer::timeout, this, &InkCanvas::cacheAdjacentNotePages);\n }\n \n // Store the target page for validation when timer fires\n pendingNoteCacheTargetPage = targetPage;\n \n // Start 1-second delay timer\n noteCacheTimer->start(1000);\n}\n QString getNotePageFilePath(int pageNumber) const {\n if (saveFolder.isEmpty() || notebookId.isEmpty()) {\n return QString();\n }\n return saveFolder + QString(\"/%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n}\n void invalidateCurrentPageCache() {\n if (currentCachedNotePage >= 0) {\n noteCache.remove(currentCachedNotePage);\n }\n}\n private:\n void processPendingTextSelection() {\n if (!hasPendingSelection) {\n return;\n }\n \n // Process the pending selection update\n updatePdfTextSelection(pendingSelectionStart, pendingSelectionEnd);\n hasPendingSelection = false;\n}\n void cacheAdjacentPages() {\n if (!pdfDocument || currentCachedPage < 0) {\n return;\n }\n \n // Check if the user has moved to a different page since the timer was started\n // If so, skip caching adjacent pages as they're no longer relevant\n if (pendingCacheTargetPage != currentCachedPage) {\n return; // User switched pages, don't cache adjacent pages for old page\n }\n \n int targetPage = currentCachedPage;\n int prevPage = targetPage - 1;\n int nextPage = targetPage + 1;\n \n // Create list of pages to cache asynchronously\n QList pagesToCache;\n \n // Add previous page if needed\n if (isValidPageNumber(prevPage) && !pdfCache.contains(prevPage)) {\n pagesToCache.append(prevPage);\n }\n \n // Add next page if needed\n if (isValidPageNumber(nextPage) && !pdfCache.contains(nextPage)) {\n pagesToCache.append(nextPage);\n }\n \n // Cache pages asynchronously\n for (int pageNum : pagesToCache) {\n QFutureWatcher *watcher = new QFutureWatcher(this);\n \n // Track the watcher for cleanup\n activePdfWatchers.append(watcher);\n \n connect(watcher, &QFutureWatcher::finished, this, [this, watcher]() {\n // Remove from active list and delete\n activePdfWatchers.removeOne(watcher);\n watcher->deleteLater();\n });\n \n // Capture pageNum by value to avoid issues with lambda capture\n QFuture future = QtConcurrent::run([this, pageNum]() {\n renderPdfPageToCache(pageNum);\n });\n \n watcher->setFuture(future);\n }\n}\n void cacheAdjacentNotePages() {\n if (saveFolder.isEmpty() || currentCachedNotePage < 0) {\n return;\n }\n \n // Check if the user has moved to a different page since the timer was started\n // If so, skip caching adjacent pages as they're no longer relevant\n if (pendingNoteCacheTargetPage != currentCachedNotePage) {\n return; // User switched pages, don't cache adjacent pages for old page\n }\n \n int targetPage = currentCachedNotePage;\n int prevPage = targetPage - 1;\n int nextPage = targetPage + 1;\n \n // Create list of note pages to cache asynchronously\n QList notePagesToCache;\n \n // Add previous page if needed (check for >= 0 since notes can start from page 0)\n if (prevPage >= 0 && !noteCache.contains(prevPage)) {\n notePagesToCache.append(prevPage);\n }\n \n // Add next page if needed (no upper limit check for notes)\n if (!noteCache.contains(nextPage)) {\n notePagesToCache.append(nextPage);\n }\n \n // Cache note pages asynchronously\n for (int pageNum : notePagesToCache) {\n QFutureWatcher *watcher = new QFutureWatcher(this);\n \n // Track the watcher for cleanup\n activeNoteWatchers.append(watcher);\n \n connect(watcher, &QFutureWatcher::finished, this, [this, watcher]() {\n // Remove from active list and delete\n activeNoteWatchers.removeOne(watcher);\n watcher->deleteLater();\n });\n \n // Capture pageNum by value to avoid issues with lambda capture\n QFuture future = QtConcurrent::run([this, pageNum]() {\n loadNotePageToCache(pageNum);\n });\n \n watcher->setFuture(future);\n }\n}\n};"], ["/SpeedyNote/source/MarkdownWindow.h", "class QMarkdownTextEdit {\n Q_OBJECT\n\npublic:\n explicit MarkdownWindow(const QRect &rect, QWidget *parent = nullptr);\n ~MarkdownWindow() = default;\n QString getMarkdownContent() const {\n return markdownEditor ? markdownEditor->toPlainText() : QString();\n}\n void setMarkdownContent(const QString &content) {\n if (markdownEditor) {\n markdownEditor->setPlainText(content);\n }\n}\n QRect getWindowRect() const {\n return geometry();\n}\n void setWindowRect(const QRect &rect) {\n setGeometry(rect);\n}\n QRect getCanvasRect() const {\n return canvasRect;\n}\n void setCanvasRect(const QRect &canvasRect) {\n canvasRect = rect;\n updateScreenPosition();\n}\n void updateScreenPosition() {\n // Prevent recursive updates\n if (isUpdatingPosition) return;\n isUpdatingPosition = true;\n \n // Debug: Log when this is called due to external changes (not during mouse movement)\n if (!dragging && !resizing) {\n // qDebug() << \"MarkdownWindow::updateScreenPosition() called for window\" << this << \"Canvas rect:\" << canvasRect;\n }\n \n // Get the canvas parent to access coordinate conversion methods\n if (QWidget *canvas = parentWidget()) {\n // Try to cast to InkCanvas to use the new coordinate methods\n if (InkCanvas *inkCanvas = qobject_cast(canvas)) {\n // Use the new coordinate conversion methods\n QRect screenRect = inkCanvas->mapCanvasToWidget(canvasRect);\n // qDebug() << \"MarkdownWindow::updateScreenPosition() - Canvas rect:\" << canvasRect << \"-> Screen rect:\" << screenRect;\n // qDebug() << \" Canvas size:\" << inkCanvas->getCanvasSize() << \"Zoom:\" << inkCanvas->getZoomFactor() << \"Pan:\" << inkCanvas->getPanOffset();\n setGeometry(screenRect);\n } else {\n // Fallback: use canvas coordinates directly\n // qDebug() << \"MarkdownWindow::updateScreenPosition() - No InkCanvas parent, using canvas rect directly:\" << canvasRect;\n setGeometry(canvasRect);\n }\n } else {\n // No parent, use canvas coordinates directly\n // qDebug() << \"MarkdownWindow::updateScreenPosition() - No parent, using canvas rect directly:\" << canvasRect;\n setGeometry(canvasRect);\n }\n \n isUpdatingPosition = false;\n}\n QVariantMap serialize() const {\n QVariantMap data;\n data[\"canvas_x\"] = canvasRect.x();\n data[\"canvas_y\"] = canvasRect.y();\n data[\"canvas_width\"] = canvasRect.width();\n data[\"canvas_height\"] = canvasRect.height();\n data[\"content\"] = getMarkdownContent();\n \n // Add canvas size information for debugging and consistency checks\n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n QSize canvasSize = inkCanvas->getCanvasSize();\n data[\"canvas_buffer_width\"] = canvasSize.width();\n data[\"canvas_buffer_height\"] = canvasSize.height();\n data[\"zoom_factor\"] = inkCanvas->getZoomFactor();\n QPointF panOffset = inkCanvas->getPanOffset();\n data[\"pan_x\"] = panOffset.x();\n data[\"pan_y\"] = panOffset.y();\n }\n \n return data;\n}\n void deserialize(const QVariantMap &data) {\n int x = data.value(\"canvas_x\", 0).toInt();\n int y = data.value(\"canvas_y\", 0).toInt();\n int width = data.value(\"canvas_width\", 300).toInt();\n int height = data.value(\"canvas_height\", 200).toInt();\n QString content = data.value(\"content\", \"# New Markdown Window\").toString();\n \n QRect loadedRect = QRect(x, y, width, height);\n // qDebug() << \"MarkdownWindow::deserialize() - Loaded canvas rect:\" << loadedRect;\n // qDebug() << \" Original canvas size:\" << data.value(\"canvas_buffer_width\", -1).toInt() << \"x\" << data.value(\"canvas_buffer_height\", -1).toInt();\n \n // Apply bounds checking to loaded coordinates\n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n QRect canvasBounds = inkCanvas->getCanvasRect();\n \n // Ensure window stays within canvas bounds\n int maxX = canvasBounds.width() - loadedRect.width();\n int maxY = canvasBounds.height() - loadedRect.height();\n \n loadedRect.setX(qMax(0, qMin(loadedRect.x(), maxX)));\n loadedRect.setY(qMax(0, qMin(loadedRect.y(), maxY)));\n \n if (loadedRect != QRect(x, y, width, height)) {\n // qDebug() << \" Bounds-corrected canvas rect:\" << loadedRect << \"Canvas bounds:\" << canvasBounds;\n }\n }\n \n canvasRect = loadedRect;\n setMarkdownContent(content);\n \n // Ensure canvas connections are set up\n ensureCanvasConnections();\n \n updateScreenPosition();\n}\n void focusEditor() {\n if (markdownEditor) {\n markdownEditor->setFocus();\n }\n}\n bool isEditorFocused() const {\n return markdownEditor && markdownEditor->hasFocus();\n}\n void setTransparent(bool transparent) {\n if (isTransparentState == transparent) return;\n \n // qDebug() << \"MarkdownWindow::setTransparent(\" << transparent << \") for window\" << this;\n isTransparentState = transparent;\n \n // Apply transparency effect by changing the background style\n if (transparent) {\n // qDebug() << \"Setting window background to semi-transparent\";\n applyTransparentStyle();\n } else {\n // qDebug() << \"Setting window background to opaque\";\n applyStyle(); // Restore normal style\n }\n}\n bool isTransparent() const {\n return isTransparentState;\n}\n bool isValidForCanvas() const {\n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n QRect canvasBounds = inkCanvas->getCanvasRect();\n \n // Check if the window is at least partially within the canvas bounds\n return canvasBounds.intersects(canvasRect);\n }\n \n // If no canvas parent, assume valid\n return true;\n}\n QString getCoordinateInfo() const {\n QString info;\n info += QString(\"Canvas Coordinates: (%1, %2) %3x%4\\n\")\n .arg(canvasRect.x()).arg(canvasRect.y())\n .arg(canvasRect.width()).arg(canvasRect.height());\n \n QRect screenRect = geometry();\n info += QString(\"Screen Coordinates: (%1, %2) %3x%4\\n\")\n .arg(screenRect.x()).arg(screenRect.y())\n .arg(screenRect.width()).arg(screenRect.height());\n \n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n QSize canvasSize = inkCanvas->getCanvasSize();\n info += QString(\"Canvas Size: %1x%2\\n\")\n .arg(canvasSize.width()).arg(canvasSize.height());\n \n info += QString(\"Zoom Factor: %1\\n\").arg(inkCanvas->getZoomFactor());\n \n QPointF panOffset = inkCanvas->getPanOffset();\n info += QString(\"Pan Offset: (%1, %2)\\n\")\n .arg(panOffset.x()).arg(panOffset.y());\n \n info += QString(\"Valid for Canvas: %1\\n\").arg(isValidForCanvas() ? \"Yes\" : \"No\");\n } else {\n info += \"No InkCanvas parent found\\n\";\n }\n \n return info;\n}\n void ensureCanvasConnections() {\n // Connect to canvas pan/zoom changes to update position\n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n // Disconnect any existing connections to avoid duplicates\n disconnect(inkCanvas, &InkCanvas::panChanged, this, &MarkdownWindow::updateScreenPosition);\n disconnect(inkCanvas, &InkCanvas::zoomChanged, this, &MarkdownWindow::updateScreenPosition);\n \n // Reconnect\n connect(inkCanvas, &InkCanvas::panChanged, this, &MarkdownWindow::updateScreenPosition);\n connect(inkCanvas, &InkCanvas::zoomChanged, this, &MarkdownWindow::updateScreenPosition);\n \n // Install event filter to handle canvas resize events (for layout changes)\n inkCanvas->installEventFilter(this);\n \n // qDebug() << \"MarkdownWindow::ensureCanvasConnections() - Connected to canvas signals for window\" << this;\n } else {\n // qDebug() << \"MarkdownWindow::ensureCanvasConnections() - No InkCanvas parent found for window\" << this;\n }\n}\n void deleteRequested(MarkdownWindow *window);\n void contentChanged();\n void windowMoved(MarkdownWindow *window);\n void windowResized(MarkdownWindow *window);\n void focusChanged(MarkdownWindow *window, bool focused);\n void editorFocusChanged(MarkdownWindow *window, bool focused);\n void windowInteracted(MarkdownWindow *window);\n protected:\n void mousePressEvent(QMouseEvent *event) override {\n if (event->button() == Qt::LeftButton) {\n // Emit signal to indicate window interaction\n emit windowInteracted(this);\n \n ResizeHandle handle = getResizeHandle(event->pos());\n \n if (handle != None) {\n // Start resizing\n resizing = true;\n isUserInteracting = true;\n currentResizeHandle = handle;\n resizeStartPosition = event->globalPosition().toPoint();\n resizeStartRect = geometry();\n } else if (event->pos().y() < 24) { // Header area\n // Start dragging\n dragging = true;\n isUserInteracting = true;\n dragStartPosition = event->globalPosition().toPoint();\n windowStartPosition = pos();\n }\n }\n \n QWidget::mousePressEvent(event);\n}\n void mouseMoveEvent(QMouseEvent *event) override {\n if (resizing) {\n QPoint delta = event->globalPosition().toPoint() - resizeStartPosition;\n QRect newRect = resizeStartRect;\n \n // Apply resize based on the stored handle\n switch (currentResizeHandle) {\n case TopLeft:\n newRect.setTopLeft(newRect.topLeft() + delta);\n break;\n case TopRight:\n newRect.setTopRight(newRect.topRight() + delta);\n break;\n case BottomLeft:\n newRect.setBottomLeft(newRect.bottomLeft() + delta);\n break;\n case BottomRight:\n newRect.setBottomRight(newRect.bottomRight() + delta);\n break;\n case Top:\n newRect.setTop(newRect.top() + delta.y());\n break;\n case Bottom:\n newRect.setBottom(newRect.bottom() + delta.y());\n break;\n case Left:\n newRect.setLeft(newRect.left() + delta.x());\n break;\n case Right:\n newRect.setRight(newRect.right() + delta.x());\n break;\n default:\n break;\n }\n \n // Enforce minimum size\n newRect.setSize(newRect.size().expandedTo(QSize(200, 150)));\n \n // Keep resized window within canvas bounds\n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n // Convert to canvas coordinates to check bounds\n QRect tempCanvasRect = inkCanvas->mapWidgetToCanvas(newRect);\n QRect canvasBounds = inkCanvas->getCanvasRect();\n \n // Apply canvas bounds constraints\n int maxCanvasX = canvasBounds.width() - tempCanvasRect.width();\n int maxCanvasY = canvasBounds.height() - tempCanvasRect.height();\n \n tempCanvasRect.setX(qMax(0, qMin(tempCanvasRect.x(), maxCanvasX)));\n tempCanvasRect.setY(qMax(0, qMin(tempCanvasRect.y(), maxCanvasY)));\n \n // Also ensure the window doesn't get resized beyond canvas bounds\n if (tempCanvasRect.right() > canvasBounds.width()) {\n tempCanvasRect.setWidth(canvasBounds.width() - tempCanvasRect.x());\n }\n if (tempCanvasRect.bottom() > canvasBounds.height()) {\n tempCanvasRect.setHeight(canvasBounds.height() - tempCanvasRect.y());\n }\n \n // Convert back to screen coordinates for the constrained geometry\n newRect = inkCanvas->mapCanvasToWidget(tempCanvasRect);\n }\n \n // Update the widget geometry directly during resizing\n setGeometry(newRect);\n \n // Convert screen coordinates back to canvas coordinates\n convertScreenToCanvasRect(newRect);\n emit windowResized(this);\n } else if (dragging) {\n QPoint delta = event->globalPosition().toPoint() - dragStartPosition;\n QPoint newPos = windowStartPosition + delta;\n \n // Keep window within canvas bounds (not just parent widget bounds)\n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n // Convert current position to canvas coordinates to check bounds\n QRect tempScreenRect(newPos, size());\n QRect tempCanvasRect = inkCanvas->mapWidgetToCanvas(tempScreenRect);\n QRect canvasBounds = inkCanvas->getCanvasRect();\n \n // Apply canvas bounds constraints\n int maxCanvasX = canvasBounds.width() - tempCanvasRect.width();\n int maxCanvasY = canvasBounds.height() - tempCanvasRect.height();\n \n tempCanvasRect.setX(qMax(0, qMin(tempCanvasRect.x(), maxCanvasX)));\n tempCanvasRect.setY(qMax(0, qMin(tempCanvasRect.y(), maxCanvasY)));\n \n // Convert back to screen coordinates for the constrained position\n QRect constrainedScreenRect = inkCanvas->mapCanvasToWidget(tempCanvasRect);\n newPos = constrainedScreenRect.topLeft();\n \n // Debug: Log when position is constrained\n if (tempCanvasRect != inkCanvas->mapWidgetToCanvas(QRect(windowStartPosition + delta, size()))) {\n // qDebug() << \"MarkdownWindow: Constraining position to canvas bounds. Canvas rect:\" << tempCanvasRect;\n }\n } else {\n // Fallback: Keep window within parent bounds\n if (parentWidget()) {\n QRect parentRect = parentWidget()->rect();\n newPos.setX(qMax(0, qMin(newPos.x(), parentRect.width() - width())));\n newPos.setY(qMax(0, qMin(newPos.y(), parentRect.height() - height())));\n }\n }\n \n // Update the widget position directly during dragging\n move(newPos);\n \n // Convert screen position back to canvas coordinates\n QRect newScreenRect(newPos, size());\n convertScreenToCanvasRect(newScreenRect);\n emit windowMoved(this);\n } else {\n // Update cursor for resize handles\n updateCursor(event->pos());\n }\n \n QWidget::mouseMoveEvent(event);\n}\n void mouseReleaseEvent(QMouseEvent *event) override {\n if (event->button() == Qt::LeftButton) {\n resizing = false;\n dragging = false;\n isUserInteracting = false;\n currentResizeHandle = None;\n }\n \n QWidget::mouseReleaseEvent(event);\n}\n void resizeEvent(QResizeEvent *event) override {\n QWidget::resizeEvent(event);\n \n // Emit windowResized if this is a user-initiated resize or if we're not updating position due to canvas changes\n if (isUserInteracting || !isUpdatingPosition) {\n emit windowResized(this);\n }\n}\n void paintEvent(QPaintEvent *event) override {\n QWidget::paintEvent(event);\n \n // Draw resize handles\n QPainter painter(this);\n painter.setRenderHint(QPainter::Antialiasing);\n \n QColor handleColor = hasFocus() ? QColor(74, 144, 226) : QColor(180, 180, 180);\n painter.setPen(QPen(handleColor, 2));\n painter.setBrush(QBrush(handleColor));\n \n // Draw corner handles\n int handleSize = 6;\n painter.drawEllipse(0, 0, handleSize, handleSize); // Top-left\n painter.drawEllipse(width() - handleSize, 0, handleSize, handleSize); // Top-right\n painter.drawEllipse(0, height() - handleSize, handleSize, handleSize); // Bottom-left\n painter.drawEllipse(width() - handleSize, height() - handleSize, handleSize, handleSize); // Bottom-right\n}\n void focusInEvent(QFocusEvent *event) override {\n // qDebug() << \"MarkdownWindow::focusInEvent() - Window\" << this << \"gained focus\";\n QWidget::focusInEvent(event);\n emit focusChanged(this, true);\n}\n void focusOutEvent(QFocusEvent *event) override {\n // qDebug() << \"MarkdownWindow::focusOutEvent() - Window\" << this << \"lost focus\";\n QWidget::focusOutEvent(event);\n emit focusChanged(this, false);\n}\n bool eventFilter(QObject *obj, QEvent *event) override {\n if (obj == markdownEditor) {\n if (event->type() == QEvent::FocusIn) {\n // qDebug() << \"MarkdownWindow::eventFilter() - Editor gained focus in window\" << this;\n emit editorFocusChanged(this, true);\n } else if (event->type() == QEvent::FocusOut) {\n // qDebug() << \"MarkdownWindow::eventFilter() - Editor lost focus in window\" << this;\n emit editorFocusChanged(this, false);\n }\n } else if (obj == parentWidget() && event->type() == QEvent::Resize) {\n // Canvas widget was resized (likely due to layout changes like showing/hiding sidebars)\n // Update our screen position to maintain canvas position\n QTimer::singleShot(0, this, [this]() {\n updateScreenPosition();\n });\n }\n return QWidget::eventFilter(obj, event);\n}\n private:\n void onDeleteClicked() {\n emit deleteRequested(this);\n}\n void onMarkdownTextChanged() {\n emit contentChanged();\n}\n private:\n enum ResizeHandle {\n None,\n TopLeft,\n TopRight,\n BottomLeft,\n BottomRight,\n Top,\n Bottom,\n Left,\n Right\n };\n QMarkdownTextEdit *markdownEditor;\n QPushButton *deleteButton;\n QLabel *titleLabel;\n QVBoxLayout *mainLayout;\n QHBoxLayout *headerLayout;\n bool dragging = false;\n QPoint dragStartPosition;\n QPoint windowStartPosition;\n bool resizing = false;\n QPoint resizeStartPosition;\n QRect resizeStartRect;\n ResizeHandle currentResizeHandle = None;\n QRect canvasRect;\n bool isTransparentState = false;\n bool isUpdatingPosition = false;\n bool isUserInteracting = false;\n ResizeHandle getResizeHandle(const QPoint &pos) const {\n const int handleSize = 8;\n const QRect rect = this->rect();\n \n // Check corner handles first\n if (QRect(0, 0, handleSize, handleSize).contains(pos))\n return TopLeft;\n if (QRect(rect.width() - handleSize, 0, handleSize, handleSize).contains(pos))\n return TopRight;\n if (QRect(0, rect.height() - handleSize, handleSize, handleSize).contains(pos))\n return BottomLeft;\n if (QRect(rect.width() - handleSize, rect.height() - handleSize, handleSize, handleSize).contains(pos))\n return BottomRight;\n \n // Check edge handles\n if (QRect(0, 0, rect.width(), handleSize).contains(pos))\n return Top;\n if (QRect(0, rect.height() - handleSize, rect.width(), handleSize).contains(pos))\n return Bottom;\n if (QRect(0, 0, handleSize, rect.height()).contains(pos))\n return Left;\n if (QRect(rect.width() - handleSize, 0, handleSize, rect.height()).contains(pos))\n return Right;\n \n return None;\n}\n void updateCursor(const QPoint &pos) {\n ResizeHandle handle = getResizeHandle(pos);\n \n switch (handle) {\n case TopLeft:\n case BottomRight:\n setCursor(Qt::SizeFDiagCursor);\n break;\n case TopRight:\n case BottomLeft:\n setCursor(Qt::SizeBDiagCursor);\n break;\n case Top:\n case Bottom:\n setCursor(Qt::SizeVerCursor);\n break;\n case Left:\n case Right:\n setCursor(Qt::SizeHorCursor);\n break;\n default:\n if (pos.y() < 24) { // Header area\n setCursor(Qt::SizeAllCursor);\n } else {\n setCursor(Qt::ArrowCursor);\n }\n break;\n }\n}\n void setupUI() {\n mainLayout = new QVBoxLayout(this);\n mainLayout->setContentsMargins(2, 2, 2, 2);\n mainLayout->setSpacing(0);\n \n // Header with title and delete button\n headerLayout = new QHBoxLayout();\n headerLayout->setContentsMargins(4, 2, 4, 2);\n headerLayout->setSpacing(4);\n \n titleLabel = new QLabel(\"Markdown\", this);\n titleLabel->setStyleSheet(\"font-weight: bold; color: #333;\");\n \n deleteButton = new QPushButton(\"×\", this);\n deleteButton->setFixedSize(16, 16);\n deleteButton->setStyleSheet(R\"(\n QPushButton {\n background-color: #ff4444;\n color: white;\n border: none;\n border-radius: 8px;\n font-weight: bold;\n font-size: 10px;\n }\n QPushButton:hover {\n background-color: #ff6666;\n }\n QPushButton:pressed {\n background-color: #cc2222;\n }\n )\");\n \n connect(deleteButton, &QPushButton::clicked, this, &MarkdownWindow::onDeleteClicked);\n \n headerLayout->addWidget(titleLabel);\n headerLayout->addStretch();\n headerLayout->addWidget(deleteButton);\n \n // Markdown editor\n markdownEditor = new QMarkdownTextEdit(this);\n markdownEditor->setPlainText(\"\"); // Start with empty content\n \n connect(markdownEditor, &QMarkdownTextEdit::textChanged, this, &MarkdownWindow::onMarkdownTextChanged);\n \n // Connect editor focus events using event filter\n markdownEditor->installEventFilter(this);\n \n mainLayout->addLayout(headerLayout);\n mainLayout->addWidget(markdownEditor);\n}\n void applyStyle() {\n // Detect dark mode using the same method as MainWindow\n bool isDarkMode = palette().color(QPalette::Window).lightness() < 128;\n \n QString backgroundColor = isDarkMode ? \"#2b2b2b\" : \"white\";\n QString borderColor = isDarkMode ? \"#555555\" : \"#cccccc\";\n QString headerBackgroundColor = isDarkMode ? \"#3c3c3c\" : \"#f0f0f0\";\n QString focusBorderColor = isDarkMode ? \"#6ca9dc\" : \"#4a90e2\";\n \n setStyleSheet(QString(R\"(\n MarkdownWindow {\n background-color: %1;\n border: 2px solid %2;\n border-radius: 4px;\n }\n MarkdownWindow:focus {\n border-color: %3;\n }\n )\").arg(backgroundColor, borderColor, focusBorderColor));\n \n // Style the header\n if (headerLayout && headerLayout->parentWidget()) {\n headerLayout->parentWidget()->setStyleSheet(QString(R\"(\n background-color: %1;\n border-bottom: 1px solid %2;\n )\").arg(headerBackgroundColor, borderColor));\n }\n \n // Reset the markdown editor style to default (opaque)\n if (markdownEditor) {\n markdownEditor->setStyleSheet(\"\"); // Clear any custom styles\n }\n}\n void applyTransparentStyle() {\n // Detect dark mode using the same method as MainWindow\n bool isDarkMode = palette().color(QPalette::Window).lightness() < 128;\n \n QString backgroundColor = isDarkMode ? \"rgba(43, 43, 43, 0.3)\" : \"rgba(255, 255, 255, 0.3)\"; // 30% opacity\n QString borderColor = isDarkMode ? \"#555555\" : \"#cccccc\";\n QString headerBackgroundColor = isDarkMode ? \"rgba(60, 60, 60, 0.3)\" : \"rgba(240, 240, 240, 0.3)\"; // 30% opacity\n QString focusBorderColor = isDarkMode ? \"#6ca9dc\" : \"#4a90e2\";\n \n setStyleSheet(QString(R\"(\n MarkdownWindow {\n background-color: %1;\n border: 2px solid %2;\n border-radius: 4px;\n }\n MarkdownWindow:focus {\n border-color: %3;\n }\n )\").arg(backgroundColor, borderColor, focusBorderColor));\n \n // Style the header with transparency\n if (headerLayout && headerLayout->parentWidget()) {\n headerLayout->parentWidget()->setStyleSheet(QString(R\"(\n background-color: %1;\n border-bottom: 1px solid %2;\n )\").arg(headerBackgroundColor, borderColor));\n }\n \n // Make the markdown editor background semi-transparent too\n if (markdownEditor) {\n QString editorBg = isDarkMode ? \"rgba(43, 43, 43, 0.3)\" : \"rgba(255, 255, 255, 0.3)\";\n markdownEditor->setStyleSheet(QString(R\"(\n QMarkdownTextEdit {\n background-color: %1;\n border: none;\n }\n )\").arg(editorBg));\n }\n}\n void convertScreenToCanvasRect(const QRect &screenRect) {\n // Get the canvas parent to access coordinate conversion methods\n if (QWidget *canvas = parentWidget()) {\n // Try to cast to InkCanvas to use the new coordinate methods\n if (InkCanvas *inkCanvas = qobject_cast(canvas)) {\n // Use the new coordinate conversion methods\n QRect oldCanvasRect = canvasRect;\n QRect newCanvasRect = inkCanvas->mapWidgetToCanvas(screenRect);\n \n // Store the converted canvas coordinates without bounds checking\n // Bounds checking should only happen during user interaction (dragging/resizing)\n canvasRect = newCanvasRect;\n // Only log if there was a significant change (and not during mouse movement)\n if ((canvasRect.topLeft() - oldCanvasRect.topLeft()).manhattanLength() > 10 && !dragging && !resizing) {\n // qDebug() << \"MarkdownWindow::convertScreenToCanvasRect() - Screen rect:\" << screenRect << \"-> Canvas rect:\" << canvasRect;\n // qDebug() << \" Old canvas rect:\" << oldCanvasRect;\n }\n } else {\n // Fallback: use screen coordinates directly\n // qDebug() << \"MarkdownWindow::convertScreenToCanvasRect() - No InkCanvas parent, using screen rect directly:\" << screenRect;\n canvasRect = screenRect;\n }\n } else {\n // No parent, use screen coordinates directly\n // qDebug() << \"MarkdownWindow::convertScreenToCanvasRect() - No parent, using screen rect directly:\" << screenRect;\n canvasRect = screenRect;\n }\n}\n};"], ["/SpeedyNote/source/ControlPanelDialog.h", "class ControlPanelDialog {\n Q_OBJECT\n\npublic:\n explicit ControlPanelDialog(MainWindow *mainWindow, InkCanvas *targetCanvas, QWidget *parent = nullptr);\n private:\n void applyChanges() {\n if (!canvas) return;\n\n BackgroundStyle style = static_cast(\n styleCombo->currentData().toInt()\n );\n\n canvas->setBackgroundStyle(style);\n canvas->setBackgroundColor(selectedColor);\n canvas->setBackgroundDensity(densitySpin->value());\n canvas->update();\n canvas->saveBackgroundMetadata();\n\n // ✅ Save these settings as defaults for new tabs\n if (mainWindowRef) {\n mainWindowRef->saveDefaultBackgroundSettings(style, selectedColor, densitySpin->value());\n }\n\n // ✅ Apply button mappings back to MainWindow with internal keys\n if (mainWindowRef) {\n for (const QString &buttonKey : holdMappingCombos.keys()) {\n QString displayString = holdMappingCombos[buttonKey]->currentText();\n QString internalKey = ButtonMappingHelper::displayToInternalKey(displayString, true); // true = isDialMode\n mainWindowRef->setHoldMapping(buttonKey, internalKey);\n }\n for (const QString &buttonKey : pressMappingCombos.keys()) {\n QString displayString = pressMappingCombos[buttonKey]->currentText();\n QString internalKey = ButtonMappingHelper::displayToInternalKey(displayString, false); // false = isAction\n mainWindowRef->setPressMapping(buttonKey, internalKey);\n }\n\n // ✅ Save to persistent settings\n mainWindowRef->saveButtonMappings();\n \n // ✅ Apply theme settings\n mainWindowRef->setUseCustomAccentColor(useCustomAccentCheckbox->isChecked());\n if (selectedAccentColor.isValid()) {\n mainWindowRef->setCustomAccentColor(selectedAccentColor);\n }\n \n // ✅ Apply color palette setting\n mainWindowRef->setUseBrighterPalette(useBrighterPaletteCheckbox->isChecked());\n }\n}\n void chooseColor() {\n QColor chosen = QColorDialog::getColor(selectedColor, this, tr(\"Select Background Color\"));\n if (chosen.isValid()) {\n selectedColor = chosen;\n colorButton->setStyleSheet(QString(\"background-color: %1\").arg(selectedColor.name()));\n }\n}\n void addKeyboardMapping() {\n // Step 1: Capture key sequence\n KeyCaptureDialog captureDialog(this);\n if (captureDialog.exec() != QDialog::Accepted) {\n return;\n }\n \n QString keySequence = captureDialog.getCapturedKeySequence();\n if (keySequence.isEmpty()) {\n return;\n }\n \n // Check if key sequence already exists\n if (mainWindowRef && mainWindowRef->getKeyboardMappings().contains(keySequence)) {\n QMessageBox::warning(this, tr(\"Key Already Mapped\"), \n tr(\"The key sequence '%1' is already mapped. Please choose a different key combination.\").arg(keySequence));\n return;\n }\n \n // Step 2: Choose action\n QStringList actions = ButtonMappingHelper::getTranslatedActions();\n bool ok;\n QString selectedAction = QInputDialog::getItem(this, tr(\"Select Action\"), \n tr(\"Choose the action to perform when '%1' is pressed:\").arg(keySequence), \n actions, 0, false, &ok);\n \n if (!ok || selectedAction.isEmpty()) {\n return;\n }\n \n // Convert display name to internal key\n QString internalKey = ButtonMappingHelper::displayToInternalKey(selectedAction, false);\n \n // Add the mapping\n if (mainWindowRef) {\n mainWindowRef->addKeyboardMapping(keySequence, internalKey);\n \n // Update table\n int row = keyboardTable->rowCount();\n keyboardTable->insertRow(row);\n keyboardTable->setItem(row, 0, new QTableWidgetItem(keySequence));\n keyboardTable->setItem(row, 1, new QTableWidgetItem(selectedAction));\n }\n}\n void removeKeyboardMapping() {\n int currentRow = keyboardTable->currentRow();\n if (currentRow < 0) {\n QMessageBox::information(this, tr(\"No Selection\"), tr(\"Please select a mapping to remove.\"));\n return;\n }\n \n QTableWidgetItem *keyItem = keyboardTable->item(currentRow, 0);\n if (!keyItem) return;\n \n QString keySequence = keyItem->text();\n \n // Confirm removal\n int ret = QMessageBox::question(this, tr(\"Remove Mapping\"), \n tr(\"Are you sure you want to remove the keyboard shortcut '%1'?\").arg(keySequence),\n QMessageBox::Yes | QMessageBox::No, QMessageBox::No);\n \n if (ret == QMessageBox::Yes) {\n // Remove from MainWindow\n if (mainWindowRef) {\n mainWindowRef->removeKeyboardMapping(keySequence);\n }\n \n // Remove from table\n keyboardTable->removeRow(currentRow);\n }\n}\n void openControllerMapping() {\n if (!mainWindowRef) {\n QMessageBox::warning(this, tr(\"Error\"), tr(\"MainWindow reference not available.\"));\n return;\n }\n \n SDLControllerManager *controllerManager = mainWindowRef->getControllerManager();\n if (!controllerManager) {\n QMessageBox::warning(this, tr(\"Controller Not Available\"), \n tr(\"Controller manager is not available. Please ensure a controller is connected and restart the application.\"));\n return;\n }\n \n if (!controllerManager->getJoystick()) {\n QMessageBox::warning(this, tr(\"No Controller Detected\"), \n tr(\"No controller is currently connected. Please connect your controller and restart the application.\"));\n return;\n }\n \n ControllerMappingDialog dialog(controllerManager, this);\n dialog.exec();\n}\n void reconnectController() {\n if (!mainWindowRef) {\n QMessageBox::warning(this, tr(\"Error\"), tr(\"MainWindow reference not available.\"));\n return;\n }\n \n SDLControllerManager *controllerManager = mainWindowRef->getControllerManager();\n if (!controllerManager) {\n QMessageBox::warning(this, tr(\"Controller Not Available\"), \n tr(\"Controller manager is not available.\"));\n return;\n }\n \n // Show reconnecting message\n controllerStatusLabel->setText(tr(\"🔄 Reconnecting...\"));\n controllerStatusLabel->setStyleSheet(\"color: orange;\");\n \n // Force the UI to update immediately\n QApplication::processEvents();\n \n // Attempt to reconnect using thread-safe method\n QMetaObject::invokeMethod(controllerManager, \"reconnect\", Qt::BlockingQueuedConnection);\n \n // Update status after reconnection attempt\n updateControllerStatus();\n \n // Show result message\n if (controllerManager->getJoystick()) {\n // Reconnect the controller signals in MainWindow\n mainWindowRef->reconnectControllerSignals();\n \n QMessageBox::information(this, tr(\"Reconnection Successful\"), \n tr(\"Controller has been successfully reconnected!\"));\n } else {\n QMessageBox::warning(this, tr(\"Reconnection Failed\"), \n tr(\"Failed to reconnect controller. Please ensure your controller is powered on and in pairing mode, then try again.\"));\n }\n}\n private:\n InkCanvas *canvas;\n QTabWidget *tabWidget;\n QWidget *backgroundTab;\n QComboBox *styleCombo;\n QPushButton *colorButton;\n QSpinBox *densitySpin;\n QPushButton *applyButton;\n QPushButton *okButton;\n QPushButton *cancelButton;\n QColor selectedColor;\n void createBackgroundTab() {\n backgroundTab = new QWidget(this);\n\n QLabel *styleLabel = new QLabel(tr(\"Background Style:\"));\n styleCombo = new QComboBox();\n styleCombo->addItem(tr(\"None\"), static_cast(BackgroundStyle::None));\n styleCombo->addItem(tr(\"Grid\"), static_cast(BackgroundStyle::Grid));\n styleCombo->addItem(tr(\"Lines\"), static_cast(BackgroundStyle::Lines));\n\n QLabel *colorLabel = new QLabel(tr(\"Background Color:\"));\n colorButton = new QPushButton();\n connect(colorButton, &QPushButton::clicked, this, &ControlPanelDialog::chooseColor);\n\n QLabel *densityLabel = new QLabel(tr(\"Density:\"));\n densitySpin = new QSpinBox();\n densitySpin->setRange(10, 200);\n densitySpin->setSuffix(\" px\");\n densitySpin->setSingleStep(5);\n\n QGridLayout *layout = new QGridLayout(backgroundTab);\n layout->addWidget(styleLabel, 0, 0);\n layout->addWidget(styleCombo, 0, 1);\n layout->addWidget(colorLabel, 1, 0);\n layout->addWidget(colorButton, 1, 1);\n layout->addWidget(densityLabel, 2, 0);\n layout->addWidget(densitySpin, 2, 1);\n // layout->setColumnStretch(1, 1); // Stretch the second column\n layout->setRowStretch(3, 1); // Stretch the last row\n}\n void loadFromCanvas() {\n styleCombo->setCurrentIndex(static_cast(canvas->getBackgroundStyle()));\n densitySpin->setValue(canvas->getBackgroundDensity());\n selectedColor = canvas->getBackgroundColor();\n\n colorButton->setStyleSheet(QString(\"background-color: %1\").arg(selectedColor.name()));\n\n if (mainWindowRef) {\n for (const QString &buttonKey : holdMappingCombos.keys()) {\n QString internalKey = mainWindowRef->getHoldMapping(buttonKey);\n QString displayString = ButtonMappingHelper::internalKeyToDisplay(internalKey, true); // true = isDialMode\n int index = holdMappingCombos[buttonKey]->findText(displayString);\n if (index >= 0) holdMappingCombos[buttonKey]->setCurrentIndex(index);\n }\n\n for (const QString &buttonKey : pressMappingCombos.keys()) {\n QString internalKey = mainWindowRef->getPressMapping(buttonKey);\n QString displayString = ButtonMappingHelper::internalKeyToDisplay(internalKey, false); // false = isAction\n int index = pressMappingCombos[buttonKey]->findText(displayString);\n if (index >= 0) pressMappingCombos[buttonKey]->setCurrentIndex(index);\n }\n \n // Load theme settings\n useCustomAccentCheckbox->setChecked(mainWindowRef->isUsingCustomAccentColor());\n \n // Get the stored custom accent color\n selectedAccentColor = mainWindowRef->getCustomAccentColor();\n \n accentColorButton->setStyleSheet(QString(\"background-color: %1\").arg(selectedAccentColor.name()));\n accentColorButton->setEnabled(useCustomAccentCheckbox->isChecked());\n \n // Load color palette setting\n useBrighterPaletteCheckbox->setChecked(mainWindowRef->isUsingBrighterPalette());\n }\n}\n MainWindow *mainWindowRef;\n InkCanvas *canvasRef;\n QWidget *performanceTab;\n QWidget *toolbarTab;\n void createToolbarTab() {\n toolbarTab = new QWidget(this);\n QVBoxLayout *toolbarLayout = new QVBoxLayout(toolbarTab);\n\n // ✅ Checkbox to show/hide benchmark controls\n QCheckBox *benchmarkVisibilityCheckbox = new QCheckBox(tr(\"Show Benchmark Controls\"), toolbarTab);\n benchmarkVisibilityCheckbox->setChecked(mainWindowRef->areBenchmarkControlsVisible());\n toolbarLayout->addWidget(benchmarkVisibilityCheckbox);\n QLabel *benchmarkNote = new QLabel(tr(\"This will show/hide the benchmark controls on the toolbar. Press the clock button to start/stop the benchmark.\"));\n benchmarkNote->setWordWrap(true);\n benchmarkNote->setStyleSheet(\"color: gray; font-size: 10px;\");\n toolbarLayout->addWidget(benchmarkNote);\n\n // ✅ Checkbox to show/hide zoom buttons\n QCheckBox *zoomButtonsVisibilityCheckbox = new QCheckBox(tr(\"Show Zoom Buttons\"), toolbarTab);\n zoomButtonsVisibilityCheckbox->setChecked(mainWindowRef->areZoomButtonsVisible());\n toolbarLayout->addWidget(zoomButtonsVisibilityCheckbox);\n QLabel *zoomButtonsNote = new QLabel(tr(\"This will show/hide the 0.5x, 1x, and 2x zoom buttons on the toolbar\"));\n zoomButtonsNote->setWordWrap(true);\n zoomButtonsNote->setStyleSheet(\"color: gray; font-size: 10px;\");\n toolbarLayout->addWidget(zoomButtonsNote);\n\n QCheckBox *scrollOnTopCheckBox = new QCheckBox(tr(\"Scroll on Top after Page Switching\"), toolbarTab);\n scrollOnTopCheckBox->setChecked(mainWindowRef->isScrollOnTopEnabled());\n toolbarLayout->addWidget(scrollOnTopCheckBox);\n QLabel *scrollNote = new QLabel(tr(\"Enabling this will make the page scroll to the top after switching to a new page.\"));\n scrollNote->setWordWrap(true);\n scrollNote->setStyleSheet(\"color: gray; font-size: 10px;\");\n toolbarLayout->addWidget(scrollNote);\n \n toolbarLayout->addStretch();\n toolbarTab->setLayout(toolbarLayout);\n tabWidget->addTab(toolbarTab, tr(\"Features\"));\n\n\n // Connect the checkbox\n connect(benchmarkVisibilityCheckbox, &QCheckBox::toggled, mainWindowRef, &MainWindow::setBenchmarkControlsVisible);\n connect(zoomButtonsVisibilityCheckbox, &QCheckBox::toggled, mainWindowRef, &MainWindow::setZoomButtonsVisible);\n connect(scrollOnTopCheckBox, &QCheckBox::toggled, mainWindowRef, &MainWindow::setScrollOnTopEnabled);\n}\n void createPerformanceTab() {\n performanceTab = new QWidget();\n QVBoxLayout *layout = new QVBoxLayout(performanceTab);\n\n QCheckBox *previewToggle = new QCheckBox(tr(\"Enable Low-Resolution PDF Previews\"));\n previewToggle->setChecked(mainWindowRef->isLowResPreviewEnabled());\n\n connect(previewToggle, &QCheckBox::toggled, mainWindowRef, &MainWindow::setLowResPreviewEnabled);\n\n QLabel *note = new QLabel(tr(\"Disabling this may improve dial smoothness on low-end devices.\"));\n note->setWordWrap(true);\n note->setStyleSheet(\"color: gray; font-size: 10px;\");\n\n QLabel *dpiLabel = new QLabel(tr(\"PDF Rendering DPI:\"));\n QComboBox *dpiSelector = new QComboBox();\n dpiSelector->addItems({\"96\", \"192\", \"288\", \"384\", \"480\"});\n dpiSelector->setCurrentText(QString::number(mainWindowRef->getPdfDPI()));\n\n connect(dpiSelector, &QComboBox::currentTextChanged, this, [=](const QString &value) {\n mainWindowRef->setPdfDPI(value.toInt());\n });\n\n QLabel *notePDF = new QLabel(tr(\"Adjust how the PDF is rendered. Higher DPI means better quality but slower performance. DO NOT CHANGE THIS OPTION WHEN MULTIPLE TABS ARE OPEN. THIS MAY LEAD TO UNDEFINED BEHAVIOR!\"));\n notePDF->setWordWrap(true);\n notePDF->setStyleSheet(\"color: gray; font-size: 10px;\");\n\n\n layout->addWidget(previewToggle);\n layout->addWidget(note);\n layout->addWidget(dpiLabel);\n layout->addWidget(dpiSelector);\n layout->addWidget(notePDF);\n\n layout->addStretch();\n\n // return performanceTab;\n}\n QWidget *controllerMappingTab;\n QPushButton *reconnectButton;\n QLabel *controllerStatusLabel;\n QMap holdMappingCombos;\n QMap pressMappingCombos;\n void createButtonMappingTab() {\n QWidget *buttonTab = new QWidget(this);\n QVBoxLayout *layout = new QVBoxLayout(buttonTab);\n\n QStringList buttonKeys = ButtonMappingHelper::getInternalButtonKeys();\n QStringList buttonDisplayNames = ButtonMappingHelper::getTranslatedButtons();\n QStringList dialModes = ButtonMappingHelper::getTranslatedDialModes();\n QStringList actions = ButtonMappingHelper::getTranslatedActions();\n\n for (int i = 0; i < buttonKeys.size(); ++i) {\n const QString &buttonKey = buttonKeys[i];\n const QString &buttonDisplayName = buttonDisplayNames[i];\n \n QHBoxLayout *h = new QHBoxLayout();\n h->addWidget(new QLabel(buttonDisplayName)); // Use translated button name\n\n QComboBox *holdCombo = new QComboBox();\n holdCombo->addItems(dialModes); // Add translated dial mode names\n holdMappingCombos[buttonKey] = holdCombo;\n h->addWidget(new QLabel(tr(\"Hold:\")));\n h->addWidget(holdCombo);\n\n QComboBox *pressCombo = new QComboBox();\n pressCombo->addItems(actions); // Add translated action names\n pressMappingCombos[buttonKey] = pressCombo;\n h->addWidget(new QLabel(tr(\"Press:\")));\n h->addWidget(pressCombo);\n\n layout->addLayout(h);\n }\n\n layout->addStretch();\n buttonTab->setLayout(layout);\n tabWidget->addTab(buttonTab, tr(\"Button Mapping\"));\n}\n void createControllerMappingTab() {\n controllerMappingTab = new QWidget(this);\n QVBoxLayout *layout = new QVBoxLayout(controllerMappingTab);\n \n // Instructions\n QLabel *instructionLabel = new QLabel(tr(\"Configure physical controller button mappings for your Joy-Con or other controller:\"), controllerMappingTab);\n instructionLabel->setWordWrap(true);\n layout->addWidget(instructionLabel);\n \n QLabel *noteLabel = new QLabel(tr(\"Note: This maps your physical controller buttons to the logical Joy-Con functions used by the application. \"\n \"After setting up the physical mapping, you can configure what actions each logical button performs in the 'Button Mapping' tab.\"), controllerMappingTab);\n noteLabel->setWordWrap(true);\n noteLabel->setStyleSheet(\"color: gray; font-size: 10px; margin-bottom: 10px;\");\n layout->addWidget(noteLabel);\n \n // Button to open controller mapping dialog\n QPushButton *openMappingButton = new QPushButton(tr(\"Configure Controller Mapping\"), controllerMappingTab);\n openMappingButton->setMinimumHeight(40);\n connect(openMappingButton, &QPushButton::clicked, this, &ControlPanelDialog::openControllerMapping);\n layout->addWidget(openMappingButton);\n \n // Button to reconnect controller\n reconnectButton = new QPushButton(tr(\"Reconnect Controller\"), controllerMappingTab);\n reconnectButton->setMinimumHeight(40);\n reconnectButton->setStyleSheet(\"QPushButton { background-color: #4CAF50; color: white; font-weight: bold; }\");\n connect(reconnectButton, &QPushButton::clicked, this, &ControlPanelDialog::reconnectController);\n layout->addWidget(reconnectButton);\n \n // Status information\n QLabel *statusLabel = new QLabel(tr(\"Current controller status:\"), controllerMappingTab);\n statusLabel->setStyleSheet(\"font-weight: bold; margin-top: 20px;\");\n layout->addWidget(statusLabel);\n \n // Dynamic status label\n controllerStatusLabel = new QLabel(controllerMappingTab);\n updateControllerStatus();\n layout->addWidget(controllerStatusLabel);\n \n layout->addStretch();\n \n tabWidget->addTab(controllerMappingTab, tr(\"Controller Mapping\"));\n}\n void createKeyboardMappingTab() {\n keyboardTab = new QWidget(this);\n QVBoxLayout *layout = new QVBoxLayout(keyboardTab);\n \n // Instructions\n QLabel *instructionLabel = new QLabel(tr(\"Configure custom keyboard shortcuts for application actions:\"), keyboardTab);\n instructionLabel->setWordWrap(true);\n layout->addWidget(instructionLabel);\n \n // Table to show current mappings\n keyboardTable = new QTableWidget(0, 2, keyboardTab);\n keyboardTable->setHorizontalHeaderLabels({tr(\"Key Sequence\"), tr(\"Action\")});\n keyboardTable->horizontalHeader()->setStretchLastSection(true);\n keyboardTable->setSelectionBehavior(QAbstractItemView::SelectRows);\n keyboardTable->setEditTriggers(QAbstractItemView::NoEditTriggers);\n layout->addWidget(keyboardTable);\n \n // Buttons\n QHBoxLayout *buttonLayout = new QHBoxLayout();\n addKeyboardMappingButton = new QPushButton(tr(\"Add Mapping\"), keyboardTab);\n removeKeyboardMappingButton = new QPushButton(tr(\"Remove Mapping\"), keyboardTab);\n \n buttonLayout->addWidget(addKeyboardMappingButton);\n buttonLayout->addWidget(removeKeyboardMappingButton);\n buttonLayout->addStretch();\n \n layout->addLayout(buttonLayout);\n \n // Connections\n connect(addKeyboardMappingButton, &QPushButton::clicked, this, &ControlPanelDialog::addKeyboardMapping);\n connect(removeKeyboardMappingButton, &QPushButton::clicked, this, &ControlPanelDialog::removeKeyboardMapping);\n \n // Load current mappings\n if (mainWindowRef) {\n QMap mappings = mainWindowRef->getKeyboardMappings();\n keyboardTable->setRowCount(mappings.size());\n int row = 0;\n for (auto it = mappings.begin(); it != mappings.end(); ++it) {\n keyboardTable->setItem(row, 0, new QTableWidgetItem(it.key()));\n QString displayAction = ButtonMappingHelper::internalKeyToDisplay(it.value(), false);\n keyboardTable->setItem(row, 1, new QTableWidgetItem(displayAction));\n row++;\n }\n }\n \n tabWidget->addTab(keyboardTab, tr(\"Keyboard Shortcuts\"));\n}\n QWidget *keyboardTab;\n QTableWidget *keyboardTable;\n QPushButton *addKeyboardMappingButton;\n QPushButton *removeKeyboardMappingButton;\n QWidget *themeTab;\n QCheckBox *useCustomAccentCheckbox;\n QPushButton *accentColorButton;\n QColor selectedAccentColor;\n QCheckBox *useBrighterPaletteCheckbox;\n void createThemeTab() {\n themeTab = new QWidget(this);\n QVBoxLayout *layout = new QVBoxLayout(themeTab);\n \n // Custom accent color\n useCustomAccentCheckbox = new QCheckBox(tr(\"Use Custom Accent Color\"), themeTab);\n layout->addWidget(useCustomAccentCheckbox);\n \n QLabel *accentColorLabel = new QLabel(tr(\"Accent Color:\"), themeTab);\n accentColorButton = new QPushButton(themeTab);\n accentColorButton->setFixedSize(100, 30);\n connect(accentColorButton, &QPushButton::clicked, this, &ControlPanelDialog::chooseAccentColor);\n \n QHBoxLayout *accentColorLayout = new QHBoxLayout();\n accentColorLayout->addWidget(accentColorLabel);\n accentColorLayout->addWidget(accentColorButton);\n accentColorLayout->addStretch();\n layout->addLayout(accentColorLayout);\n \n QLabel *accentColorNote = new QLabel(tr(\"When enabled, use a custom accent color instead of the system accent color for the toolbar, dial, and tab selection.\"));\n accentColorNote->setWordWrap(true);\n accentColorNote->setStyleSheet(\"color: gray; font-size: 10px;\");\n layout->addWidget(accentColorNote);\n \n // Enable/disable accent color button based on checkbox\n connect(useCustomAccentCheckbox, &QCheckBox::toggled, accentColorButton, &QPushButton::setEnabled);\n connect(useCustomAccentCheckbox, &QCheckBox::toggled, accentColorLabel, &QLabel::setEnabled);\n \n // Color palette preference\n useBrighterPaletteCheckbox = new QCheckBox(tr(\"Use Brighter Color Palette\"), themeTab);\n layout->addWidget(useBrighterPaletteCheckbox);\n \n QLabel *paletteNote = new QLabel(tr(\"When enabled, use brighter colors (good for dark PDF backgrounds). When disabled, use darker colors (good for light PDF backgrounds). This setting is independent of the UI theme.\"));\n paletteNote->setWordWrap(true);\n paletteNote->setStyleSheet(\"color: gray; font-size: 10px;\");\n layout->addWidget(paletteNote);\n \n layout->addStretch();\n \n tabWidget->addTab(themeTab, tr(\"Theme\"));\n}\n void chooseAccentColor() {\n QColor chosen = QColorDialog::getColor(selectedAccentColor, this, tr(\"Select Accent Color\"));\n if (chosen.isValid()) {\n selectedAccentColor = chosen;\n accentColorButton->setStyleSheet(QString(\"background-color: %1\").arg(selectedAccentColor.name()));\n }\n}\n void updateControllerStatus() {\n if (!mainWindowRef || !controllerStatusLabel) return;\n \n SDLControllerManager *controllerManager = mainWindowRef->getControllerManager();\n if (!controllerManager) {\n controllerStatusLabel->setText(tr(\"✗ Controller manager not available\"));\n controllerStatusLabel->setStyleSheet(\"color: red;\");\n return;\n }\n \n if (controllerManager->getJoystick()) {\n controllerStatusLabel->setText(tr(\"✓ Controller connected\"));\n controllerStatusLabel->setStyleSheet(\"color: green; font-weight: bold;\");\n } else {\n controllerStatusLabel->setText(tr(\"✗ No controller detected\"));\n controllerStatusLabel->setStyleSheet(\"color: red; font-weight: bold;\");\n }\n}\n};"], ["/SpeedyNote/source/ControllerMappingDialog.h", "class SDLControllerManager {\n Q_OBJECT\n\npublic:\n explicit ControllerMappingDialog(SDLControllerManager *controllerManager, QWidget *parent = nullptr);\n private:\n void startButtonMapping(const QString &logicalButton) {\n if (!controller) return;\n \n // Disable all mapping buttons during mapping\n for (auto button : mappingButtons) {\n button->setEnabled(false);\n }\n \n // Update the current button being mapped\n currentMappingButton = logicalButton;\n mappingButtons[logicalButton]->setText(tr(\"Press button...\"));\n \n // Start button detection mode\n controller->startButtonDetection();\n \n // Start timeout timer\n mappingTimeoutTimer->start();\n \n // Show status message\n QApplication::setOverrideCursor(Qt::WaitCursor);\n}\n void onRawButtonPressed(int sdlButton, const QString &buttonName) {\n if (currentMappingButton.isEmpty()) return;\n \n // Stop detection and timeout\n controller->stopButtonDetection();\n mappingTimeoutTimer->stop();\n QApplication::restoreOverrideCursor();\n \n // Check if this button is already mapped to another function\n QMap currentMappings = controller->getAllPhysicalMappings();\n QString conflictingButton;\n for (auto it = currentMappings.begin(); it != currentMappings.end(); ++it) {\n if (it.value() == sdlButton && it.key() != currentMappingButton) {\n conflictingButton = it.key();\n break;\n }\n }\n \n if (!conflictingButton.isEmpty()) {\n int ret = QMessageBox::question(this, tr(\"Button Conflict\"), \n tr(\"The button '%1' is already mapped to '%2'.\\n\\nDo you want to reassign it to '%3'?\")\n .arg(buttonName).arg(conflictingButton).arg(currentMappingButton),\n QMessageBox::Yes | QMessageBox::No);\n \n if (ret != QMessageBox::Yes) {\n // Reset UI and return\n mappingButtons[currentMappingButton]->setText(tr(\"Map\"));\n for (auto button : mappingButtons) {\n button->setEnabled(true);\n }\n currentMappingButton.clear();\n return;\n }\n \n // Clear the conflicting mapping\n controller->setPhysicalButtonMapping(conflictingButton, -1);\n currentMappingLabels[conflictingButton]->setText(\"Not mapped\");\n currentMappingLabels[conflictingButton]->setStyleSheet(\"color: gray;\");\n }\n \n // Set the new mapping\n controller->setPhysicalButtonMapping(currentMappingButton, sdlButton);\n \n // Get appropriate text color for current theme\n QString textColor = isDarkMode() ? \"white\" : \"black\";\n \n // Update UI\n currentMappingLabels[currentMappingButton]->setText(buttonName);\n currentMappingLabels[currentMappingButton]->setStyleSheet(QString(\"color: %1; font-weight: bold;\").arg(textColor));\n mappingButtons[currentMappingButton]->setText(tr(\"Map\"));\n \n // Re-enable all buttons\n for (auto button : mappingButtons) {\n button->setEnabled(true);\n }\n \n currentMappingButton.clear();\n \n QMessageBox::information(this, tr(\"Mapping Complete\"), \n tr(\"Button '%1' has been successfully mapped!\").arg(buttonName));\n}\n void resetToDefaults() {\n int ret = QMessageBox::question(this, tr(\"Reset to Defaults\"), \n tr(\"Are you sure you want to reset all button mappings to their default values?\\n\\nThis will overwrite your current configuration.\"),\n QMessageBox::Yes | QMessageBox::No);\n \n if (ret == QMessageBox::Yes) {\n // Get default mappings and apply them\n QMap defaults = controller->getDefaultMappings();\n for (auto it = defaults.begin(); it != defaults.end(); ++it) {\n controller->setPhysicalButtonMapping(it.key(), it.value());\n }\n \n // Update display\n updateMappingDisplay();\n \n QMessageBox::information(this, tr(\"Reset Complete\"), \n tr(\"All button mappings have been reset to their default values.\"));\n }\n}\n void applyMappings() {\n // Mappings are already applied in real-time, just close the dialog\n accept();\n}\n private:\n SDLControllerManager *controller;\n QGridLayout *mappingLayout;\n QMap buttonLabels;\n QMap currentMappingLabels;\n QMap mappingButtons;\n QPushButton *resetButton;\n QPushButton *applyButton;\n QPushButton *cancelButton;\n QString currentMappingButton;\n QTimer *mappingTimeoutTimer;\n void setupUI() {\n QVBoxLayout *mainLayout = new QVBoxLayout(this);\n \n // Instructions\n QLabel *instructionLabel = new QLabel(tr(\"Map your physical controller buttons to Joy-Con functions.\\n\"\n \"Click 'Map' next to each function, then press the corresponding button on your controller.\"), this);\n instructionLabel->setWordWrap(true);\n instructionLabel->setStyleSheet(\"font-weight: bold; margin-bottom: 10px;\");\n mainLayout->addWidget(instructionLabel);\n \n // Mapping grid\n QWidget *mappingWidget = new QWidget(this);\n mappingLayout = new QGridLayout(mappingWidget);\n \n // Headers\n mappingLayout->addWidget(new QLabel(tr(\"Joy-Con Function\"), this), 0, 0);\n mappingLayout->addWidget(new QLabel(tr(\"Description\"), this), 0, 1);\n mappingLayout->addWidget(new QLabel(tr(\"Current Mapping\"), this), 0, 2);\n mappingLayout->addWidget(new QLabel(tr(\"Action\"), this), 0, 3);\n \n // Get logical button descriptions\n QMap descriptions = getLogicalButtonDescriptions();\n \n // Create mapping rows for each logical button\n QStringList logicalButtons = {\"LEFTSHOULDER\", \"RIGHTSHOULDER\", \"PADDLE2\", \"PADDLE4\", \n \"Y\", \"A\", \"B\", \"X\", \"LEFTSTICK\", \"START\", \"GUIDE\"};\n \n int row = 1;\n for (const QString &logicalButton : logicalButtons) {\n // Function name\n QLabel *functionLabel = new QLabel(logicalButton, this);\n functionLabel->setStyleSheet(\"font-weight: bold;\");\n buttonLabels[logicalButton] = functionLabel;\n mappingLayout->addWidget(functionLabel, row, 0);\n \n // Description\n QLabel *descLabel = new QLabel(descriptions.value(logicalButton, \"Unknown\"), this);\n descLabel->setWordWrap(true);\n mappingLayout->addWidget(descLabel, row, 1);\n \n // Current mapping display\n QLabel *currentLabel = new QLabel(\"Not mapped\", this);\n currentLabel->setStyleSheet(\"color: gray;\");\n currentMappingLabels[logicalButton] = currentLabel;\n mappingLayout->addWidget(currentLabel, row, 2);\n \n // Map button\n QPushButton *mapButton = new QPushButton(tr(\"Map\"), this);\n mappingButtons[logicalButton] = mapButton;\n connect(mapButton, &QPushButton::clicked, this, [this, logicalButton]() {\n startButtonMapping(logicalButton);\n });\n mappingLayout->addWidget(mapButton, row, 3);\n \n row++;\n }\n \n mainLayout->addWidget(mappingWidget);\n \n // Buttons\n QHBoxLayout *buttonLayout = new QHBoxLayout();\n \n resetButton = new QPushButton(tr(\"Reset to Defaults\"), this);\n connect(resetButton, &QPushButton::clicked, this, &ControllerMappingDialog::resetToDefaults);\n buttonLayout->addWidget(resetButton);\n \n buttonLayout->addStretch();\n \n applyButton = new QPushButton(tr(\"Apply\"), this);\n connect(applyButton, &QPushButton::clicked, this, &ControllerMappingDialog::applyMappings);\n buttonLayout->addWidget(applyButton);\n \n cancelButton = new QPushButton(tr(\"Cancel\"), this);\n connect(cancelButton, &QPushButton::clicked, this, &QDialog::reject);\n buttonLayout->addWidget(cancelButton);\n \n mainLayout->addLayout(buttonLayout);\n}\n QMap getLogicalButtonDescriptions() const {\n QMap descriptions;\n descriptions[\"LEFTSHOULDER\"] = tr(\"L Button (Left Shoulder)\");\n descriptions[\"RIGHTSHOULDER\"] = tr(\"ZL Button (Left Trigger)\");\n descriptions[\"PADDLE2\"] = tr(\"SL Button (Side Left)\");\n descriptions[\"PADDLE4\"] = tr(\"SR Button (Side Right)\");\n descriptions[\"Y\"] = tr(\"Up Arrow (D-Pad Up)\");\n descriptions[\"A\"] = tr(\"Down Arrow (D-Pad Down)\");\n descriptions[\"B\"] = tr(\"Left Arrow (D-Pad Left)\");\n descriptions[\"X\"] = tr(\"Right Arrow (D-Pad Right)\");\n descriptions[\"LEFTSTICK\"] = tr(\"Analog Stick Press\");\n descriptions[\"START\"] = tr(\"Minus Button (-)\");\n descriptions[\"GUIDE\"] = tr(\"Screenshot Button\");\n return descriptions;\n}\n void loadCurrentMappings() {\n QMap currentMappings = controller->getAllPhysicalMappings();\n \n // Get appropriate text color for current theme\n QString textColor = isDarkMode() ? \"white\" : \"black\";\n \n for (auto it = currentMappings.begin(); it != currentMappings.end(); ++it) {\n const QString &logicalButton = it.key();\n int physicalButton = it.value();\n \n if (currentMappingLabels.contains(logicalButton)) {\n QString physicalName = controller->getPhysicalButtonName(physicalButton);\n currentMappingLabels[logicalButton]->setText(physicalName);\n currentMappingLabels[logicalButton]->setStyleSheet(QString(\"color: %1; font-weight: bold;\").arg(textColor));\n }\n }\n}\n void updateMappingDisplay() {\n loadCurrentMappings();\n}\n bool isDarkMode() const {\n // Same logic as MainWindow::isDarkMode()\n QColor bg = palette().color(QPalette::Window);\n return bg.lightness() < 128; // Lightness scale: 0 (black) - 255 (white)\n}\n};"], ["/SpeedyNote/source/RecentNotebooksManager.h", "class InkCanvas {\n Q_OBJECT\n\npublic:\n explicit RecentNotebooksManager(QObject *parent = nullptr);\n void addRecentNotebook(const QString& folderPath, InkCanvas* canvasForPreview = nullptr) {\n if (folderPath.isEmpty()) return;\n\n // Remove if already exists to move it to the front\n recentNotebookPaths.removeAll(folderPath);\n recentNotebookPaths.prepend(folderPath);\n\n // Trim the list if it exceeds the maximum size\n while (recentNotebookPaths.size() > MAX_RECENT_NOTEBOOKS) {\n recentNotebookPaths.removeLast();\n }\n\n generateAndSaveCoverPreview(folderPath, canvasForPreview);\n saveRecentNotebooks();\n}\n QStringList getRecentNotebooks() const {\n return recentNotebookPaths;\n}\n QString getCoverImagePathForNotebook(const QString& folderPath) const {\n QString coverDir = getCoverImageDir();\n QString coverFileName = sanitizeFolderName(folderPath) + \"_cover.png\";\n QString coverFilePath = coverDir + coverFileName;\n if (QFile::exists(coverFilePath)) {\n return coverFilePath;\n }\n return \"\"; // Return empty if no cover exists\n}\n QString getNotebookDisplayName(const QString& folderPath) const {\n // Check for PDF metadata first\n QString metadataFile = folderPath + \"/.pdf_path.txt\";\n if (QFile::exists(metadataFile)) {\n QFile file(metadataFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString pdfPath = in.readLine().trimmed();\n file.close();\n if (!pdfPath.isEmpty()) {\n return QFileInfo(pdfPath).fileName();\n }\n }\n }\n // Fallback to folder name\n return QFileInfo(folderPath).fileName();\n}\n void generateAndSaveCoverPreview(const QString& folderPath, InkCanvas* optionalCanvas = nullptr) {\n QString coverDir = getCoverImageDir();\n QString coverFileName = sanitizeFolderName(folderPath) + \"_cover.png\";\n QString coverFilePath = coverDir + coverFileName;\n\n QImage coverImage(400, 300, QImage::Format_ARGB32_Premultiplied);\n coverImage.fill(Qt::white); // Default background\n QPainter painter(&coverImage);\n painter.setRenderHint(QPainter::SmoothPixmapTransform);\n\n if (optionalCanvas && optionalCanvas->width() > 0 && optionalCanvas->height() > 0) {\n int logicalCanvasWidth = optionalCanvas->width();\n int logicalCanvasHeight = optionalCanvas->height();\n\n double targetAspectRatio = 4.0 / 3.0;\n double canvasAspectRatio = (double)logicalCanvasWidth / logicalCanvasHeight;\n\n int grabWidth, grabHeight;\n int xOffset = 0, yOffset = 0;\n\n if (canvasAspectRatio > targetAspectRatio) { // Canvas is wider than target 4:3\n grabHeight = logicalCanvasHeight;\n grabWidth = qRound(logicalCanvasHeight * targetAspectRatio);\n xOffset = (logicalCanvasWidth - grabWidth) / 2;\n } else { // Canvas is taller than or equal to target 4:3\n grabWidth = logicalCanvasWidth;\n grabHeight = qRound(logicalCanvasWidth / targetAspectRatio);\n yOffset = (logicalCanvasHeight - grabHeight) / 2;\n }\n\n if (grabWidth > 0 && grabHeight > 0) {\n QRect grabRect(xOffset, yOffset, grabWidth, grabHeight);\n QPixmap capturedView = optionalCanvas->grab(grabRect);\n painter.drawPixmap(coverImage.rect(), capturedView, capturedView.rect());\n } else {\n // Fallback if calculated grab dimensions are invalid, draw placeholder or fill\n // This case should ideally not be hit if canvas width/height > 0\n painter.fillRect(coverImage.rect(), Qt::lightGray);\n painter.setPen(Qt::black);\n painter.drawText(coverImage.rect(), Qt::AlignCenter, tr(\"Preview Error\"));\n }\n } else {\n // Fallback: check for a saved \"annotated_..._00000.png\" or the first page\n // This part remains the same as it deals with pre-rendered images.\n QString notebookIdStr;\n InkCanvas tempCanvas(nullptr); // Temporary canvas to access potential notebookId property logic if it were there\n // However, notebookId is specific to an instance with a saveFolder.\n // For a generic fallback, we might need a different way or assume a common naming if notebookId is unknown.\n // For now, let's assume a simple naming or improve this fallback if needed.\n \n // Attempt to get notebookId if folderPath is a valid notebook with an ID file\n QFile idFile(folderPath + \"/.notebook_id.txt\");\n if (idFile.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&idFile);\n notebookIdStr = in.readLine().trimmed();\n idFile.close();\n }\n\n QString firstPagePath, firstAnnotatedPagePath;\n if (!notebookIdStr.isEmpty()) {\n firstPagePath = folderPath + QString(\"/%1_00000.png\").arg(notebookIdStr);\n firstAnnotatedPagePath = folderPath + QString(\"/annotated_%1_00000.png\").arg(notebookIdStr);\n } else {\n // Fallback if no ID, try a generic name (less ideal)\n // This situation should be rare if notebooks are managed properly\n // For robustness, one might iterate files or use a known default page name\n // For this example, we'll stick to a pattern that might not always work without an ID\n // Consider that `InkCanvas(nullptr).property(\"notebookId\")` was problematic as `notebookId` is instance specific.\n }\n\n QImage pageImage;\n if (!firstAnnotatedPagePath.isEmpty() && QFile::exists(firstAnnotatedPagePath)) {\n pageImage.load(firstAnnotatedPagePath);\n } else if (!firstPagePath.isEmpty() && QFile::exists(firstPagePath)) {\n pageImage.load(firstPagePath);\n }\n\n if (!pageImage.isNull()) {\n painter.drawImage(coverImage.rect(), pageImage, pageImage.rect());\n } else {\n // If no image found, draw a placeholder\n painter.fillRect(coverImage.rect(), Qt::darkGray);\n painter.setPen(Qt::white);\n painter.drawText(coverImage.rect(), Qt::AlignCenter, tr(\"No Page 0 Preview\"));\n }\n }\n coverImage.save(coverFilePath, \"PNG\");\n}\n private:\n void loadRecentNotebooks() {\n recentNotebookPaths = settings.value(\"recentNotebooks\").toStringList();\n}\n void saveRecentNotebooks() {\n settings.setValue(\"recentNotebooks\", recentNotebookPaths);\n}\n QString getCoverImageDir() const {\n return QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/RecentCovers/\";\n}\n QString sanitizeFolderName(const QString& folderPath) const {\n return QFileInfo(folderPath).baseName().replace(QRegularExpression(\"[^a-zA-Z0-9_]\"), \"_\");\n}\n QStringList recentNotebookPaths;\n const int MAX_RECENT_NOTEBOOKS = 16;\n QSettings settings;\n};"], ["/SpeedyNote/source/RecentNotebooksDialog.h", "class QPushButton {\n Q_OBJECT\n\npublic:\n explicit RecentNotebooksDialog(MainWindow *mainWindow, RecentNotebooksManager *manager, QWidget *parent = nullptr);\n private:\n void onNotebookClicked() {\n QPushButton *button = qobject_cast(sender());\n if (button) {\n QString notebookPath = button->property(\"notebookPath\").toString();\n if (!notebookPath.isEmpty() && mainWindowRef) {\n // This logic is similar to MainWindow::selectFolder but directly sets the folder.\n InkCanvas *canvas = mainWindowRef->currentCanvas(); // Get current canvas from MainWindow\n if (canvas) {\n if (canvas->isEdited()){\n mainWindowRef->saveCurrentPage(); // Use MainWindow's save method\n }\n canvas->setSaveFolder(notebookPath);\n mainWindowRef->switchPageWithDirection(1, 1); // Use MainWindow's direction-aware switchPage method\n mainWindowRef->pageInput->setValue(1); // Update pageInput in MainWindow\n mainWindowRef->updateTabLabel(); // Update tab label in MainWindow\n \n // Update recent notebooks list and refresh cover page\n if (notebookManager) {\n // Generate and save fresh cover preview\n notebookManager->generateAndSaveCoverPreview(notebookPath, canvas);\n // Add/update in recent list (this moves it to the top)\n notebookManager->addRecentNotebook(notebookPath, canvas);\n }\n }\n accept(); // Close the dialog\n }\n }\n}\n private:\n void setupUi() {\n QVBoxLayout *mainLayout = new QVBoxLayout(this);\n QScrollArea *scrollArea = new QScrollArea(this);\n scrollArea->setWidgetResizable(true);\n QWidget *gridContainer = new QWidget();\n gridLayout = new QGridLayout(gridContainer);\n gridLayout->setSpacing(15);\n\n scrollArea->setWidget(gridContainer);\n mainLayout->addWidget(scrollArea);\n setLayout(mainLayout);\n}\n void populateGrid() {\n QStringList recentPaths = notebookManager->getRecentNotebooks();\n int row = 0;\n int col = 0;\n const int numCols = 4;\n\n for (const QString &path : recentPaths) {\n if (path.isEmpty()) continue;\n\n QPushButton *button = new QPushButton(this);\n button->setFixedSize(180, 180); // Larger buttons\n button->setProperty(\"notebookPath\", path); // Store path for slot\n connect(button, &QPushButton::clicked, this, &RecentNotebooksDialog::onNotebookClicked);\n\n QVBoxLayout *buttonLayout = new QVBoxLayout(button);\n buttonLayout->setContentsMargins(5,5,5,5);\n\n QLabel *coverLabel = new QLabel(this);\n coverLabel->setFixedSize(170, 127); // 4:3 aspect ratio for cover\n coverLabel->setAlignment(Qt::AlignCenter);\n QString coverPath = notebookManager->getCoverImagePathForNotebook(path);\n if (!coverPath.isEmpty()) {\n QPixmap coverPixmap(coverPath);\n coverLabel->setPixmap(coverPixmap.scaled(coverLabel->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));\n } else {\n coverLabel->setText(tr(\"No Preview\"));\n }\n coverLabel->setStyleSheet(\"border: 1px solid gray;\");\n\n QLabel *nameLabel = new QLabel(notebookManager->getNotebookDisplayName(path), this);\n nameLabel->setAlignment(Qt::AlignCenter);\n nameLabel->setWordWrap(true);\n nameLabel->setFixedHeight(40); // Fixed height for name label\n\n buttonLayout->addWidget(coverLabel);\n buttonLayout->addWidget(nameLabel);\n button->setLayout(buttonLayout);\n\n gridLayout->addWidget(button, row, col);\n\n col++;\n if (col >= numCols) {\n col = 0;\n row++;\n }\n }\n}\n RecentNotebooksManager *notebookManager;\n QGridLayout *gridLayout;\n MainWindow *mainWindowRef;\n};"], ["/SpeedyNote/markdown/qmarkdowntextedit.h", "class LineNumArea {\n Q_OBJECT\n Q_PROPERTY(\n bool highlighting READ highlightingEnabled WRITE setHighlightingEnabled);\n friend class LineNumArea;\n public:\n enum AutoTextOption {\n None = 0x0000,\n\n // inserts closing characters for brackets and Markdown characters\n BracketClosing = 0x0001,\n\n // removes matching brackets and Markdown characters\n BracketRemoval = 0x0002\n };\n Q_DECLARE_FLAGS(AutoTextOptions, AutoTextOption);\n explicit QMarkdownTextEdit(QWidget *parent = nullptr,\n bool initHighlighter = true) {\n installEventFilter(this);\n viewport()->installEventFilter(this);\n _autoTextOptions = AutoTextOption::BracketClosing;\n\n _lineNumArea = new LineNumArea(this);\n updateLineNumberAreaWidth(0);\n\n // Markdown highlighting is enabled by default\n _highlightingEnabled = initHighlighter;\n if (initHighlighter) {\n _highlighter = new MarkdownHighlighter(document());\n }\n\n QFont font = this->font();\n\n // set the tab stop to the width of 4 spaces in the editor\n constexpr int tabStop = 4;\n QFontMetrics metrics(font);\n\n#if QT_VERSION < QT_VERSION_CHECK(5, 11, 0)\n setTabStopWidth(tabStop * metrics.width(' '));\n#else\n setTabStopDistance(tabStop * metrics.horizontalAdvance(QLatin1Char(' ')));\n#endif\n\n // add shortcuts for duplicating text\n // new QShortcut( QKeySequence( \"Ctrl+D\" ), this, SLOT( duplicateText() )\n // ); new QShortcut( QKeySequence( \"Ctrl+Alt+Down\" ), this, SLOT(\n // duplicateText() ) );\n\n // add a layout to the widget\n auto *layout = new QVBoxLayout(this);\n layout->setContentsMargins(0, 0, 0, 0);\n layout->addStretch();\n this->setLayout(layout);\n\n // add the hidden search widget\n _searchWidget = new QPlainTextEditSearchWidget(this);\n this->layout()->addWidget(_searchWidget);\n\n connect(this, &QPlainTextEdit::textChanged, this,\n &QMarkdownTextEdit::adjustRightMargin);\n connect(this, &QPlainTextEdit::cursorPositionChanged, this,\n &QMarkdownTextEdit::centerTheCursor);\n connect(verticalScrollBar(), &QScrollBar::valueChanged, this,\n [this](int) { _lineNumArea->update(); });\n connect(this, &QPlainTextEdit::cursorPositionChanged, this, [this]() {\n _lineNumArea->update();\n\n auto oldArea = blockBoundingGeometry(_textCursor.block())\n .translated(contentOffset());\n _textCursor = textCursor();\n auto newArea = blockBoundingGeometry(_textCursor.block())\n .translated(contentOffset());\n auto areaToUpdate = oldArea | newArea;\n viewport()->update(areaToUpdate.toRect());\n });\n connect(document(), &QTextDocument::blockCountChanged, this,\n &QMarkdownTextEdit::updateLineNumberAreaWidth);\n connect(this, &QPlainTextEdit::updateRequest, this,\n &QMarkdownTextEdit::updateLineNumberArea);\n\n updateSettings();\n\n // workaround for disabled signals up initialization\n QTimer::singleShot(300, this, &QMarkdownTextEdit::adjustRightMargin);\n}\n MarkdownHighlighter *highlighter();\n QPlainTextEditSearchWidget *searchWidget();\n void setIgnoredClickUrlSchemata(QStringList ignoredUrlSchemata) {\n _ignoredClickUrlSchemata = std::move(ignoredUrlSchemata);\n}\n virtual void openUrl(const QString &urlString) {\n qDebug() << \"QMarkdownTextEdit \" << __func__\n << \" - 'urlString': \" << urlString;\n\n QDesktopServices::openUrl(QUrl(urlString));\n}\n QString getMarkdownUrlAtPosition(const QString &text, int position) {\n QString url;\n\n // get a map of parsed Markdown urls with their link texts as key\n const QMap urlMap = parseMarkdownUrlsFromText(text);\n QMap::const_iterator i = urlMap.constBegin();\n for (; i != urlMap.constEnd(); ++i) {\n const QString &linkText = i.key();\n const QString &urlString = i.value();\n\n const int foundPositionStart = text.indexOf(linkText);\n\n if (foundPositionStart >= 0) {\n // calculate end position of found linkText\n const int foundPositionEnd = foundPositionStart + linkText.size();\n\n // check if position is in found string range\n if ((position >= foundPositionStart) &&\n (position <= foundPositionEnd)) {\n url = urlString;\n break;\n }\n }\n }\n\n return url;\n}\n void initSearchFrame(QWidget *searchFrame, bool darkMode = false) {\n _searchFrame = searchFrame;\n\n // remove the search widget from our layout\n layout()->removeWidget(_searchWidget);\n\n QLayout *layout = _searchFrame->layout();\n\n // create a grid layout for the frame and add the search widget to it\n if (layout == nullptr) {\n layout = new QVBoxLayout(_searchFrame);\n layout->setSpacing(0);\n layout->setContentsMargins(0, 0, 0, 0);\n }\n\n _searchWidget->setDarkMode(darkMode);\n layout->addWidget(_searchWidget);\n _searchFrame->setLayout(layout);\n}\n void setAutoTextOptions(AutoTextOptions options) {\n _autoTextOptions = options;\n}\n static bool isValidUrl(const QString &urlString) {\n static QRegularExpression regex(R\"(^\\w+:\\/\\/.+)\");\n const QRegularExpressionMatch match = regex.match(urlString);\n return match.hasMatch();\n}\n void resetMouseCursor() const {\n QWidget *viewPort = viewport();\n viewPort->setCursor(Qt::IBeamCursor);\n}\n void setReadOnly(bool ro) {\n QPlainTextEdit::setReadOnly(ro);\n\n // attempted to fix a problem with Chinese and Japanese input methods\n // @see https://github.com/pbek/QOwnNotes/issues/976\n setAttribute(Qt::WA_InputMethodEnabled, !isReadOnly());\n}\n void doSearch(QString &searchText,\n QPlainTextEditSearchWidget::SearchMode searchMode =\n QPlainTextEditSearchWidget::SearchMode::PlainTextMode) {\n _searchWidget->setSearchText(searchText);\n _searchWidget->setSearchMode(searchMode);\n _searchWidget->doSearchCount();\n _searchWidget->activate(false);\n}\n void hideSearchWidget(bool reset) {\n _searchWidget->deactivate();\n\n if (reset) {\n _searchWidget->reset();\n }\n}\n void updateSettings() {\n // if true: centers the screen if cursor reaches bottom (but not top)\n searchWidget()->setDebounceDelay(_debounceDelay);\n setCenterOnScroll(_centerCursor);\n}\n void setLineNumbersCurrentLineColor(QColor color) {\n _lineNumArea->setCurrentLineColor(std::move(color));\n}\n void setLineNumbersOtherLineColor(QColor color) {\n _lineNumArea->setOtherLineColor(std::move(color));\n}\n void setSearchWidgetDebounceDelay(uint debounceDelay) {\n _debounceDelay = debounceDelay;\n searchWidget()->setDebounceDelay(_debounceDelay);\n}\n void setHighlightingEnabled(bool enabled) {\n if (_highlightingEnabled == enabled || _highlighter == nullptr) {\n return;\n }\n\n _highlightingEnabled = enabled;\n _highlighter->setDocument(enabled ? document() : Q_NULLPTR);\n\n if (enabled) {\n _highlighter->rehighlight();\n }\n}\n [[nodiscard]] bool highlightingEnabled() const {\n return _highlightingEnabled && _highlighter != nullptr;\n}\n void setHighlightCurrentLine(bool set) {\n _highlightCurrentLine = set;\n}\n bool highlightCurrentLine() { return _highlightCurrentLine; }\n void setCurrentLineHighlightColor(const QColor &c) {\n _currentLineHighlightColor = color;\n}\n QColor currentLineHighlightColor() {\n return _currentLineHighlightColor;\n}\n public:\n void duplicateText() {\n if (isReadOnly()) {\n return;\n }\n\n QTextCursor cursor = this->textCursor();\n QString selectedText = cursor.selectedText();\n\n // duplicate line if no text was selected\n if (selectedText.isEmpty()) {\n const int position = cursor.position();\n\n // select the whole line\n cursor.movePosition(QTextCursor::StartOfBlock);\n cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);\n\n const int positionDiff = cursor.position() - position;\n selectedText = \"\\n\" + cursor.selectedText();\n\n // insert text with new line at end of the selected line\n cursor.setPosition(cursor.selectionEnd());\n cursor.insertText(selectedText);\n\n // set the position to same position it was in the duplicated line\n cursor.setPosition(cursor.position() - positionDiff);\n } else {\n // duplicate selected text\n cursor.setPosition(cursor.selectionEnd());\n const int selectionStart = cursor.position();\n\n // insert selected text\n cursor.insertText(selectedText);\n const int selectionEnd = cursor.position();\n\n // select the inserted text\n cursor.setPosition(selectionStart);\n cursor.setPosition(selectionEnd, QTextCursor::KeepAnchor);\n }\n\n this->setTextCursor(cursor);\n}\n void setText(const QString &text) { setPlainText(text); }\n void setPlainText(const QString &text) {\n // clear the dirty blocks vector to increase performance and prevent\n // a possible crash in QSyntaxHighlighter::rehighlightBlock\n if (_highlighter) _highlighter->clearDirtyBlocks();\n\n QPlainTextEdit::setPlainText(text);\n adjustRightMargin();\n}\n void adjustRightMargin() {\n QMargins margins = layout()->contentsMargins();\n const int rightMargin =\n document()->size().height() > viewport()->size().height() ? 24 : 0;\n margins.setRight(rightMargin);\n layout()->setContentsMargins(margins);\n}\n void hide() {\n _searchWidget->hide();\n QWidget::hide();\n}\n bool openLinkAtCursorPosition() {\n QTextCursor cursor = this->textCursor();\n const int clickedPosition = cursor.position();\n\n // select the text in the clicked block and find out on\n // which position we clicked\n cursor.movePosition(QTextCursor::StartOfBlock);\n const int positionFromStart = clickedPosition - cursor.position();\n cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);\n\n const QString selectedText = cursor.selectedText();\n\n // find out which url in the selected text was clicked\n const QString urlString =\n getMarkdownUrlAtPosition(selectedText, positionFromStart);\n const QUrl url = QUrl(urlString);\n const bool isRelativeFileUrl =\n urlString.startsWith(QLatin1String(\"file://..\"));\n const bool isLegacyAttachmentUrl =\n urlString.startsWith(QLatin1String(\"file://attachments\"));\n\n qDebug() << __func__ << \" - 'emit urlClicked( urlString )': \" << urlString;\n\n Q_EMIT urlClicked(urlString);\n\n if ((url.isValid() && isValidUrl(urlString)) || isRelativeFileUrl ||\n isLegacyAttachmentUrl) {\n // ignore some schemata\n if (!(_ignoredClickUrlSchemata.contains(url.scheme()) ||\n isRelativeFileUrl || isLegacyAttachmentUrl)) {\n // open the url\n openUrl(urlString);\n }\n\n return true;\n }\n\n return false;\n}\n bool handleBackspaceEntered() {\n if (!(_autoTextOptions & AutoTextOption::BracketRemoval) || isReadOnly()) {\n return false;\n }\n\n QTextCursor cursor = textCursor();\n\n // return if some text was selected\n if (!cursor.selectedText().isEmpty()) {\n return false;\n }\n\n int position = cursor.position();\n const int positionInBlock = cursor.positionInBlock();\n int block = cursor.block().blockNumber();\n\n if (_highlighter)\n if (_highlighter->isPosInACodeSpan(block, positionInBlock - 1))\n return false;\n\n // return if backspace was pressed at the beginning of a block\n if (positionInBlock == 0) {\n return false;\n }\n\n // get the current text from the block\n const QString text = cursor.block().text();\n\n char charToRemove{};\n\n // current char\n const char charInFront = text.at(positionInBlock - 1).toLatin1();\n\n if (charInFront == '*')\n return handleCharRemoval(MarkdownHighlighter::RangeType::Emphasis,\n block, positionInBlock - 1);\n else if (charInFront == '`')\n return handleCharRemoval(MarkdownHighlighter::RangeType::CodeSpan,\n block, positionInBlock - 1);\n\n // handle removal of \", ', and brackets\n\n // is it opener?\n int pos = _openingCharacters.indexOf(charInFront);\n // for \" and '\n bool isOpener = false;\n bool isCloser = false;\n if (pos == 5 || pos == 6) {\n isOpener = isQuotOpener(positionInBlock - 1, text);\n } else {\n isOpener = pos != -1;\n }\n if (isOpener) {\n charToRemove = _closingCharacters.at(pos);\n } else {\n // is it closer?\n pos = _closingCharacters.indexOf(charInFront);\n if (pos == 5 || pos == 6)\n isCloser = isQuotCloser(positionInBlock - 1, text);\n else\n isCloser = pos != -1;\n if (isCloser)\n charToRemove = _openingCharacters.at(pos);\n else\n return false;\n }\n\n int charToRemoveIndex = -1;\n if (isOpener) {\n bool closer = true;\n charToRemoveIndex = text.indexOf(charToRemove, positionInBlock);\n if (charToRemoveIndex == -1) return false;\n if (pos == 5 || pos == 6)\n closer = isQuotCloser(charToRemoveIndex, text);\n if (!closer) return false;\n cursor.setPosition(position + (charToRemoveIndex - positionInBlock));\n cursor.deleteChar();\n } else if (isCloser) {\n charToRemoveIndex = text.lastIndexOf(charToRemove, positionInBlock - 2);\n if (charToRemoveIndex == -1) return false;\n bool opener = true;\n if (pos == 5 || pos == 6)\n opener = isQuotOpener(charToRemoveIndex, text);\n if (!opener) return false;\n const int pos = position - (positionInBlock - charToRemoveIndex);\n cursor.setPosition(pos);\n cursor.deleteChar();\n position -= 1;\n } else {\n charToRemoveIndex = text.lastIndexOf(charToRemove, positionInBlock - 2);\n if (charToRemoveIndex == -1) return false;\n const int pos = position - (positionInBlock - charToRemoveIndex);\n cursor.setPosition(pos);\n cursor.deleteChar();\n position -= 1;\n }\n\n // moving the cursor back to the old position so the previous character\n // can be removed\n cursor.setPosition(position);\n setTextCursor(cursor);\n return false;\n}\n void centerTheCursor() {\n if (_mouseButtonDown || !_centerCursor) {\n return;\n }\n\n // Centers the cursor every time, but not on the top and bottom,\n // bottom is done by setCenterOnScroll() in updateSettings()\n centerCursor();\n\n /*\n QRect cursor = cursorRect();\n QRect vp = viewport()->rect();\n\n qDebug() << __func__ << \" - 'cursor.top': \" << cursor.top();\n qDebug() << __func__ << \" - 'cursor.bottom': \" << cursor.bottom();\n qDebug() << __func__ << \" - 'vp': \" << vp.bottom();\n\n int bottom = 0;\n int top = 0;\n\n qDebug() << __func__ << \" - 'viewportMargins().top()': \"\n << viewportMargins().top();\n\n qDebug() << __func__ << \" - 'viewportMargins().bottom()': \"\n << viewportMargins().bottom();\n\n int vpBottom = viewportMargins().top() + viewportMargins().bottom() +\n vp.bottom(); int vpCenter = vpBottom / 2; int cBottom = cursor.bottom() +\n viewportMargins().top();\n\n qDebug() << __func__ << \" - 'vpBottom': \" << vpBottom;\n qDebug() << __func__ << \" - 'vpCenter': \" << vpCenter;\n qDebug() << __func__ << \" - 'cBottom': \" << cBottom;\n\n\n if (cBottom >= vpCenter) {\n bottom = cBottom + viewportMargins().top() / 2 +\n viewportMargins().bottom() / 2 - (vp.bottom() / 2);\n // bottom = cBottom - (vp.bottom() / 2);\n // bottom *= 1.5;\n }\n\n // setStyleSheet(QString(\"QPlainTextEdit {padding-bottom:\n %1px;}\").arg(QString::number(bottom)));\n\n // if (cursor.top() < (vp.bottom() / 2)) {\n // top = (vp.bottom() / 2) - cursor.top() + viewportMargins().top() /\n 2 + viewportMargins().bottom() / 2;\n //// top *= -1;\n //// bottom *= 1.5;\n // }\n qDebug() << __func__ << \" - 'top': \" << top;\n qDebug() << __func__ << \" - 'bottom': \" << bottom;\n setViewportMargins(0,top,0, bottom);\n\n\n // QScrollBar* scrollbar = verticalScrollBar();\n //\n // qDebug() << __func__ << \" - 'scrollbar->value();': \" <<\n scrollbar->value();;\n // qDebug() << __func__ << \" - 'scrollbar->maximum();': \"\n // << scrollbar->maximum();;\n\n\n // scrollbar->setValue(scrollbar->value() - offset.y());\n //\n // setViewportMargins\n\n // setViewportMargins(0, 0, 0, bottom);\n */\n}\n void undo() {\n if (isReadOnly()) {\n return;\n }\n\n QTextCursor cursor = textCursor();\n // if no text selected, call undo\n if (!cursor.hasSelection()) {\n QPlainTextEdit::undo();\n return;\n }\n\n // if text is selected and bracket closing was used\n // we retain our selection\n if (_handleBracketClosingUsed) {\n // get the selection\n int selectionEnd = cursor.selectionEnd();\n int selectionStart = cursor.selectionStart();\n // call undo\n QPlainTextEdit::undo();\n // select again\n cursor.setPosition(selectionStart - 1);\n cursor.setPosition(selectionEnd - 1, QTextCursor::KeepAnchor);\n this->setTextCursor(cursor);\n _handleBracketClosingUsed = false;\n } else {\n // if text was selected but bracket closing wasn't used\n // do normal undo\n QPlainTextEdit::undo();\n return;\n }\n}\n void moveTextUpDown(bool up) {\n if (isReadOnly()) {\n return;\n }\n\n QTextCursor cursor = textCursor();\n QTextCursor move = cursor;\n\n move.setVisualNavigation(false);\n\n move.beginEditBlock(); // open an edit block to keep undo operations sane\n bool hasSelection = cursor.hasSelection();\n\n if (hasSelection) {\n // if there's a selection inside the block, we select the whole block\n move.setPosition(cursor.selectionStart());\n move.movePosition(QTextCursor::StartOfBlock);\n move.setPosition(cursor.selectionEnd(), QTextCursor::KeepAnchor);\n move.movePosition(\n move.atBlockStart() ? QTextCursor::Left : QTextCursor::EndOfBlock,\n QTextCursor::KeepAnchor);\n } else {\n move.movePosition(QTextCursor::StartOfBlock);\n move.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);\n }\n\n // get the text of the current block\n QString text = move.selectedText();\n\n move.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor);\n move.removeSelectedText();\n\n if (up) { // up key\n move.movePosition(QTextCursor::PreviousBlock);\n move.insertBlock();\n move.movePosition(QTextCursor::Left);\n } else { // down key\n move.movePosition(QTextCursor::EndOfBlock);\n if (move.atBlockStart()) { // empty block\n move.movePosition(QTextCursor::NextBlock);\n move.insertBlock();\n move.movePosition(QTextCursor::Left);\n } else {\n move.insertBlock();\n }\n }\n\n int start = move.position();\n move.clearSelection();\n move.insertText(text);\n int end = move.position();\n\n // reselect\n if (hasSelection) {\n move.setPosition(end);\n move.setPosition(start, QTextCursor::KeepAnchor);\n } else {\n move.setPosition(start);\n }\n\n move.endEditBlock();\n\n setTextCursor(move);\n}\n void setLineNumberEnabled(bool enabled) {\n _lineNumArea->setLineNumAreaEnabled(enabled);\n updateLineNumberAreaWidth(0);\n}\n protected:\n QTextCursor _textCursor;\n MarkdownHighlighter *_highlighter = nullptr;\n bool _highlightingEnabled;\n QStringList _ignoredClickUrlSchemata;\n QPlainTextEditSearchWidget *_searchWidget;\n QWidget *_searchFrame;\n AutoTextOptions _autoTextOptions;\n bool _mouseButtonDown = false;\n bool _centerCursor = false;\n bool _highlightCurrentLine = false;\n QColor _currentLineHighlightColor = QColor();\n uint _debounceDelay = 0;\n bool eventFilter(QObject *obj, QEvent *event) override {\n // qDebug() << event->type();\n if (event->type() == QEvent::HoverMove) {\n auto *mouseEvent = static_cast(event);\n\n QWidget *viewPort = this->viewport();\n // toggle cursor when control key has been pressed or released\n viewPort->setCursor(\n mouseEvent->modifiers().testFlag(Qt::ControlModifier)\n ? Qt::PointingHandCursor\n : Qt::IBeamCursor);\n } else if (event->type() == QEvent::KeyPress) {\n auto *keyEvent = static_cast(event);\n\n // set cursor to pointing hand if control key was pressed\n if (keyEvent->modifiers().testFlag(Qt::ControlModifier)) {\n QWidget *viewPort = this->viewport();\n viewPort->setCursor(Qt::PointingHandCursor);\n }\n\n // disallow keys if text edit hasn't focus\n if (!this->hasFocus()) {\n return true;\n }\n\n if ((keyEvent->key() == Qt::Key_Escape) && _searchWidget->isVisible()) {\n _searchWidget->deactivate();\n return true;\n } else if (keyEvent->key() == Qt::Key_Insert &&\n keyEvent->modifiers().testFlag(Qt::NoModifier)) {\n setOverwriteMode(!overwriteMode());\n\n // This solves a UI glitch if the visual cursor was not properly\n // updated when characters have different widths\n QTextCursor cursor = this->textCursor();\n cursor.movePosition(QTextCursor::Right);\n setTextCursor(cursor);\n cursor.movePosition(QTextCursor::Left);\n setTextCursor(cursor);\n\n return false;\n } else if ((keyEvent->key() == Qt::Key_Tab) ||\n (keyEvent->key() == Qt::Key_Backtab)) {\n // handle entered tab and reverse tab keys\n return handleTabEntered(keyEvent->key() == Qt::Key_Backtab);\n } else if ((keyEvent->key() == Qt::Key_F) &&\n keyEvent->modifiers().testFlag(Qt::ControlModifier)) {\n _searchWidget->activate();\n return true;\n } else if ((keyEvent->key() == Qt::Key_R) &&\n keyEvent->modifiers().testFlag(Qt::ControlModifier)) {\n _searchWidget->activateReplace();\n return true;\n // } else if (keyEvent->key() == Qt::Key_Delete) {\n } else if (keyEvent->key() == Qt::Key_Backspace) {\n return handleBackspaceEntered();\n } else if (keyEvent->key() == Qt::Key_Asterisk) {\n return handleBracketClosing(QLatin1Char('*'));\n } else if (keyEvent->key() == Qt::Key_QuoteDbl) {\n return quotationMarkCheck(QLatin1Char('\"'));\n // apostrophe bracket closing is temporary disabled because\n // apostrophes are used in different contexts\n // } else if (keyEvent->key() == Qt::Key_Apostrophe) {\n // return handleBracketClosing(\"'\");\n // underline bracket closing is temporary disabled because\n // underlines are used in different contexts\n // } else if (keyEvent->key() == Qt::Key_Underscore) {\n // return handleBracketClosing(\"_\");\n } else if (keyEvent->key() == Qt::Key_QuoteLeft) {\n return quotationMarkCheck(QLatin1Char('`'));\n } else if (keyEvent->key() == Qt::Key_AsciiTilde) {\n return handleBracketClosing(QLatin1Char('~'));\n#ifdef Q_OS_MAC\n } else if (keyEvent->modifiers().testFlag(Qt::AltModifier) &&\n keyEvent->key() == Qt::Key_ParenLeft) {\n // bracket closing for US keyboard on macOS\n return handleBracketClosing(QLatin1Char('{'), QLatin1Char('}'));\n#endif\n } else if (keyEvent->key() == Qt::Key_ParenLeft) {\n return handleBracketClosing(QLatin1Char('('), QLatin1Char(')'));\n } else if (keyEvent->key() == Qt::Key_BraceLeft) {\n return handleBracketClosing(QLatin1Char('{'), QLatin1Char('}'));\n } else if (keyEvent->key() == Qt::Key_BracketLeft) {\n return handleBracketClosing(QLatin1Char('['), QLatin1Char(']'));\n } else if (keyEvent->key() == Qt::Key_Less) {\n return handleBracketClosing(QLatin1Char('<'), QLatin1Char('>'));\n#ifdef Q_OS_MAC\n } else if (keyEvent->modifiers().testFlag(Qt::AltModifier) &&\n keyEvent->key() == Qt::Key_ParenRight) {\n // bracket closing for US keyboard on macOS\n return bracketClosingCheck(QLatin1Char('{'), QLatin1Char('}'));\n#endif\n } else if (keyEvent->key() == Qt::Key_ParenRight) {\n return bracketClosingCheck(QLatin1Char('('), QLatin1Char(')'));\n } else if (keyEvent->key() == Qt::Key_BraceRight) {\n return bracketClosingCheck(QLatin1Char('{'), QLatin1Char('}'));\n } else if (keyEvent->key() == Qt::Key_BracketRight) {\n return bracketClosingCheck(QLatin1Char('['), QLatin1Char(']'));\n } else if (keyEvent->key() == Qt::Key_Greater) {\n return bracketClosingCheck(QLatin1Char('<'), QLatin1Char('>'));\n } else if ((keyEvent->key() == Qt::Key_Return ||\n keyEvent->key() == Qt::Key_Enter) &&\n !isReadOnly() &&\n keyEvent->modifiers().testFlag(Qt::ShiftModifier)) {\n QTextCursor cursor = this->textCursor();\n cursor.insertText(\" \\n\");\n return true;\n } else if ((keyEvent->key() == Qt::Key_Return ||\n keyEvent->key() == Qt::Key_Enter) &&\n !isReadOnly() &&\n keyEvent->modifiers().testFlag(Qt::ControlModifier)) {\n QTextCursor cursor = this->textCursor();\n cursor.movePosition(QTextCursor::EndOfBlock);\n cursor.insertText(QStringLiteral(\"\\n\"));\n setTextCursor(cursor);\n return true;\n } else if (keyEvent == QKeySequence::Copy ||\n keyEvent == QKeySequence::Cut) {\n QTextCursor cursor = this->textCursor();\n if (!cursor.hasSelection()) {\n QString text;\n if (cursor.block().length() <= 1) // no content\n text = \"\\n\";\n else {\n // cursor.select(QTextCursor::BlockUnderCursor); //\n // negative, it will include the previous paragraph\n // separator\n cursor.movePosition(QTextCursor::StartOfBlock);\n cursor.movePosition(QTextCursor::EndOfBlock,\n QTextCursor::KeepAnchor);\n text = cursor.selectedText();\n if (!cursor.atEnd()) {\n text += \"\\n\";\n // this is the paragraph separator\n cursor.movePosition(QTextCursor::NextCharacter,\n QTextCursor::KeepAnchor, 1);\n }\n }\n if (keyEvent == QKeySequence::Cut) {\n if (!cursor.atEnd() && text == \"\\n\")\n cursor.deletePreviousChar();\n else\n cursor.removeSelectedText();\n cursor.movePosition(QTextCursor::StartOfBlock);\n setTextCursor(cursor);\n }\n qApp->clipboard()->setText(text);\n return true;\n }\n } else if ((keyEvent->key() == Qt::Key_Down) &&\n keyEvent->modifiers().testFlag(Qt::ControlModifier) &&\n keyEvent->modifiers().testFlag(Qt::AltModifier)) {\n // duplicate text with `Ctrl + Alt + Down`\n duplicateText();\n return true;\n#ifndef Q_OS_MAC\n } else if ((keyEvent->key() == Qt::Key_Down) &&\n keyEvent->modifiers().testFlag(Qt::ControlModifier) &&\n !keyEvent->modifiers().testFlag(Qt::ShiftModifier)) {\n // scroll the page down\n auto *scrollBar = verticalScrollBar();\n scrollBar->setSliderPosition(scrollBar->sliderPosition() + 1);\n return true;\n } else if ((keyEvent->key() == Qt::Key_Up) &&\n keyEvent->modifiers().testFlag(Qt::ControlModifier) &&\n !keyEvent->modifiers().testFlag(Qt::ShiftModifier)) {\n // scroll the page up\n auto *scrollBar = verticalScrollBar();\n scrollBar->setSliderPosition(scrollBar->sliderPosition() - 1);\n return true;\n#endif\n } else if ((keyEvent->key() == Qt::Key_Down) &&\n keyEvent->modifiers().testFlag(Qt::NoModifier)) {\n // if you are in the last line and press cursor down the cursor will\n // jump to the end of the line\n QTextCursor cursor = textCursor();\n if (cursor.position() >= document()->lastBlock().position()) {\n cursor.movePosition(QTextCursor::EndOfLine);\n\n // check if we are really in the last line, not only in\n // the last block\n if (cursor.atBlockEnd()) {\n setTextCursor(cursor);\n }\n }\n return QPlainTextEdit::eventFilter(obj, event);\n } else if ((keyEvent->key() == Qt::Key_Up) &&\n keyEvent->modifiers().testFlag(Qt::NoModifier)) {\n // if you are in the first line and press cursor up the cursor will\n // jump to the start of the line\n QTextCursor cursor = textCursor();\n QTextBlock block = document()->firstBlock();\n int endOfFirstLinePos = block.position() + block.length();\n\n if (cursor.position() <= endOfFirstLinePos) {\n cursor.movePosition(QTextCursor::StartOfLine);\n\n // check if we are really in the first line, not only in\n // the first block\n if (cursor.atBlockStart()) {\n setTextCursor(cursor);\n }\n }\n return QPlainTextEdit::eventFilter(obj, event);\n } else if (keyEvent->key() == Qt::Key_Return ||\n keyEvent->key() == Qt::Key_Enter) {\n return handleReturnEntered();\n } else if ((keyEvent->key() == Qt::Key_F3)) {\n _searchWidget->doSearch(\n !keyEvent->modifiers().testFlag(Qt::ShiftModifier));\n return true;\n } else if ((keyEvent->key() == Qt::Key_Z) &&\n (keyEvent->modifiers().testFlag(Qt::ControlModifier)) &&\n !(keyEvent->modifiers().testFlag(Qt::ShiftModifier))) {\n undo();\n return true;\n } else if ((keyEvent->key() == Qt::Key_Down) &&\n (keyEvent->modifiers().testFlag(Qt::ControlModifier)) &&\n (keyEvent->modifiers().testFlag(Qt::ShiftModifier))) {\n moveTextUpDown(false);\n return true;\n } else if ((keyEvent->key() == Qt::Key_Up) &&\n (keyEvent->modifiers().testFlag(Qt::ControlModifier)) &&\n (keyEvent->modifiers().testFlag(Qt::ShiftModifier))) {\n moveTextUpDown(true);\n return true;\n#ifdef Q_OS_MAC\n // https://github.com/pbek/QOwnNotes/issues/1593\n // https://github.com/pbek/QOwnNotes/issues/2643\n } else if (keyEvent->key() == Qt::Key_Home) {\n QTextCursor cursor = textCursor();\n // Meta is Control on macOS\n cursor.movePosition(\n keyEvent->modifiers().testFlag(Qt::MetaModifier)\n ? QTextCursor::Start\n : QTextCursor::StartOfLine,\n keyEvent->modifiers().testFlag(Qt::ShiftModifier)\n ? QTextCursor::KeepAnchor\n : QTextCursor::MoveAnchor);\n this->setTextCursor(cursor);\n return true;\n } else if (keyEvent->key() == Qt::Key_End) {\n QTextCursor cursor = textCursor();\n // Meta is Control on macOS\n cursor.movePosition(\n keyEvent->modifiers().testFlag(Qt::MetaModifier)\n ? QTextCursor::End\n : QTextCursor::EndOfLine,\n keyEvent->modifiers().testFlag(Qt::ShiftModifier)\n ? QTextCursor::KeepAnchor\n : QTextCursor::MoveAnchor);\n this->setTextCursor(cursor);\n return true;\n#endif\n }\n\n return QPlainTextEdit::eventFilter(obj, event);\n } else if (event->type() == QEvent::KeyRelease) {\n auto *keyEvent = static_cast(event);\n\n // reset cursor if control key was released\n if (keyEvent->key() == Qt::Key_Control) {\n resetMouseCursor();\n }\n\n return QPlainTextEdit::eventFilter(obj, event);\n } else if (event->type() == QEvent::MouseButtonRelease) {\n _mouseButtonDown = false;\n auto *mouseEvent = static_cast(event);\n\n // track `Ctrl + Click` in the text edit\n if ((obj == this->viewport()) &&\n (mouseEvent->button() == Qt::LeftButton) &&\n (QGuiApplication::keyboardModifiers() == Qt::ExtraButton24)) {\n // open the link (if any) at the current position\n // in the noteTextEdit\n openLinkAtCursorPosition();\n return true;\n }\n } else if (event->type() == QEvent::MouseButtonPress) {\n _mouseButtonDown = true;\n } else if (event->type() == QEvent::MouseButtonDblClick) {\n _mouseButtonDown = true;\n } else if (event->type() == QEvent::Wheel) {\n auto *wheel = dynamic_cast(event);\n\n // emit zoom signals\n if (wheel->modifiers() == Qt::ControlModifier) {\n if (wheel->angleDelta().y() > 0) {\n Q_EMIT zoomIn();\n } else {\n Q_EMIT zoomOut();\n }\n\n return true;\n }\n }\n\n return QPlainTextEdit::eventFilter(obj, event);\n}\n QMargins viewportMargins() {\n return QPlainTextEdit::viewportMargins();\n}\n bool increaseSelectedTextIndention(\n bool reverse,\n const QString &indentCharacters = QChar::fromLatin1('\\t')) {\n QTextCursor cursor = this->textCursor();\n QString selectedText = cursor.selectedText();\n\n if (!selectedText.isEmpty()) {\n // Start the selection at start of the first block of the selection\n int end = cursor.selectionEnd();\n cursor.setPosition(cursor.selectionStart());\n cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor);\n cursor.setPosition(end, QTextCursor::KeepAnchor);\n this->setTextCursor(cursor);\n selectedText = cursor.selectedText();\n\n // we need this strange newline character we are getting in the\n // selected text for newlines\n const QString newLine =\n QString::fromUtf8(QByteArray::fromHex(QByteArrayLiteral(\"e280a9\")));\n QString newText;\n\n if (reverse) {\n // un-indent text\n\n const int indentSize = indentCharacters == QStringLiteral(\"\\t\")\n ? 4\n : indentCharacters.length();\n\n // remove leading \\t or spaces in following lines\n newText = selectedText.replace(\n QRegularExpression(newLine + QStringLiteral(\"(\\\\t| {1,\") +\n QString::number(indentSize) +\n QStringLiteral(\"})\")),\n QStringLiteral(\"\\n\"));\n\n // remove leading \\t or spaces in first line\n newText.remove(QRegularExpression(QStringLiteral(\"^(\\\\t| {1,\") +\n QString::number(indentSize) +\n QStringLiteral(\"})\")));\n } else {\n // replace trailing new line to prevent an indent of the line after\n // the selection\n newText = selectedText.replace(\n QRegularExpression(QRegularExpression::escape(newLine) +\n QStringLiteral(\"$\")),\n QStringLiteral(\"\\n\"));\n\n // indent text\n newText.replace(newLine, QStringLiteral(\"\\n\") + indentCharacters)\n .prepend(indentCharacters);\n\n // remove trailing \\t\n static QRegularExpression regex1(QStringLiteral(\"\\\\t$\"));\n newText.remove(regex1);\n }\n\n // insert the new text\n cursor.insertText(newText);\n\n // update the selection to the new text\n cursor.setPosition(cursor.position() - newText.size(),\n QTextCursor::KeepAnchor);\n this->setTextCursor(cursor);\n\n return true;\n } else if (reverse) {\n const int indentSize = indentCharacters.length();\n\n // do the check as often as we have characters to un-indent\n for (int i = 1; i <= indentSize; i++) {\n // if nothing was selected but we want to reverse the indention\n // check if there is a \\t in front or after the cursor and remove it\n // if so\n const int position = cursor.position();\n\n if (!cursor.atStart()) {\n // get character in front of cursor\n cursor.setPosition(position - 1, QTextCursor::KeepAnchor);\n }\n\n // check for \\t or space in front of cursor\n static QRegularExpression regex1(QStringLiteral(\"[\\\\t ]\"));\n QRegularExpressionMatch match = regex1.match(cursor.selectedText());\n\n if (!match.hasMatch()) {\n // (select to) check for \\t or space after the cursor\n cursor.setPosition(position);\n\n if (!cursor.atEnd()) {\n cursor.setPosition(position + 1, QTextCursor::KeepAnchor);\n }\n }\n\n match = regex1.match(cursor.selectedText());\n\n if (match.hasMatch()) {\n cursor.removeSelectedText();\n }\n\n cursor = this->textCursor();\n }\n\n return true;\n }\n\n // else just insert indentCharacters\n cursor.insertText(indentCharacters);\n\n return true;\n}\n bool handleTabEntered(bool reverse, const QString &indentCharacters =\n QChar::fromLatin1('\\t')) {\n if (isReadOnly()) {\n return true;\n }\n\n QTextCursor cursor = this->textCursor();\n\n // only check for lists if we haven't a text selected\n if (cursor.selectedText().isEmpty()) {\n cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);\n const QString currentLineText = cursor.selectedText();\n\n // check if we want to indent or un-indent an ordered list\n // Valid listCharacters: '+ ', '-' , '* ', '+ [ ] ', '+ [x] ', '- [ ] ',\n // '- [x] ', '- [-] ', '* [ ] ', '* [x] '.\n static QRegularExpression regex1(\n R\"(^(\\s*)([+|\\-|\\*] \\[(x|-| )\\]|[+\\-\\*])(\\s+)$)\");\n QRegularExpressionMatchIterator i = regex1.globalMatch(currentLineText);\n\n if (i.hasNext()) {\n QRegularExpressionMatch match = i.next();\n QString whitespaces = match.captured(1);\n const QString listCharacter = match.captured(2);\n const QString whitespaceCharacter = match.captured(4);\n\n // add or remove one tabulator key\n if (reverse) {\n // remove one set of indentCharacters or a tabulator\n whitespaces.remove(QRegularExpression(\n QStringLiteral(\"^(\\\\t|\") +\n QRegularExpression::escape(indentCharacters) +\n QStringLiteral(\")\")));\n\n } else {\n whitespaces += indentCharacters;\n }\n\n cursor.insertText(whitespaces + listCharacter +\n whitespaceCharacter);\n return true;\n }\n\n // check if we want to indent or un-indent an ordered list\n static QRegularExpression regex2(R\"(^(\\s*)(\\d+)([\\.|\\)])(\\s+)$)\");\n i = regex2.globalMatch(currentLineText);\n\n if (i.hasNext()) {\n const QRegularExpressionMatch match = i.next();\n QString whitespaces = match.captured(1);\n const QString listCharacter = match.captured(2);\n const QString listMarker = match.captured(3);\n const QString whitespaceCharacter = match.captured(4);\n\n // add or remove one tabulator key\n if (reverse) {\n whitespaces.chop(1);\n } else {\n whitespaces += indentCharacters;\n }\n\n cursor.insertText(whitespaces + listCharacter + listMarker +\n whitespaceCharacter);\n return true;\n }\n }\n\n // check if we want to indent the whole text\n return increaseSelectedTextIndention(reverse, indentCharacters);\n}\n QMap parseMarkdownUrlsFromText(const QString &text) {\n QMap urlMap;\n QRegularExpressionMatchIterator iterator;\n\n // match urls like this: \n // re = QRegularExpression(\"(<(.+?:\\\\/\\\\/.+?)>)\");\n static QRegularExpression regex1(QStringLiteral(\"(<(.+?)>)\"));\n iterator = regex1.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString linkText = match.captured(1);\n QString url = match.captured(2);\n urlMap[linkText] = url;\n }\n\n // match urls like this: [this url](http://mylink)\n // QRegularExpression re(\"(\\\\[.*?\\\\]\\\\((.+?:\\\\/\\\\/.+?)\\\\))\");\n static QRegularExpression regex2(R\"((\\[.*?\\]\\((.+?)\\)))\");\n iterator = regex2.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString linkText = match.captured(1);\n QString url = match.captured(2);\n urlMap[linkText] = url;\n }\n\n // match urls like this: http://mylink\n static QRegularExpression regex3(R\"(\\b\\w+?:\\/\\/[^\\s]+[^\\s>\\)])\");\n iterator = regex3.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString url = match.captured(0);\n urlMap[url] = url;\n }\n\n // match urls like this: www.github.com\n static QRegularExpression regex4(R\"(\\bwww\\.[^\\s]+\\.[^\\s]+\\b)\");\n iterator = regex4.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString url = match.captured(0);\n urlMap[url] = QStringLiteral(\"http://\") + url;\n }\n\n // match reference urls like this: [this url][1] with this later:\n // [1]: http://domain\n static QRegularExpression regex5(R\"((\\[.*?\\]\\[(.+?)\\]))\");\n iterator = regex5.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString linkText = match.captured(1);\n QString referenceId = match.captured(2);\n\n // search for the referenced url in the whole text edit\n // QRegularExpression refRegExp(\n // \"\\\\[\" + QRegularExpression::escape(referenceId) +\n // \"\\\\]: (.+?:\\\\/\\\\/.+)\");\n QRegularExpression refRegExp(QStringLiteral(\"\\\\[\") +\n QRegularExpression::escape(referenceId) +\n QStringLiteral(\"\\\\]: (.+)\"));\n QRegularExpressionMatch urlMatch = refRegExp.match(toPlainText());\n\n if (urlMatch.hasMatch()) {\n QString url = urlMatch.captured(1);\n urlMap[linkText] = url;\n }\n }\n\n return urlMap;\n}\n bool handleReturnEntered() {\n if (isReadOnly()) {\n return true;\n }\n\n // This will be the main cursor to add or remove text\n QTextCursor cursor = this->textCursor();\n\n // We need a 2nd cursor to get the text of the current block without moving\n // the main cursor that is used to remove the selected text\n QTextCursor cursor2 = this->textCursor();\n cursor2.select(QTextCursor::BlockUnderCursor);\n const QString currentLineText = cursor2.selectedText().trimmed();\n\n const int position = cursor.position();\n const bool cursorAtBlockStart = cursor.atBlockStart();\n cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);\n const QString currentLinePartialText = cursor.selectedText();\n\n // if return is pressed and there is just an unordered list symbol then we\n // want to remove the list symbol Valid listCharacters: '+ ', '-' , '* ', '+\n // [ ] ', '+ [x] ', '- [ ] ', '- [-] ', '- [x] ', '* [ ] ', '* [x] '.\n static QRegularExpression regex1(\n R\"(^(\\s*)([+|\\-|\\*] \\[(x|-| |)\\]|[+\\-\\*])(\\s+)$)\");\n QRegularExpressionMatchIterator iterator =\n regex1.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n cursor.removeSelectedText();\n return true;\n }\n\n // if return is pressed and there is just an ordered list symbol then we\n // want to remove the list symbol\n static QRegularExpression regex2(R\"(^(\\s*)(\\d+[\\.|\\)])(\\s+)$)\");\n iterator = regex2.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n qDebug() << cursor.selectedText();\n cursor.removeSelectedText();\n return true;\n }\n\n // Check if we are in an unordered list.\n // We are in a list when we have '* ', '- ' or '+ ', possibly with preceding\n // whitespace. If e.g. user has entered '**text**' and pressed enter - we\n // don't want to do more list-stuff.\n QString currentLine = currentLinePartialText.trimmed();\n QChar char0;\n QChar char1;\n if (currentLine.length() >= 1) char0 = currentLine.at(0);\n if (currentLine.length() >= 2) char1 = currentLine.at(1);\n const bool inList =\n ((char0 == QLatin1Char('*') || char0 == QLatin1Char('-') ||\n char0 == QLatin1Char('+')) &&\n char1 == QLatin1Char(' '));\n\n if (inList) {\n // if the current line starts with a list character (possibly after\n // whitespaces) add the whitespaces at the next line too\n // Valid listCharacters: '+ ', '-' , '* ', '+ [ ] ', '+ [x] ', '- [ ] ',\n // '- [x] ', '- [-] ', '* [ ] ', '* [x] '.\n static QRegularExpression regex3(\n R\"(^(\\s*)([+|\\-|\\*] \\[(x|-| |)\\]|[+\\-\\*])(\\s+))\");\n iterator = regex3.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n const QString whitespaces = match.captured(1);\n QString listCharacter = match.captured(2);\n const QString whitespaceCharacter = match.captured(4);\n\n static QRegularExpression regex4(R\"(^([+|\\-|\\*]) \\[(x| |\\-|)\\])\");\n // start new checkbox list item with an unchecked checkbox\n iterator = regex4.globalMatch(listCharacter);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match1 = iterator.next();\n const QString realListCharacter = match1.captured(1);\n listCharacter = realListCharacter + QStringLiteral(\" [ ]\");\n }\n\n cursor.setPosition(position);\n cursor.insertText(\"\\n\" + whitespaces + listCharacter +\n whitespaceCharacter);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n }\n\n // check for ordered lists and increment the list number in the next line\n static QRegularExpression regex5(R\"(^(\\s*)(\\d+)([\\.|\\)])(\\s+))\");\n iterator = regex5.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n const QString whitespaces = match.captured(1);\n const uint listNumber = match.captured(2).toUInt();\n const QString listMarker = match.captured(3);\n const QString whitespaceCharacter = match.captured(4);\n\n cursor.setPosition(position);\n cursor.insertText(\"\\n\" + whitespaces + QString::number(listNumber + 1) +\n listMarker + whitespaceCharacter);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n\n // intent next line with same whitespaces as in current line\n static QRegularExpression regex6(R\"(^(\\s+))\");\n iterator = regex6.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n const QString whitespaces = match.captured(1);\n\n cursor.setPosition(position);\n cursor.insertText(\"\\n\" + whitespaces);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n\n // Add new list item above current line if we are at the start the line of a\n // list item\n if (cursorAtBlockStart) {\n static QRegularExpression regex7(\n R\"(^([+|\\-|\\*] \\[(x|-| |)\\]|[+\\-\\*])(\\s+))\");\n iterator = regex7.globalMatch(currentLineText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n QString listCharacter = match.captured(1);\n const QString whitespaceCharacter = match.captured(3);\n\n static QRegularExpression regex8(R\"(^([+|\\-|\\*]) \\[(x| |\\-|)\\])\");\n // start new checkbox list item with an unchecked checkbox\n iterator = regex8.globalMatch(listCharacter);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match1 = iterator.next();\n const QString realListCharacter = match1.captured(1);\n listCharacter = realListCharacter + QStringLiteral(\" [ ]\");\n }\n\n cursor.setPosition(position);\n // Enter new list item above current line\n cursor.insertText(listCharacter + whitespaceCharacter + \"\\n\");\n // Move the cursor at the end of the new list item\n cursor.movePosition(QTextCursor::Left);\n setTextCursor(cursor);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n }\n\n return false;\n}\n bool handleBracketClosing(const QChar openingCharacter,\n QChar closingCharacter = QChar()) {\n // check if bracket closing or read-only are enabled\n if (!(_autoTextOptions & AutoTextOption::BracketClosing) || isReadOnly()) {\n return false;\n }\n\n QTextCursor cursor = textCursor();\n\n if (closingCharacter.isNull()) {\n closingCharacter = openingCharacter;\n }\n\n const QString selectedText = cursor.selectedText();\n\n // When user currently has text selected, we prepend the openingCharacter\n // and append the closingCharacter. E.g. 'text' -> '(text)'. We keep the\n // current selectedText selected.\n if (!selectedText.isEmpty()) {\n // Insert. The selectedText is overwritten.\n const QString newText =\n openingCharacter + selectedText + closingCharacter;\n cursor.insertText(newText);\n\n // Re-select the selectedText.\n const int selectionEnd = cursor.position() - 1;\n const int selectionStart = selectionEnd - selectedText.length();\n\n cursor.setPosition(selectionStart);\n cursor.setPosition(selectionEnd, QTextCursor::KeepAnchor);\n this->setTextCursor(cursor);\n _handleBracketClosingUsed = true;\n return true;\n }\n\n // get the current text from the block (inserted character not included)\n // Remove whitespace at start of string (e.g. in multilevel-lists).\n static QRegularExpression regex1(\"^\\\\s+\");\n const QString text = cursor.block().text().remove(regex1);\n\n const int pib = cursor.positionInBlock();\n bool isPreviousAsterisk =\n pib > 0 && pib < text.length() && text.at(pib - 1) == '*';\n bool isNextAsterisk = pib < text.length() && text.at(pib) == '*';\n bool isMaybeBold = isPreviousAsterisk && isNextAsterisk;\n if (pib < text.length() && !isMaybeBold && !text.at(pib).isSpace()) {\n return false;\n }\n\n // Default positions to move the cursor back.\n int cursorSubtract = 1;\n // Special handling for `*` opening character, as this could be:\n // - start of a list (or sublist);\n // - start of a bold text;\n if (openingCharacter == QLatin1Char('*')) {\n // don't auto complete in code block\n bool isInCode =\n MarkdownHighlighter::isCodeBlock(cursor.block().userState());\n // we only do auto completion if there is a space before the cursor pos\n bool hasSpaceOrAsteriskBefore = !text.isEmpty() && pib > 0 &&\n (text.at(pib - 1).isSpace() ||\n text.at(pib - 1) == QLatin1Char('*'));\n // This could be the start of a list, don't autocomplete.\n bool isEmpty = text.isEmpty();\n\n if (isInCode || !hasSpaceOrAsteriskBefore || isEmpty) {\n return false;\n }\n\n // bold\n if (isPreviousAsterisk && isNextAsterisk) {\n cursorSubtract = 1;\n }\n\n // User wants: '**'.\n // Not the start of a list, probably bold text. We autocomplete with\n // extra closingCharacter and cursorSubtract to 'catchup'.\n if (text == QLatin1String(\"*\")) {\n cursor.insertText(QStringLiteral(\"*\"));\n cursorSubtract = 2;\n }\n }\n\n // Auto-completion for ``` pair\n if (openingCharacter == QLatin1Char('`')) {\n#if QT_VERSION < QT_VERSION_CHECK(5, 12, 0)\n if (QRegExp(QStringLiteral(\"[^`]*``\")).exactMatch(text)) {\n#else\n if (QRegularExpression(\n QRegularExpression::anchoredPattern(QStringLiteral(\"[^`]*``\")))\n .match(text)\n .hasMatch()) {\n#endif\n cursor.insertText(QStringLiteral(\"``\"));\n cursorSubtract = 3;\n }\n }\n\n // don't auto complete in code block\n if (openingCharacter == QLatin1Char('<') &&\n MarkdownHighlighter::isCodeBlock(cursor.block().userState())) {\n return false;\n }\n\n cursor.beginEditBlock();\n cursor.insertText(openingCharacter);\n cursor.insertText(closingCharacter);\n cursor.setPosition(cursor.position() - cursorSubtract);\n cursor.endEditBlock();\n\n setTextCursor(cursor);\n return true;\n}\n\n/**\n * Checks if the closing character should be output or not\n *\n * @param openingCharacter\n * @param closingCharacter\n * @return\n */\nbool QMarkdownTextEdit::bracketClosingCheck(const QChar openingCharacter,\n QChar closingCharacter) {\n // check if bracket closing or read-only are enabled\n if (!(_autoTextOptions & AutoTextOption::BracketClosing) || isReadOnly()) {\n return false;\n }\n\n if (closingCharacter.isNull()) {\n closingCharacter = openingCharacter;\n }\n\n QTextCursor cursor = textCursor();\n const int positionInBlock = cursor.positionInBlock();\n\n // get the current text from the block\n const QString text = cursor.block().text();\n const int textLength = text.length();\n\n // if we are at the end of the line we just want to enter the character\n if (positionInBlock >= textLength) {\n return false;\n }\n\n const QChar currentChar = text.at(positionInBlock);\n\n // if (closingCharacter == openingCharacter) {\n\n // }\n\n qDebug() << __func__ << \" - 'currentChar': \" << currentChar;\n\n // if the current character is not the closing character we just want to\n // enter the character\n if (currentChar != closingCharacter) {\n return false;\n }\n\n const QString leftText = text.left(positionInBlock);\n const int openingCharacterCount = leftText.count(openingCharacter);\n const int closingCharacterCount = leftText.count(closingCharacter);\n\n // if there were enough opening characters just enter the character\n if (openingCharacterCount < (closingCharacterCount + 1)) {\n return false;\n }\n\n // move the cursor to the right and don't enter the character\n cursor.movePosition(QTextCursor::Right);\n setTextCursor(cursor);\n return true;\n}\n\n/**\n * Checks if the closing character should be output or not or if a closing\n * character after an opening character if needed\n *\n * @param quotationCharacter\n * @return\n */\nbool QMarkdownTextEdit::quotationMarkCheck(const QChar quotationCharacter) {\n // check if bracket closing or read-only are enabled\n if (!(_autoTextOptions & AutoTextOption::BracketClosing) || isReadOnly()) {\n return false;\n }\n\n QTextCursor cursor = textCursor();\n const int positionInBlock = cursor.positionInBlock();\n\n // get the current text from the block\n const QString text = cursor.block().text();\n const int textLength = text.length();\n\n // if last char is not space, we are at word end, no autocompletion\n const bool isBacktick = quotationCharacter == '`';\n if (!isBacktick && positionInBlock != 0 &&\n !text.at(positionInBlock - 1).isSpace()) {\n return false;\n }\n\n // if we are at the end of the line we just want to enter the character\n if (positionInBlock >= textLength) {\n return handleBracketClosing(quotationCharacter);\n }\n\n const QChar currentChar = text.at(positionInBlock);\n\n // if the current character is not the quotation character we just want to\n // enter the character\n if (currentChar != quotationCharacter) {\n return handleBracketClosing(quotationCharacter);\n }\n\n // move the cursor to the right and don't enter the character\n cursor.movePosition(QTextCursor::Right);\n setTextCursor(cursor);\n return true;\n}\n\n/***********************************\n * helper methods for char removal\n * Rules for (') and (\"):\n * if [sp]\" -> opener (sp = space)\n * if \"[sp] -> closer\n ***********************************/\nbool isQuotOpener(int position, const QString &text) {\n if (position == 0) return true;\n const int prevCharPos = position - 1;\n return text.at(prevCharPos).isSpace();\n}\nbool isQuotCloser(int position, const QString &text) {\n const int nextCharPos = position + 1;\n if (nextCharPos >= text.length()) return true;\n return text.at(nextCharPos).isSpace();\n}\n\n/**\n * Handles removing of matching brackets and other Markdown characters\n * Only works with backspace to remove text\n *\n * @return\n */\nbool QMarkdownTextEdit::handleBackspaceEntered() {\n if (!(_autoTextOptions & AutoTextOption::BracketRemoval) || isReadOnly()) {\n return false;\n }\n\n QTextCursor cursor = textCursor();\n\n // return if some text was selected\n if (!cursor.selectedText().isEmpty()) {\n return false;\n }\n\n int position = cursor.position();\n const int positionInBlock = cursor.positionInBlock();\n int block = cursor.block().blockNumber();\n\n if (_highlighter)\n if (_highlighter->isPosInACodeSpan(block, positionInBlock - 1))\n return false;\n\n // return if backspace was pressed at the beginning of a block\n if (positionInBlock == 0) {\n return false;\n }\n\n // get the current text from the block\n const QString text = cursor.block().text();\n\n char charToRemove{};\n\n // current char\n const char charInFront = text.at(positionInBlock - 1).toLatin1();\n\n if (charInFront == '*')\n return handleCharRemoval(MarkdownHighlighter::RangeType::Emphasis,\n block, positionInBlock - 1);\n else if (charInFront == '`')\n return handleCharRemoval(MarkdownHighlighter::RangeType::CodeSpan,\n block, positionInBlock - 1);\n\n // handle removal of \", ', and brackets\n\n // is it opener?\n int pos = _openingCharacters.indexOf(charInFront);\n // for \" and '\n bool isOpener = false;\n bool isCloser = false;\n if (pos == 5 || pos == 6) {\n isOpener = isQuotOpener(positionInBlock - 1, text);\n } else {\n isOpener = pos != -1;\n }\n if (isOpener) {\n charToRemove = _closingCharacters.at(pos);\n } else {\n // is it closer?\n pos = _closingCharacters.indexOf(charInFront);\n if (pos == 5 || pos == 6)\n isCloser = isQuotCloser(positionInBlock - 1, text);\n else\n isCloser = pos != -1;\n if (isCloser)\n charToRemove = _openingCharacters.at(pos);\n else\n return false;\n }\n\n int charToRemoveIndex = -1;\n if (isOpener) {\n bool closer = true;\n charToRemoveIndex = text.indexOf(charToRemove, positionInBlock);\n if (charToRemoveIndex == -1) return false;\n if (pos == 5 || pos == 6)\n closer = isQuotCloser(charToRemoveIndex, text);\n if (!closer) return false;\n cursor.setPosition(position + (charToRemoveIndex - positionInBlock));\n cursor.deleteChar();\n } else if (isCloser) {\n charToRemoveIndex = text.lastIndexOf(charToRemove, positionInBlock - 2);\n if (charToRemoveIndex == -1) return false;\n bool opener = true;\n if (pos == 5 || pos == 6)\n opener = isQuotOpener(charToRemoveIndex, text);\n if (!opener) return false;\n const int pos = position - (positionInBlock - charToRemoveIndex);\n cursor.setPosition(pos);\n cursor.deleteChar();\n position -= 1;\n } else {\n charToRemoveIndex = text.lastIndexOf(charToRemove, positionInBlock - 2);\n if (charToRemoveIndex == -1) return false;\n const int pos = position - (positionInBlock - charToRemoveIndex);\n cursor.setPosition(pos);\n cursor.deleteChar();\n position -= 1;\n }\n\n // moving the cursor back to the old position so the previous character\n // can be removed\n cursor.setPosition(position);\n setTextCursor(cursor);\n return false;\n}\n\nbool QMarkdownTextEdit::handleCharRemoval(MarkdownHighlighter::RangeType type,\n int block, int position) {\n if (!_highlighter) return false;\n\n auto range = _highlighter->findPositionInRanges(type, block, position);\n if (range == QPair{-1, -1}) return false;\n\n int charToRemovePos = range.first;\n if (position == range.first) charToRemovePos = range.second;\n\n QTextCursor cursor = textCursor();\n auto gpos = cursor.position();\n\n if (charToRemovePos > position) {\n cursor.setPosition(gpos + (charToRemovePos - (position + 1)));\n } else {\n cursor.setPosition(gpos - (position - charToRemovePos + 1));\n gpos--;\n }\n\n cursor.deleteChar();\n cursor.setPosition(gpos);\n setTextCursor(cursor);\n return false;\n}\n\nvoid QMarkdownTextEdit::updateLineNumAreaGeometry() {\n const auto contentsRect = this->contentsRect();\n const QRect newGeometry = {contentsRect.left(), contentsRect.top(),\n _lineNumArea->sizeHint().width(),\n contentsRect.height()};\n auto oldGeometry = _lineNumArea->geometry();\n if (newGeometry != oldGeometry) {\n _lineNumArea->setGeometry(newGeometry);\n }\n}\n\nvoid QMarkdownTextEdit::resizeEvent(QResizeEvent *event) {\n QPlainTextEdit::resizeEvent(event);\n updateLineNumAreaGeometry();\n}\n\n/**\n * Increases (or decreases) the indention of the selected text\n * (if there is a text selected) in the noteTextEdit\n * @return\n */\nbool QMarkdownTextEdit::increaseSelectedTextIndention(\n bool reverse, const QString &indentCharacters) {\n QTextCursor cursor = this->textCursor();\n QString selectedText = cursor.selectedText();\n\n if (!selectedText.isEmpty()) {\n // Start the selection at start of the first block of the selection\n int end = cursor.selectionEnd();\n cursor.setPosition(cursor.selectionStart());\n cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor);\n cursor.setPosition(end, QTextCursor::KeepAnchor);\n this->setTextCursor(cursor);\n selectedText = cursor.selectedText();\n\n // we need this strange newline character we are getting in the\n // selected text for newlines\n const QString newLine =\n QString::fromUtf8(QByteArray::fromHex(QByteArrayLiteral(\"e280a9\")));\n QString newText;\n\n if (reverse) {\n // un-indent text\n\n const int indentSize = indentCharacters == QStringLiteral(\"\\t\")\n ? 4\n : indentCharacters.length();\n\n // remove leading \\t or spaces in following lines\n newText = selectedText.replace(\n QRegularExpression(newLine + QStringLiteral(\"(\\\\t| {1,\") +\n QString::number(indentSize) +\n QStringLiteral(\"})\")),\n QStringLiteral(\"\\n\"));\n\n // remove leading \\t or spaces in first line\n newText.remove(QRegularExpression(QStringLiteral(\"^(\\\\t| {1,\") +\n QString::number(indentSize) +\n QStringLiteral(\"})\")));\n } else {\n // replace trailing new line to prevent an indent of the line after\n // the selection\n newText = selectedText.replace(\n QRegularExpression(QRegularExpression::escape(newLine) +\n QStringLiteral(\"$\")),\n QStringLiteral(\"\\n\"));\n\n // indent text\n newText.replace(newLine, QStringLiteral(\"\\n\") + indentCharacters)\n .prepend(indentCharacters);\n\n // remove trailing \\t\n static QRegularExpression regex1(QStringLiteral(\"\\\\t$\"));\n newText.remove(regex1);\n }\n\n // insert the new text\n cursor.insertText(newText);\n\n // update the selection to the new text\n cursor.setPosition(cursor.position() - newText.size(),\n QTextCursor::KeepAnchor);\n this->setTextCursor(cursor);\n\n return true;\n } else if (reverse) {\n const int indentSize = indentCharacters.length();\n\n // do the check as often as we have characters to un-indent\n for (int i = 1; i <= indentSize; i++) {\n // if nothing was selected but we want to reverse the indention\n // check if there is a \\t in front or after the cursor and remove it\n // if so\n const int position = cursor.position();\n\n if (!cursor.atStart()) {\n // get character in front of cursor\n cursor.setPosition(position - 1, QTextCursor::KeepAnchor);\n }\n\n // check for \\t or space in front of cursor\n static QRegularExpression regex1(QStringLiteral(\"[\\\\t ]\"));\n QRegularExpressionMatch match = regex1.match(cursor.selectedText());\n\n if (!match.hasMatch()) {\n // (select to) check for \\t or space after the cursor\n cursor.setPosition(position);\n\n if (!cursor.atEnd()) {\n cursor.setPosition(position + 1, QTextCursor::KeepAnchor);\n }\n }\n\n match = regex1.match(cursor.selectedText());\n\n if (match.hasMatch()) {\n cursor.removeSelectedText();\n }\n\n cursor = this->textCursor();\n }\n\n return true;\n }\n\n // else just insert indentCharacters\n cursor.insertText(indentCharacters);\n\n return true;\n}\n\n/**\n * @brief Opens the link (if any) at the current cursor position\n */\nbool QMarkdownTextEdit::openLinkAtCursorPosition() {\n QTextCursor cursor = this->textCursor();\n const int clickedPosition = cursor.position();\n\n // select the text in the clicked block and find out on\n // which position we clicked\n cursor.movePosition(QTextCursor::StartOfBlock);\n const int positionFromStart = clickedPosition - cursor.position();\n cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);\n\n const QString selectedText = cursor.selectedText();\n\n // find out which url in the selected text was clicked\n const QString urlString =\n getMarkdownUrlAtPosition(selectedText, positionFromStart);\n const QUrl url = QUrl(urlString);\n const bool isRelativeFileUrl =\n urlString.startsWith(QLatin1String(\"file://..\"));\n const bool isLegacyAttachmentUrl =\n urlString.startsWith(QLatin1String(\"file://attachments\"));\n\n qDebug() << __func__ << \" - 'emit urlClicked( urlString )': \" << urlString;\n\n Q_EMIT urlClicked(urlString);\n\n if ((url.isValid() && isValidUrl(urlString)) || isRelativeFileUrl ||\n isLegacyAttachmentUrl) {\n // ignore some schemata\n if (!(_ignoredClickUrlSchemata.contains(url.scheme()) ||\n isRelativeFileUrl || isLegacyAttachmentUrl)) {\n // open the url\n openUrl(urlString);\n }\n\n return true;\n }\n\n return false;\n}\n\n/**\n * Checks if urlString is a valid url\n *\n * @param urlString\n * @return\n */\nbool QMarkdownTextEdit::isValidUrl(const QString &urlString) {\n static QRegularExpression regex(R\"(^\\w+:\\/\\/.+)\");\n const QRegularExpressionMatch match = regex.match(urlString);\n return match.hasMatch();\n}\n\n/**\n * Handles clicked urls\n *\n * examples:\n * - opens the webpage\n * - opens the file\n * \"/path/to/my/file/QOwnNotes.pdf\" if the operating system supports that\n * handler\n */\nvoid QMarkdownTextEdit::openUrl(const QString &urlString) {\n qDebug() << \"QMarkdownTextEdit \" << __func__\n << \" - 'urlString': \" << urlString;\n\n QDesktopServices::openUrl(QUrl(urlString));\n}\n\n/**\n * @brief Returns the highlighter instance\n * @return\n */\nMarkdownHighlighter *QMarkdownTextEdit::highlighter() { return _highlighter; }\n\n/**\n * @brief Returns the searchWidget instance\n * @return\n */\nQPlainTextEditSearchWidget *QMarkdownTextEdit::searchWidget() {\n return _searchWidget;\n}\n\n/**\n * @brief Sets url schemata that will be ignored when clicked on\n * @param urlSchemes\n */\nvoid QMarkdownTextEdit::setIgnoredClickUrlSchemata(\n QStringList ignoredUrlSchemata) {\n _ignoredClickUrlSchemata = std::move(ignoredUrlSchemata);\n}\n\n/**\n * @brief Returns a map of parsed Markdown urls with their link texts as key\n *\n * @param text\n * @return parsed urls\n */\nQMap QMarkdownTextEdit::parseMarkdownUrlsFromText(\n const QString &text) {\n QMap urlMap;\n QRegularExpressionMatchIterator iterator;\n\n // match urls like this: \n // re = QRegularExpression(\"(<(.+?:\\\\/\\\\/.+?)>)\");\n static QRegularExpression regex1(QStringLiteral(\"(<(.+?)>)\"));\n iterator = regex1.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString linkText = match.captured(1);\n QString url = match.captured(2);\n urlMap[linkText] = url;\n }\n\n // match urls like this: [this url](http://mylink)\n // QRegularExpression re(\"(\\\\[.*?\\\\]\\\\((.+?:\\\\/\\\\/.+?)\\\\))\");\n static QRegularExpression regex2(R\"((\\[.*?\\]\\((.+?)\\)))\");\n iterator = regex2.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString linkText = match.captured(1);\n QString url = match.captured(2);\n urlMap[linkText] = url;\n }\n\n // match urls like this: http://mylink\n static QRegularExpression regex3(R\"(\\b\\w+?:\\/\\/[^\\s]+[^\\s>\\)])\");\n iterator = regex3.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString url = match.captured(0);\n urlMap[url] = url;\n }\n\n // match urls like this: www.github.com\n static QRegularExpression regex4(R\"(\\bwww\\.[^\\s]+\\.[^\\s]+\\b)\");\n iterator = regex4.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString url = match.captured(0);\n urlMap[url] = QStringLiteral(\"http://\") + url;\n }\n\n // match reference urls like this: [this url][1] with this later:\n // [1]: http://domain\n static QRegularExpression regex5(R\"((\\[.*?\\]\\[(.+?)\\]))\");\n iterator = regex5.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString linkText = match.captured(1);\n QString referenceId = match.captured(2);\n\n // search for the referenced url in the whole text edit\n // QRegularExpression refRegExp(\n // \"\\\\[\" + QRegularExpression::escape(referenceId) +\n // \"\\\\]: (.+?:\\\\/\\\\/.+)\");\n QRegularExpression refRegExp(QStringLiteral(\"\\\\[\") +\n QRegularExpression::escape(referenceId) +\n QStringLiteral(\"\\\\]: (.+)\"));\n QRegularExpressionMatch urlMatch = refRegExp.match(toPlainText());\n\n if (urlMatch.hasMatch()) {\n QString url = urlMatch.captured(1);\n urlMap[linkText] = url;\n }\n }\n\n return urlMap;\n}\n\n/**\n * @brief Returns the Markdown url at position\n * @param text\n * @param position\n * @return url string\n */\nQString QMarkdownTextEdit::getMarkdownUrlAtPosition(const QString &text,\n int position) {\n QString url;\n\n // get a map of parsed Markdown urls with their link texts as key\n const QMap urlMap = parseMarkdownUrlsFromText(text);\n QMap::const_iterator i = urlMap.constBegin();\n for (; i != urlMap.constEnd(); ++i) {\n const QString &linkText = i.key();\n const QString &urlString = i.value();\n\n const int foundPositionStart = text.indexOf(linkText);\n\n if (foundPositionStart >= 0) {\n // calculate end position of found linkText\n const int foundPositionEnd = foundPositionStart + linkText.size();\n\n // check if position is in found string range\n if ((position >= foundPositionStart) &&\n (position <= foundPositionEnd)) {\n url = urlString;\n break;\n }\n }\n }\n\n return url;\n}\n\n/**\n * @brief Duplicates the text in the text edit\n */\nvoid QMarkdownTextEdit::duplicateText() {\n if (isReadOnly()) {\n return;\n }\n\n QTextCursor cursor = this->textCursor();\n QString selectedText = cursor.selectedText();\n\n // duplicate line if no text was selected\n if (selectedText.isEmpty()) {\n const int position = cursor.position();\n\n // select the whole line\n cursor.movePosition(QTextCursor::StartOfBlock);\n cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);\n\n const int positionDiff = cursor.position() - position;\n selectedText = \"\\n\" + cursor.selectedText();\n\n // insert text with new line at end of the selected line\n cursor.setPosition(cursor.selectionEnd());\n cursor.insertText(selectedText);\n\n // set the position to same position it was in the duplicated line\n cursor.setPosition(cursor.position() - positionDiff);\n } else {\n // duplicate selected text\n cursor.setPosition(cursor.selectionEnd());\n const int selectionStart = cursor.position();\n\n // insert selected text\n cursor.insertText(selectedText);\n const int selectionEnd = cursor.position();\n\n // select the inserted text\n cursor.setPosition(selectionStart);\n cursor.setPosition(selectionEnd, QTextCursor::KeepAnchor);\n }\n\n this->setTextCursor(cursor);\n}\n\nvoid QMarkdownTextEdit::setText(const QString &text) { setPlainText(text); }\n\nvoid QMarkdownTextEdit::setPlainText(const QString &text) {\n // clear the dirty blocks vector to increase performance and prevent\n // a possible crash in QSyntaxHighlighter::rehighlightBlock\n if (_highlighter) _highlighter->clearDirtyBlocks();\n\n QPlainTextEdit::setPlainText(text);\n adjustRightMargin();\n}\n\n/**\n * Uses another widget as parent for the search widget\n */\nvoid QMarkdownTextEdit::initSearchFrame(QWidget *searchFrame, bool darkMode) {\n _searchFrame = searchFrame;\n\n // remove the search widget from our layout\n layout()->removeWidget(_searchWidget);\n\n QLayout *layout = _searchFrame->layout();\n\n // create a grid layout for the frame and add the search widget to it\n if (layout == nullptr) {\n layout = new QVBoxLayout(_searchFrame);\n layout->setSpacing(0);\n layout->setContentsMargins(0, 0, 0, 0);\n }\n\n _searchWidget->setDarkMode(darkMode);\n layout->addWidget(_searchWidget);\n _searchFrame->setLayout(layout);\n}\n\n/**\n * Hides the text edit and the search widget\n */\nvoid QMarkdownTextEdit::hide() {\n _searchWidget->hide();\n QWidget::hide();\n}\n\n/**\n * Handles an entered return key\n */\nbool QMarkdownTextEdit::handleReturnEntered() {\n if (isReadOnly()) {\n return true;\n }\n\n // This will be the main cursor to add or remove text\n QTextCursor cursor = this->textCursor();\n\n // We need a 2nd cursor to get the text of the current block without moving\n // the main cursor that is used to remove the selected text\n QTextCursor cursor2 = this->textCursor();\n cursor2.select(QTextCursor::BlockUnderCursor);\n const QString currentLineText = cursor2.selectedText().trimmed();\n\n const int position = cursor.position();\n const bool cursorAtBlockStart = cursor.atBlockStart();\n cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);\n const QString currentLinePartialText = cursor.selectedText();\n\n // if return is pressed and there is just an unordered list symbol then we\n // want to remove the list symbol Valid listCharacters: '+ ', '-' , '* ', '+\n // [ ] ', '+ [x] ', '- [ ] ', '- [-] ', '- [x] ', '* [ ] ', '* [x] '.\n static QRegularExpression regex1(\n R\"(^(\\s*)([+|\\-|\\*] \\[(x|-| |)\\]|[+\\-\\*])(\\s+)$)\");\n QRegularExpressionMatchIterator iterator =\n regex1.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n cursor.removeSelectedText();\n return true;\n }\n\n // if return is pressed and there is just an ordered list symbol then we\n // want to remove the list symbol\n static QRegularExpression regex2(R\"(^(\\s*)(\\d+[\\.|\\)])(\\s+)$)\");\n iterator = regex2.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n qDebug() << cursor.selectedText();\n cursor.removeSelectedText();\n return true;\n }\n\n // Check if we are in an unordered list.\n // We are in a list when we have '* ', '- ' or '+ ', possibly with preceding\n // whitespace. If e.g. user has entered '**text**' and pressed enter - we\n // don't want to do more list-stuff.\n QString currentLine = currentLinePartialText.trimmed();\n QChar char0;\n QChar char1;\n if (currentLine.length() >= 1) char0 = currentLine.at(0);\n if (currentLine.length() >= 2) char1 = currentLine.at(1);\n const bool inList =\n ((char0 == QLatin1Char('*') || char0 == QLatin1Char('-') ||\n char0 == QLatin1Char('+')) &&\n char1 == QLatin1Char(' '));\n\n if (inList) {\n // if the current line starts with a list character (possibly after\n // whitespaces) add the whitespaces at the next line too\n // Valid listCharacters: '+ ', '-' , '* ', '+ [ ] ', '+ [x] ', '- [ ] ',\n // '- [x] ', '- [-] ', '* [ ] ', '* [x] '.\n static QRegularExpression regex3(\n R\"(^(\\s*)([+|\\-|\\*] \\[(x|-| |)\\]|[+\\-\\*])(\\s+))\");\n iterator = regex3.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n const QString whitespaces = match.captured(1);\n QString listCharacter = match.captured(2);\n const QString whitespaceCharacter = match.captured(4);\n\n static QRegularExpression regex4(R\"(^([+|\\-|\\*]) \\[(x| |\\-|)\\])\");\n // start new checkbox list item with an unchecked checkbox\n iterator = regex4.globalMatch(listCharacter);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match1 = iterator.next();\n const QString realListCharacter = match1.captured(1);\n listCharacter = realListCharacter + QStringLiteral(\" [ ]\");\n }\n\n cursor.setPosition(position);\n cursor.insertText(\"\\n\" + whitespaces + listCharacter +\n whitespaceCharacter);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n }\n\n // check for ordered lists and increment the list number in the next line\n static QRegularExpression regex5(R\"(^(\\s*)(\\d+)([\\.|\\)])(\\s+))\");\n iterator = regex5.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n const QString whitespaces = match.captured(1);\n const uint listNumber = match.captured(2).toUInt();\n const QString listMarker = match.captured(3);\n const QString whitespaceCharacter = match.captured(4);\n\n cursor.setPosition(position);\n cursor.insertText(\"\\n\" + whitespaces + QString::number(listNumber + 1) +\n listMarker + whitespaceCharacter);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n\n // intent next line with same whitespaces as in current line\n static QRegularExpression regex6(R\"(^(\\s+))\");\n iterator = regex6.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n const QString whitespaces = match.captured(1);\n\n cursor.setPosition(position);\n cursor.insertText(\"\\n\" + whitespaces);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n\n // Add new list item above current line if we are at the start the line of a\n // list item\n if (cursorAtBlockStart) {\n static QRegularExpression regex7(\n R\"(^([+|\\-|\\*] \\[(x|-| |)\\]|[+\\-\\*])(\\s+))\");\n iterator = regex7.globalMatch(currentLineText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n QString listCharacter = match.captured(1);\n const QString whitespaceCharacter = match.captured(3);\n\n static QRegularExpression regex8(R\"(^([+|\\-|\\*]) \\[(x| |\\-|)\\])\");\n // start new checkbox list item with an unchecked checkbox\n iterator = regex8.globalMatch(listCharacter);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match1 = iterator.next();\n const QString realListCharacter = match1.captured(1);\n listCharacter = realListCharacter + QStringLiteral(\" [ ]\");\n }\n\n cursor.setPosition(position);\n // Enter new list item above current line\n cursor.insertText(listCharacter + whitespaceCharacter + \"\\n\");\n // Move the cursor at the end of the new list item\n cursor.movePosition(QTextCursor::Left);\n setTextCursor(cursor);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Handles entered tab or reverse tab keys\n */\nbool QMarkdownTextEdit::handleTabEntered(bool reverse,\n const QString &indentCharacters) {\n if (isReadOnly()) {\n return true;\n }\n\n QTextCursor cursor = this->textCursor();\n\n // only check for lists if we haven't a text selected\n if (cursor.selectedText().isEmpty()) {\n cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);\n const QString currentLineText = cursor.selectedText();\n\n // check if we want to indent or un-indent an ordered list\n // Valid listCharacters: '+ ', '-' , '* ', '+ [ ] ', '+ [x] ', '- [ ] ',\n // '- [x] ', '- [-] ', '* [ ] ', '* [x] '.\n static QRegularExpression regex1(\n R\"(^(\\s*)([+|\\-|\\*] \\[(x|-| )\\]|[+\\-\\*])(\\s+)$)\");\n QRegularExpressionMatchIterator i = regex1.globalMatch(currentLineText);\n\n if (i.hasNext()) {\n QRegularExpressionMatch match = i.next();\n QString whitespaces = match.captured(1);\n const QString listCharacter = match.captured(2);\n const QString whitespaceCharacter = match.captured(4);\n\n // add or remove one tabulator key\n if (reverse) {\n // remove one set of indentCharacters or a tabulator\n whitespaces.remove(QRegularExpression(\n QStringLiteral(\"^(\\\\t|\") +\n QRegularExpression::escape(indentCharacters) +\n QStringLiteral(\")\")));\n\n } else {\n whitespaces += indentCharacters;\n }\n\n cursor.insertText(whitespaces + listCharacter +\n whitespaceCharacter);\n return true;\n }\n\n // check if we want to indent or un-indent an ordered list\n static QRegularExpression regex2(R\"(^(\\s*)(\\d+)([\\.|\\)])(\\s+)$)\");\n i = regex2.globalMatch(currentLineText);\n\n if (i.hasNext()) {\n const QRegularExpressionMatch match = i.next();\n QString whitespaces = match.captured(1);\n const QString listCharacter = match.captured(2);\n const QString listMarker = match.captured(3);\n const QString whitespaceCharacter = match.captured(4);\n\n // add or remove one tabulator key\n if (reverse) {\n whitespaces.chop(1);\n } else {\n whitespaces += indentCharacters;\n }\n\n cursor.insertText(whitespaces + listCharacter + listMarker +\n whitespaceCharacter);\n return true;\n }\n }\n\n // check if we want to indent the whole text\n return increaseSelectedTextIndention(reverse, indentCharacters);\n}\n\n/**\n * Sets the auto text options\n */\nvoid QMarkdownTextEdit::setAutoTextOptions(AutoTextOptions options) {\n _autoTextOptions = options;\n}\n\nvoid QMarkdownTextEdit::updateLineNumberArea(const QRect rect, int dy) {\n if (dy)\n _lineNumArea->scroll(0, dy);\n else\n _lineNumArea->update(0, rect.y(), _lineNumArea->sizeHint().width(),\n rect.height());\n\n updateLineNumAreaGeometry();\n\n if (rect.contains(viewport()->rect())) {\n updateLineNumberAreaWidth(0);\n }\n}\n\nvoid QMarkdownTextEdit::updateLineNumberAreaWidth(int) {\n QSignalBlocker blocker(this);\n const auto oldMargins = viewportMargins();\n const int width =\n _lineNumArea->isLineNumAreaEnabled()\n ? _lineNumArea->sizeHint().width() + _lineNumberLeftMarginOffset\n : oldMargins.left();\n const auto newMargins = QMargins{width, oldMargins.top(),\n oldMargins.right(), oldMargins.bottom()};\n\n if (newMargins != oldMargins) {\n setViewportMargins(newMargins);\n }\n\n // Grow lineNumArea font-size with the font size of the editor\n const int pointSize = this->font().pointSize();\n if (pointSize > 0) {\n QFont font = _lineNumArea->font();\n font.setPointSize(pointSize);\n _lineNumArea->setFont(font);\n }\n}\n\n/**\n * @param e\n * @details This does two things\n * 1. Overrides QPlainTextEdit::paintEvent to fix the RTL bug of QPlainTextEdit\n * 2. Paints a rectangle around code block fences [Code taken from\n * ghostwriter(which in turn is based on QPlaintextEdit::paintEvent() with\n * modifications and minor improvements for our use\n */\nvoid QMarkdownTextEdit::paintEvent(QPaintEvent *e) {\n QTextBlock block = firstVisibleBlock();\n\n QPainter painter(viewport());\n const QRect viewportRect = viewport()->rect();\n // painter.fillRect(viewportRect, Qt::transparent);\n bool firstVisible = true;\n QPointF offset(contentOffset());\n QRectF blockAreaRect; // Code or block quote rect.\n bool inBlockArea = false;\n\n bool clipTop = false;\n bool drawBlock = false;\n qreal dy = 0.0;\n bool done = false;\n\n const QColor &color = MarkdownHighlighter::codeBlockBackgroundColor();\n const int cornerRadius = 5;\n\n while (block.isValid() && !done) {\n const QRectF r = blockBoundingRect(block).translated(offset);\n const int state = block.userState();\n\n if (!inBlockArea && MarkdownHighlighter::isCodeBlock(state)) {\n // skip the backticks\n if (!block.text().startsWith(QLatin1String(\"```\")) &&\n !block.text().startsWith(QLatin1String(\"~~~\"))) {\n blockAreaRect = r;\n dy = 0.0;\n inBlockArea = true;\n }\n\n // If this is the first visible block within the viewport\n // and if the previous block is part of the text block area,\n // then the rectangle to draw for the block area will have\n // its top clipped by the viewport and will need to be\n // drawn specially.\n const int prevBlockState = block.previous().userState();\n if (firstVisible &&\n MarkdownHighlighter::isCodeBlock(prevBlockState)) {\n clipTop = true;\n }\n }\n // Else if the block ends a text block area...\n else if (inBlockArea && MarkdownHighlighter::isCodeBlockEnd(state)) {\n drawBlock = true;\n inBlockArea = false;\n blockAreaRect.setHeight(dy);\n }\n // If the block is at the end of the document and ends a text\n // block area...\n //\n if (inBlockArea && block == this->document()->lastBlock()) {\n drawBlock = true;\n inBlockArea = false;\n dy += r.height();\n blockAreaRect.setHeight(dy);\n }\n offset.ry() += r.height();\n dy += r.height();\n\n // If this is the last text block visible within the viewport...\n if (offset.y() > viewportRect.height()) {\n if (inBlockArea) {\n blockAreaRect.setHeight(dy);\n drawBlock = true;\n }\n\n // Finished drawing.\n done = true;\n }\n // If this is the last text block visible within the viewport...\n if (offset.y() > viewportRect.height()) {\n if (inBlockArea) {\n blockAreaRect.setHeight(dy);\n drawBlock = true;\n }\n // Finished drawing.\n done = true;\n }\n\n if (drawBlock) {\n painter.setCompositionMode(QPainter::CompositionMode_SourceOver);\n painter.setPen(Qt::NoPen);\n painter.setBrush(QBrush(color));\n\n // If the first visible block is \"clipped\" such that the previous\n // block is part of the text block area, then only draw a rectangle\n // with the bottom corners rounded, and with the top corners square\n // to reflect that the first visible block is part of a larger block\n // of text.\n //\n if (clipTop) {\n QPainterPath path;\n path.setFillRule(Qt::WindingFill);\n path.addRoundedRect(blockAreaRect, cornerRadius, cornerRadius);\n qreal adjustedHeight = blockAreaRect.height() / 2;\n path.addRect(blockAreaRect.adjusted(0, 0, 0, -adjustedHeight));\n painter.drawPath(path.simplified());\n clipTop = false;\n }\n // Else draw the entire rectangle with all corners rounded.\n else {\n painter.drawRoundedRect(blockAreaRect, cornerRadius,\n cornerRadius);\n }\n\n drawBlock = false;\n }\n\n // this fixes the RTL bug of QPlainTextEdit\n // https://bugreports.qt.io/browse/QTBUG-7516\n if (block.text().isRightToLeft()) {\n QTextLayout *layout = block.layout();\n // opt = document()->defaultTextOption();\n QTextOption opt = QTextOption(Qt::AlignRight);\n opt.setTextDirection(Qt::RightToLeft);\n layout->setTextOption(opt);\n }\n\n // Current line highlight\n QTextCursor cursor = textCursor();\n if (highlightCurrentLine() && cursor.block() == block) {\n QTextLine line =\n block.layout()->lineForTextPosition(cursor.positionInBlock());\n QRectF lineRect = line.rect();\n lineRect.moveTop(lineRect.top() + r.top());\n lineRect.setLeft(0.);\n lineRect.setRight(viewportRect.width());\n painter.fillRect(lineRect.toAlignedRect(),\n currentLineHighlightColor());\n }\n\n block = block.next();\n firstVisible = false;\n }\n\n painter.end();\n QPlainTextEdit::paintEvent(e);\n}\n\n/**\n * Overrides QPlainTextEdit::setReadOnly to fix a problem with Chinese and\n * Japanese input methods\n *\n * @param ro\n */\nvoid QMarkdownTextEdit::setReadOnly(bool ro) {\n QPlainTextEdit::setReadOnly(ro);\n\n // attempted to fix a problem with Chinese and Japanese input methods\n // @see https://github.com/pbek/QOwnNotes/issues/976\n setAttribute(Qt::WA_InputMethodEnabled, !isReadOnly());\n}\n\nvoid QMarkdownTextEdit::doSearch(\n QString &searchText, QPlainTextEditSearchWidget::SearchMode searchMode) {\n _searchWidget->setSearchText(searchText);\n _searchWidget->setSearchMode(searchMode);\n _searchWidget->doSearchCount();\n _searchWidget->activate(false);\n}\n\nvoid QMarkdownTextEdit::hideSearchWidget(bool reset) {\n _searchWidget->deactivate();\n\n if (reset) {\n _searchWidget->reset();\n }\n}\n\nvoid QMarkdownTextEdit::updateSettings() {\n // if true: centers the screen if cursor reaches bottom (but not top)\n searchWidget()->setDebounceDelay(_debounceDelay);\n setCenterOnScroll(_centerCursor);\n}\n\nvoid QMarkdownTextEdit::setLineNumberLeftMarginOffset(int offset) {\n _lineNumberLeftMarginOffset = offset;\n}\n\nQMargins QMarkdownTextEdit::viewportMargins() {\n return QPlainTextEdit::viewportMargins();\n}\n bool bracketClosingCheck(const QChar openingCharacter,\n QChar closingCharacter) {\n // check if bracket closing or read-only are enabled\n if (!(_autoTextOptions & AutoTextOption::BracketClosing) || isReadOnly()) {\n return false;\n }\n\n if (closingCharacter.isNull()) {\n closingCharacter = openingCharacter;\n }\n\n QTextCursor cursor = textCursor();\n const int positionInBlock = cursor.positionInBlock();\n\n // get the current text from the block\n const QString text = cursor.block().text();\n const int textLength = text.length();\n\n // if we are at the end of the line we just want to enter the character\n if (positionInBlock >= textLength) {\n return false;\n }\n\n const QChar currentChar = text.at(positionInBlock);\n\n // if (closingCharacter == openingCharacter) {\n\n // }\n\n qDebug() << __func__ << \" - 'currentChar': \" << currentChar;\n\n // if the current character is not the closing character we just want to\n // enter the character\n if (currentChar != closingCharacter) {\n return false;\n }\n\n const QString leftText = text.left(positionInBlock);\n const int openingCharacterCount = leftText.count(openingCharacter);\n const int closingCharacterCount = leftText.count(closingCharacter);\n\n // if there were enough opening characters just enter the character\n if (openingCharacterCount < (closingCharacterCount + 1)) {\n return false;\n }\n\n // move the cursor to the right and don't enter the character\n cursor.movePosition(QTextCursor::Right);\n setTextCursor(cursor);\n return true;\n}\n bool quotationMarkCheck(const QChar quotationCharacter) {\n // check if bracket closing or read-only are enabled\n if (!(_autoTextOptions & AutoTextOption::BracketClosing) || isReadOnly()) {\n return false;\n }\n\n QTextCursor cursor = textCursor();\n const int positionInBlock = cursor.positionInBlock();\n\n // get the current text from the block\n const QString text = cursor.block().text();\n const int textLength = text.length();\n\n // if last char is not space, we are at word end, no autocompletion\n const bool isBacktick = quotationCharacter == '`';\n if (!isBacktick && positionInBlock != 0 &&\n !text.at(positionInBlock - 1).isSpace()) {\n return false;\n }\n\n // if we are at the end of the line we just want to enter the character\n if (positionInBlock >= textLength) {\n return handleBracketClosing(quotationCharacter);\n }\n\n const QChar currentChar = text.at(positionInBlock);\n\n // if the current character is not the quotation character we just want to\n // enter the character\n if (currentChar != quotationCharacter) {\n return handleBracketClosing(quotationCharacter);\n }\n\n // move the cursor to the right and don't enter the character\n cursor.movePosition(QTextCursor::Right);\n setTextCursor(cursor);\n return true;\n}\n void focusOutEvent(QFocusEvent *event) override {\n resetMouseCursor();\n QPlainTextEdit::focusOutEvent(event);\n}\n void paintEvent(QPaintEvent *e) override {\n QTextBlock block = firstVisibleBlock();\n\n QPainter painter(viewport());\n const QRect viewportRect = viewport()->rect();\n // painter.fillRect(viewportRect, Qt::transparent);\n bool firstVisible = true;\n QPointF offset(contentOffset());\n QRectF blockAreaRect; // Code or block quote rect.\n bool inBlockArea = false;\n\n bool clipTop = false;\n bool drawBlock = false;\n qreal dy = 0.0;\n bool done = false;\n\n const QColor &color = MarkdownHighlighter::codeBlockBackgroundColor();\n const int cornerRadius = 5;\n\n while (block.isValid() && !done) {\n const QRectF r = blockBoundingRect(block).translated(offset);\n const int state = block.userState();\n\n if (!inBlockArea && MarkdownHighlighter::isCodeBlock(state)) {\n // skip the backticks\n if (!block.text().startsWith(QLatin1String(\"```\")) &&\n !block.text().startsWith(QLatin1String(\"~~~\"))) {\n blockAreaRect = r;\n dy = 0.0;\n inBlockArea = true;\n }\n\n // If this is the first visible block within the viewport\n // and if the previous block is part of the text block area,\n // then the rectangle to draw for the block area will have\n // its top clipped by the viewport and will need to be\n // drawn specially.\n const int prevBlockState = block.previous().userState();\n if (firstVisible &&\n MarkdownHighlighter::isCodeBlock(prevBlockState)) {\n clipTop = true;\n }\n }\n // Else if the block ends a text block area...\n else if (inBlockArea && MarkdownHighlighter::isCodeBlockEnd(state)) {\n drawBlock = true;\n inBlockArea = false;\n blockAreaRect.setHeight(dy);\n }\n // If the block is at the end of the document and ends a text\n // block area...\n //\n if (inBlockArea && block == this->document()->lastBlock()) {\n drawBlock = true;\n inBlockArea = false;\n dy += r.height();\n blockAreaRect.setHeight(dy);\n }\n offset.ry() += r.height();\n dy += r.height();\n\n // If this is the last text block visible within the viewport...\n if (offset.y() > viewportRect.height()) {\n if (inBlockArea) {\n blockAreaRect.setHeight(dy);\n drawBlock = true;\n }\n\n // Finished drawing.\n done = true;\n }\n // If this is the last text block visible within the viewport...\n if (offset.y() > viewportRect.height()) {\n if (inBlockArea) {\n blockAreaRect.setHeight(dy);\n drawBlock = true;\n }\n // Finished drawing.\n done = true;\n }\n\n if (drawBlock) {\n painter.setCompositionMode(QPainter::CompositionMode_SourceOver);\n painter.setPen(Qt::NoPen);\n painter.setBrush(QBrush(color));\n\n // If the first visible block is \"clipped\" such that the previous\n // block is part of the text block area, then only draw a rectangle\n // with the bottom corners rounded, and with the top corners square\n // to reflect that the first visible block is part of a larger block\n // of text.\n //\n if (clipTop) {\n QPainterPath path;\n path.setFillRule(Qt::WindingFill);\n path.addRoundedRect(blockAreaRect, cornerRadius, cornerRadius);\n qreal adjustedHeight = blockAreaRect.height() / 2;\n path.addRect(blockAreaRect.adjusted(0, 0, 0, -adjustedHeight));\n painter.drawPath(path.simplified());\n clipTop = false;\n }\n // Else draw the entire rectangle with all corners rounded.\n else {\n painter.drawRoundedRect(blockAreaRect, cornerRadius,\n cornerRadius);\n }\n\n drawBlock = false;\n }\n\n // this fixes the RTL bug of QPlainTextEdit\n // https://bugreports.qt.io/browse/QTBUG-7516\n if (block.text().isRightToLeft()) {\n QTextLayout *layout = block.layout();\n // opt = document()->defaultTextOption();\n QTextOption opt = QTextOption(Qt::AlignRight);\n opt.setTextDirection(Qt::RightToLeft);\n layout->setTextOption(opt);\n }\n\n // Current line highlight\n QTextCursor cursor = textCursor();\n if (highlightCurrentLine() && cursor.block() == block) {\n QTextLine line =\n block.layout()->lineForTextPosition(cursor.positionInBlock());\n QRectF lineRect = line.rect();\n lineRect.moveTop(lineRect.top() + r.top());\n lineRect.setLeft(0.);\n lineRect.setRight(viewportRect.width());\n painter.fillRect(lineRect.toAlignedRect(),\n currentLineHighlightColor());\n }\n\n block = block.next();\n firstVisible = false;\n }\n\n painter.end();\n QPlainTextEdit::paintEvent(e);\n}\n bool handleCharRemoval(MarkdownHighlighter::RangeType type, int block,\n int position) {\n if (!_highlighter) return false;\n\n auto range = _highlighter->findPositionInRanges(type, block, position);\n if (range == QPair{-1, -1}) return false;\n\n int charToRemovePos = range.first;\n if (position == range.first) charToRemovePos = range.second;\n\n QTextCursor cursor = textCursor();\n auto gpos = cursor.position();\n\n if (charToRemovePos > position) {\n cursor.setPosition(gpos + (charToRemovePos - (position + 1)));\n } else {\n cursor.setPosition(gpos - (position - charToRemovePos + 1));\n gpos--;\n }\n\n cursor.deleteChar();\n cursor.setPosition(gpos);\n setTextCursor(cursor);\n return false;\n}\n void resizeEvent(QResizeEvent *event) override {\n QPlainTextEdit::resizeEvent(event);\n updateLineNumAreaGeometry();\n}\n void setLineNumberLeftMarginOffset(int offset) {\n _lineNumberLeftMarginOffset = offset;\n}\n int _lineNumberLeftMarginOffset = 0;\n void updateLineNumAreaGeometry() {\n const auto contentsRect = this->contentsRect();\n const QRect newGeometry = {contentsRect.left(), contentsRect.top(),\n _lineNumArea->sizeHint().width(),\n contentsRect.height()};\n auto oldGeometry = _lineNumArea->geometry();\n if (newGeometry != oldGeometry) {\n _lineNumArea->setGeometry(newGeometry);\n }\n}\n void updateLineNumberArea(const QRect rect, int dy) {\n if (dy)\n _lineNumArea->scroll(0, dy);\n else\n _lineNumArea->update(0, rect.y(), _lineNumArea->sizeHint().width(),\n rect.height());\n\n updateLineNumAreaGeometry();\n\n if (rect.contains(viewport()->rect())) {\n updateLineNumberAreaWidth(0);\n }\n}\n Q_SLOT void updateLineNumberAreaWidth(int) {\n QSignalBlocker blocker(this);\n const auto oldMargins = viewportMargins();\n const int width =\n _lineNumArea->isLineNumAreaEnabled()\n ? _lineNumArea->sizeHint().width() + _lineNumberLeftMarginOffset\n : oldMargins.left();\n const auto newMargins = QMargins{width, oldMargins.top(),\n oldMargins.right(), oldMargins.bottom()};\n\n if (newMargins != oldMargins) {\n setViewportMargins(newMargins);\n }\n\n // Grow lineNumArea font-size with the font size of the editor\n const int pointSize = this->font().pointSize();\n if (pointSize > 0) {\n QFont font = _lineNumArea->font();\n font.setPointSize(pointSize);\n _lineNumArea->setFont(font);\n }\n}\n bool _handleBracketClosingUsed;\n LineNumArea *_lineNumArea;\n void urlClicked(QString url);\n void zoomIn();\n void zoomOut();\n};"], ["/SpeedyNote/source/MarkdownWindowManager.h", "class MarkdownWindow {\n Q_OBJECT\n\npublic:\n explicit MarkdownWindowManager(InkCanvas *canvas, QObject *parent = nullptr);\n ~MarkdownWindowManager() {\n clearAllWindows();\n}\n MarkdownWindow* createMarkdownWindow(const QRect &rect);\n void removeMarkdownWindow(MarkdownWindow *window) {\n if (!window) return;\n \n // Remove from current windows\n currentWindows.removeAll(window);\n \n // Remove from all page windows\n for (auto it = pageWindows.begin(); it != pageWindows.end(); ++it) {\n it.value().removeAll(window);\n }\n \n emit windowRemoved(window);\n \n // Delete the window\n window->deleteLater();\n}\n void clearAllWindows() {\n // Stop transparency timer\n transparencyTimer->stop();\n currentlyFocusedWindow = nullptr;\n windowsAreTransparent = false;\n \n // Clear current windows\n for (MarkdownWindow *window : currentWindows) {\n window->deleteLater();\n }\n currentWindows.clear();\n \n // Clear page windows\n for (auto it = pageWindows.begin(); it != pageWindows.end(); ++it) {\n for (MarkdownWindow *window : it.value()) {\n window->deleteLater();\n }\n }\n pageWindows.clear();\n}\n void saveWindowsForPage(int pageNumber) {\n if (!canvas || currentWindows.isEmpty()) return;\n \n // Update page windows map\n pageWindows[pageNumber] = currentWindows;\n \n // Save to file\n saveWindowData(pageNumber, currentWindows);\n}\n void loadWindowsForPage(int pageNumber) {\n if (!canvas) return;\n\n // qDebug() << \"MarkdownWindowManager::loadWindowsForPage(\" << pageNumber << \")\";\n\n // This method is now only responsible for loading and showing the\n // windows for the specified page. Hiding of old windows is handled before this.\n\n QList newPageWindows;\n\n // Check if we have windows for this page in memory\n if (pageWindows.contains(pageNumber)) {\n // qDebug() << \"Found windows in memory for page\" << pageNumber;\n newPageWindows = pageWindows[pageNumber];\n } else {\n // qDebug() << \"Loading windows from file for page\" << pageNumber;\n // Load from file\n newPageWindows = loadWindowData(pageNumber);\n\n // Update page windows map\n if (!newPageWindows.isEmpty()) {\n pageWindows[pageNumber] = newPageWindows;\n }\n }\n\n // qDebug() << \"Loaded\" << newPageWindows.size() << \"windows for page\" << pageNumber;\n\n // Update the current window list and show the windows\n currentWindows = newPageWindows;\n for (MarkdownWindow *window : currentWindows) {\n // Validate that the window is within canvas bounds\n if (!window->isValidForCanvas()) {\n // qDebug() << \"Warning: Markdown window at\" << window->getCanvasRect() \n // << \"is outside canvas bounds\" << canvas->getCanvasRect();\n // Optionally adjust the window position to fit within bounds\n QRect canvasBounds = canvas->getCanvasRect();\n QRect windowRect = window->getCanvasRect();\n \n // Clamp the window position to canvas bounds\n int newX = qMax(0, qMin(windowRect.x(), canvasBounds.width() - windowRect.width()));\n int newY = qMax(0, qMin(windowRect.y(), canvasBounds.height() - windowRect.height()));\n \n if (newX != windowRect.x() || newY != windowRect.y()) {\n QRect adjustedRect(newX, newY, windowRect.width(), windowRect.height());\n window->setCanvasRect(adjustedRect);\n // qDebug() << \"Adjusted window position to\" << adjustedRect;\n }\n }\n \n // Ensure canvas connections are set up for loaded windows\n window->ensureCanvasConnections();\n \n window->show();\n window->updateScreenPosition();\n // Make sure window is not transparent when loaded\n window->setTransparent(false);\n }\n \n // Start transparency timer if there are windows but none are focused\n if (!currentWindows.isEmpty()) {\n // qDebug() << \"Starting transparency timer for\" << currentWindows.size() << \"windows\";\n resetTransparencyTimer();\n } else {\n // qDebug() << \"No windows to show, not starting timer\";\n }\n}\n void deleteWindowsForPage(int pageNumber) {\n // Remove windows from memory\n if (pageWindows.contains(pageNumber)) {\n QList windows = pageWindows[pageNumber];\n for (MarkdownWindow *window : windows) {\n window->deleteLater();\n }\n pageWindows.remove(pageNumber);\n }\n \n // Delete file\n QString filePath = getWindowDataFilePath(pageNumber);\n if (QFile::exists(filePath)) {\n QFile::remove(filePath);\n }\n \n // Clear current windows if they belong to this page\n if (pageWindows.value(pageNumber) == currentWindows) {\n currentWindows.clear();\n }\n}\n void setSelectionMode(bool enabled) {\n selectionMode = enabled;\n \n // Change cursor for canvas\n if (canvas) {\n canvas->setCursor(enabled ? Qt::CrossCursor : Qt::ArrowCursor);\n }\n}\n QList getCurrentPageWindows() const {\n return currentWindows;\n}\n void resetTransparencyTimer() {\n // qDebug() << \"MarkdownWindowManager::resetTransparencyTimer() called\";\n transparencyTimer->stop();\n \n // DON'T make all windows opaque here - only stop the timer\n // The focused window should be made opaque by the caller if needed\n windowsAreTransparent = false; // Reset the state\n \n // Start the timer again\n transparencyTimer->start();\n // qDebug() << \"Transparency timer started for 10 seconds\";\n}\n void setWindowsTransparent(bool transparent) {\n if (windowsAreTransparent == transparent) return;\n \n // qDebug() << \"MarkdownWindowManager::setWindowsTransparent(\" << transparent << \")\";\n // qDebug() << \"Current windows count:\" << currentWindows.size();\n // qDebug() << \"Currently focused window:\" << currentlyFocusedWindow;\n \n windowsAreTransparent = transparent;\n \n // Apply transparency logic:\n // - If transparent=true: make all windows except focused one transparent\n // - If transparent=false: make all windows opaque\n for (MarkdownWindow *window : currentWindows) {\n if (transparent) {\n // When making transparent, only make non-focused windows transparent\n if (window != currentlyFocusedWindow) {\n // qDebug() << \"Setting unfocused window\" << window << \"transparent: true\";\n window->setTransparent(true);\n } else {\n // qDebug() << \"Keeping focused window\" << window << \"opaque\";\n window->setTransparent(false);\n }\n } else {\n // When making opaque, make all windows opaque\n // qDebug() << \"Setting window\" << window << \"transparent: false\";\n window->setTransparent(false);\n }\n }\n}\n void hideAllWindows() {\n // Stop transparency timer when hiding windows\n transparencyTimer->stop();\n currentlyFocusedWindow = nullptr;\n windowsAreTransparent = false;\n \n // Hide all current windows\n for (MarkdownWindow *window : currentWindows) {\n window->hide();\n window->setTransparent(false); // Reset transparency state\n }\n}\n void windowCreated(MarkdownWindow *window);\n void windowRemoved(MarkdownWindow *window);\n private:\n void onWindowDeleteRequested(MarkdownWindow *window) {\n removeMarkdownWindow(window);\n \n // Mark canvas as edited since we deleted a markdown window\n if (canvas) {\n canvas->setEdited(true);\n }\n \n // Save current state\n if (canvas) {\n MainWindow *mainWindow = qobject_cast(canvas->parent());\n if (mainWindow) {\n int currentPage = mainWindow->getCurrentPageForCanvas(canvas);\n saveWindowsForPage(currentPage);\n }\n }\n}\n void onWindowFocusChanged(MarkdownWindow *window, bool focused) {\n // qDebug() << \"MarkdownWindowManager::onWindowFocusChanged(\" << window << \", \" << focused << \")\";\n \n if (focused) {\n // A window gained focus - make it opaque immediately and reset timer\n // qDebug() << \"Window gained focus, setting as currently focused\";\n currentlyFocusedWindow = window;\n \n // Make the focused window opaque immediately\n window->setTransparent(false);\n \n // Reset timer to start counting down for making other windows transparent\n resetTransparencyTimer();\n } else {\n // A window lost focus\n // qDebug() << \"Window lost focus\";\n if (currentlyFocusedWindow == window) {\n // qDebug() << \"Clearing currently focused window\";\n currentlyFocusedWindow = nullptr;\n }\n \n // Check if any window still has focus\n bool anyWindowFocused = false;\n for (MarkdownWindow *w : currentWindows) {\n if (w->isEditorFocused()) {\n // qDebug() << \"Found another focused window:\" << w;\n anyWindowFocused = true;\n currentlyFocusedWindow = w;\n // Make the newly focused window opaque\n w->setTransparent(false);\n break;\n }\n }\n \n if (!anyWindowFocused) {\n // qDebug() << \"No window has focus, starting transparency timer\";\n // No window has focus, start transparency timer\n resetTransparencyTimer();\n } else {\n // qDebug() << \"Another window still has focus, resetting timer\";\n // Another window has focus, reset timer\n resetTransparencyTimer();\n }\n }\n}\n void onWindowContentChanged(MarkdownWindow *window) {\n // qDebug() << \"MarkdownWindowManager::onWindowContentChanged(\" << window << \")\";\n \n // Content changed, make this window the focused one and reset transparency timer\n currentlyFocusedWindow = window;\n window->setTransparent(false); // Make the active window opaque\n \n // Reset transparency timer\n resetTransparencyTimer();\n}\n void onTransparencyTimerTimeout() {\n // qDebug() << \"MarkdownWindowManager::onTransparencyTimerTimeout() - Timer expired!\";\n // Make all windows except the focused one semi-transparent\n setWindowsTransparent(true);\n}\n private:\n InkCanvas *canvas;\n bool selectionMode = false;\n QMap> pageWindows;\n QList currentWindows;\n QTimer *transparencyTimer;\n MarkdownWindow *currentlyFocusedWindow = nullptr;\n bool windowsAreTransparent = false;\n QString getWindowDataFilePath(int pageNumber) const {\n QString saveFolder = getSaveFolder();\n QString notebookId = getNotebookId();\n \n if (saveFolder.isEmpty() || notebookId.isEmpty()) {\n return QString();\n }\n \n return saveFolder + QString(\"/.%1_markdown_%2.json\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n}\n void saveWindowData(int pageNumber, const QList &windows) {\n QString filePath = getWindowDataFilePath(pageNumber);\n if (filePath.isEmpty()) return;\n \n QJsonArray windowsArray;\n for (MarkdownWindow *window : windows) {\n QVariantMap windowData = window->serialize();\n windowsArray.append(QJsonObject::fromVariantMap(windowData));\n }\n \n QJsonDocument doc(windowsArray);\n \n QFile file(filePath);\n if (file.open(QIODevice::WriteOnly)) {\n file.write(doc.toJson());\n file.close();\n \n #ifdef Q_OS_WIN\n // Set hidden attribute on Windows\n SetFileAttributesW(reinterpret_cast(filePath.utf16()), FILE_ATTRIBUTE_HIDDEN);\n #endif\n }\n}\n QList loadWindowData(int pageNumber) {\n QList windows;\n \n QString filePath = getWindowDataFilePath(pageNumber);\n if (filePath.isEmpty() || !QFile::exists(filePath)) {\n return windows;\n }\n \n QFile file(filePath);\n if (!file.open(QIODevice::ReadOnly)) {\n return windows;\n }\n \n QByteArray data = file.readAll();\n file.close();\n \n QJsonParseError error;\n QJsonDocument doc = QJsonDocument::fromJson(data, &error);\n if (error.error != QJsonParseError::NoError) {\n qWarning() << \"Failed to parse markdown window data:\" << error.errorString();\n return windows;\n }\n \n QJsonArray windowsArray = doc.array();\n for (const QJsonValue &value : windowsArray) {\n QJsonObject windowObj = value.toObject();\n QVariantMap windowData = windowObj.toVariantMap();\n \n // Create window with default rect (will be updated by deserialize)\n MarkdownWindow *window = new MarkdownWindow(QRect(0, 0, 300, 200), canvas);\n window->deserialize(windowData);\n \n // Connect signals\n connectWindowSignals(window);\n \n windows.append(window);\n window->show();\n }\n \n return windows;\n}\n QString getSaveFolder() const {\n return canvas ? canvas->getSaveFolder() : QString();\n}\n QString getNotebookId() const {\n if (!canvas) return QString();\n \n QString saveFolder = canvas->getSaveFolder();\n if (saveFolder.isEmpty()) return QString();\n \n QString idFile = saveFolder + \"/.notebook_id.txt\";\n if (QFile::exists(idFile)) {\n QFile file(idFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString notebookId = in.readLine().trimmed();\n file.close();\n return notebookId;\n }\n }\n \n return \"notebook\"; // Default fallback\n}\n QRect convertScreenToCanvasRect(const QRect &screenRect) const {\n if (!canvas) {\n // qDebug() << \"MarkdownWindowManager::convertScreenToCanvasRect() - No canvas, returning screen rect:\" << screenRect;\n return screenRect;\n }\n \n // Use the new coordinate conversion methods from InkCanvas\n QRect canvasRect = canvas->mapWidgetToCanvas(screenRect);\n // qDebug() << \"MarkdownWindowManager::convertScreenToCanvasRect() - Screen rect:\" << screenRect << \"-> Canvas rect:\" << canvasRect;\n // qDebug() << \" Canvas size:\" << canvas->getCanvasSize() << \"Zoom:\" << canvas->getZoomFactor() << \"Pan:\" << canvas->getPanOffset();\n return canvasRect;\n}\n void connectWindowSignals(MarkdownWindow *window) {\n // qDebug() << \"MarkdownWindowManager::connectWindowSignals() - Connecting signals for window\" << window;\n \n // Connect existing signals\n connect(window, &MarkdownWindow::deleteRequested, this, &MarkdownWindowManager::onWindowDeleteRequested);\n connect(window, &MarkdownWindow::contentChanged, this, [this, window]() {\n onWindowContentChanged(window);\n \n // Mark canvas as edited since markdown content changed\n if (canvas) {\n canvas->setEdited(true);\n \n // Get current page and save windows\n MainWindow *mainWindow = qobject_cast(canvas->parent());\n if (mainWindow) {\n int currentPage = mainWindow->getCurrentPageForCanvas(canvas);\n saveWindowsForPage(currentPage);\n }\n }\n });\n connect(window, &MarkdownWindow::windowMoved, this, [this, window](MarkdownWindow*) {\n // qDebug() << \"Window moved:\" << window;\n \n // Window was moved, make it the focused one and reset transparency timer\n currentlyFocusedWindow = window;\n window->setTransparent(false); // Make the active window opaque\n resetTransparencyTimer();\n \n // Mark canvas as edited since window was moved\n if (canvas) {\n canvas->setEdited(true);\n }\n });\n connect(window, &MarkdownWindow::windowResized, this, [this, window](MarkdownWindow*) {\n // qDebug() << \"Window resized:\" << window;\n \n // Window was resized, make it the focused one and reset transparency timer\n currentlyFocusedWindow = window;\n window->setTransparent(false); // Make the active window opaque\n resetTransparencyTimer();\n \n // Mark canvas as edited since window was resized\n if (canvas) {\n canvas->setEdited(true);\n }\n });\n \n // Connect new transparency-related signals\n connect(window, &MarkdownWindow::focusChanged, this, &MarkdownWindowManager::onWindowFocusChanged);\n connect(window, &MarkdownWindow::editorFocusChanged, this, &MarkdownWindowManager::onWindowFocusChanged);\n connect(window, &MarkdownWindow::windowInteracted, this, [this, window](MarkdownWindow*) {\n // qDebug() << \"Window interacted:\" << window;\n \n // Window was clicked/interacted with, make it the focused one and reset transparency timer\n currentlyFocusedWindow = window;\n window->setTransparent(false); // Make the active window opaque\n resetTransparencyTimer();\n });\n \n // qDebug() << \"All signals connected for window\" << window;\n}\n public:\n void updateAllWindowPositions() {\n // Update positions of all current windows\n for (MarkdownWindow *window : currentWindows) {\n if (window) {\n window->updateScreenPosition();\n }\n }\n}\n};"], ["/SpeedyNote/markdown/qplaintexteditsearchwidget.h", "class QPlainTextEditSearchWidget {\n Q_OBJECT\n\n public:\n enum SearchMode { PlainTextMode, WholeWordsMode, RegularExpressionMode };\n explicit QPlainTextEditSearchWidget(QPlainTextEdit *parent = nullptr) {\n ui->setupUi(this);\n _textEdit = parent;\n _darkMode = false;\n hide();\n ui->searchCountLabel->setStyleSheet(QStringLiteral(\"* {color: grey}\"));\n // hiding will leave a open space in the horizontal layout\n ui->searchCountLabel->setEnabled(false);\n _currentSearchResult = 0;\n _searchResultCount = 0;\n\n connect(ui->closeButton, &QPushButton::clicked, this,\n &QPlainTextEditSearchWidget::deactivate);\n connect(ui->searchLineEdit, &QLineEdit::textChanged, this,\n &QPlainTextEditSearchWidget::searchLineEditTextChanged);\n connect(ui->searchDownButton, &QPushButton::clicked, this,\n &QPlainTextEditSearchWidget::doSearchDown);\n connect(ui->searchUpButton, &QPushButton::clicked, this,\n &QPlainTextEditSearchWidget::doSearchUp);\n connect(ui->replaceToggleButton, &QPushButton::toggled, this,\n &QPlainTextEditSearchWidget::setReplaceMode);\n connect(ui->replaceButton, &QPushButton::clicked, this,\n &QPlainTextEditSearchWidget::doReplace);\n connect(ui->replaceAllButton, &QPushButton::clicked, this,\n &QPlainTextEditSearchWidget::doReplaceAll);\n\n connect(&_debounceTimer, &QTimer::timeout, this,\n &QPlainTextEditSearchWidget::performSearch);\n\n installEventFilter(this);\n ui->searchLineEdit->installEventFilter(this);\n ui->replaceLineEdit->installEventFilter(this);\n\n#ifdef Q_OS_MAC\n // set the spacing to 8 for OS X\n layout()->setSpacing(8);\n ui->buttonFrame->layout()->setSpacing(9);\n\n // set the margin to 0 for the top buttons for OS X\n QString buttonStyle = QStringLiteral(\"QPushButton {margin: 0}\");\n ui->closeButton->setStyleSheet(buttonStyle);\n ui->searchDownButton->setStyleSheet(buttonStyle);\n ui->searchUpButton->setStyleSheet(buttonStyle);\n ui->replaceToggleButton->setStyleSheet(buttonStyle);\n ui->matchCaseSensitiveButton->setStyleSheet(buttonStyle);\n#endif\n}\n bool doSearch(bool searchDown = true, bool allowRestartAtTop = true,\n bool updateUI = true) {\n if (_debounceTimer.isActive()) {\n stopDebounce();\n }\n\n const QString text = ui->searchLineEdit->text();\n\n if (text.isEmpty()) {\n if (updateUI) {\n ui->searchLineEdit->setStyleSheet(QLatin1String(\"\"));\n }\n\n return false;\n }\n\n const int searchMode = ui->modeComboBox->currentIndex();\n const bool caseSensitive = ui->matchCaseSensitiveButton->isChecked();\n\n QFlags options =\n searchDown ? QTextDocument::FindFlag(0) : QTextDocument::FindBackward;\n if (searchMode == WholeWordsMode) {\n options |= QTextDocument::FindWholeWords;\n }\n\n if (caseSensitive) {\n options |= QTextDocument::FindCaseSensitively;\n }\n\n // block signal to reduce too many signals being fired and too many updates\n _textEdit->blockSignals(true);\n\n bool found =\n searchMode == RegularExpressionMode\n ?\n#if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0))\n _textEdit->find(\n QRegularExpression(\n text, caseSensitive\n ? QRegularExpression::NoPatternOption\n : QRegularExpression::CaseInsensitiveOption),\n options)\n :\n#else\n _textEdit->find(QRegExp(text, caseSensitive ? Qt::CaseSensitive\n : Qt::CaseInsensitive),\n options)\n :\n#endif\n _textEdit->find(text, options);\n\n _textEdit->blockSignals(false);\n\n if (found) {\n const int result =\n searchDown ? ++_currentSearchResult : --_currentSearchResult;\n _currentSearchResult = std::min(result, _searchResultCount);\n\n updateSearchCountLabelText();\n }\n\n // start at the top (or bottom) if not found\n if (!found && allowRestartAtTop) {\n _textEdit->moveCursor(searchDown ? QTextCursor::Start\n : QTextCursor::End);\n found =\n searchMode == RegularExpressionMode\n ?\n#if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0))\n _textEdit->find(\n QRegularExpression(\n text, caseSensitive\n ? QRegularExpression::NoPatternOption\n : QRegularExpression::CaseInsensitiveOption),\n options)\n :\n#else\n _textEdit->find(\n QRegExp(text, caseSensitive ? Qt::CaseSensitive\n : Qt::CaseInsensitive),\n options)\n :\n#endif\n _textEdit->find(text, options);\n\n if (found && updateUI) {\n _currentSearchResult = searchDown ? 1 : _searchResultCount;\n updateSearchCountLabelText();\n }\n }\n\n if (updateUI) {\n const QRect rect = _textEdit->cursorRect();\n QMargins margins = _textEdit->layout()->contentsMargins();\n const int searchWidgetHotArea = _textEdit->height() - this->height();\n const int marginBottom =\n (rect.y() > searchWidgetHotArea) ? (this->height() + 10) : 0;\n\n // move the search box a bit up if we would block the search result\n if (margins.bottom() != marginBottom) {\n margins.setBottom(marginBottom);\n _textEdit->layout()->setContentsMargins(margins);\n }\n\n // add a background color according if we found the text or not\n const QString bgColorCode = _darkMode\n ? (found ? QStringLiteral(\"#135a13\")\n : QStringLiteral(\"#8d2b36\"))\n : found ? QStringLiteral(\"#D5FAE2\")\n : QStringLiteral(\"#FAE9EB\");\n const QString fgColorCode =\n _darkMode ? QStringLiteral(\"#cccccc\") : QStringLiteral(\"#404040\");\n\n ui->searchLineEdit->setStyleSheet(\n QStringLiteral(\"* { background: \") + bgColorCode +\n QStringLiteral(\"; color: \") + fgColorCode + QStringLiteral(\"; }\"));\n\n // restore the search extra selections after the find command\n this->setSearchExtraSelections();\n }\n\n return found;\n}\n void setDarkMode(bool enabled) {\n _darkMode = enabled;\n}\n ~QPlainTextEditSearchWidget() { delete ui; }\n void setSearchText(const QString &searchText) {\n ui->searchLineEdit->setText(searchText);\n}\n void setSearchMode(SearchMode searchMode) {\n ui->modeComboBox->setCurrentIndex(searchMode);\n}\n void setDebounceDelay(uint debounceDelay) {\n _debounceTimer.setInterval(static_cast(debounceDelay));\n}\n void activate(bool focus) {\n setReplaceMode(ui->modeComboBox->currentIndex() !=\n SearchMode::PlainTextMode);\n show();\n\n // preset the selected text as search text if there is any and there is no\n // other search text\n const QString selectedText = _textEdit->textCursor().selectedText();\n if (!selectedText.isEmpty() && ui->searchLineEdit->text().isEmpty()) {\n ui->searchLineEdit->setText(selectedText);\n }\n\n if (focus) {\n ui->searchLineEdit->setFocus();\n }\n\n ui->searchLineEdit->selectAll();\n updateSearchExtraSelections();\n doSearchDown();\n}\n void clearSearchExtraSelections() {\n _searchExtraSelections.clear();\n setSearchExtraSelections();\n}\n void updateSearchExtraSelections() {\n _searchExtraSelections.clear();\n const auto textCursor = _textEdit->textCursor();\n _textEdit->moveCursor(QTextCursor::Start);\n const QColor color = selectionColor;\n QTextCharFormat extraFmt;\n extraFmt.setBackground(color);\n int findCounter = 0;\n const int searchMode = ui->modeComboBox->currentIndex();\n\n while (doSearch(true, false, false)) {\n findCounter++;\n\n // prevent infinite loops from regular expression searches like \"$\", \"^\"\n // or \"\\b\"\n if (searchMode == RegularExpressionMode && findCounter >= 10000) {\n break;\n }\n\n QTextEdit::ExtraSelection extra = QTextEdit::ExtraSelection();\n extra.format = extraFmt;\n\n extra.cursor = _textEdit->textCursor();\n _searchExtraSelections.append(extra);\n }\n\n _textEdit->setTextCursor(textCursor);\n this->setSearchExtraSelections();\n}\n private:\n Ui::QPlainTextEditSearchWidget *ui;\n int _searchResultCount;\n int _currentSearchResult;\n QList _searchExtraSelections;\n QColor selectionColor;\n QTimer _debounceTimer;\n QString _searchTerm;\n void setSearchExtraSelections() const {\n this->_textEdit->setExtraSelections(this->_searchExtraSelections);\n}\n void stopDebounce() {\n _debounceTimer.stop();\n ui->searchDownButton->setEnabled(true);\n ui->searchUpButton->setEnabled(true);\n}\n protected:\n QPlainTextEdit *_textEdit;\n bool _darkMode;\n bool eventFilter(QObject *obj, QEvent *event) override {\n if (event->type() == QEvent::KeyPress) {\n auto *keyEvent = static_cast(event);\n\n if (keyEvent->key() == Qt::Key_Escape) {\n deactivate();\n return true;\n } else if ((!_debounceTimer.isActive() &&\n keyEvent->modifiers().testFlag(Qt::ShiftModifier) &&\n (keyEvent->key() == Qt::Key_Return)) ||\n (keyEvent->key() == Qt::Key_Up)) {\n doSearchUp();\n return true;\n } else if (!_debounceTimer.isActive() &&\n ((keyEvent->key() == Qt::Key_Return) ||\n (keyEvent->key() == Qt::Key_Down))) {\n doSearchDown();\n return true;\n } else if (!_debounceTimer.isActive() &&\n keyEvent->key() == Qt::Key_F3) {\n doSearch(!keyEvent->modifiers().testFlag(Qt::ShiftModifier));\n return true;\n }\n\n // if ((obj == ui->replaceLineEdit) && (keyEvent->key() ==\n // Qt::Key_Tab)\n // && ui->replaceToggleButton->isChecked()) {\n // ui->replaceLineEdit->setFocus();\n // }\n\n return false;\n }\n\n return QWidget::eventFilter(obj, event);\n}\n public:\n void activate() {\n setReplaceMode(ui->modeComboBox->currentIndex() !=\n SearchMode::PlainTextMode);\n show();\n\n // preset the selected text as search text if there is any and there is no\n // other search text\n const QString selectedText = _textEdit->textCursor().selectedText();\n if (!selectedText.isEmpty() && ui->searchLineEdit->text().isEmpty()) {\n ui->searchLineEdit->setText(selectedText);\n }\n\n if (focus) {\n ui->searchLineEdit->setFocus();\n }\n\n ui->searchLineEdit->selectAll();\n updateSearchExtraSelections();\n doSearchDown();\n}\n void deactivate() {\n stopDebounce();\n\n hide();\n\n // Clear the search extra selections when closing the search bar\n clearSearchExtraSelections();\n\n _textEdit->setFocus();\n}\n void doSearchDown() { doSearch(true); }\n void doSearchUp() { doSearch(false); }\n void setReplaceMode(bool enabled) {\n ui->replaceToggleButton->setChecked(enabled);\n ui->replaceLabel->setVisible(enabled);\n ui->replaceLineEdit->setVisible(enabled);\n ui->modeLabel->setVisible(enabled);\n ui->buttonFrame->setVisible(enabled);\n ui->matchCaseSensitiveButton->setVisible(enabled);\n}\n void activateReplace() {\n // replacing is prohibited if the text edit is readonly\n if (_textEdit->isReadOnly()) {\n return;\n }\n\n ui->searchLineEdit->setText(_textEdit->textCursor().selectedText());\n ui->searchLineEdit->selectAll();\n activate();\n setReplaceMode(true);\n}\n bool doReplace(bool forAll = false) {\n if (_textEdit->isReadOnly()) {\n return false;\n }\n\n QTextCursor cursor = _textEdit->textCursor();\n\n if (!forAll && cursor.selectedText().isEmpty()) {\n return false;\n }\n\n const int searchMode = ui->modeComboBox->currentIndex();\n if (searchMode == RegularExpressionMode) {\n QString text = cursor.selectedText();\n text.replace(QRegularExpression(ui->searchLineEdit->text()),\n ui->replaceLineEdit->text());\n cursor.insertText(text);\n } else {\n cursor.insertText(ui->replaceLineEdit->text());\n }\n\n if (!forAll) {\n const int position = cursor.position();\n\n if (!doSearch(true)) {\n // restore the last cursor position if text wasn't found any more\n cursor.setPosition(position);\n _textEdit->setTextCursor(cursor);\n }\n }\n\n return true;\n}\n void doReplaceAll() {\n if (_textEdit->isReadOnly()) {\n return;\n }\n\n // start at the top\n _textEdit->moveCursor(QTextCursor::Start);\n\n // replace until everything to the bottom is replaced\n while (doSearch(true, false) && doReplace(true)) {\n }\n}\n void reset() {\n ui->searchLineEdit->clear();\n setSearchMode(SearchMode::PlainTextMode);\n setReplaceMode(false);\n ui->searchCountLabel->setEnabled(false);\n}\n void doSearchCount() {\n // Note that we are moving the anchor, so the search will start from the top\n // again! Alternative: Restore cursor position afterward, but then we will\n // not know\n // at what _currentSearchResult we currently are\n _textEdit->moveCursor(QTextCursor::Start, QTextCursor::MoveAnchor);\n\n bool found;\n _searchResultCount = 0;\n _currentSearchResult = 0;\n const int searchMode = ui->modeComboBox->currentIndex();\n\n do {\n found = doSearch(true, false, false);\n if (found) {\n _searchResultCount++;\n }\n\n // prevent infinite loops from regular expression searches like \"$\", \"^\"\n // or \"\\b\"\n if (searchMode == RegularExpressionMode &&\n _searchResultCount >= 10000) {\n break;\n }\n } while (found);\n\n updateSearchCountLabelText();\n}\n protected:\n void searchLineEditTextChanged(const QString &arg1) {\n _searchTerm = arg1;\n\n if (_debounceTimer.interval() != 0 && !_searchTerm.isEmpty()) {\n _debounceTimer.start();\n ui->searchDownButton->setEnabled(false);\n ui->searchUpButton->setEnabled(false);\n } else {\n performSearch();\n }\n}\n void performSearch() {\n doSearchCount();\n updateSearchExtraSelections();\n doSearchDown();\n}\n void updateSearchCountLabelText() {\n ui->searchCountLabel->setEnabled(true);\n ui->searchCountLabel->setText(QStringLiteral(\"%1/%2\").arg(\n _currentSearchResult == 0 ? QChar('-')\n : QString::number(_currentSearchResult),\n _searchResultCount == 0 ? QChar('-')\n : QString::number(_searchResultCount)));\n}\n void setSearchSelectionColor(const QColor &color) {\n selectionColor = color;\n}\n private:\n void on_modeComboBox_currentIndexChanged(int index) {\n Q_UNUSED(index)\n doSearchCount();\n doSearchDown();\n}\n void on_matchCaseSensitiveButton_toggled(bool checked) {\n Q_UNUSED(checked)\n doSearchCount();\n doSearchDown();\n}\n};"], ["/SpeedyNote/source/SDLControllerManager.h", "class SDLControllerManager {\n Q_OBJECT\npublic:\n explicit SDLControllerManager(QObject *parent = nullptr);\n ~SDLControllerManager() {\n if (joystick) SDL_JoystickClose(joystick);\n if (sdlInitialized) SDL_QuitSubSystem(SDL_INIT_JOYSTICK);\n}\n void setPhysicalButtonMapping(const QString &logicalButton, int physicalSDLButton) {\n physicalButtonMappings[logicalButton] = physicalSDLButton;\n saveControllerMappings();\n}\n int getPhysicalButtonMapping(const QString &logicalButton) const {\n return physicalButtonMappings.value(logicalButton, -1);\n}\n QMap getAllPhysicalMappings() const {\n return physicalButtonMappings;\n}\n void saveControllerMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.beginGroup(\"ControllerPhysicalMappings\");\n for (auto it = physicalButtonMappings.begin(); it != physicalButtonMappings.end(); ++it) {\n settings.setValue(it.key(), it.value());\n }\n settings.endGroup();\n}\n void loadControllerMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.beginGroup(\"ControllerPhysicalMappings\");\n QStringList keys = settings.allKeys();\n \n if (keys.isEmpty()) {\n // No saved mappings, use defaults\n physicalButtonMappings = getDefaultMappings();\n saveControllerMappings(); // Save defaults for next time\n } else {\n // Load saved mappings\n for (const QString &key : keys) {\n physicalButtonMappings[key] = settings.value(key).toInt();\n }\n }\n settings.endGroup();\n}\n QStringList getAvailablePhysicalButtons() const {\n QStringList buttons;\n if (joystick) {\n int buttonCount = SDL_JoystickNumButtons(joystick);\n for (int i = 0; i < buttonCount; ++i) {\n buttons << getPhysicalButtonName(i);\n }\n } else {\n // If no joystick connected, show a reasonable range\n for (int i = 0; i < 20; ++i) {\n buttons << getPhysicalButtonName(i);\n }\n }\n return buttons;\n}\n QString getPhysicalButtonName(int sdlButton) const {\n // Return human-readable names for physical SDL joystick buttons\n // Since we're using raw joystick buttons, we'll use generic names\n return QString(\"Button %1\").arg(sdlButton);\n}\n int getJoystickButtonCount() const {\n if (joystick) {\n return SDL_JoystickNumButtons(joystick);\n }\n return 0;\n}\n QMap getDefaultMappings() const {\n // Default mappings for Joy-Con L using raw button indices\n // These will need to be adjusted based on actual Joy-Con button indices\n QMap defaults;\n defaults[\"LEFTSHOULDER\"] = 4; // L button\n defaults[\"RIGHTSHOULDER\"] = 6; // ZL button \n defaults[\"PADDLE2\"] = 14; // SL button\n defaults[\"PADDLE4\"] = 15; // SR button\n defaults[\"Y\"] = 0; // Up arrow\n defaults[\"A\"] = 1; // Down arrow\n defaults[\"B\"] = 2; // Left arrow\n defaults[\"X\"] = 3; // Right arrow\n defaults[\"LEFTSTICK\"] = 10; // Stick press\n defaults[\"START\"] = 8; // Minus button\n defaults[\"GUIDE\"] = 13; // Screenshot button\n return defaults;\n}\n void buttonHeld(QString buttonName);\n void buttonReleased(QString buttonName);\n void buttonSinglePress(QString buttonName);\n void leftStickAngleChanged(int angle);\n void leftStickReleased();\n void rawButtonPressed(int sdlButton, QString buttonName);\n public:\n void start() {\n if (!sdlInitialized) {\n if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) != 0) {\n qWarning() << \"Failed to initialize SDL joystick subsystem:\" << SDL_GetError();\n return;\n }\n sdlInitialized = true;\n }\n\n SDL_JoystickEventState(SDL_ENABLE); // ✅ Enable joystick events\n\n // Look for any available joystick\n int numJoysticks = SDL_NumJoysticks();\n // qDebug() << \"Found\" << numJoysticks << \"joystick(s)\";\n \n for (int i = 0; i < numJoysticks; ++i) {\n const char* joystickName = SDL_JoystickNameForIndex(i);\n // qDebug() << \"Joystick\" << i << \":\" << (joystickName ? joystickName : \"Unknown\");\n \n joystick = SDL_JoystickOpen(i);\n if (joystick) {\n // qDebug() << \"Joystick connected!\";\n // qDebug() << \"Number of buttons:\" << SDL_JoystickNumButtons(joystick);\n // qDebug() << \"Number of axes:\" << SDL_JoystickNumAxes(joystick);\n // qDebug() << \"Number of hats:\" << SDL_JoystickNumHats(joystick);\n break;\n }\n }\n\n if (!joystick) {\n qWarning() << \"No joystick could be opened\";\n }\n\n pollTimer->start(16); // 60 FPS polling\n}\n void stop() {\n pollTimer->stop();\n}\n void reconnect() {\n // Stop current polling\n pollTimer->stop();\n \n // Close existing joystick if open\n if (joystick) {\n SDL_JoystickClose(joystick);\n joystick = nullptr;\n }\n \n // Clear any cached state\n buttonPressTime.clear();\n buttonHeldEmitted.clear();\n lastAngle = -1;\n leftStickActive = false;\n buttonDetectionMode = false;\n \n // Re-initialize SDL joystick subsystem\n SDL_QuitSubSystem(SDL_INIT_JOYSTICK);\n if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) != 0) {\n qWarning() << \"Failed to re-initialize SDL joystick subsystem:\" << SDL_GetError();\n sdlInitialized = false;\n return;\n }\n sdlInitialized = true;\n \n SDL_JoystickEventState(SDL_ENABLE);\n \n // Look for any available joystick\n int numJoysticks = SDL_NumJoysticks();\n qDebug() << \"Reconnect: Found\" << numJoysticks << \"joystick(s)\";\n \n for (int i = 0; i < numJoysticks; ++i) {\n const char* joystickName = SDL_JoystickNameForIndex(i);\n qDebug() << \"Reconnect: Trying joystick\" << i << \":\" << (joystickName ? joystickName : \"Unknown\");\n \n joystick = SDL_JoystickOpen(i);\n if (joystick) {\n qDebug() << \"Reconnect: Joystick connected successfully!\";\n qDebug() << \"Number of buttons:\" << SDL_JoystickNumButtons(joystick);\n qDebug() << \"Number of axes:\" << SDL_JoystickNumAxes(joystick);\n qDebug() << \"Number of hats:\" << SDL_JoystickNumHats(joystick);\n break;\n }\n }\n \n if (!joystick) {\n qWarning() << \"Reconnect: No joystick could be opened\";\n }\n \n // Restart polling\n pollTimer->start(16); // 60 FPS polling\n}\n void startButtonDetection() {\n buttonDetectionMode = true;\n}\n void stopButtonDetection() {\n buttonDetectionMode = false;\n}\n private:\n QTimer *pollTimer;\n SDL_Joystick *joystick = nullptr;\n bool sdlInitialized = false;\n bool leftStickActive = false;\n bool buttonDetectionMode = false;\n int lastAngle = -1;\n QString getButtonName(Uint8 sdlButton) {\n // This method is now deprecated in favor of getLogicalButtonName\n return getLogicalButtonName(sdlButton);\n}\n QString getLogicalButtonName(Uint8 sdlButton) {\n // Find which logical button this physical button is mapped to\n for (auto it = physicalButtonMappings.begin(); it != physicalButtonMappings.end(); ++it) {\n if (it.value() == sdlButton) {\n return it.key(); // Return the logical button name\n }\n }\n return QString(); // Return empty string if not mapped\n}\n QMap physicalButtonMappings;\n QMap buttonPressTime;\n QMap buttonHeldEmitted;\n const quint32 HOLD_THRESHOLD = 300;\n const quint32 POLL_INTERVAL = 16;\n};"], ["/SpeedyNote/source/Main.cpp", "#ifdef _WIN32\n#include \n#endif\n\n#include \n#include \n#include \n#include \"MainWindow.h\"\n\nint main(int argc, char *argv[]) {\n#ifdef _WIN32\n FreeConsole(); // Hide console safely on Windows\n\n /*\n AllocConsole();\n freopen(\"CONOUT$\", \"w\", stdout);\n freopen(\"CONOUT$\", \"w\", stderr);\n */\n \n \n // to show console for debugging\n \n \n#endif\n SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI, \"1\");\n SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_SWITCH, \"1\");\n SDL_Init(SDL_INIT_GAMECONTROLLER | SDL_INIT_JOYSTICK);\n\n /*\n qDebug() << \"SDL2 version:\" << SDL_GetRevision();\n qDebug() << \"Num Joysticks:\" << SDL_NumJoysticks();\n\n for (int i = 0; i < SDL_NumJoysticks(); ++i) {\n if (SDL_IsGameController(i)) {\n qDebug() << \"Controller\" << i << \"is\" << SDL_GameControllerNameForIndex(i);\n } else {\n qDebug() << \"Joystick\" << i << \"is not a recognized controller\";\n }\n }\n */ // For sdl2 debugging\n \n\n\n // Enable Windows IME support for multi-language input\n QApplication app(argc, argv);\n \n // Ensure IME is properly enabled for Windows\n #ifdef _WIN32\n app.setAttribute(Qt::AA_EnableHighDpiScaling, true);\n app.setAttribute(Qt::AA_UseHighDpiPixmaps, true);\n #endif\n\n \n QTranslator translator;\n QString locale = QLocale::system().name(); // e.g., \"zh_CN\", \"es_ES\"\n QString langCode = locale.section('_', 0, 0); // e.g., \"zh\"\n\n // printf(\"Locale: %s\\n\", locale.toStdString().c_str());\n // printf(\"Language Code: %s\\n\", langCode.toStdString().c_str());\n\n // QString locale = \"es-ES\"; // e.g., \"zh_CN\", \"es_ES\"\n // QString langCode = \"es\"; // e.g., \"zh\"\n QString translationsPath = QCoreApplication::applicationDirPath();\n\n if (translator.load(translationsPath + \"/app_\" + langCode + \".qm\")) {\n app.installTranslator(&translator);\n }\n\n QString inputFile;\n if (argc >= 2) {\n inputFile = QString::fromLocal8Bit(argv[1]);\n // qDebug() << \"Input file received:\" << inputFile;\n }\n\n MainWindow w;\n if (!inputFile.isEmpty()) {\n // Check file extension to determine how to handle it\n if (inputFile.toLower().endsWith(\".pdf\")) {\n // Handle PDF file association\n w.show(); // Show window first for dialog parent\n w.openPdfFile(inputFile);\n } else if (inputFile.toLower().endsWith(\".snpkg\")) {\n // Handle notebook package import\n w.importNotebookFromFile(inputFile);\n w.show();\n } else {\n // Unknown file type, just show the application\n w.show();\n }\n } else {\n w.show();\n }\n return app.exec();\n}\n"], ["/SpeedyNote/markdown/linenumberarea.h", "#ifndef LINENUMBERAREA_H\n#define LINENUMBERAREA_H\n\n#include \n#include \n#include \n#include \n\n#include \"qmarkdowntextedit.h\"\n\nclass LineNumArea final : public QWidget {\n Q_OBJECT\n\n public:\n explicit LineNumArea(QMarkdownTextEdit *parent)\n : QWidget(parent), textEdit(parent) {\n Q_ASSERT(parent);\n\n _currentLineColor = QColor(QStringLiteral(\"#eef067\"));\n _otherLinesColor = QColor(QStringLiteral(\"#a6a6a6\"));\n setHidden(true);\n\n // We always use fixed font to avoid \"width\" issues\n setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont));\n }\n\n void setCurrentLineColor(QColor color) { _currentLineColor = color; }\n\n void setOtherLineColor(QColor color) {\n _otherLinesColor = std::move(color);\n }\n\n int lineNumAreaWidth() const {\n if (!enabled) {\n return 0;\n }\n\n int digits = 2;\n int max = std::max(1, textEdit->blockCount());\n while (max >= 10) {\n max /= 10;\n ++digits;\n }\n\n#if QT_VERSION >= 0x050B00\n int space =\n 13 + textEdit->fontMetrics().horizontalAdvance(u'9') * digits;\n#else\n int space =\n 13 + textEdit->fontMetrics().width(QLatin1Char('9')) * digits;\n#endif\n\n return space;\n }\n\n bool isLineNumAreaEnabled() const { return enabled; }\n\n void setLineNumAreaEnabled(bool e) {\n enabled = e;\n setHidden(!e);\n }\n\n QSize sizeHint() const override { return {lineNumAreaWidth(), 0}; }\n\n protected:\n void paintEvent(QPaintEvent *event) override {\n QPainter painter(this);\n\n painter.fillRect(event->rect(),\n palette().color(QPalette::Active, QPalette::Window));\n\n auto block = textEdit->firstVisibleBlock();\n int blockNumber = block.blockNumber();\n qreal top = textEdit->blockBoundingGeometry(block)\n .translated(textEdit->contentOffset())\n .top();\n // Maybe the top is not 0?\n top += textEdit->viewportMargins().top();\n qreal bottom = top;\n\n const QPen currentLine = _currentLineColor;\n const QPen otherLines = _otherLinesColor;\n painter.setFont(font());\n\n while (block.isValid() && top <= event->rect().bottom()) {\n top = bottom;\n bottom = top + textEdit->blockBoundingRect(block).height();\n if (block.isVisible() && bottom >= event->rect().top()) {\n QString number = QString::number(blockNumber + 1);\n\n auto isCurrentLine =\n textEdit->textCursor().blockNumber() == blockNumber;\n painter.setPen(isCurrentLine ? currentLine : otherLines);\n\n painter.drawText(-5, top, sizeHint().width(),\n textEdit->fontMetrics().height(),\n Qt::AlignRight, number);\n }\n\n block = block.next();\n ++blockNumber;\n }\n }\n\n private:\n bool enabled = false;\n QMarkdownTextEdit *textEdit;\n QColor _currentLineColor;\n QColor _otherLinesColor;\n};\n\n#endif // LINENUMBERAREA_H\n"], ["/SpeedyNote/source/ButtonMappingTypes.h", "class InternalDialMode {\n Q_DECLARE_TR_FUNCTIONS(ButtonMappingHelper)\n public:\n static QString dialModeToInternalKey(InternalDialMode mode) {\n switch (mode) {\n case InternalDialMode::None: return \"none\";\n case InternalDialMode::PageSwitching: return \"page_switching\";\n case InternalDialMode::ZoomControl: return \"zoom_control\";\n case InternalDialMode::ThicknessControl: return \"thickness_control\";\n\n case InternalDialMode::ToolSwitching: return \"tool_switching\";\n case InternalDialMode::PresetSelection: return \"preset_selection\";\n case InternalDialMode::PanAndPageScroll: return \"pan_and_page_scroll\";\n }\n return \"none\";\n}\n static QString actionToInternalKey(InternalControllerAction action) {\n switch (action) {\n case InternalControllerAction::None: return \"none\";\n case InternalControllerAction::ToggleFullscreen: return \"toggle_fullscreen\";\n case InternalControllerAction::ToggleDial: return \"toggle_dial\";\n case InternalControllerAction::Zoom50: return \"zoom_50\";\n case InternalControllerAction::ZoomOut: return \"zoom_out\";\n case InternalControllerAction::Zoom200: return \"zoom_200\";\n case InternalControllerAction::AddPreset: return \"add_preset\";\n case InternalControllerAction::DeletePage: return \"delete_page\";\n case InternalControllerAction::FastForward: return \"fast_forward\";\n case InternalControllerAction::OpenControlPanel: return \"open_control_panel\";\n case InternalControllerAction::RedColor: return \"red_color\";\n case InternalControllerAction::BlueColor: return \"blue_color\";\n case InternalControllerAction::YellowColor: return \"yellow_color\";\n case InternalControllerAction::GreenColor: return \"green_color\";\n case InternalControllerAction::BlackColor: return \"black_color\";\n case InternalControllerAction::WhiteColor: return \"white_color\";\n case InternalControllerAction::CustomColor: return \"custom_color\";\n case InternalControllerAction::ToggleSidebar: return \"toggle_sidebar\";\n case InternalControllerAction::Save: return \"save\";\n case InternalControllerAction::StraightLineTool: return \"straight_line_tool\";\n case InternalControllerAction::RopeTool: return \"rope_tool\";\n case InternalControllerAction::SetPenTool: return \"set_pen_tool\";\n case InternalControllerAction::SetMarkerTool: return \"set_marker_tool\";\n case InternalControllerAction::SetEraserTool: return \"set_eraser_tool\";\n case InternalControllerAction::TogglePdfTextSelection: return \"toggle_pdf_text_selection\";\n case InternalControllerAction::ToggleOutline: return \"toggle_outline\";\n case InternalControllerAction::ToggleBookmarks: return \"toggle_bookmarks\";\n case InternalControllerAction::AddBookmark: return \"add_bookmark\";\n case InternalControllerAction::ToggleTouchGestures: return \"toggle_touch_gestures\";\n }\n return \"none\";\n}\n static InternalDialMode internalKeyToDialMode(const QString &key) {\n if (key == \"none\") return InternalDialMode::None;\n if (key == \"page_switching\") return InternalDialMode::PageSwitching;\n if (key == \"zoom_control\") return InternalDialMode::ZoomControl;\n if (key == \"thickness_control\") return InternalDialMode::ThicknessControl;\n\n if (key == \"tool_switching\") return InternalDialMode::ToolSwitching;\n if (key == \"preset_selection\") return InternalDialMode::PresetSelection;\n if (key == \"pan_and_page_scroll\") return InternalDialMode::PanAndPageScroll;\n return InternalDialMode::None;\n}\n static InternalControllerAction internalKeyToAction(const QString &key) {\n if (key == \"none\") return InternalControllerAction::None;\n if (key == \"toggle_fullscreen\") return InternalControllerAction::ToggleFullscreen;\n if (key == \"toggle_dial\") return InternalControllerAction::ToggleDial;\n if (key == \"zoom_50\") return InternalControllerAction::Zoom50;\n if (key == \"zoom_out\") return InternalControllerAction::ZoomOut;\n if (key == \"zoom_200\") return InternalControllerAction::Zoom200;\n if (key == \"add_preset\") return InternalControllerAction::AddPreset;\n if (key == \"delete_page\") return InternalControllerAction::DeletePage;\n if (key == \"fast_forward\") return InternalControllerAction::FastForward;\n if (key == \"open_control_panel\") return InternalControllerAction::OpenControlPanel;\n if (key == \"red_color\") return InternalControllerAction::RedColor;\n if (key == \"blue_color\") return InternalControllerAction::BlueColor;\n if (key == \"yellow_color\") return InternalControllerAction::YellowColor;\n if (key == \"green_color\") return InternalControllerAction::GreenColor;\n if (key == \"black_color\") return InternalControllerAction::BlackColor;\n if (key == \"white_color\") return InternalControllerAction::WhiteColor;\n if (key == \"custom_color\") return InternalControllerAction::CustomColor;\n if (key == \"toggle_sidebar\") return InternalControllerAction::ToggleSidebar;\n if (key == \"save\") return InternalControllerAction::Save;\n if (key == \"straight_line_tool\") return InternalControllerAction::StraightLineTool;\n if (key == \"rope_tool\") return InternalControllerAction::RopeTool;\n if (key == \"set_pen_tool\") return InternalControllerAction::SetPenTool;\n if (key == \"set_marker_tool\") return InternalControllerAction::SetMarkerTool;\n if (key == \"set_eraser_tool\") return InternalControllerAction::SetEraserTool;\n if (key == \"toggle_pdf_text_selection\") return InternalControllerAction::TogglePdfTextSelection;\n if (key == \"toggle_outline\") return InternalControllerAction::ToggleOutline;\n if (key == \"toggle_bookmarks\") return InternalControllerAction::ToggleBookmarks;\n if (key == \"add_bookmark\") return InternalControllerAction::AddBookmark;\n if (key == \"toggle_touch_gestures\") return InternalControllerAction::ToggleTouchGestures;\n return InternalControllerAction::None;\n}\n static QStringList getTranslatedDialModes() {\n return {\n tr(\"None\"),\n tr(\"Page Switching\"),\n tr(\"Zoom Control\"),\n tr(\"Thickness Control\"),\n\n tr(\"Tool Switching\"),\n tr(\"Preset Selection\"),\n tr(\"Pan and Page Scroll\")\n };\n}\n static QStringList getTranslatedActions() {\n return {\n tr(\"None\"),\n tr(\"Toggle Fullscreen\"),\n tr(\"Toggle Dial\"),\n tr(\"Zoom 50%\"),\n tr(\"Zoom Out\"),\n tr(\"Zoom 200%\"),\n tr(\"Add Preset\"),\n tr(\"Delete Page\"),\n tr(\"Fast Forward\"),\n tr(\"Open Control Panel\"),\n tr(\"Red\"),\n tr(\"Blue\"),\n tr(\"Yellow\"),\n tr(\"Green\"),\n tr(\"Black\"),\n tr(\"White\"),\n tr(\"Custom Color\"),\n tr(\"Toggle Sidebar\"),\n tr(\"Save\"),\n tr(\"Straight Line Tool\"),\n tr(\"Rope Tool\"),\n tr(\"Set Pen Tool\"),\n tr(\"Set Marker Tool\"),\n tr(\"Set Eraser Tool\"),\n tr(\"Toggle PDF Text Selection\"),\n tr(\"Toggle PDF Outline\"),\n tr(\"Toggle Bookmarks\"),\n tr(\"Add/Remove Bookmark\"),\n tr(\"Toggle Touch Gestures\")\n };\n}\n static QStringList getTranslatedButtons() {\n return {\n tr(\"Left Shoulder\"),\n tr(\"Right Shoulder\"),\n tr(\"Paddle 2\"),\n tr(\"Paddle 4\"),\n tr(\"Y Button\"),\n tr(\"A Button\"),\n tr(\"B Button\"),\n tr(\"X Button\"),\n tr(\"Left Stick\"),\n tr(\"Start Button\"),\n tr(\"Guide Button\")\n };\n}\n static QStringList getInternalDialModeKeys() {\n return {\n \"none\",\n \"page_switching\",\n \"zoom_control\",\n \"thickness_control\",\n\n \"tool_switching\",\n \"preset_selection\",\n \"pan_and_page_scroll\"\n };\n}\n static QStringList getInternalActionKeys() {\n return {\n \"none\",\n \"toggle_fullscreen\",\n \"toggle_dial\",\n \"zoom_50\",\n \"zoom_out\",\n \"zoom_200\",\n \"add_preset\",\n \"delete_page\",\n \"fast_forward\",\n \"open_control_panel\",\n \"red_color\",\n \"blue_color\",\n \"yellow_color\",\n \"green_color\",\n \"black_color\",\n \"white_color\",\n \"custom_color\",\n \"toggle_sidebar\",\n \"save\",\n \"straight_line_tool\",\n \"rope_tool\",\n \"set_pen_tool\",\n \"set_marker_tool\",\n \"set_eraser_tool\",\n \"toggle_pdf_text_selection\",\n \"toggle_outline\",\n \"toggle_bookmarks\",\n \"add_bookmark\",\n \"toggle_touch_gestures\"\n };\n}\n static QStringList getInternalButtonKeys() {\n return {\n \"LEFTSHOULDER\",\n \"RIGHTSHOULDER\", \n \"PADDLE2\",\n \"PADDLE4\",\n \"Y\",\n \"A\",\n \"B\",\n \"X\",\n \"LEFTSTICK\",\n \"START\",\n \"GUIDE\"\n };\n}\n static QString displayToInternalKey(const QString &displayString, bool isDialMode) {\n if (isDialMode) {\n QStringList translated = getTranslatedDialModes();\n QStringList internal = getInternalDialModeKeys();\n int index = translated.indexOf(displayString);\n return (index >= 0) ? internal[index] : \"none\";\n } else {\n QStringList translated = getTranslatedActions();\n QStringList internal = getInternalActionKeys();\n int index = translated.indexOf(displayString);\n return (index >= 0) ? internal[index] : \"none\";\n }\n}\n static QString internalKeyToDisplay(const QString &internalKey, bool isDialMode) {\n if (isDialMode) {\n QStringList translated = getTranslatedDialModes();\n QStringList internal = getInternalDialModeKeys();\n int index = internal.indexOf(internalKey);\n return (index >= 0) ? translated[index] : tr(\"None\");\n } else {\n QStringList translated = getTranslatedActions();\n QStringList internal = getInternalActionKeys();\n int index = internal.indexOf(internalKey);\n return (index >= 0) ? translated[index] : tr(\"None\");\n }\n}\n};"], ["/SpeedyNote/source/KeyCaptureDialog.h", "class KeyCaptureDialog {\n Q_OBJECT\n\npublic:\n explicit KeyCaptureDialog(QWidget *parent = nullptr);\n protected:\n void keyPressEvent(QKeyEvent *event) override {\n // Build key sequence string\n QStringList modifiers;\n \n if (event->modifiers() & Qt::ControlModifier) modifiers << \"Ctrl\";\n if (event->modifiers() & Qt::ShiftModifier) modifiers << \"Shift\";\n if (event->modifiers() & Qt::AltModifier) modifiers << \"Alt\";\n if (event->modifiers() & Qt::MetaModifier) modifiers << \"Meta\";\n \n // Don't capture modifier keys alone\n if (event->key() == Qt::Key_Control || event->key() == Qt::Key_Shift ||\n event->key() == Qt::Key_Alt || event->key() == Qt::Key_Meta) {\n return;\n }\n \n // Don't capture Escape (let it close the dialog)\n if (event->key() == Qt::Key_Escape) {\n QDialog::keyPressEvent(event);\n return;\n }\n \n QString keyString = QKeySequence(event->key()).toString();\n \n if (!modifiers.isEmpty()) {\n capturedSequence = modifiers.join(\"+\") + \"+\" + keyString;\n } else {\n capturedSequence = keyString;\n }\n \n updateDisplay();\n event->accept();\n}\n private:\n void clearSequence() {\n capturedSequence.clear();\n updateDisplay();\n setFocus(); // Return focus to dialog for key capture\n}\n private:\n QLabel *instructionLabel;\n QLabel *capturedLabel;\n QPushButton *clearButton;\n QPushButton *okButton;\n QPushButton *cancelButton;\n QString capturedSequence;\n void updateDisplay() {\n if (capturedSequence.isEmpty()) {\n capturedLabel->setText(tr(\"(No key captured yet)\"));\n okButton->setEnabled(false);\n } else {\n capturedLabel->setText(capturedSequence);\n okButton->setEnabled(true);\n }\n}\n};"], ["/SpeedyNote/markdown/main.cpp", "/*\n * MIT License\n *\n * Copyright (c) 2014-2025 Patrizio Bekerle -- \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#include \n\n#include \"mainwindow.h\"\n\nint main(int argc, char *argv[]) {\n QApplication a(argc, argv);\n MainWindow w;\n w.show();\n\n return a.exec();\n}\n"], ["/SpeedyNote/markdown/mainwindow.h", "class MainWindow {\n Q_OBJECT\n\n public:\n explicit MainWindow(QWidget *parent = nullptr);\n ~MainWindow() { delete ui; }\n private:\n Ui::MainWindow *ui;\n};"], ["/SpeedyNote/source/ToolType.h", "#ifndef TOOLTYPE_H\n#define TOOLTYPE_H\n\n// ✅ Now it can be used anywhere\nenum class ToolType {\n Pen,\n Marker,\n Eraser\n};\n\n#endif // TOOLTYPE_H"], ["/SpeedyNote/markdown/qownlanguagedata.h", "class qownlanguagedata {\n};"], ["/SpeedyNote/markdown/markdownhighlighter.h", "class QTextDocument {\n};"]], "task_instance_info": {"created_time": "2025-08-20 19:30:37", "created_task_model": "DeepSeek-R1", "class_skeleton": "class\nPdfOpenDialog\n{\nQ_OBJECT\n\npublic:\n enum Result {\n Cancel,\n CreateNewFolder,\n UseExistingFolder\n };\nexplicit PdfOpenDialog(const QString &pdfPath, QWidget *parent = nullptr) {}\nstatic bool hasValidNotebookFolder(const QString &pdfPath, QString &folderPath) {}\nprotected:\nvoid resizeEvent(QResizeEvent *event) override {}\nprivate:\nvoid onCreateNewFolder() {}\nvoid onUseExistingFolder() {}\nvoid onCancel() {}\nprivate:\nvoid setupUI() {}\nstatic bool isValidNotebookFolder(const QString &folderPath, const QString &pdfPath) {}\nResult result;\nQString selectedFolder;\nQString pdfPath;\n};", "code_description": "This code segment functions to: Provide a user interface dialog for selecting notebook storage locations when opening PDF files, handling folder creation with conflict resolution, validating existing directory compatibility, and enforcing window size constraints based on display characteristics."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```cpp\n[TASK_BEGIN]\nclass PdfOpenDialog\n{\n Q_OBJECT\n\npublic:\n enum Result {\n Cancel,\n CreateNewFolder,\n UseExistingFolder\n };\n\n explicit PdfOpenDialog(const QString &pdfPath, QWidget *parent = nullptr) \n : QWidget(parent), pdfPath(pdfPath), result(Cancel)\n {\n setupUI();\n }\n\n static bool hasValidNotebookFolder(const QString &pdfPath, QString &folderPath) {\n QFileInfo pdfInfo(pdfPath);\n QDir dir = pdfInfo.dir();\n if(isValidNotebookFolder(dir.path(), pdfPath)) {\n folderPath = dir.path();\n return true;\n }\n return false;\n }\n\nprotected:\n void resizeEvent(QResizeEvent *event) override {\n QWidget::resizeEvent(event);\n // Update layout or widget positions here\n }\n\nprivate slots:\n void onCreateNewFolder() {\n result = CreateNewFolder;\n close();\n }\n\n void onUseExistingFolder() {\n result = UseExistingFolder;\n close();\n }\n\n void onCancel() {\n result = Cancel;\n close();\n }\n\nprivate:\n void setupUI() {\n QVBoxLayout *layout = new QVBoxLayout(this);\n QPushButton *newFolderBtn = new QPushButton(\"Create New Folder\", this);\n QPushButton *existingFolderBtn = new QPushButton(\"Use Existing Folder\", this);\n QPushButton *cancelBtn = new QPushButton(\"Cancel\", this);\n\n connect(newFolderBtn, &QPushButton::clicked, this, &PdfOpenDialog::onCreateNewFolder);\n connect(existingFolderBtn, &QPushButton::clicked, this, &PdfOpenDialog::onUseExistingFolder);\n connect(cancelBtn, &QPushButton::clicked, this, &PdfOpenDialog::onCancel);\n\n layout->addWidget(newFolderBtn);\n layout->addWidget(existingFolderBtn);\n layout->addWidget(cancelBtn);\n }\n\n static bool isValidNotebookFolder(const QString &folderPath, const QString &pdfPath) {\n QDir dir(folderPath);\n return dir.exists(\"notebook.json\") && \n QFileInfo(pdfPath).dir() == QDir(folderPath);\n }\n\n Result result;\n QString selectedFolder;\n QString pdfPath;\n};\n[TASK_END]\n```", "inference_time": "2025-08-20 19-31-10"}, "editdistance_info": {"edit_distance": 14.6604, "calculate_time": "2025-08-20 19:31:10", "true_code_clean": "class PdfOpenDialog {\n Q_OBJECT\npublic:\n enum Result {\n Cancel,\n CreateNewFolder,\n UseExistingFolder\n };\n explicit PdfOpenDialog(const QString &pdfPath, QWidget *parent = nullptr) {\n setWindowTitle(tr(\"Open PDF with SpeedyNote\"));\n setWindowIcon(QIcon(\":/resources/icons/mainicon.png\"));\n setModal(true);\n QScreen *screen = QGuiApplication::primaryScreen();\n qreal dpr = screen ? screen->devicePixelRatio() : 1.0;\n int baseWidth = 500;\n int baseHeight = 200;\n int scaledWidth = static_cast(baseWidth * qMax(1.0, dpr * 0.8));\n int scaledHeight = static_cast(baseHeight * qMax(1.0, dpr * 0.8));\n setMinimumSize(scaledWidth, scaledHeight);\n setMaximumSize(scaledWidth + 100, scaledHeight + 50); \n setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);\n setupUI();\n adjustSize();\n if (parent) {\n move(parent->geometry().center() - rect().center());\n } else {\n move(screen->geometry().center() - rect().center());\n }\n}\n static bool hasValidNotebookFolder(const QString &pdfPath, QString &folderPath) {\n QFileInfo fileInfo(pdfPath);\n QString suggestedFolderName = fileInfo.baseName(); \n QString pdfDir = fileInfo.absolutePath(); \n QString potentialFolderPath = pdfDir + \"/\" + suggestedFolderName;\n if (isValidNotebookFolder(potentialFolderPath, pdfPath)) {\n folderPath = potentialFolderPath;\n return true;\n }\n return false;\n}\n protected:\n void resizeEvent(QResizeEvent *event) override {\n if (event->size() != event->oldSize()) {\n QDialog::resizeEvent(event);\n QSize newSize = event->size();\n QSize minSize = minimumSize();\n QSize maxSize = maximumSize();\n newSize = newSize.expandedTo(minSize).boundedTo(maxSize);\n if (newSize != event->size()) {\n resize(newSize);\n }\n } else {\n QDialog::resizeEvent(event);\n }\n}\n private:\n void onCreateNewFolder() {\n QFileInfo fileInfo(pdfPath);\n QString suggestedFolderName = fileInfo.baseName();\n QString pdfDir = fileInfo.absolutePath();\n QString newFolderPath = pdfDir + \"/\" + suggestedFolderName;\n if (QDir(newFolderPath).exists()) {\n QMessageBox::StandardButton reply = QMessageBox::question(\n this, \n tr(\"Folder Exists\"), \n tr(\"A folder named \\\"%1\\\" already exists in the same directory as the PDF.\\n\\nDo you want to use this existing folder?\").arg(suggestedFolderName),\n QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel\n );\n if (reply == QMessageBox::Yes) {\n selectedFolder = newFolderPath;\n result = UseExistingFolder;\n accept();\n return;\n } else if (reply == QMessageBox::Cancel) {\n return; \n }\n int counter = 1;\n do {\n newFolderPath = pdfDir + \"/\" + suggestedFolderName + QString(\"_%1\").arg(counter);\n counter++;\n } while (QDir(newFolderPath).exists() && counter < 100);\n if (counter >= 100) {\n QMessageBox::warning(this, tr(\"Error\"), tr(\"Could not create a unique folder name.\"));\n return;\n }\n }\n QDir dir;\n if (dir.mkpath(newFolderPath)) {\n selectedFolder = newFolderPath;\n result = CreateNewFolder;\n accept();\n } else {\n QMessageBox::warning(this, tr(\"Error\"), tr(\"Failed to create folder: %1\").arg(newFolderPath));\n }\n}\n void onUseExistingFolder() {\n QString folder = QFileDialog::getExistingDirectory(\n this, \n tr(\"Select Existing Notebook Folder\"), \n QFileInfo(pdfPath).absolutePath()\n );\n if (!folder.isEmpty()) {\n selectedFolder = folder;\n result = UseExistingFolder;\n accept();\n }\n}\n void onCancel() {\n result = Cancel;\n reject();\n}\n private:\n void setupUI() {\n QVBoxLayout *mainLayout = new QVBoxLayout(this);\n mainLayout->setSpacing(15);\n mainLayout->setContentsMargins(20, 20, 20, 20);\n mainLayout->setSizeConstraint(QLayout::SetMinAndMaxSize);\n QHBoxLayout *headerLayout = new QHBoxLayout();\n headerLayout->setSpacing(10);\n QLabel *iconLabel = new QLabel();\n QPixmap icon = QIcon(\":/resources/icons/mainicon.png\").pixmap(48, 48);\n iconLabel->setPixmap(icon);\n iconLabel->setFixedSize(48, 48);\n iconLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);\n QLabel *titleLabel = new QLabel(tr(\"Open PDF with SpeedyNote\"));\n titleLabel->setStyleSheet(\"font-size: 16px; font-weight: bold;\");\n titleLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);\n headerLayout->addWidget(iconLabel);\n headerLayout->addWidget(titleLabel);\n headerLayout->addStretch();\n mainLayout->addLayout(headerLayout);\n QFileInfo fileInfo(pdfPath);\n QString fileName = fileInfo.fileName();\n QString folderName = fileInfo.baseName(); \n QLabel *messageLabel = new QLabel(tr(\"PDF File: %1\\n\\nHow would you like to open this PDF?\").arg(fileName));\n messageLabel->setWordWrap(true);\n messageLabel->setStyleSheet(\"font-size: 12px; color: #666;\");\n messageLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);\n mainLayout->addWidget(messageLabel);\n QVBoxLayout *buttonLayout = new QVBoxLayout();\n buttonLayout->setSpacing(10);\n QPushButton *createFolderBtn = new QPushButton(tr(\"Create New Notebook Folder (\\\"%1\\\")\").arg(folderName));\n createFolderBtn->setIcon(QApplication::style()->standardIcon(QStyle::SP_DirIcon));\n createFolderBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);\n createFolderBtn->setMinimumHeight(40);\n createFolderBtn->setStyleSheet(R\"(\n QPushButton {\n text-align: left;\n padding: 10px;\n border: 1px solid palette(mid);\n border-radius: 5px;\n background: palette(button);\n }\n QPushButton:hover {\n background: palette(light);\n border-color: palette(dark);\n }\n QPushButton:pressed {\n background: palette(midlight);\n }\n )\");\n connect(createFolderBtn, &QPushButton::clicked, this, &PdfOpenDialog::onCreateNewFolder);\n QPushButton *existingFolderBtn = new QPushButton(tr(\"Use Existing Notebook Folder...\"));\n existingFolderBtn->setIcon(QApplication::style()->standardIcon(QStyle::SP_DirOpenIcon));\n existingFolderBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);\n existingFolderBtn->setMinimumHeight(40);\n existingFolderBtn->setStyleSheet(R\"(\n QPushButton {\n text-align: left;\n padding: 10px;\n border: 1px solid palette(mid);\n border-radius: 5px;\n background: palette(button);\n }\n QPushButton:hover {\n background: palette(light);\n border-color: palette(dark);\n }\n QPushButton:pressed {\n background: palette(midlight);\n }\n )\");\n connect(existingFolderBtn, &QPushButton::clicked, this, &PdfOpenDialog::onUseExistingFolder);\n buttonLayout->addWidget(createFolderBtn);\n buttonLayout->addWidget(existingFolderBtn);\n mainLayout->addLayout(buttonLayout);\n QHBoxLayout *cancelLayout = new QHBoxLayout();\n cancelLayout->addStretch();\n QPushButton *cancelBtn = new QPushButton(tr(\"Cancel\"));\n cancelBtn->setIcon(QApplication::style()->standardIcon(QStyle::SP_DialogCancelButton));\n cancelBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);\n cancelBtn->setMinimumSize(80, 30);\n cancelBtn->setStyleSheet(R\"(\n QPushButton {\n padding: 8px 20px;\n border: 1px solid palette(mid);\n border-radius: 3px;\n background: palette(button);\n }\n QPushButton:hover {\n background: palette(light);\n }\n QPushButton:pressed {\n background: palette(midlight);\n }\n )\");\n connect(cancelBtn, &QPushButton::clicked, this, &PdfOpenDialog::onCancel);\n cancelLayout->addWidget(cancelBtn);\n mainLayout->addLayout(cancelLayout);\n}\n static bool isValidNotebookFolder(const QString &folderPath, const QString &pdfPath) {\n QDir folder(folderPath);\n if (!folder.exists()) {\n return false;\n }\n QString pdfPathFile = folderPath + \"/.pdf_path.txt\";\n if (QFile::exists(pdfPathFile)) {\n QFile file(pdfPathFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString storedPdfPath = in.readLine().trimmed();\n file.close();\n if (!storedPdfPath.isEmpty()) {\n QFileInfo currentPdf(pdfPath);\n QFileInfo storedPdf(storedPdfPath);\n if (storedPdf.exists() && \n currentPdf.absoluteFilePath() == storedPdf.absoluteFilePath()) {\n return true;\n }\n }\n }\n }\n QString notebookIdFile = folderPath + \"/.notebook_id.txt\";\n if (QFile::exists(notebookIdFile)) {\n QStringList contentFiles = folder.entryList(\n QStringList() << \"*.png\" << \".pdf_path.txt\" << \".bookmarks.txt\" << \".background_config.txt\", \n QDir::Files\n );\n if (!contentFiles.isEmpty()) {\n return false;\n }\n }\n return false;\n}\n Result result;\n QString selectedFolder;\n QString pdfPath;\n}", "predict_code_clean": "class PdfOpenDialog\n{\n Q_OBJECT\npublic:\n enum Result {\n Cancel,\n CreateNewFolder,\n UseExistingFolder\n };\n explicit PdfOpenDialog(const QString &pdfPath, QWidget *parent = nullptr) \n : QWidget(parent), pdfPath(pdfPath), result(Cancel)\n {\n setupUI();\n }\n static bool hasValidNotebookFolder(const QString &pdfPath, QString &folderPath) {\n QFileInfo pdfInfo(pdfPath);\n QDir dir = pdfInfo.dir();\n if(isValidNotebookFolder(dir.path(), pdfPath)) {\n folderPath = dir.path();\n return true;\n }\n return false;\n }\nprotected:\n void resizeEvent(QResizeEvent *event) override {\n QWidget::resizeEvent(event);\n }\nprivate slots:\n void onCreateNewFolder() {\n result = CreateNewFolder;\n close();\n }\n void onUseExistingFolder() {\n result = UseExistingFolder;\n close();\n }\n void onCancel() {\n result = Cancel;\n close();\n }\nprivate:\n void setupUI() {\n QVBoxLayout *layout = new QVBoxLayout(this);\n QPushButton *newFolderBtn = new QPushButton(\"Create New Folder\", this);\n QPushButton *existingFolderBtn = new QPushButton(\"Use Existing Folder\", this);\n QPushButton *cancelBtn = new QPushButton(\"Cancel\", this);\n connect(newFolderBtn, &QPushButton::clicked, this, &PdfOpenDialog::onCreateNewFolder);\n connect(existingFolderBtn, &QPushButton::clicked, this, &PdfOpenDialog::onUseExistingFolder);\n connect(cancelBtn, &QPushButton::clicked, this, &PdfOpenDialog::onCancel);\n layout->addWidget(newFolderBtn);\n layout->addWidget(existingFolderBtn);\n layout->addWidget(cancelBtn);\n }\n static bool isValidNotebookFolder(const QString &folderPath, const QString &pdfPath) {\n QDir dir(folderPath);\n return dir.exists(\"notebook.json\") && \n QFileInfo(pdfPath).dir() == QDir(folderPath);\n }\n Result result;\n QString selectedFolder;\n QString pdfPath;\n};"}} {"repo_name": "SpeedyNote", "file_name": "/SpeedyNote/source/RecentNotebooksDialog.h", "inference_info": {"prefix_code": "", "suffix_code": ";", "middle_code": "class QPushButton {\n Q_OBJECT\npublic:\n explicit RecentNotebooksDialog(MainWindow *mainWindow, RecentNotebooksManager *manager, QWidget *parent = nullptr);\n private:\n void onNotebookClicked() {\n QPushButton *button = qobject_cast(sender());\n if (button) {\n QString notebookPath = button->property(\"notebookPath\").toString();\n if (!notebookPath.isEmpty() && mainWindowRef) {\n InkCanvas *canvas = mainWindowRef->currentCanvas(); \n if (canvas) {\n if (canvas->isEdited()){\n mainWindowRef->saveCurrentPage(); \n }\n canvas->setSaveFolder(notebookPath);\n mainWindowRef->switchPageWithDirection(1, 1); \n mainWindowRef->pageInput->setValue(1); \n mainWindowRef->updateTabLabel(); \n if (notebookManager) {\n notebookManager->generateAndSaveCoverPreview(notebookPath, canvas);\n notebookManager->addRecentNotebook(notebookPath, canvas);\n }\n }\n accept(); \n }\n }\n}\n private:\n void setupUi() {\n QVBoxLayout *mainLayout = new QVBoxLayout(this);\n QScrollArea *scrollArea = new QScrollArea(this);\n scrollArea->setWidgetResizable(true);\n QWidget *gridContainer = new QWidget();\n gridLayout = new QGridLayout(gridContainer);\n gridLayout->setSpacing(15);\n scrollArea->setWidget(gridContainer);\n mainLayout->addWidget(scrollArea);\n setLayout(mainLayout);\n}\n void populateGrid() {\n QStringList recentPaths = notebookManager->getRecentNotebooks();\n int row = 0;\n int col = 0;\n const int numCols = 4;\n for (const QString &path : recentPaths) {\n if (path.isEmpty()) continue;\n QPushButton *button = new QPushButton(this);\n button->setFixedSize(180, 180); \n button->setProperty(\"notebookPath\", path); \n connect(button, &QPushButton::clicked, this, &RecentNotebooksDialog::onNotebookClicked);\n QVBoxLayout *buttonLayout = new QVBoxLayout(button);\n buttonLayout->setContentsMargins(5,5,5,5);\n QLabel *coverLabel = new QLabel(this);\n coverLabel->setFixedSize(170, 127); \n coverLabel->setAlignment(Qt::AlignCenter);\n QString coverPath = notebookManager->getCoverImagePathForNotebook(path);\n if (!coverPath.isEmpty()) {\n QPixmap coverPixmap(coverPath);\n coverLabel->setPixmap(coverPixmap.scaled(coverLabel->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));\n } else {\n coverLabel->setText(tr(\"No Preview\"));\n }\n coverLabel->setStyleSheet(\"border: 1px solid gray;\");\n QLabel *nameLabel = new QLabel(notebookManager->getNotebookDisplayName(path), this);\n nameLabel->setAlignment(Qt::AlignCenter);\n nameLabel->setWordWrap(true);\n nameLabel->setFixedHeight(40); \n buttonLayout->addWidget(coverLabel);\n buttonLayout->addWidget(nameLabel);\n button->setLayout(buttonLayout);\n gridLayout->addWidget(button, row, col);\n col++;\n if (col >= numCols) {\n col = 0;\n row++;\n }\n }\n}\n RecentNotebooksManager *notebookManager;\n QGridLayout *gridLayout;\n MainWindow *mainWindowRef;\n}", "code_description": null, "fill_type": "CLASS_TYPE", "language_type": "cpp", "sub_task_type": null}, "context_code": [["/SpeedyNote/source/MainWindow.h", "class QTreeWidgetItem {\n Q_OBJECT\n\npublic:\n explicit MainWindow(QWidget *parent = nullptr);\n virtual ~MainWindow() {\n\n saveButtonMappings(); // ✅ Save on exit, as backup\n delete canvas;\n}\n int getCurrentPageForCanvas(InkCanvas *canvas) {\n return pageMap.contains(canvas) ? pageMap[canvas] : 0;\n}\n bool lowResPreviewEnabled = true;\n void setLowResPreviewEnabled(bool enabled) {\n lowResPreviewEnabled = enabled;\n\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"lowResPreviewEnabled\", enabled);\n}\n bool isLowResPreviewEnabled() const {\n return lowResPreviewEnabled;\n}\n bool areBenchmarkControlsVisible() const {\n return benchmarkButton->isVisible() && benchmarkLabel->isVisible();\n}\n void setBenchmarkControlsVisible(bool visible) {\n benchmarkButton->setVisible(visible);\n benchmarkLabel->setVisible(visible);\n}\n bool zoomButtonsVisible = true;\n bool areZoomButtonsVisible() const {\n return zoomButtonsVisible;\n}\n void setZoomButtonsVisible(bool visible) {\n zoom50Button->setVisible(visible);\n dezoomButton->setVisible(visible);\n zoom200Button->setVisible(visible);\n\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"zoomButtonsVisible\", visible);\n \n // Update zoomButtonsVisible flag and trigger layout update\n zoomButtonsVisible = visible;\n \n // Trigger layout update to adjust responsive thresholds\n if (layoutUpdateTimer) {\n layoutUpdateTimer->stop();\n layoutUpdateTimer->start(50); // Quick update for settings change\n } else {\n updateToolbarLayout(); // Direct update if no timer exists yet\n }\n}\n bool scrollOnTopEnabled = false;\n bool isScrollOnTopEnabled() const {\n return scrollOnTopEnabled;\n}\n void setScrollOnTopEnabled(bool enabled) {\n scrollOnTopEnabled = enabled;\n\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"scrollOnTopEnabled\", enabled);\n}\n bool touchGesturesEnabled = true;\n bool areTouchGesturesEnabled() const {\n return touchGesturesEnabled;\n}\n void setTouchGesturesEnabled(bool enabled) {\n touchGesturesEnabled = enabled;\n \n // Apply to all canvases\n for (int i = 0; i < canvasStack->count(); ++i) {\n InkCanvas *canvas = qobject_cast(canvasStack->widget(i));\n if (canvas) {\n canvas->setTouchGesturesEnabled(enabled);\n }\n }\n \n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"touchGesturesEnabled\", enabled);\n}\n QColor customAccentColor;\n bool useCustomAccentColor = false;\n QColor getAccentColor() const {\n if (useCustomAccentColor && customAccentColor.isValid()) {\n return customAccentColor;\n }\n \n // Return system accent color\n QPalette palette = QGuiApplication::palette();\n return palette.highlight().color();\n}\n void setCustomAccentColor(const QColor &color) {\n if (customAccentColor != color) {\n customAccentColor = color;\n saveThemeSettings();\n // Always update theme if custom accent color is enabled\n if (useCustomAccentColor) {\n updateTheme();\n }\n }\n}\n void setUseCustomAccentColor(bool use) {\n if (useCustomAccentColor != use) {\n useCustomAccentColor = use;\n updateTheme();\n saveThemeSettings();\n }\n}\n void setUseBrighterPalette(bool use) {\n if (useBrighterPalette != use) {\n useBrighterPalette = use;\n \n // Update all colors - call updateColorPalette which handles null checks\n updateColorPalette();\n \n // Save preference\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"useBrighterPalette\", useBrighterPalette);\n }\n}\n QColor getDefaultPenColor() {\n return isDarkMode() ? Qt::white : Qt::black;\n}\n SDLControllerManager *controllerManager = nullptr;\n QThread *controllerThread = nullptr;\n QString getHoldMapping(const QString &buttonName) {\n return buttonHoldMapping.value(buttonName, \"None\");\n}\n QString getPressMapping(const QString &buttonName) {\n return buttonPressMapping.value(buttonName, \"None\");\n}\n void saveButtonMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n\n settings.beginGroup(\"ButtonHoldMappings\");\n for (auto it = buttonHoldMapping.begin(); it != buttonHoldMapping.end(); ++it) {\n settings.setValue(it.key(), it.value());\n }\n settings.endGroup();\n\n settings.beginGroup(\"ButtonPressMappings\");\n for (auto it = buttonPressMapping.begin(); it != buttonPressMapping.end(); ++it) {\n settings.setValue(it.key(), it.value());\n }\n settings.endGroup();\n}\n void loadButtonMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n\n // First, check if we need to migrate old settings\n migrateOldButtonMappings();\n\n settings.beginGroup(\"ButtonHoldMappings\");\n QStringList holdKeys = settings.allKeys();\n for (const QString &key : holdKeys) {\n buttonHoldMapping[key] = settings.value(key, \"none\").toString();\n }\n settings.endGroup();\n\n settings.beginGroup(\"ButtonPressMappings\");\n QStringList pressKeys = settings.allKeys();\n for (const QString &key : pressKeys) {\n QString value = settings.value(key, \"none\").toString();\n buttonPressMapping[key] = value;\n\n // ✅ Convert internal key to action enum\n buttonPressActionMapping[key] = stringToAction(value);\n }\n settings.endGroup();\n}\n void setHoldMapping(const QString &buttonName, const QString &dialMode) {\n buttonHoldMapping[buttonName] = dialMode;\n}\n void setPressMapping(const QString &buttonName, const QString &action) {\n buttonPressMapping[buttonName] = action;\n buttonPressActionMapping[buttonName] = stringToAction(action); // ✅ THIS LINE WAS MISSING\n}\n DialMode dialModeFromString(const QString &mode) {\n // Convert internal key to our existing DialMode enum\n InternalDialMode internalMode = ButtonMappingHelper::internalKeyToDialMode(mode);\n \n switch (internalMode) {\n case InternalDialMode::None: return PageSwitching; // Default fallback\n case InternalDialMode::PageSwitching: return PageSwitching;\n case InternalDialMode::ZoomControl: return ZoomControl;\n case InternalDialMode::ThicknessControl: return ThicknessControl;\n\n case InternalDialMode::ToolSwitching: return ToolSwitching;\n case InternalDialMode::PresetSelection: return PresetSelection;\n case InternalDialMode::PanAndPageScroll: return PanAndPageScroll;\n }\n return PanAndPageScroll; // Default fallback\n}\n void importNotebookFromFile(const QString &packageFile) {\n\n QString destDir = QFileDialog::getExistingDirectory(this, tr(\"Select Working Directory for Notebook\"));\n\n if (destDir.isEmpty()) {\n QMessageBox::warning(this, tr(\"Import Cancelled\"), tr(\"No directory selected. Notebook will not be opened.\"));\n return;\n }\n\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n\n canvas->importNotebookTo(packageFile, destDir);\n\n // Change saveFolder in InkCanvas\n canvas->setSaveFolder(destDir);\n canvas->loadPage(0);\n updateZoom(); // ✅ Update zoom and pan range after importing notebook\n}\n void openPdfFile(const QString &pdfPath) {\n // Check if the PDF file exists\n if (!QFile::exists(pdfPath)) {\n QMessageBox::warning(this, tr(\"File Not Found\"), tr(\"The PDF file could not be found:\\n%1\").arg(pdfPath));\n return;\n }\n \n // First, check if there's already a valid notebook folder for this PDF\n QString existingFolderPath;\n if (PdfOpenDialog::hasValidNotebookFolder(pdfPath, existingFolderPath)) {\n // Found a valid notebook folder, open it directly without showing dialog\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n \n // Save current work if edited\n if (canvas->isEdited()) {\n saveCurrentPage();\n }\n \n // Set the existing folder as save folder\n canvas->setSaveFolder(existingFolderPath);\n \n // Load the PDF\n canvas->loadPdf(pdfPath);\n \n // Update tab label and recent notebooks\n updateTabLabel();\n if (recentNotebooksManager) {\n recentNotebooksManager->addRecentNotebook(existingFolderPath, canvas);\n }\n \n // Switch to page 1 and update UI\n switchPageWithDirection(1, 1);\n pageInput->setValue(1);\n updateZoom();\n updatePanRange();\n \n return; // Exit early, no need to show dialog\n }\n \n // No valid notebook folder found, show the dialog with options\n PdfOpenDialog dialog(pdfPath, this);\n dialog.exec();\n \n PdfOpenDialog::Result result = dialog.getResult();\n QString selectedFolder = dialog.getSelectedFolder();\n \n if (result == PdfOpenDialog::Cancel) {\n return; // User cancelled, do nothing\n }\n \n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n \n // Save current work if edited\n if (canvas->isEdited()) {\n saveCurrentPage();\n }\n \n if (result == PdfOpenDialog::CreateNewFolder) {\n // Set the new folder as save folder\n canvas->setSaveFolder(selectedFolder);\n \n // Load the PDF\n canvas->loadPdf(pdfPath);\n \n // Update tab label and recent notebooks\n updateTabLabel();\n if (recentNotebooksManager) {\n recentNotebooksManager->addRecentNotebook(selectedFolder, canvas);\n }\n \n // Switch to page 1 and update UI\n switchPageWithDirection(1, 1);\n pageInput->setValue(1);\n updateZoom();\n updatePanRange();\n \n } else if (result == PdfOpenDialog::UseExistingFolder) {\n // Check if the existing folder is linked to the same PDF\n QString metadataFile = selectedFolder + \"/.pdf_path.txt\";\n bool isLinkedToSamePdf = false;\n \n if (QFile::exists(metadataFile)) {\n QFile file(metadataFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString existingPdfPath = in.readLine().trimmed();\n file.close();\n \n // Compare absolute paths\n QFileInfo existingInfo(existingPdfPath);\n QFileInfo newInfo(pdfPath);\n isLinkedToSamePdf = (existingInfo.absoluteFilePath() == newInfo.absoluteFilePath());\n }\n }\n \n if (!isLinkedToSamePdf && QFile::exists(metadataFile)) {\n // Folder is linked to a different PDF, ask user what to do\n QMessageBox::StandardButton reply = QMessageBox::question(\n this,\n tr(\"Different PDF Linked\"),\n tr(\"This notebook folder is already linked to a different PDF file.\\n\\nDo you want to replace the link with the new PDF?\"),\n QMessageBox::Yes | QMessageBox::No\n );\n \n if (reply == QMessageBox::No) {\n return; // User chose not to replace\n }\n }\n \n // Set the existing folder as save folder\n canvas->setSaveFolder(selectedFolder);\n \n // Load the PDF\n canvas->loadPdf(pdfPath);\n \n // Update tab label and recent notebooks\n updateTabLabel();\n if (recentNotebooksManager) {\n recentNotebooksManager->addRecentNotebook(selectedFolder, canvas);\n }\n \n // Switch to page 1 and update UI\n switchPageWithDirection(1, 1);\n pageInput->setValue(1);\n updateZoom();\n updatePanRange();\n }\n}\n void setPdfDPI(int dpi) {\n if (dpi != pdfRenderDPI) {\n pdfRenderDPI = dpi;\n savePdfDPI(dpi);\n\n // Apply immediately to current canvas if needed\n if (currentCanvas()) {\n currentCanvas()->setPDFRenderDPI(dpi);\n currentCanvas()->clearPdfCache();\n currentCanvas()->loadPdfPage(getCurrentPageForCanvas(currentCanvas())); // Optional: add this if needed\n updateZoom();\n updatePanRange();\n }\n }\n}\n void savePdfDPI(int dpi) {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"pdfRenderDPI\", dpi);\n}\n void saveDefaultBackgroundSettings(BackgroundStyle style, QColor color, int density) {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"defaultBackgroundStyle\", static_cast(style));\n settings.setValue(\"defaultBackgroundColor\", color.name());\n settings.setValue(\"defaultBackgroundDensity\", density);\n}\n void loadDefaultBackgroundSettings(BackgroundStyle &style, QColor &color, int &density) {\n QSettings settings(\"SpeedyNote\", \"App\");\n style = static_cast(settings.value(\"defaultBackgroundStyle\", static_cast(BackgroundStyle::Grid)).toInt());\n color = QColor(settings.value(\"defaultBackgroundColor\", \"#FFFFFF\").toString());\n density = settings.value(\"defaultBackgroundDensity\", 30).toInt();\n \n // Ensure valid values\n if (!color.isValid()) color = Qt::white;\n if (density < 10) density = 10;\n if (density > 200) density = 200;\n}\n void saveThemeSettings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"useCustomAccentColor\", useCustomAccentColor);\n if (customAccentColor.isValid()) {\n settings.setValue(\"customAccentColor\", customAccentColor.name());\n }\n settings.setValue(\"useBrighterPalette\", useBrighterPalette);\n}\n void loadThemeSettings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n useCustomAccentColor = settings.value(\"useCustomAccentColor\", false).toBool();\n QString colorName = settings.value(\"customAccentColor\", \"#0078D4\").toString();\n customAccentColor = QColor(colorName);\n useBrighterPalette = settings.value(\"useBrighterPalette\", false).toBool();\n \n // Ensure valid values\n if (!customAccentColor.isValid()) {\n customAccentColor = QColor(\"#0078D4\"); // Default blue\n }\n \n // Apply theme immediately after loading\n updateTheme();\n}\n void updateTheme() {\n // Update control bar background color\n QColor accentColor = getAccentColor();\n if (controlBar) {\n controlBar->setStyleSheet(QString(R\"(\n QWidget#controlBar {\n background-color: %1;\n }\n )\").arg(accentColor.name()));\n }\n \n // Update dial background color\n if (pageDial) {\n pageDial->setStyleSheet(QString(R\"(\n QDial {\n background-color: %1;\n }\n )\").arg(accentColor.name()));\n }\n \n // Update add tab button styling\n if (addTabButton) {\n bool darkMode = isDarkMode();\n QString buttonBgColor = darkMode ? \"rgba(80, 80, 80, 255)\" : \"rgba(220, 220, 220, 255)\";\n QString buttonHoverColor = darkMode ? \"rgba(90, 90, 90, 255)\" : \"rgba(200, 200, 200, 255)\";\n QString buttonPressColor = darkMode ? \"rgba(70, 70, 70, 255)\" : \"rgba(180, 180, 180, 255)\";\n QString borderColor = darkMode ? \"rgba(100, 100, 100, 255)\" : \"rgba(180, 180, 180, 255)\";\n \n addTabButton->setStyleSheet(QString(R\"(\n QPushButton {\n background-color: %1;\n border: 1px solid %2;\n border-radius: 12px;\n margin: 2px;\n }\n QPushButton:hover {\n background-color: %3;\n }\n QPushButton:pressed {\n background-color: %4;\n }\n )\").arg(buttonBgColor).arg(borderColor).arg(buttonHoverColor).arg(buttonPressColor));\n }\n \n // Update PDF outline sidebar styling\n if (outlineSidebar && outlineTree) {\n bool darkMode = isDarkMode();\n QString bgColor = darkMode ? \"rgba(45, 45, 45, 255)\" : \"rgba(250, 250, 250, 255)\";\n QString borderColor = darkMode ? \"rgba(80, 80, 80, 255)\" : \"rgba(200, 200, 200, 255)\";\n QString textColor = darkMode ? \"#E0E0E0\" : \"#333\";\n QString hoverColor = darkMode ? \"rgba(60, 60, 60, 255)\" : \"rgba(240, 240, 240, 255)\";\n QString selectedColor = QString(\"rgba(%1, %2, %3, 100)\").arg(accentColor.red()).arg(accentColor.green()).arg(accentColor.blue());\n \n outlineSidebar->setStyleSheet(QString(R\"(\n QWidget {\n background-color: %1;\n border-right: 1px solid %2;\n }\n QLabel {\n color: %3;\n background: transparent;\n }\n )\").arg(bgColor).arg(borderColor).arg(textColor));\n \n outlineTree->setStyleSheet(QString(R\"(\n QTreeWidget {\n background-color: %1;\n border: none;\n color: %2;\n outline: none;\n }\n QTreeWidget::item {\n padding: 4px;\n border: none;\n }\n QTreeWidget::item:hover {\n background-color: %3;\n }\n QTreeWidget::item:selected {\n background-color: %4;\n color: %2;\n }\n QTreeWidget::branch {\n background: transparent;\n }\n QTreeWidget::branch:has-children:!has-siblings:closed,\n QTreeWidget::branch:closed:has-children:has-siblings {\n border-image: none;\n image: url(:/resources/icons/down_arrow.png);\n }\n QTreeWidget::branch:open:has-children:!has-siblings,\n QTreeWidget::branch:open:has-children:has-siblings {\n border-image: none;\n image: url(:/resources/icons/up_arrow.png);\n }\n QScrollBar:vertical {\n background: rgba(200, 200, 200, 80);\n border: none;\n margin: 0px;\n width: 16px !important;\n max-width: 16px !important;\n }\n QScrollBar:vertical:hover {\n background: rgba(200, 200, 200, 120);\n }\n QScrollBar::handle:vertical {\n background: rgba(100, 100, 100, 150);\n border-radius: 2px;\n min-height: 120px;\n }\n QScrollBar::handle:vertical:hover {\n background: rgba(80, 80, 80, 210);\n }\n QScrollBar::add-line:vertical, \n QScrollBar::sub-line:vertical {\n width: 0px;\n height: 0px;\n background: none;\n border: none;\n }\n QScrollBar::add-page:vertical, \n QScrollBar::sub-page:vertical {\n background: transparent;\n }\n )\").arg(bgColor).arg(textColor).arg(hoverColor).arg(selectedColor));\n \n // Apply same styling to bookmarks tree\n bookmarksTree->setStyleSheet(QString(R\"(\n QTreeWidget {\n background-color: %1;\n border: none;\n color: %2;\n outline: none;\n }\n QTreeWidget::item {\n padding: 2px;\n border: none;\n min-height: 26px;\n }\n QTreeWidget::item:hover {\n background-color: %3;\n }\n QTreeWidget::item:selected {\n background-color: %4;\n color: %2;\n }\n QScrollBar:vertical {\n background: rgba(200, 200, 200, 80);\n border: none;\n margin: 0px;\n width: 16px !important;\n max-width: 16px !important;\n }\n QScrollBar:vertical:hover {\n background: rgba(200, 200, 200, 120);\n }\n QScrollBar::handle:vertical {\n background: rgba(100, 100, 100, 150);\n border-radius: 2px;\n min-height: 120px;\n }\n QScrollBar::handle:vertical:hover {\n background: rgba(80, 80, 80, 210);\n }\n QScrollBar::add-line:vertical, \n QScrollBar::sub-line:vertical {\n width: 0px;\n height: 0px;\n background: none;\n border: none;\n }\n QScrollBar::add-page:vertical, \n QScrollBar::sub-page:vertical {\n background: transparent;\n }\n )\").arg(bgColor).arg(textColor).arg(hoverColor).arg(selectedColor));\n }\n \n // Update horizontal tab bar styling with accent color\n if (tabList) {\n bool darkMode = isDarkMode();\n QString bgColor = darkMode ? \"rgba(60, 60, 60, 255)\" : \"rgba(240, 240, 240, 255)\";\n QString itemBgColor = darkMode ? \"rgba(80, 80, 80, 255)\" : \"rgba(220, 220, 220, 255)\";\n QString selectedBgColor = darkMode ? \"rgba(45, 45, 45, 255)\" : \"white\";\n QString borderColor = darkMode ? \"rgba(100, 100, 100, 255)\" : \"rgba(180, 180, 180, 255)\";\n QString hoverBgColor = darkMode ? \"rgba(90, 90, 90, 255)\" : \"rgba(230, 230, 230, 255)\";\n \n tabList->setStyleSheet(QString(R\"(\n QListWidget {\n background-color: %1;\n border: none;\n border-bottom: 2px solid %2;\n outline: none;\n }\n QListWidget::item {\n background-color: %3;\n border: 1px solid %4;\n border-bottom: none;\n margin-right: 1px;\n margin-top: 2px;\n padding: 0px;\n min-width: 80px;\n max-width: 120px;\n }\n QListWidget::item:selected {\n background-color: %5;\n border: 1px solid %4;\n border-bottom: 2px solid %2;\n margin-top: 1px;\n }\n QListWidget::item:hover:!selected {\n background-color: %6;\n }\n QScrollBar:horizontal {\n background: %1;\n height: 8px;\n border: none;\n margin: 0px;\n border-top: 1px solid %4;\n }\n QScrollBar::handle:horizontal {\n background: rgba(150, 150, 150, 120);\n border-radius: 4px;\n min-width: 20px;\n margin: 1px;\n }\n QScrollBar::handle:horizontal:hover {\n background: rgba(120, 120, 120, 200);\n }\n QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal {\n width: 0px;\n height: 0px;\n background: none;\n border: none;\n }\n QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {\n background: transparent;\n }\n )\").arg(bgColor)\n .arg(accentColor.name())\n .arg(itemBgColor)\n .arg(borderColor)\n .arg(selectedBgColor)\n .arg(hoverBgColor));\n }\n \n\n \n // Force icon reload for all buttons that use themed icons\n if (loadPdfButton) loadPdfButton->setIcon(loadThemedIcon(\"pdf\"));\n if (clearPdfButton) clearPdfButton->setIcon(loadThemedIcon(\"pdfdelete\"));\n if (pdfTextSelectButton) pdfTextSelectButton->setIcon(loadThemedIcon(\"ibeam\"));\n if (exportNotebookButton) exportNotebookButton->setIcon(loadThemedIcon(\"export\"));\n if (importNotebookButton) importNotebookButton->setIcon(loadThemedIcon(\"import\"));\n if (benchmarkButton) benchmarkButton->setIcon(loadThemedIcon(\"benchmark\"));\n if (toggleTabBarButton) toggleTabBarButton->setIcon(loadThemedIcon(\"tabs\"));\n if (toggleOutlineButton) toggleOutlineButton->setIcon(loadThemedIcon(\"outline\"));\n if (toggleBookmarksButton) toggleBookmarksButton->setIcon(loadThemedIcon(\"bookmark\"));\n if (toggleBookmarkButton) toggleBookmarkButton->setIcon(loadThemedIcon(\"star\"));\n if (selectFolderButton) selectFolderButton->setIcon(loadThemedIcon(\"folder\"));\n if (saveButton) saveButton->setIcon(loadThemedIcon(\"save\"));\n if (saveAnnotatedButton) saveAnnotatedButton->setIcon(loadThemedIcon(\"saveannotated\"));\n if (fullscreenButton) fullscreenButton->setIcon(loadThemedIcon(\"fullscreen\"));\n if (backgroundButton) backgroundButton->setIcon(loadThemedIcon(\"background\"));\n if (straightLineToggleButton) straightLineToggleButton->setIcon(loadThemedIcon(\"straightLine\"));\n if (ropeToolButton) ropeToolButton->setIcon(loadThemedIcon(\"rope\"));\n if (markdownButton) markdownButton->setIcon(loadThemedIcon(\"markdown\"));\n if (deletePageButton) deletePageButton->setIcon(loadThemedIcon(\"trash\"));\n if (zoomButton) zoomButton->setIcon(loadThemedIcon(\"zoom\"));\n if (dialToggleButton) dialToggleButton->setIcon(loadThemedIcon(\"dial\"));\n if (fastForwardButton) fastForwardButton->setIcon(loadThemedIcon(\"fastforward\"));\n if (jumpToPageButton) jumpToPageButton->setIcon(loadThemedIcon(\"bookpage\"));\n if (thicknessButton) thicknessButton->setIcon(loadThemedIcon(\"thickness\"));\n if (btnPageSwitch) btnPageSwitch->setIcon(loadThemedIcon(\"bookpage\"));\n if (btnZoom) btnZoom->setIcon(loadThemedIcon(\"zoom\"));\n if (btnThickness) btnThickness->setIcon(loadThemedIcon(\"thickness\"));\n if (btnTool) btnTool->setIcon(loadThemedIcon(\"pen\"));\n if (btnPresets) btnPresets->setIcon(loadThemedIcon(\"preset\"));\n if (btnPannScroll) btnPannScroll->setIcon(loadThemedIcon(\"scroll\"));\n if (addPresetButton) addPresetButton->setIcon(loadThemedIcon(\"savepreset\"));\n if (openControlPanelButton) openControlPanelButton->setIcon(loadThemedIcon(\"settings\"));\n if (openRecentNotebooksButton) openRecentNotebooksButton->setIcon(loadThemedIcon(\"recent\"));\n if (penToolButton) penToolButton->setIcon(loadThemedIcon(\"pen\"));\n if (markerToolButton) markerToolButton->setIcon(loadThemedIcon(\"marker\"));\n if (eraserToolButton) eraserToolButton->setIcon(loadThemedIcon(\"eraser\"));\n \n // Update button styles with new theme\n bool darkMode = isDarkMode();\n QString newButtonStyle = createButtonStyle(darkMode);\n \n // Update all buttons that use the buttonStyle\n if (loadPdfButton) loadPdfButton->setStyleSheet(newButtonStyle);\n if (clearPdfButton) clearPdfButton->setStyleSheet(newButtonStyle);\n if (pdfTextSelectButton) pdfTextSelectButton->setStyleSheet(newButtonStyle);\n if (exportNotebookButton) exportNotebookButton->setStyleSheet(newButtonStyle);\n if (importNotebookButton) importNotebookButton->setStyleSheet(newButtonStyle);\n if (benchmarkButton) benchmarkButton->setStyleSheet(newButtonStyle);\n if (toggleTabBarButton) toggleTabBarButton->setStyleSheet(newButtonStyle);\n if (toggleOutlineButton) toggleOutlineButton->setStyleSheet(newButtonStyle);\n if (toggleBookmarksButton) toggleBookmarksButton->setStyleSheet(newButtonStyle);\n if (toggleBookmarkButton) toggleBookmarkButton->setStyleSheet(newButtonStyle);\n if (selectFolderButton) selectFolderButton->setStyleSheet(newButtonStyle);\n if (saveButton) saveButton->setStyleSheet(newButtonStyle);\n if (saveAnnotatedButton) saveAnnotatedButton->setStyleSheet(newButtonStyle);\n if (fullscreenButton) fullscreenButton->setStyleSheet(newButtonStyle);\n if (redButton) redButton->setStyleSheet(newButtonStyle);\n if (blueButton) blueButton->setStyleSheet(newButtonStyle);\n if (yellowButton) yellowButton->setStyleSheet(newButtonStyle);\n if (greenButton) greenButton->setStyleSheet(newButtonStyle);\n if (blackButton) blackButton->setStyleSheet(newButtonStyle);\n if (whiteButton) whiteButton->setStyleSheet(newButtonStyle);\n if (thicknessButton) thicknessButton->setStyleSheet(newButtonStyle);\n if (penToolButton) penToolButton->setStyleSheet(newButtonStyle);\n if (markerToolButton) markerToolButton->setStyleSheet(newButtonStyle);\n if (eraserToolButton) eraserToolButton->setStyleSheet(newButtonStyle);\n if (backgroundButton) backgroundButton->setStyleSheet(newButtonStyle);\n if (straightLineToggleButton) straightLineToggleButton->setStyleSheet(newButtonStyle);\n if (ropeToolButton) ropeToolButton->setStyleSheet(newButtonStyle);\n if (markdownButton) markdownButton->setStyleSheet(newButtonStyle);\n if (deletePageButton) deletePageButton->setStyleSheet(newButtonStyle);\n if (zoomButton) zoomButton->setStyleSheet(newButtonStyle);\n if (dialToggleButton) dialToggleButton->setStyleSheet(newButtonStyle);\n if (fastForwardButton) fastForwardButton->setStyleSheet(newButtonStyle);\n if (jumpToPageButton) jumpToPageButton->setStyleSheet(newButtonStyle);\n if (btnPageSwitch) btnPageSwitch->setStyleSheet(newButtonStyle);\n if (btnZoom) btnZoom->setStyleSheet(newButtonStyle);\n if (btnThickness) btnThickness->setStyleSheet(newButtonStyle);\n if (btnTool) btnTool->setStyleSheet(newButtonStyle);\n if (btnPresets) btnPresets->setStyleSheet(newButtonStyle);\n if (btnPannScroll) btnPannScroll->setStyleSheet(newButtonStyle);\n if (addPresetButton) addPresetButton->setStyleSheet(newButtonStyle);\n if (openControlPanelButton) openControlPanelButton->setStyleSheet(newButtonStyle);\n if (openRecentNotebooksButton) openRecentNotebooksButton->setStyleSheet(newButtonStyle);\n if (zoom50Button) zoom50Button->setStyleSheet(newButtonStyle);\n if (dezoomButton) dezoomButton->setStyleSheet(newButtonStyle);\n if (zoom200Button) zoom200Button->setStyleSheet(newButtonStyle);\n if (prevPageButton) prevPageButton->setStyleSheet(newButtonStyle);\n if (nextPageButton) nextPageButton->setStyleSheet(newButtonStyle);\n \n // Update color buttons with palette-based icons\n if (redButton) {\n QString redIconPath = useBrighterPalette ? \":/resources/icons/pen_light_red.png\" : \":/resources/icons/pen_dark_red.png\";\n redButton->setIcon(QIcon(redIconPath));\n }\n if (blueButton) {\n QString blueIconPath = useBrighterPalette ? \":/resources/icons/pen_light_blue.png\" : \":/resources/icons/pen_dark_blue.png\";\n blueButton->setIcon(QIcon(blueIconPath));\n }\n if (yellowButton) {\n QString yellowIconPath = useBrighterPalette ? \":/resources/icons/pen_light_yellow.png\" : \":/resources/icons/pen_dark_yellow.png\";\n yellowButton->setIcon(QIcon(yellowIconPath));\n }\n if (greenButton) {\n QString greenIconPath = useBrighterPalette ? \":/resources/icons/pen_light_green.png\" : \":/resources/icons/pen_dark_green.png\";\n greenButton->setIcon(QIcon(greenIconPath));\n }\n if (blackButton) {\n QString blackIconPath = darkMode ? \":/resources/icons/pen_light_black.png\" : \":/resources/icons/pen_dark_black.png\";\n blackButton->setIcon(QIcon(blackIconPath));\n }\n if (whiteButton) {\n QString whiteIconPath = darkMode ? \":/resources/icons/pen_light_white.png\" : \":/resources/icons/pen_dark_white.png\";\n whiteButton->setIcon(QIcon(whiteIconPath));\n }\n \n // Update tab close button icons and label styling\n if (tabList) {\n bool darkMode = isDarkMode();\n QString labelColor = darkMode ? \"#E0E0E0\" : \"#333\";\n \n for (int i = 0; i < tabList->count(); ++i) {\n QListWidgetItem *item = tabList->item(i);\n if (item) {\n QWidget *tabWidget = tabList->itemWidget(item);\n if (tabWidget) {\n QPushButton *closeButton = tabWidget->findChild();\n if (closeButton) {\n closeButton->setIcon(loadThemedIcon(\"cross\"));\n }\n \n QLabel *tabLabel = tabWidget->findChild(\"tabLabel\");\n if (tabLabel) {\n tabLabel->setStyleSheet(QString(\"color: %1; font-weight: 500; padding: 2px; text-align: left;\").arg(labelColor));\n }\n }\n }\n }\n }\n \n // Update dial display\n updateDialDisplay();\n}\n void migrateOldButtonMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n \n // Check if migration is needed by looking for old format strings\n settings.beginGroup(\"ButtonHoldMappings\");\n QStringList holdKeys = settings.allKeys();\n bool needsMigration = false;\n \n for (const QString &key : holdKeys) {\n QString value = settings.value(key).toString();\n // If we find old English strings, we need to migrate\n if (value == \"PageSwitching\" || value == \"ZoomControl\" || value == \"ThicknessControl\" ||\n value == \"ToolSwitching\" || value == \"PresetSelection\" ||\n value == \"PanAndPageScroll\") {\n needsMigration = true;\n break;\n }\n }\n settings.endGroup();\n \n if (!needsMigration) {\n settings.beginGroup(\"ButtonPressMappings\");\n QStringList pressKeys = settings.allKeys();\n for (const QString &key : pressKeys) {\n QString value = settings.value(key).toString();\n // Check for old English action strings\n if (value == \"Toggle Fullscreen\" || value == \"Toggle Dial\" || value == \"Zoom 50%\" ||\n value == \"Add Preset\" || value == \"Delete Page\" || value == \"Fast Forward\" ||\n value == \"Open Control Panel\" || value == \"Custom Color\") {\n needsMigration = true;\n break;\n }\n }\n settings.endGroup();\n }\n \n if (!needsMigration) return;\n \n // Perform migration\n // qDebug() << \"Migrating old button mappings to new format...\";\n \n // Migrate hold mappings\n settings.beginGroup(\"ButtonHoldMappings\");\n holdKeys = settings.allKeys();\n for (const QString &key : holdKeys) {\n QString oldValue = settings.value(key).toString();\n QString newValue = migrateOldDialModeString(oldValue);\n if (newValue != oldValue) {\n settings.setValue(key, newValue);\n }\n }\n settings.endGroup();\n \n // Migrate press mappings\n settings.beginGroup(\"ButtonPressMappings\");\n QStringList pressKeys = settings.allKeys();\n for (const QString &key : pressKeys) {\n QString oldValue = settings.value(key).toString();\n QString newValue = migrateOldActionString(oldValue);\n if (newValue != oldValue) {\n settings.setValue(key, newValue);\n }\n }\n settings.endGroup();\n \n // qDebug() << \"Button mapping migration completed.\";\n}\n QString migrateOldDialModeString(const QString &oldString) {\n // Convert old English strings to new internal keys\n if (oldString == \"None\") return \"none\";\n if (oldString == \"PageSwitching\") return \"page_switching\";\n if (oldString == \"ZoomControl\") return \"zoom_control\";\n if (oldString == \"ThicknessControl\") return \"thickness_control\";\n\n if (oldString == \"ToolSwitching\") return \"tool_switching\";\n if (oldString == \"PresetSelection\") return \"preset_selection\";\n if (oldString == \"PanAndPageScroll\") return \"pan_and_page_scroll\";\n return oldString; // Return as-is if not found (might already be new format)\n}\n QString migrateOldActionString(const QString &oldString) {\n // Convert old English strings to new internal keys\n if (oldString == \"None\") return \"none\";\n if (oldString == \"Toggle Fullscreen\") return \"toggle_fullscreen\";\n if (oldString == \"Toggle Dial\") return \"toggle_dial\";\n if (oldString == \"Zoom 50%\") return \"zoom_50\";\n if (oldString == \"Zoom Out\") return \"zoom_out\";\n if (oldString == \"Zoom 200%\") return \"zoom_200\";\n if (oldString == \"Add Preset\") return \"add_preset\";\n if (oldString == \"Delete Page\") return \"delete_page\";\n if (oldString == \"Fast Forward\") return \"fast_forward\";\n if (oldString == \"Open Control Panel\") return \"open_control_panel\";\n if (oldString == \"Red\") return \"red_color\";\n if (oldString == \"Blue\") return \"blue_color\";\n if (oldString == \"Yellow\") return \"yellow_color\";\n if (oldString == \"Green\") return \"green_color\";\n if (oldString == \"Black\") return \"black_color\";\n if (oldString == \"White\") return \"white_color\";\n if (oldString == \"Custom Color\") return \"custom_color\";\n if (oldString == \"Toggle Sidebar\") return \"toggle_sidebar\";\n if (oldString == \"Save\") return \"save\";\n if (oldString == \"Straight Line Tool\") return \"straight_line_tool\";\n if (oldString == \"Rope Tool\") return \"rope_tool\";\n if (oldString == \"Set Pen Tool\") return \"set_pen_tool\";\n if (oldString == \"Set Marker Tool\") return \"set_marker_tool\";\n if (oldString == \"Set Eraser Tool\") return \"set_eraser_tool\";\n if (oldString == \"Toggle PDF Text Selection\") return \"toggle_pdf_text_selection\";\n return oldString; // Return as-is if not found (might already be new format)\n}\n InkCanvas* currentCanvas();\n void saveCurrentPage() {\n currentCanvas()->saveToFile(getCurrentPageForCanvas(currentCanvas()));\n}\n void saveCurrentPageConcurrent() {\n InkCanvas *canvas = currentCanvas();\n if (!canvas || !canvas->isEdited()) return;\n \n int pageNumber = getCurrentPageForCanvas(canvas);\n QString saveFolder = canvas->getSaveFolder();\n \n if (saveFolder.isEmpty()) return;\n \n // Create a copy of the buffer for concurrent saving\n QPixmap bufferCopy = canvas->getBuffer();\n \n // Save markdown windows for this page (this must be done on the main thread)\n if (canvas->getMarkdownManager()) {\n canvas->getMarkdownManager()->saveWindowsForPage(pageNumber);\n }\n \n // Run the save operation concurrently\n QFuture future = QtConcurrent::run([saveFolder, pageNumber, bufferCopy]() {\n // Get notebook ID from the save folder (similar to how InkCanvas does it)\n QString notebookId = \"notebook\"; // Default fallback\n QString idFile = saveFolder + \"/.notebook_id.txt\";\n if (QFile::exists(idFile)) {\n QFile file(idFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n notebookId = in.readLine().trimmed();\n file.close();\n }\n }\n \n QString filePath = saveFolder + QString(\"/%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n \n QImage image(bufferCopy.size(), QImage::Format_ARGB32);\n image.fill(Qt::transparent);\n QPainter painter(&image);\n painter.drawPixmap(0, 0, bufferCopy);\n image.save(filePath, \"PNG\");\n });\n \n // Mark as not edited since we're saving\n canvas->setEdited(false);\n}\n void switchPage(int pageNumber) {\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n\n if (currentCanvas()->isEdited()){\n saveCurrentPageConcurrent(); // Use concurrent saving for smoother page flipping\n }\n\n int oldPage = getCurrentPageForCanvas(currentCanvas()) + 1; // Convert to 1-based for comparison\n int newPage = pageNumber - 1;\n pageMap[canvas] = newPage; // ✅ Save the page for this tab\n\n if (canvas->isPdfLoadedFunc() && pageNumber - 1 < canvas->getTotalPdfPages()) {\n canvas->loadPdfPage(newPage);\n } else {\n canvas->loadPage(newPage);\n }\n\n canvas->setLastActivePage(newPage);\n updateZoom();\n // It seems panXSlider and panYSlider can be null here during startup.\n if(panXSlider && panYSlider){\n canvas->setLastPanX(panXSlider->maximum());\n canvas->setLastPanY(panYSlider->maximum());\n \n // ✅ Enhanced scroll-on-top functionality\n if (scrollOnTopEnabled && panYSlider->maximum() > 0) {\n if (pageNumber > oldPage) {\n // Forward page switching → scroll to top\n panYSlider->setValue(0);\n } else if (pageNumber < oldPage) {\n // Backward page switching → scroll to bottom\n panYSlider->setValue(panYSlider->maximum());\n }\n }\n }\n updateDialDisplay();\n updateBookmarkButtonState(); // Update bookmark button state when switching pages\n}\n void switchPageWithDirection(int pageNumber, int direction) {\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n\n if (currentCanvas()->isEdited()){\n saveCurrentPageConcurrent(); // Use concurrent saving for smoother page flipping\n }\n\n int newPage = pageNumber - 1;\n pageMap[canvas] = newPage; // ✅ Save the page for this tab\n\n if (canvas->isPdfLoadedFunc() && pageNumber - 1 < canvas->getTotalPdfPages()) {\n canvas->loadPdfPage(newPage);\n } else {\n canvas->loadPage(newPage);\n }\n\n canvas->setLastActivePage(newPage);\n updateZoom();\n // It seems panXSlider and panYSlider can be null here during startup.\n if(panXSlider && panYSlider){\n canvas->setLastPanX(panXSlider->maximum());\n canvas->setLastPanY(panYSlider->maximum());\n \n // ✅ Enhanced scroll-on-top functionality with explicit direction\n if (scrollOnTopEnabled && panYSlider->maximum() > 0) {\n if (direction > 0) {\n // Forward page switching → scroll to top\n panYSlider->setValue(0);\n } else if (direction < 0) {\n // Backward page switching → scroll to bottom\n panYSlider->setValue(panYSlider->maximum());\n }\n }\n }\n updateDialDisplay();\n updateBookmarkButtonState(); // Update bookmark button state when switching pages\n}\n void updateTabLabel() {\n int index = tabList->currentRow();\n if (index < 0) return;\n\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n\n QString folderPath = canvas->getSaveFolder(); // ✅ Get save folder\n if (folderPath.isEmpty()) return;\n\n QString tabName;\n\n // ✅ Check if there is an assigned PDF\n QString metadataFile = folderPath + \"/.pdf_path.txt\";\n if (QFile::exists(metadataFile)) {\n QFile file(metadataFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString pdfPath = in.readLine().trimmed();\n file.close();\n\n // ✅ Extract just the PDF filename (not full path)\n QFileInfo pdfInfo(pdfPath);\n if (pdfInfo.exists()) {\n tabName = elideTabText(pdfInfo.fileName(), 90); // e.g., \"mydocument.pdf\" (elided)\n }\n }\n }\n\n // ✅ If no PDF, use the folder name\n if (tabName.isEmpty()) {\n QFileInfo folderInfo(folderPath);\n tabName = elideTabText(folderInfo.fileName(), 90); // e.g., \"MyNotebook\" (elided)\n }\n\n QListWidgetItem *tabItem = tabList->item(index);\n if (tabItem) {\n QWidget *tabWidget = tabList->itemWidget(tabItem); // Get the tab's custom widget\n if (tabWidget) {\n QLabel *tabLabel = tabWidget->findChild(); // Get the QLabel inside\n if (tabLabel) {\n tabLabel->setText(tabName); // ✅ Update tab label\n tabLabel->setWordWrap(false); // No wrapping for horizontal tabs\n }\n }\n }\n}\n QSpinBox *pageInput;\n QPushButton *prevPageButton;\n QPushButton *nextPageButton;\n void addKeyboardMapping(const QString &keySequence, const QString &action) {\n // List of IME-related shortcuts that should not be intercepted\n QStringList imeShortcuts = {\n \"Ctrl+Space\", // Primary IME toggle\n \"Ctrl+Shift\", // Language switching\n \"Ctrl+Alt\", // IME functions\n \"Shift+Alt\", // Alternative language switching\n \"Alt+Shift\" // Alternative language switching (reversed)\n };\n \n // Don't allow mapping of IME-related shortcuts\n if (imeShortcuts.contains(keySequence)) {\n qWarning() << \"Cannot map IME-related shortcut:\" << keySequence;\n return;\n }\n \n keyboardMappings[keySequence] = action;\n keyboardActionMapping[keySequence] = stringToAction(action);\n saveKeyboardMappings();\n}\n void removeKeyboardMapping(const QString &keySequence) {\n keyboardMappings.remove(keySequence);\n keyboardActionMapping.remove(keySequence);\n saveKeyboardMappings();\n}\n QMap getKeyboardMappings() const {\n return keyboardMappings;\n}\n void reconnectControllerSignals() {\n if (!controllerManager || !pageDial) {\n return;\n }\n \n // Reset internal dial state\n tracking = false;\n accumulatedRotation = 0;\n grossTotalClicks = 0;\n tempClicks = 0;\n lastAngle = 0;\n startAngle = 0;\n pendingPageFlip = 0;\n accumulatedRotationAfterLimit = 0;\n \n // Disconnect all existing connections to avoid duplicates\n disconnect(controllerManager, nullptr, this, nullptr);\n disconnect(controllerManager, nullptr, pageDial, nullptr);\n \n // Reconnect all controller signals\n connect(controllerManager, &SDLControllerManager::buttonHeld, this, &MainWindow::handleButtonHeld);\n connect(controllerManager, &SDLControllerManager::buttonReleased, this, &MainWindow::handleButtonReleased);\n connect(controllerManager, &SDLControllerManager::leftStickAngleChanged, pageDial, &QDial::setValue);\n connect(controllerManager, &SDLControllerManager::leftStickReleased, pageDial, &QDial::sliderReleased);\n connect(controllerManager, &SDLControllerManager::buttonSinglePress, this, &MainWindow::handleControllerButton);\n \n // Re-establish dial mode connections by changing to current mode\n DialMode currentMode = currentDialMode;\n changeDialMode(currentMode);\n \n // Update dial display to reflect current state\n updateDialDisplay();\n \n // qDebug() << \"Controller signals reconnected successfully\";\n}\n void updateDialButtonState() {\n // Check if dial is visible\n bool isDialVisible = dialContainer && dialContainer->isVisible();\n \n if (dialToggleButton) {\n dialToggleButton->setProperty(\"selected\", isDialVisible);\n \n // Force style update\n dialToggleButton->style()->unpolish(dialToggleButton);\n dialToggleButton->style()->polish(dialToggleButton);\n }\n}\n void updateFastForwardButtonState() {\n if (fastForwardButton) {\n fastForwardButton->setProperty(\"selected\", fastForwardMode);\n \n // Force style update\n fastForwardButton->style()->unpolish(fastForwardButton);\n fastForwardButton->style()->polish(fastForwardButton);\n }\n}\n void updateToolButtonStates() {\n if (!currentCanvas()) return;\n \n // Reset all tool buttons\n penToolButton->setProperty(\"selected\", false);\n markerToolButton->setProperty(\"selected\", false);\n eraserToolButton->setProperty(\"selected\", false);\n \n // Set the selected property for the current tool\n ToolType currentTool = currentCanvas()->getCurrentTool();\n switch (currentTool) {\n case ToolType::Pen:\n penToolButton->setProperty(\"selected\", true);\n break;\n case ToolType::Marker:\n markerToolButton->setProperty(\"selected\", true);\n break;\n case ToolType::Eraser:\n eraserToolButton->setProperty(\"selected\", true);\n break;\n }\n \n // Force style update\n penToolButton->style()->unpolish(penToolButton);\n penToolButton->style()->polish(penToolButton);\n markerToolButton->style()->unpolish(markerToolButton);\n markerToolButton->style()->polish(markerToolButton);\n eraserToolButton->style()->unpolish(eraserToolButton);\n eraserToolButton->style()->polish(eraserToolButton);\n}\n void handleColorButtonClick() {\n if (!currentCanvas()) return;\n \n ToolType currentTool = currentCanvas()->getCurrentTool();\n \n // If in eraser mode, switch back to pen mode\n if (currentTool == ToolType::Eraser) {\n currentCanvas()->setTool(ToolType::Pen);\n updateToolButtonStates();\n updateThicknessSliderForCurrentTool();\n }\n \n // If rope tool is enabled, turn it off\n if (currentCanvas()->isRopeToolMode()) {\n currentCanvas()->setRopeToolMode(false);\n updateRopeToolButtonState();\n }\n \n // For marker and straight line mode, leave them as they are\n // No special handling needed - they can work with color changes\n}\n void updateThicknessSliderForCurrentTool() {\n if (!currentCanvas() || !thicknessSlider) return;\n \n // Block signals to prevent recursive calls\n thicknessSlider->blockSignals(true);\n \n // Update slider to reflect current tool's thickness\n qreal currentThickness = currentCanvas()->getPenThickness();\n \n // Convert thickness back to slider value (reverse of updateThickness calculation)\n qreal visualThickness = currentThickness * (currentCanvas()->getZoom() / 100.0);\n int sliderValue = qBound(1, static_cast(qRound(visualThickness)), 50);\n \n thicknessSlider->setValue(sliderValue);\n thicknessSlider->blockSignals(false);\n}\n void updatePdfTextSelectButtonState() {\n // Check if PDF text selection is enabled\n bool isEnabled = currentCanvas() && currentCanvas()->isPdfTextSelectionEnabled();\n \n if (pdfTextSelectButton) {\n pdfTextSelectButton->setProperty(\"selected\", isEnabled);\n \n // Force style update (uses the same buttonStyle as other toggle buttons)\n pdfTextSelectButton->style()->unpolish(pdfTextSelectButton);\n pdfTextSelectButton->style()->polish(pdfTextSelectButton);\n }\n}\n private:\n void toggleBenchmark() {\n benchmarking = !benchmarking;\n if (benchmarking) {\n currentCanvas()->startBenchmark();\n benchmarkTimer->start(1000); // Update every second\n } else {\n currentCanvas()->stopBenchmark();\n benchmarkTimer->stop();\n benchmarkLabel->setText(tr(\"PR:N/A\"));\n }\n}\n void updateBenchmarkDisplay() {\n int sampleRate = currentCanvas()->getProcessedRate();\n benchmarkLabel->setText(QString(tr(\"PR:%1 Hz\")).arg(sampleRate));\n}\n void applyCustomColor() {\n QString colorCode = customColorInput->text();\n if (!colorCode.startsWith(\"#\")) {\n colorCode.prepend(\"#\");\n }\n currentCanvas()->setPenColor(QColor(colorCode));\n updateDialDisplay(); \n}\n void updateThickness(int value) {\n // Calculate thickness based on the slider value at 100% zoom\n // The slider value represents the desired visual thickness\n qreal visualThickness = value; // Scale slider value to reasonable thickness\n \n // Apply zoom scaling to maintain visual consistency\n qreal actualThickness = visualThickness * (100.0 / currentCanvas()->getZoom()); \n \n currentCanvas()->setPenThickness(actualThickness);\n}\n void adjustThicknessForZoom(int oldZoom, int newZoom) {\n // Adjust all tool thicknesses to maintain visual consistency when zoom changes\n if (oldZoom == newZoom || oldZoom <= 0 || newZoom <= 0) return;\n \n InkCanvas* canvas = currentCanvas();\n if (!canvas) return;\n \n qreal zoomRatio = qreal(oldZoom) / qreal(newZoom);\n ToolType currentTool = canvas->getCurrentTool();\n \n // Adjust thickness for all tools, not just the current one\n canvas->adjustAllToolThicknesses(zoomRatio);\n \n // Update the thickness slider to reflect the current tool's new thickness\n updateThicknessSliderForCurrentTool();\n \n // ✅ FIXED: Update dial display to show new thickness immediately during zoom changes\n updateDialDisplay();\n}\n void changeTool(int index) {\n if (index == 0) {\n currentCanvas()->setTool(ToolType::Pen);\n } else if (index == 1) {\n currentCanvas()->setTool(ToolType::Marker);\n } else if (index == 2) {\n currentCanvas()->setTool(ToolType::Eraser);\n }\n updateToolButtonStates();\n updateThicknessSliderForCurrentTool();\n updateDialDisplay();\n}\n void selectFolder() {\n QString folder = QFileDialog::getExistingDirectory(this, tr(\"Select Save Folder\"));\n if (!folder.isEmpty()) {\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n if (canvas->isEdited()){\n saveCurrentPage();\n }\n canvas->setSaveFolder(folder);\n switchPageWithDirection(1, 1); // Going to page 1 is forward direction\n pageInput->setValue(1);\n updateTabLabel();\n recentNotebooksManager->addRecentNotebook(folder, canvas); // Track when folder is selected\n }\n }\n}\n void saveCanvas() {\n currentCanvas()->saveToFile(getCurrentPageForCanvas(currentCanvas()));\n}\n void saveAnnotated() {\n currentCanvas()->saveAnnotated(getCurrentPageForCanvas(currentCanvas()));\n}\n void deleteCurrentPage() {\n currentCanvas()->deletePage(getCurrentPageForCanvas(currentCanvas()));\n}\n void loadPdf() {\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n\n QString saveFolder = canvas->getSaveFolder();\n QString tempDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\";\n \n // Check if no save folder is set or if it's the temporary directory\n if (saveFolder.isEmpty() || saveFolder == tempDir) {\n QMessageBox::warning(this, tr(\"Cannot Load PDF\"), \n tr(\"Please select a permanent save folder before loading a PDF.\\n\\nClick the folder icon to choose a location for your notebook.\"));\n return;\n }\n\n QString filePath = QFileDialog::getOpenFileName(this, tr(\"Select PDF\"), \"\", \"PDF Files (*.pdf)\");\n if (!filePath.isEmpty()) {\n currentCanvas()->loadPdf(filePath);\n updateTabLabel(); // ✅ Update the tab name after assigning a PDF\n updateZoom(); // ✅ Update zoom and pan range after PDF is loaded\n \n // Refresh PDF outline if sidebar is visible\n if (outlineSidebarVisible) {\n loadPdfOutline();\n }\n }\n}\n void clearPdf() {\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n \n canvas->clearPdf();\n updateZoom(); // ✅ Update zoom and pan range after PDF is cleared\n}\n void updateZoom() {\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n canvas->setZoom(zoomSlider->value());\n canvas->setLastZoomLevel(zoomSlider->value()); // ✅ Store zoom level per tab\n updatePanRange();\n // updateThickness(thicknessSlider->value()); // ✅ REMOVED: This was resetting thickness on page switch\n // updateDialDisplay();\n }\n}\n void onZoomSliderChanged(int value) {\n // This handles manual zoom slider changes and preserves thickness\n int oldZoom = currentCanvas() ? currentCanvas()->getZoom() : 100;\n int newZoom = value;\n \n updateZoom();\n adjustThicknessForZoom(oldZoom, newZoom); // Maintain visual thickness consistency\n}\n void applyZoom() {\n bool ok;\n int zoomValue = zoomInput->text().toInt(&ok);\n if (ok && zoomValue > 0) {\n currentCanvas()->setZoom(zoomValue);\n updatePanRange(); // Update slider range after zoom change\n }\n}\n void updatePanRange() {\n int zoom = currentCanvas()->getZoom();\n\n QSize canvasSize = currentCanvas()->getCanvasSize();\n QSize viewportSize = QGuiApplication::primaryScreen()->size() * QGuiApplication::primaryScreen()->devicePixelRatio();\n qreal dpr = initialDpr;\n \n // Get the actual widget size instead of screen size for more accurate calculation\n QSize actualViewportSize = size();\n \n // Adjust viewport size for toolbar and tab bar layout\n QSize effectiveViewportSize = actualViewportSize;\n int toolbarHeight = isToolbarTwoRows ? 80 : 50; // Toolbar height\n int tabBarHeight = (tabBarContainer && tabBarContainer->isVisible()) ? 38 : 0; // Tab bar height\n effectiveViewportSize.setHeight(actualViewportSize.height() - toolbarHeight - tabBarHeight);\n \n // Calculate scaled canvas size using proper DPR scaling\n int scaledCanvasWidth = canvasSize.width() * zoom / 100;\n int scaledCanvasHeight = canvasSize.height() * zoom / 100;\n \n // Calculate max pan values - if canvas is smaller than viewport, pan should be 0\n int maxPanX = qMax(0, scaledCanvasWidth - effectiveViewportSize.width());\n int maxPanY = qMax(0, scaledCanvasHeight - effectiveViewportSize.height());\n\n // Scale the pan range properly\n int maxPanX_scaled = maxPanX * 100 / zoom;\n int maxPanY_scaled = maxPanY * 100 / zoom;\n\n // Set range to 0 when canvas is smaller than viewport (centered)\n if (scaledCanvasWidth <= effectiveViewportSize.width()) {\n panXSlider->setRange(0, 0);\n panXSlider->setValue(0);\n // No need for horizontal scrollbar\n panXSlider->setVisible(false);\n } else {\n panXSlider->setRange(0, maxPanX_scaled);\n // Show scrollbar only if mouse is near and timeout hasn't occurred\n if (scrollbarsVisible && !scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->start();\n }\n }\n \n if (scaledCanvasHeight <= effectiveViewportSize.height()) {\n panYSlider->setRange(0, 0);\n panYSlider->setValue(0);\n // No need for vertical scrollbar\n panYSlider->setVisible(false);\n } else {\n panYSlider->setRange(0, maxPanY_scaled);\n // Show scrollbar only if mouse is near and timeout hasn't occurred\n if (scrollbarsVisible && !scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->start();\n }\n }\n}\n void updatePanX(int value) {\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n canvas->setPanX(value);\n canvas->setLastPanX(value); // ✅ Store panX per tab\n \n // Show horizontal scrollbar temporarily\n if (panXSlider->maximum() > 0) {\n panXSlider->setVisible(true);\n scrollbarsVisible = true;\n \n // Make sure scrollbar position matches the canvas position\n if (panXSlider->value() != value) {\n panXSlider->blockSignals(true);\n panXSlider->setValue(value);\n panXSlider->blockSignals(false);\n }\n \n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n scrollbarHideTimer->start();\n }\n }\n}\n void updatePanY(int value) {\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n canvas->setPanY(value);\n canvas->setLastPanY(value); // ✅ Store panY per tab\n \n // Show vertical scrollbar temporarily\n if (panYSlider->maximum() > 0) {\n panYSlider->setVisible(true);\n scrollbarsVisible = true;\n \n // Make sure scrollbar position matches the canvas position\n if (panYSlider->value() != value) {\n panYSlider->blockSignals(true);\n panYSlider->setValue(value);\n panYSlider->blockSignals(false);\n }\n \n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n scrollbarHideTimer->start();\n }\n }\n}\n void selectBackground() {\n QString filePath = QFileDialog::getOpenFileName(this, tr(\"Select Background Image\"), \"\", \"Images (*.png *.jpg *.jpeg)\");\n if (!filePath.isEmpty()) {\n currentCanvas()->setBackground(filePath, getCurrentPageForCanvas(currentCanvas()));\n updateZoom(); // ✅ Update zoom and pan range after background is set\n }\n}\n void forceUIRefresh() {\n setWindowState(Qt::WindowNoState); // Restore first\n setWindowState(Qt::WindowMaximized); // Maximize again\n}\n void switchTab(int index) {\n if (!canvasStack || !tabList || !pageInput || !zoomSlider || !panXSlider || !panYSlider) {\n // qDebug() << \"Error: switchTab() called before UI was fully initialized!\";\n return;\n }\n\n if (index >= 0 && index < canvasStack->count()) {\n canvasStack->setCurrentIndex(index);\n \n // Ensure the tab list selection is properly set and styled\n if (tabList->currentRow() != index) {\n tabList->setCurrentRow(index);\n }\n \n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n int savedPage = canvas->getLastActivePage();\n \n // ✅ Only call blockSignals if pageInput is valid\n if (pageInput) { \n pageInput->blockSignals(true);\n pageInput->setValue(savedPage + 1);\n pageInput->blockSignals(false);\n }\n\n // ✅ Ensure zoomSlider exists before calling methods\n if (zoomSlider) {\n zoomSlider->blockSignals(true);\n zoomSlider->setValue(canvas->getLastZoomLevel());\n zoomSlider->blockSignals(false);\n canvas->setZoom(canvas->getLastZoomLevel());\n }\n\n // ✅ Ensure pan sliders exist before modifying values\n if (panXSlider && panYSlider) {\n panXSlider->blockSignals(true);\n panYSlider->blockSignals(true);\n panXSlider->setValue(canvas->getLastPanX());\n panYSlider->setValue(canvas->getLastPanY());\n panXSlider->blockSignals(false);\n panYSlider->blockSignals(false);\n updatePanRange();\n }\n updateDialDisplay();\n updateColorButtonStates(); // Update button states when switching tabs\n updateStraightLineButtonState(); // Update straight line button state when switching tabs\n updateRopeToolButtonState(); // Update rope tool button state when switching tabs\n updateMarkdownButtonState(); // Update markdown button state when switching tabs\n updatePdfTextSelectButtonState(); // Update PDF text selection button state when switching tabs\n updateBookmarkButtonState(); // Update bookmark button state when switching tabs\n updateDialButtonState(); // Update dial button state when switching tabs\n updateFastForwardButtonState(); // Update fast forward button state when switching tabs\n updateToolButtonStates(); // Update tool button states when switching tabs\n updateThicknessSliderForCurrentTool(); // Update thickness slider for current tool when switching tabs\n \n // Refresh PDF outline if sidebar is visible\n if (outlineSidebarVisible) {\n loadPdfOutline();\n }\n }\n }\n}\n void addNewTab() {\n if (!tabList || !canvasStack) return; // Ensure tabList and canvasStack exist\n\n int newTabIndex = tabList->count(); // New tab index\n QWidget *tabWidget = new QWidget(); // Custom tab container\n tabWidget->setObjectName(\"tabWidget\"); // Name the widget for easy retrieval later\n QHBoxLayout *tabLayout = new QHBoxLayout(tabWidget);\n tabLayout->setContentsMargins(5, 2, 5, 2);\n\n // ✅ Create the label (Tab Name) - optimized for horizontal layout\n QLabel *tabLabel = new QLabel(QString(\"Tab %1\").arg(newTabIndex + 1), tabWidget); \n tabLabel->setObjectName(\"tabLabel\"); // ✅ Name the label for easy retrieval later\n tabLabel->setWordWrap(false); // ✅ No wrapping for horizontal tabs\n tabLabel->setFixedWidth(115); // ✅ Narrower width for compact layout\n tabLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);\n tabLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter); // Left-align to show filename start\n tabLabel->setTextFormat(Qt::PlainText); // Ensure plain text for proper eliding\n // Tab label styling will be updated by theme\n\n // ✅ Create the close button (❌) - styled for browser-like tabs\n QPushButton *closeButton = new QPushButton(tabWidget);\n closeButton->setFixedSize(14, 14); // Smaller to fit narrower tabs\n closeButton->setIcon(loadThemedIcon(\"cross\")); // Set themed icon\n closeButton->setStyleSheet(R\"(\n QPushButton { \n border: none; \n background: transparent; \n border-radius: 6px;\n padding: 1px;\n }\n QPushButton:hover { \n background: rgba(255, 100, 100, 150); \n border-radius: 6px;\n }\n QPushButton:pressed { \n background: rgba(255, 50, 50, 200); \n border-radius: 6px;\n }\n )\"); // Themed styling with hover and press effects\n \n // ✅ Create new InkCanvas instance EARLIER so it can be captured by the lambda\n InkCanvas *newCanvas = new InkCanvas(this);\n \n // ✅ Handle tab closing when the button is clicked\n connect(closeButton, &QPushButton::clicked, this, [=]() { // newCanvas is now captured\n\n // Prevent closing if it's the last remaining tab\n if (tabList->count() <= 1) {\n // Optional: show a message or do nothing silently\n QMessageBox::information(this, tr(\"Notice\"), tr(\"At least one tab must remain open.\"));\n\n return;\n }\n\n // Find the index of the tab associated with this button's parent (tabWidget)\n int indexToRemove = -1;\n // newCanvas is captured by the lambda, representing the canvas of the tab being closed.\n // tabWidget is also captured.\n for (int i = 0; i < tabList->count(); ++i) {\n if (tabList->itemWidget(tabList->item(i)) == tabWidget) {\n indexToRemove = i;\n break;\n }\n }\n\n if (indexToRemove == -1) {\n qWarning() << \"Could not find tab to remove based on tabWidget.\";\n // Fallback or error handling if needed, though this shouldn't happen if tabWidget is valid.\n // As a fallback, try to find the index based on newCanvas if lists are in sync.\n for (int i = 0; i < canvasStack->count(); ++i) {\n if (canvasStack->widget(i) == newCanvas) {\n indexToRemove = i;\n break;\n }\n }\n if (indexToRemove == -1) {\n qWarning() << \"Could not find tab to remove based on newCanvas either.\";\n return; // Critical error, cannot proceed.\n }\n }\n \n // At this point, newCanvas is the InkCanvas instance for the tab being closed.\n // And indexToRemove is its index in tabList and canvasStack.\n\n // 1. Ensure the notebook has a unique save folder if it's temporary/edited\n ensureTabHasUniqueSaveFolder(newCanvas); // Pass the specific canvas\n\n // 2. Get the final save folder path\n QString folderPath = newCanvas->getSaveFolder();\n QString tempDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\";\n\n // 3. Update cover preview and recent list if it's a permanent notebook\n if (!folderPath.isEmpty() && folderPath != tempDir && recentNotebooksManager) {\n recentNotebooksManager->generateAndSaveCoverPreview(folderPath, newCanvas);\n // Add/update in recent list. This also moves it to the top.\n recentNotebooksManager->addRecentNotebook(folderPath, newCanvas);\n }\n \n // 4. Update the tab's label directly as folderPath might have changed\n QLabel *label = tabWidget->findChild(\"tabLabel\");\n if (label) {\n QString tabNameText;\n if (!folderPath.isEmpty() && folderPath != tempDir) { // Only for permanent notebooks\n QString metadataFile = folderPath + \"/.pdf_path.txt\";\n if (QFile::exists(metadataFile)) {\n QFile file(metadataFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString pdfPath = in.readLine().trimmed();\n file.close();\n if (QFile::exists(pdfPath)) { // Check if PDF file actually exists\n tabNameText = elideTabText(QFileInfo(pdfPath).fileName(), 90); // Elide to fit tab width\n }\n }\n }\n // Fallback to folder name if no PDF or PDF path invalid\n if (tabNameText.isEmpty()) {\n tabNameText = elideTabText(QFileInfo(folderPath).fileName(), 90); // Elide to fit tab width\n }\n }\n // Only update the label if a new valid name was determined.\n // If it's still a temp folder, the original \"Tab X\" label remains appropriate.\n if (!tabNameText.isEmpty()) {\n label->setText(tabNameText);\n }\n }\n\n // 5. Remove the tab\n removeTabAt(indexToRemove);\n });\n\n\n // ✅ Add widgets to the tab layout\n tabLayout->addWidget(tabLabel);\n tabLayout->addWidget(closeButton);\n tabLayout->setStretch(0, 1);\n tabLayout->setStretch(1, 0);\n \n // ✅ Create the tab item and set widget (horizontal layout)\n QListWidgetItem *tabItem = new QListWidgetItem();\n tabItem->setSizeHint(QSize(135, 22)); // ✅ Narrower and thinner for compact layout\n tabList->addItem(tabItem);\n tabList->setItemWidget(tabItem, tabWidget); // Attach tab layout\n\n canvasStack->addWidget(newCanvas);\n\n // ✅ Connect touch gesture signals\n connect(newCanvas, &InkCanvas::zoomChanged, this, &MainWindow::handleTouchZoomChange);\n connect(newCanvas, &InkCanvas::panChanged, this, &MainWindow::handleTouchPanChange);\n connect(newCanvas, &InkCanvas::touchGestureEnded, this, &MainWindow::handleTouchGestureEnd);\n connect(newCanvas, &InkCanvas::ropeSelectionCompleted, this, &MainWindow::showRopeSelectionMenu);\n connect(newCanvas, &InkCanvas::pdfLinkClicked, this, [this](int targetPage) {\n // Navigate to the target page when a PDF link is clicked\n if (targetPage >= 0 && targetPage < 9999) {\n switchPageWithDirection(targetPage + 1, (targetPage + 1 > getCurrentPageForCanvas(currentCanvas()) + 1) ? 1 : -1);\n pageInput->setValue(targetPage + 1);\n }\n });\n connect(newCanvas, &InkCanvas::pdfLoaded, this, [this]() {\n // Refresh PDF outline if sidebar is visible\n if (outlineSidebarVisible) {\n loadPdfOutline();\n }\n });\n connect(newCanvas, &InkCanvas::markdownSelectionModeChanged, this, &MainWindow::updateMarkdownButtonState);\n \n // Install event filter to detect mouse movement for scrollbar visibility\n newCanvas->setMouseTracking(true);\n newCanvas->installEventFilter(this);\n \n // Disable tablet tracking for canvases for now to prevent crashes\n // TODO: Find a safer way to implement hover tooltips without tablet tracking\n // QTimer::singleShot(50, this, [newCanvas]() {\n // try {\n // if (newCanvas && newCanvas->window() && newCanvas->window()->windowHandle()) {\n // newCanvas->setAttribute(Qt::WA_TabletTracking, true);\n // }\n // } catch (...) {\n // // Silently ignore tablet tracking errors\n // }\n // });\n \n // ✅ Apply touch gesture setting\n newCanvas->setTouchGesturesEnabled(touchGesturesEnabled);\n\n pageMap[newCanvas] = 0;\n\n // ✅ Select the new tab\n tabList->setCurrentItem(tabItem);\n canvasStack->setCurrentWidget(newCanvas);\n\n zoomSlider->setValue(100 / initialDpr); // Set initial zoom level based on DPR\n updateDialDisplay();\n updateStraightLineButtonState(); // Initialize straight line button state for the new tab\n updateRopeToolButtonState(); // Initialize rope tool button state for the new tab\n updatePdfTextSelectButtonState(); // Initialize PDF text selection button state for the new tab\n updateBookmarkButtonState(); // Initialize bookmark button state for the new tab\n updateMarkdownButtonState(); // Initialize markdown button state for the new tab\n updateDialButtonState(); // Initialize dial button state for the new tab\n updateFastForwardButtonState(); // Initialize fast forward button state for the new tab\n updateToolButtonStates(); // Initialize tool button states for the new tab\n\n QString tempDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\";\n newCanvas->setSaveFolder(tempDir);\n \n // Load persistent background settings\n BackgroundStyle defaultStyle;\n QColor defaultColor;\n int defaultDensity;\n loadDefaultBackgroundSettings(defaultStyle, defaultColor, defaultDensity);\n \n newCanvas->setBackgroundStyle(defaultStyle);\n newCanvas->setBackgroundColor(defaultColor);\n newCanvas->setBackgroundDensity(defaultDensity);\n newCanvas->setPDFRenderDPI(getPdfDPI());\n \n // Update color button states for the new tab\n updateColorButtonStates();\n}\n void removeTabAt(int index) {\n if (!tabList || !canvasStack) return; // Ensure UI elements exist\n if (index < 0 || index >= canvasStack->count()) return;\n\n // ✅ Remove tab entry\n QListWidgetItem *item = tabList->takeItem(index);\n delete item;\n\n // ✅ Remove and delete the canvas safely\n QWidget *canvasWidget = canvasStack->widget(index); // Get widget before removal\n // ensureTabHasUniqueSaveFolder(currentCanvas()); // Moved to the close button lambda\n\n if (canvasWidget) {\n canvasStack->removeWidget(canvasWidget); // Remove from stack\n // InkCanvas *canvasInstance = qobject_cast(canvasWidget);\n // if (canvasInstance) {\n // QString folderPath = canvasInstance->getSaveFolder();\n // QString tempDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\";\n // if (!folderPath.isEmpty() && folderPath != tempDir && recentNotebooksManager) {\n // recentNotebooksManager->addRecentNotebook(folderPath, canvasInstance); // Moved to close button lambda\n // }\n // }\n delete canvasWidget; // Now delete the widget (and its InkCanvas)\n }\n\n // ✅ Select the previous tab (or first tab if none left)\n if (tabList->count() > 0) {\n int newIndex = qMax(0, index - 1);\n tabList->setCurrentRow(newIndex);\n canvasStack->setCurrentWidget(canvasStack->widget(newIndex));\n }\n\n // QWidget *canvasWidget = canvasStack->widget(index); // Redeclaration - remove this block\n // InkCanvas *canvasInstance = qobject_cast(canvasWidget);\n //\n // if (canvasInstance) {\n // QString folderPath = canvasInstance->getSaveFolder();\n // if (!folderPath.isEmpty() && folderPath != QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\") {\n // // recentNotebooksManager->addRecentNotebook(folderPath, canvasInstance); // Moved to close button lambda\n // }\n // }\n}\n void toggleZoomSlider() {\n if (zoomFrame->isVisible()) {\n zoomFrame->hide();\n return;\n }\n\n // ✅ Set as a standalone pop-up window so it can receive events\n zoomFrame->setWindowFlags(Qt::Popup);\n\n // ✅ Position it right below the button\n QPoint buttonPos = zoomButton->mapToGlobal(QPoint(0, zoomButton->height()));\n zoomFrame->move(buttonPos.x(), buttonPos.y() + 5);\n zoomFrame->show();\n}\n void toggleThicknessSlider() {\n if (thicknessFrame->isVisible()) {\n thicknessFrame->hide();\n return;\n }\n\n // ✅ Set as a standalone pop-up window so it can receive events\n thicknessFrame->setWindowFlags(Qt::Popup);\n\n // ✅ Position it right below the button\n QPoint buttonPos = thicknessButton->mapToGlobal(QPoint(0, thicknessButton->height()));\n thicknessFrame->move(buttonPos.x(), buttonPos.y() + 5);\n\n thicknessFrame->show();\n}\n void toggleFullscreen() {\n if (isFullScreen()) {\n showNormal(); // Exit fullscreen mode\n } else {\n showFullScreen(); // Enter fullscreen mode\n }\n}\n void showJumpToPageDialog() {\n bool ok;\n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1; // ✅ Convert zero-based to one-based\n int newPage = QInputDialog::getInt(this, \"Jump to Page\", \"Enter Page Number:\", \n currentPage, 1, 9999, 1, &ok);\n if (ok) {\n // ✅ Use direction-aware page switching for jump-to-page\n int direction = (newPage > currentPage) ? 1 : (newPage < currentPage) ? -1 : 0;\n if (direction != 0) {\n switchPageWithDirection(newPage, direction);\n } else {\n switchPage(newPage); // Same page, no direction needed\n }\n pageInput->setValue(newPage);\n }\n}\n void goToPreviousPage() {\n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1; // Convert to 1-based\n if (currentPage > 1) {\n int newPage = currentPage - 1;\n switchPageWithDirection(newPage, -1); // -1 indicates backward\n pageInput->setValue(newPage);\n }\n}\n void goToNextPage() {\n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1; // Convert to 1-based\n int newPage = currentPage + 1;\n switchPageWithDirection(newPage, 1); // 1 indicates forward\n pageInput->setValue(newPage);\n}\n void onPageInputChanged(int newPage) {\n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1; // Convert to 1-based\n \n // ✅ Use direction-aware page switching for spinbox\n int direction = (newPage > currentPage) ? 1 : (newPage < currentPage) ? -1 : 0;\n if (direction != 0) {\n switchPageWithDirection(newPage, direction);\n } else {\n switchPage(newPage); // Same page, no direction needed\n }\n}\n void toggleDial() {\n if (!dialContainer) { \n // ✅ Create floating container for the dial\n dialContainer = new QWidget(this);\n dialContainer->setObjectName(\"dialContainer\");\n dialContainer->setFixedSize(140, 140);\n dialContainer->setAttribute(Qt::WA_TranslucentBackground);\n dialContainer->setAttribute(Qt::WA_NoSystemBackground);\n dialContainer->setAttribute(Qt::WA_OpaquePaintEvent);\n dialContainer->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);\n dialContainer->setStyleSheet(\"background: transparent; border-radius: 100px;\"); // ✅ More transparent\n\n // ✅ Create dial\n pageDial = new QDial(dialContainer);\n pageDial->setFixedSize(140, 140);\n pageDial->setMinimum(0);\n pageDial->setMaximum(360);\n pageDial->setWrapping(true); // ✅ Allow full-circle rotation\n \n // Apply theme color immediately when dial is created\n QColor accentColor = getAccentColor();\n pageDial->setStyleSheet(QString(R\"(\n QDial {\n background-color: %1;\n }\n )\").arg(accentColor.name()));\n\n /*\n\n modeDial = new QDial(dialContainer);\n modeDial->setFixedSize(150, 150);\n modeDial->setMinimum(0);\n modeDial->setMaximum(300); // 6 modes, 60° each\n modeDial->setSingleStep(60);\n modeDial->setWrapping(true);\n modeDial->setStyleSheet(\"background:rgb(0, 76, 147);\");\n modeDial->move(25, 25);\n \n */\n \n\n dialColorPreview = new QFrame(dialContainer);\n dialColorPreview->setFixedSize(30, 30);\n dialColorPreview->setStyleSheet(\"border-radius: 15px; border: 1px solid black;\");\n dialColorPreview->move(55, 35); // Center of dial\n\n dialIconView = new QLabel(dialContainer);\n dialIconView->setFixedSize(30, 30);\n dialIconView->setStyleSheet(\"border-radius: 1px; border: 1px solid black;\");\n dialIconView->move(55, 35); // Center of dial\n\n // ✅ Position dial near top-right corner initially\n positionDialContainer();\n\n dialDisplay = new QLabel(dialContainer);\n dialDisplay->setAlignment(Qt::AlignCenter);\n dialDisplay->setFixedSize(80, 80);\n dialDisplay->move(30, 30); // Center position inside the dial\n \n\n int fontId = QFontDatabase::addApplicationFont(\":/resources/fonts/Jersey20-Regular.ttf\");\n // int chnFontId = QFontDatabase::addApplicationFont(\":/resources/fonts/NotoSansSC-Medium.ttf\");\n QStringList fontFamilies = QFontDatabase::applicationFontFamilies(fontId);\n\n if (!fontFamilies.isEmpty()) {\n QFont pixelFont(fontFamilies.at(0), 11);\n dialDisplay->setFont(pixelFont);\n }\n\n dialDisplay->setStyleSheet(\"background-color: black; color: white; font-size: 14px; border-radius: 4px;\");\n\n dialHiddenButton = new QPushButton(dialContainer);\n dialHiddenButton->setFixedSize(80, 80);\n dialHiddenButton->move(30, 30); // Same position as dialDisplay\n dialHiddenButton->setStyleSheet(\"background: transparent; border: none;\"); // ✅ Fully invisible\n dialHiddenButton->setFocusPolicy(Qt::NoFocus); // ✅ Prevents accidental focus issues\n dialHiddenButton->setEnabled(false); // ✅ Disabled by default\n\n // ✅ Connection will be set in changeDialMode() based on current mode\n\n dialColorPreview->raise(); // ✅ Ensure it's on top\n dialIconView->raise();\n // ✅ Connect dial input and release\n // connect(pageDial, &QDial::valueChanged, this, &MainWindow::handleDialInput);\n // connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onDialReleased);\n\n // connect(modeDial, &QDial::valueChanged, this, &MainWindow::handleModeSelection);\n changeDialMode(currentDialMode); // ✅ Set initial mode\n\n // ✅ Enable drag detection\n dialContainer->installEventFilter(this);\n }\n\n // ✅ Ensure that `dialContainer` is always initialized before setting visibility\n if (dialContainer) {\n dialContainer->setVisible(!dialContainer->isVisible());\n }\n\n initializeDialSound(); // ✅ Ensure sound is loaded\n\n // Inside toggleDial():\n \n if (!dialDisplay) {\n dialDisplay = new QLabel(dialContainer);\n }\n updateDialDisplay(); // ✅ Ensure it's updated before showing\n\n if (controllerManager) {\n connect(controllerManager, &SDLControllerManager::buttonHeld, this, &MainWindow::handleButtonHeld);\n connect(controllerManager, &SDLControllerManager::buttonReleased, this, &MainWindow::handleButtonReleased);\n connect(controllerManager, &SDLControllerManager::leftStickAngleChanged, pageDial, &QDial::setValue);\n connect(controllerManager, &SDLControllerManager::leftStickReleased, pageDial, &QDial::sliderReleased);\n connect(controllerManager, &SDLControllerManager::buttonSinglePress, this, &MainWindow::handleControllerButton);\n }\n\n loadButtonMappings(); // ✅ Load button mappings for the controller\n\n // Update button state to reflect dial visibility\n updateDialButtonState();\n}\n void positionDialContainer() {\n if (!dialContainer) return;\n \n // Get window dimensions\n int windowWidth = width();\n int windowHeight = height();\n \n // Get dial dimensions\n int dialWidth = dialContainer->width(); // 140px\n int dialHeight = dialContainer->height(); // 140px\n \n // Calculate toolbar height based on current layout\n int toolbarHeight = isToolbarTwoRows ? 80 : 50; // Approximate heights\n \n // Add tab bar height if visible\n int tabBarHeight = (tabBarContainer && tabBarContainer->isVisible()) ? 38 : 0;\n \n // Define margins from edges\n int rightMargin = 20; // Distance from right edge\n int topMargin = 20; // Distance from top edge (below toolbar and tabs)\n \n // Calculate ideal position (top-right corner with margins)\n int idealX = windowWidth - dialWidth - rightMargin;\n int idealY = toolbarHeight + tabBarHeight + topMargin;\n \n // Ensure dial stays within window bounds with minimum margins\n int minMargin = 10;\n int maxX = windowWidth - dialWidth - minMargin;\n int maxY = windowHeight - dialHeight - minMargin;\n \n // Clamp position to stay within bounds\n int finalX = qBound(minMargin, idealX, maxX);\n int finalY = qBound(toolbarHeight + tabBarHeight + minMargin, idealY, maxY);\n \n // Move the dial to the calculated position\n dialContainer->move(finalX, finalY);\n}\n void handleDialInput(int angle) {\n if (!tracking) {\n startAngle = angle; // ✅ Set initial position\n accumulatedRotation = 0; // ✅ Reset tracking\n tracking = true;\n lastAngle = angle;\n return;\n }\n\n int delta = angle - lastAngle;\n\n // ✅ Handle 360-degree wrapping\n if (delta > 180) delta -= 360; // Example: 350° → 10° should be -20° instead of +340°\n if (delta < -180) delta += 360; // Example: 10° → 350° should be +20° instead of -340°\n\n accumulatedRotation += delta; // ✅ Accumulate movement\n\n // ✅ Detect crossing a 45-degree boundary\n int currentClicks = accumulatedRotation / 45; // Total number of \"clicks\" crossed\n int previousClicks = (accumulatedRotation - delta) / 45; // Previous click count\n\n if (currentClicks != previousClicks) { // ✅ Play sound if a new boundary is crossed\n \n if (dialClickSound) {\n dialClickSound->play();\n \n // ✅ Vibrate controller\n SDL_Joystick *joystick = controllerManager->getJoystick();\n if (joystick) {\n // Note: SDL_JoystickRumble requires SDL 2.0.9+\n // For older versions, this will be a no-op\n #if SDL_VERSION_ATLEAST(2, 0, 9)\n SDL_JoystickRumble(joystick, 0xA000, 0xF000, 10); // Vibrate shortly\n #endif\n }\n \n grossTotalClicks += 1;\n tempClicks = currentClicks;\n updateDialDisplay();\n \n if (isLowResPreviewEnabled()) {\n int previewPage = qBound(1, getCurrentPageForCanvas(currentCanvas()) + currentClicks, 99999);\n currentCanvas()->loadPdfPreviewAsync(previewPage);\n }\n }\n }\n\n lastAngle = angle; // ✅ Store last position\n}\n void onDialReleased() {\n if (!tracking) return; // ✅ Ignore if no tracking\n\n int pagesToAdvance = fastForwardMode ? 8 : 1;\n int totalClicks = accumulatedRotation / 45; // ✅ Convert degrees to pages\n\n /*\n int leftOver = accumulatedRotation % 45; // ✅ Track remaining rotation\n if (leftOver > 22 && totalClicks >= 0) {\n totalClicks += 1; // ✅ Round up if more than halfway\n } \n else if (leftOver <= -22 && totalClicks >= 0) {\n totalClicks -= 1; // ✅ Round down if more than halfway\n }\n */\n \n\n if (totalClicks != 0 || grossTotalClicks != 0) { // ✅ Only switch pages if movement happened\n // Use concurrent autosave for smoother dial operation\n if (currentCanvas()->isEdited()) {\n saveCurrentPageConcurrent();\n }\n\n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1;\n int newPage = qBound(1, currentPage + totalClicks * pagesToAdvance, 99999);\n \n // ✅ Use direction-aware page switching for dial\n int direction = (totalClicks * pagesToAdvance > 0) ? 1 : -1;\n switchPageWithDirection(newPage, direction);\n pageInput->setValue(newPage);\n tempClicks = 0;\n updateDialDisplay(); \n /*\n if (dialClickSound) {\n dialClickSound->play();\n }\n */\n }\n\n accumulatedRotation = 0; // ✅ Reset tracking\n grossTotalClicks = 0;\n tracking = false;\n}\n void initializeDialSound() {\n if (!dialClickSound) {\n dialClickSound = new QSoundEffect(this);\n dialClickSound->setSource(QUrl::fromLocalFile(\":/resources/sounds/dial_click.wav\")); // ✅ Path to the sound file\n dialClickSound->setVolume(0.8); // ✅ Set volume (0.0 - 1.0)\n }\n}\n void changeDialMode(DialMode mode) {\n\n if (!dialContainer) return; // ✅ Ensure dial container exists\n currentDialMode = mode; // ✅ Set new mode\n updateDialDisplay();\n\n // ✅ Enable dialHiddenButton for PanAndPageScroll and ZoomControl modes\n dialHiddenButton->setEnabled(currentDialMode == PanAndPageScroll || currentDialMode == ZoomControl);\n\n // ✅ Disconnect previous slots\n disconnect(pageDial, &QDial::valueChanged, nullptr, nullptr);\n disconnect(pageDial, &QDial::sliderReleased, nullptr, nullptr);\n \n // ✅ Disconnect dialHiddenButton to reconnect with appropriate function\n disconnect(dialHiddenButton, &QPushButton::clicked, nullptr, nullptr);\n \n // ✅ Connect dialHiddenButton to appropriate function based on mode\n if (currentDialMode == PanAndPageScroll) {\n connect(dialHiddenButton, &QPushButton::clicked, this, &MainWindow::toggleControlBar);\n } else if (currentDialMode == ZoomControl) {\n connect(dialHiddenButton, &QPushButton::clicked, this, &MainWindow::cycleZoomLevels);\n }\n\n dialColorPreview->hide();\n dialDisplay->setStyleSheet(\"background-color: black; color: white; font-size: 14px; border-radius: 40px;\");\n\n // ✅ Connect the correct function set for the current mode\n switch (currentDialMode) {\n case PageSwitching:\n connect(pageDial, &QDial::valueChanged, this, &MainWindow::handleDialInput);\n connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onDialReleased);\n break;\n case ZoomControl:\n connect(pageDial, &QDial::valueChanged, this, &MainWindow::handleDialZoom);\n connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onZoomReleased);\n break;\n case ThicknessControl:\n connect(pageDial, &QDial::valueChanged, this, &MainWindow::handleDialThickness);\n connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onThicknessReleased);\n break;\n\n case ToolSwitching:\n connect(pageDial, &QDial::valueChanged, this, &MainWindow::handleToolSelection);\n connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onToolReleased);\n break;\n case PresetSelection:\n connect(pageDial, &QDial::valueChanged, this, &MainWindow::handlePresetSelection);\n connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onPresetReleased);\n break;\n case PanAndPageScroll:\n connect(pageDial, &QDial::valueChanged, this, &MainWindow::handleDialPanScroll);\n connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onPanScrollReleased);\n break;\n \n }\n}\n void handleDialZoom(int angle) {\n if (!tracking) {\n startAngle = angle; \n accumulatedRotation = 0; \n tracking = true;\n lastAngle = angle;\n return;\n }\n\n int delta = angle - lastAngle;\n\n // ✅ Handle 360-degree wrapping\n if (delta > 180) delta -= 360;\n if (delta < -180) delta += 360;\n\n accumulatedRotation += delta;\n\n if (abs(delta) < 4) { \n return; \n }\n\n // ✅ Apply zoom dynamically (instead of waiting for release)\n int oldZoom = zoomSlider->value();\n int newZoom = qBound(10, oldZoom + (delta / 4), 400); \n zoomSlider->setValue(newZoom);\n updateZoom(); // ✅ Ensure zoom updates immediately\n updateDialDisplay(); \n\n lastAngle = angle;\n}\n void handleDialThickness(int angle) {\n if (!tracking) {\n startAngle = angle;\n tracking = true;\n lastAngle = angle;\n return;\n }\n\n int delta = angle - lastAngle;\n if (delta > 180) delta -= 360;\n if (delta < -180) delta += 360;\n\n int thicknessStep = fastForwardMode ? 5 : 1;\n currentCanvas()->setPenThickness(qBound(1.0, currentCanvas()->getPenThickness() + (delta / 10.0) * thicknessStep, 50.0));\n\n updateDialDisplay();\n lastAngle = angle;\n}\n void onZoomReleased() {\n accumulatedRotation = 0;\n tracking = false;\n}\n void onThicknessReleased() {\n accumulatedRotation = 0;\n tracking = false;\n}\n void updateDialDisplay() {\n if (!dialDisplay) return;\n if (!dialColorPreview) return;\n if (!dialIconView) return;\n dialIconView->show();\n qreal dpr = initialDpr;\n QColor currentColor = currentCanvas()->getPenColor();\n switch (currentDialMode) {\n case DialMode::PageSwitching:\n if (fastForwardMode){\n dialDisplay->setText(QString(tr(\"\\n\\nPage\\n%1\").arg(getCurrentPageForCanvas(currentCanvas()) + 1 + tempClicks * 8)));\n }\n else {\n dialDisplay->setText(QString(tr(\"\\n\\nPage\\n%1\").arg(getCurrentPageForCanvas(currentCanvas()) + 1 + tempClicks)));\n }\n dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/bookpage_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n break;\n case DialMode::ThicknessControl:\n {\n QString toolName;\n switch (currentCanvas()->getCurrentTool()) {\n case ToolType::Pen:\n toolName = tr(\"Pen\");\n break;\n case ToolType::Marker:\n toolName = tr(\"Marker\");\n break;\n case ToolType::Eraser:\n toolName = tr(\"Eraser\");\n break;\n }\n dialDisplay->setText(QString(tr(\"\\n\\n%1\\n%2\").arg(toolName).arg(QString::number(currentCanvas()->getPenThickness(), 'f', 1))));\n dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/thickness_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n }\n break;\n case DialMode::ZoomControl:\n dialDisplay->setText(QString(tr(\"\\n\\nZoom\\n%1%\").arg(currentCanvas() ? currentCanvas()->getZoom() * initialDpr : zoomSlider->value() * initialDpr)));\n dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/zoom_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n break;\n \n case DialMode::ToolSwitching:\n // ✅ Convert ToolType to QString for display\n switch (currentCanvas()->getCurrentTool()) {\n case ToolType::Pen:\n dialDisplay->setText(tr(\"\\n\\n\\nPen\"));\n dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/pen_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n break;\n case ToolType::Marker:\n dialDisplay->setText(tr(\"\\n\\n\\nMarker\"));\n dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/marker_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n break;\n case ToolType::Eraser:\n dialDisplay->setText(tr(\"\\n\\n\\nEraser\"));\n dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/eraser_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n break;\n }\n break;\n case PresetSelection:\n dialColorPreview->show();\n dialIconView->hide();\n dialColorPreview->setStyleSheet(QString(\"background-color: %1; border-radius: 15px; border: 1px solid black;\")\n .arg(colorPresets[currentPresetIndex].name()));\n dialDisplay->setText(QString(tr(\"\\n\\nPreset %1\\n#%2\"))\n .arg(currentPresetIndex + 1) // ✅ Display preset index (1-based)\n .arg(colorPresets[currentPresetIndex].name().remove(\"#\"))); // ✅ Display hex color\n // dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/preset_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n break;\n case DialMode::PanAndPageScroll:\n dialIconView->setPixmap(QPixmap(\":/resources/icons/scroll_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n QString fullscreenStatus = controlBarVisible ? tr(\"Etr\") : tr(\"Exit\");\n dialDisplay->setText(QString(tr(\"\\n\\nPage %1\\n%2 FulScr\")).arg(getCurrentPageForCanvas(currentCanvas()) + 1).arg(fullscreenStatus));\n break;\n }\n}\n void handleToolSelection(int angle) {\n static int lastToolIndex = -1; // ✅ Track last tool index\n\n // ✅ Snap to closest fixed 120° step\n int snappedAngle = (angle + 60) / 120 * 120; // Round to nearest 120°\n int toolIndex = snappedAngle / 120; // Convert to tool index (0, 1, 2)\n\n if (toolIndex >= 3) toolIndex = 0; // ✅ Wrap around at 360° → Back to Pen (0)\n\n if (toolIndex != lastToolIndex) { // ✅ Only switch if tool actually changes\n toolSelector->setCurrentIndex(toolIndex); // ✅ Change tool\n lastToolIndex = toolIndex; // ✅ Update last selected tool\n\n // ✅ Play click sound when tool changes\n if (dialClickSound) {\n dialClickSound->play();\n }\n\n SDL_Joystick *joystick = controllerManager->getJoystick();\n\n if (joystick) {\n #if SDL_VERSION_ATLEAST(2, 0, 9)\n SDL_JoystickRumble(joystick, 0xA000, 0xF000, 20); // ✅ Vibrate controller\n #endif\n }\n\n updateToolButtonStates(); // ✅ Update tool button states\n updateDialDisplay(); // ✅ Update dial display]\n }\n}\n void onToolReleased() {\n \n}\n void handlePresetSelection(int angle) {\n static int lastAngle = angle;\n int delta = angle - lastAngle;\n\n // ✅ Handle 360-degree wrapping\n if (delta > 180) delta -= 360;\n if (delta < -180) delta += 360;\n\n if (abs(delta) >= 60) { // ✅ Change preset every 60° (6 presets)\n lastAngle = angle;\n currentPresetIndex = (currentPresetIndex + (delta > 0 ? 1 : -1) + colorPresets.size()) % colorPresets.size();\n \n QColor selectedColor = colorPresets[currentPresetIndex];\n currentCanvas()->setPenColor(selectedColor);\n updateCustomColorButtonStyle(selectedColor);\n updateDialDisplay();\n updateColorButtonStates(); // Update button states when preset is selected\n \n if (dialClickSound) dialClickSound->play(); // ✅ Provide feedback\n SDL_Joystick *joystick = controllerManager->getJoystick();\n if (joystick) {\n #if SDL_VERSION_ATLEAST(2, 0, 9)\n SDL_JoystickRumble(joystick, 0xA000, 0xF000, 25); // Vibrate shortly\n #endif\n }\n }\n}\n void onPresetReleased() {\n accumulatedRotation = 0;\n tracking = false;\n}\n void addColorPreset() {\n QColor currentColor = currentCanvas()->getPenColor();\n\n // ✅ Prevent duplicates\n if (!colorPresets.contains(currentColor)) {\n if (colorPresets.size() >= 6) {\n colorPresets.dequeue(); // ✅ Remove oldest color\n }\n colorPresets.enqueue(currentColor);\n }\n}\n void updateColorPalette() {\n // Clear existing presets\n colorPresets.clear();\n currentPresetIndex = 0;\n \n // Add default pen color (theme-aware)\n colorPresets.enqueue(getDefaultPenColor());\n \n // Add palette colors\n colorPresets.enqueue(getPaletteColor(\"red\"));\n colorPresets.enqueue(getPaletteColor(\"yellow\"));\n colorPresets.enqueue(getPaletteColor(\"blue\"));\n colorPresets.enqueue(getPaletteColor(\"green\"));\n colorPresets.enqueue(QColor(\"#000000\")); // Black (always same)\n colorPresets.enqueue(QColor(\"#FFFFFF\")); // White (always same)\n \n // Only update UI elements if they exist\n if (redButton && blueButton && yellowButton && greenButton) {\n bool darkMode = isDarkMode();\n \n // Update color button icons based on current palette (not theme)\n QString redIconPath = useBrighterPalette ? \":/resources/icons/pen_light_red.png\" : \":/resources/icons/pen_dark_red.png\";\n QString blueIconPath = useBrighterPalette ? \":/resources/icons/pen_light_blue.png\" : \":/resources/icons/pen_dark_blue.png\";\n QString yellowIconPath = useBrighterPalette ? \":/resources/icons/pen_light_yellow.png\" : \":/resources/icons/pen_dark_yellow.png\";\n QString greenIconPath = useBrighterPalette ? \":/resources/icons/pen_light_green.png\" : \":/resources/icons/pen_dark_green.png\";\n \n redButton->setIcon(QIcon(redIconPath));\n blueButton->setIcon(QIcon(blueIconPath));\n yellowButton->setIcon(QIcon(yellowIconPath));\n greenButton->setIcon(QIcon(greenIconPath));\n \n // Update color button states\n updateColorButtonStates();\n }\n}\n QColor getPaletteColor(const QString &colorName) {\n if (useBrighterPalette) {\n // Brighter colors (good for dark backgrounds)\n if (colorName == \"red\") return QColor(\"#FF7755\");\n if (colorName == \"yellow\") return QColor(\"#EECC00\");\n if (colorName == \"blue\") return QColor(\"#66CCFF\");\n if (colorName == \"green\") return QColor(\"#55FF77\");\n } else {\n // Darker colors (good for light backgrounds)\n if (colorName == \"red\") return QColor(\"#AA0000\");\n if (colorName == \"yellow\") return QColor(\"#997700\");\n if (colorName == \"blue\") return QColor(\"#0000AA\");\n if (colorName == \"green\") return QColor(\"#007700\");\n }\n \n // Fallback colors\n if (colorName == \"black\") return QColor(\"#000000\");\n if (colorName == \"white\") return QColor(\"#FFFFFF\");\n \n return QColor(\"#000000\"); // Default fallback\n}\n qreal getDevicePixelRatio() {\n QScreen *screen = QGuiApplication::primaryScreen();\n qreal devicePixelRatio = screen ? screen->devicePixelRatio() : 1.0; // Default to 1.0 if null\n return devicePixelRatio;\n}\n bool isDarkMode() {\n QColor bg = palette().color(QPalette::Window);\n return bg.lightness() < 128; // Lightness scale: 0 (black) - 255 (white)\n}\n QIcon loadThemedIcon(const QString& baseName) {\n QString path = isDarkMode()\n ? QString(\":/resources/icons/%1_reversed.png\").arg(baseName)\n : QString(\":/resources/icons/%1.png\").arg(baseName);\n return QIcon(path);\n}\n QString createButtonStyle(bool darkMode) {\n if (darkMode) {\n // Dark mode: Keep current white highlights (good contrast)\n return R\"(\n QPushButton {\n background: transparent;\n border: none;\n padding: 6px;\n }\n QPushButton:hover {\n background: rgba(255, 255, 255, 50);\n }\n QPushButton:pressed {\n background: rgba(0, 0, 0, 50);\n }\n QPushButton[selected=\"true\"] {\n background: rgba(255, 255, 255, 100);\n border: 2px solid rgba(255, 255, 255, 150);\n padding: 4px;\n border-radius: 4px;\n }\n QPushButton[selected=\"true\"]:hover {\n background: rgba(255, 255, 255, 120);\n }\n QPushButton[selected=\"true\"]:pressed {\n background: rgba(0, 0, 0, 50);\n }\n )\";\n } else {\n // Light mode: Use darker colors for better visibility\n return R\"(\n QPushButton {\n background: transparent;\n border: none;\n padding: 6px;\n }\n QPushButton:hover {\n background: rgba(0, 0, 0, 30);\n }\n QPushButton:pressed {\n background: rgba(0, 0, 0, 60);\n }\n QPushButton[selected=\"true\"] {\n background: rgba(0, 0, 0, 80);\n border: 2px solid rgba(0, 0, 0, 120);\n padding: 4px;\n border-radius: 4px;\n }\n QPushButton[selected=\"true\"]:hover {\n background: rgba(0, 0, 0, 100);\n }\n QPushButton[selected=\"true\"]:pressed {\n background: rgba(0, 0, 0, 140);\n }\n )\";\n }\n}\n void handleDialPanScroll(int angle) {\n if (!tracking) {\n startAngle = angle;\n accumulatedRotation = 0;\n accumulatedRotationAfterLimit = 0;\n tracking = true;\n lastAngle = angle;\n pendingPageFlip = 0;\n return;\n }\n\n int delta = angle - lastAngle;\n\n // Handle 360 wrap\n if (delta > 180) delta -= 360;\n if (delta < -180) delta += 360;\n\n accumulatedRotation += delta;\n\n // Pan scroll\n int panDelta = delta * 4; // Adjust scroll sensitivity here\n int currentPan = panYSlider->value();\n int newPan = currentPan + panDelta;\n\n // Clamp pan slider\n newPan = qBound(panYSlider->minimum(), newPan, panYSlider->maximum());\n panYSlider->setValue(newPan);\n\n // ✅ NEW → if slider reached top/bottom, accumulate AFTER LIMIT\n if (newPan == panYSlider->maximum()) {\n accumulatedRotationAfterLimit += delta;\n\n if (accumulatedRotationAfterLimit >= 120) {\n pendingPageFlip = +1; // Flip next when released\n }\n } \n else if (newPan == panYSlider->minimum()) {\n accumulatedRotationAfterLimit += delta;\n\n if (accumulatedRotationAfterLimit <= -120) {\n pendingPageFlip = -1; // Flip previous when released\n }\n } \n else {\n // Reset after limit accumulator when not at limit\n accumulatedRotationAfterLimit = 0;\n pendingPageFlip = 0;\n }\n\n lastAngle = angle;\n}\n void onPanScrollReleased() {\n // ✅ Perform page flip only when dial released and flip is pending\n if (pendingPageFlip != 0) {\n // Use concurrent saving for smooth dial operation\n if (currentCanvas()->isEdited()) {\n saveCurrentPageConcurrent();\n }\n\n int currentPage = getCurrentPageForCanvas(currentCanvas());\n int newPage = qBound(1, currentPage + pendingPageFlip + 1, 99999);\n \n // ✅ Use direction-aware page switching for pan-and-scroll dial\n switchPageWithDirection(newPage, pendingPageFlip);\n pageInput->setValue(newPage);\n updateDialDisplay();\n\n SDL_Joystick *joystick = controllerManager->getJoystick();\n if (joystick) {\n #if SDL_VERSION_ATLEAST(2, 0, 9)\n SDL_JoystickRumble(joystick, 0xA000, 0xF000, 25); // Vibrate shortly\n #endif\n }\n }\n\n // Reset states\n pendingPageFlip = 0;\n accumulatedRotation = 0;\n accumulatedRotationAfterLimit = 0;\n tracking = false;\n}\n void handleTouchZoomChange(int newZoom) {\n // Update zoom slider without triggering updateZoom again\n zoomSlider->blockSignals(true);\n int oldZoom = zoomSlider->value(); // Get the old zoom value before updating the slider\n zoomSlider->setValue(newZoom);\n zoomSlider->blockSignals(false);\n \n // Show both scrollbars during gesture\n if (panXSlider->maximum() > 0) {\n panXSlider->setVisible(true);\n }\n if (panYSlider->maximum() > 0) {\n panYSlider->setVisible(true);\n }\n scrollbarsVisible = true;\n \n // Update canvas zoom directly\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n // The canvas zoom has already been set by the gesture processing in InkCanvas::event()\n // So we don't need to set it again, just update the last zoom level\n canvas->setLastZoomLevel(newZoom);\n updatePanRange();\n \n // ✅ FIXED: Add thickness adjustment for pinch-to-zoom gestures to maintain visual consistency\n adjustThicknessForZoom(oldZoom, newZoom);\n \n updateDialDisplay();\n }\n}\n void handleTouchPanChange(int panX, int panY) {\n // Clamp values to valid ranges\n panX = qBound(panXSlider->minimum(), panX, panXSlider->maximum());\n panY = qBound(panYSlider->minimum(), panY, panYSlider->maximum());\n \n // Show both scrollbars during gesture\n if (panXSlider->maximum() > 0) {\n panXSlider->setVisible(true);\n }\n if (panYSlider->maximum() > 0) {\n panYSlider->setVisible(true);\n }\n scrollbarsVisible = true;\n \n // Update sliders without triggering their valueChanged signals\n panXSlider->blockSignals(true);\n panYSlider->blockSignals(true);\n panXSlider->setValue(panX);\n panYSlider->setValue(panY);\n panXSlider->blockSignals(false);\n panYSlider->blockSignals(false);\n \n // Update canvas pan directly\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n canvas->setPanX(panX);\n canvas->setPanY(panY);\n canvas->setLastPanX(panX);\n canvas->setLastPanY(panY);\n }\n}\n void handleTouchGestureEnd() {\n // Hide scrollbars immediately when touch gesture ends\n panXSlider->setVisible(false);\n panYSlider->setVisible(false);\n scrollbarsVisible = false;\n}\n void updateColorButtonStates() {\n // Check if there's a current canvas\n if (!currentCanvas()) return;\n \n // Get current pen color\n QColor currentColor = currentCanvas()->getPenColor();\n \n // Determine if we're in dark mode to match the correct colors\n bool darkMode = isDarkMode();\n \n // Reset all color buttons to original style\n redButton->setProperty(\"selected\", false);\n blueButton->setProperty(\"selected\", false);\n yellowButton->setProperty(\"selected\", false);\n greenButton->setProperty(\"selected\", false);\n blackButton->setProperty(\"selected\", false);\n whiteButton->setProperty(\"selected\", false);\n \n // Set the selected property for the matching color button based on current palette\n QColor redColor = getPaletteColor(\"red\");\n QColor blueColor = getPaletteColor(\"blue\");\n QColor yellowColor = getPaletteColor(\"yellow\");\n QColor greenColor = getPaletteColor(\"green\");\n \n if (currentColor == redColor) {\n redButton->setProperty(\"selected\", true);\n } else if (currentColor == blueColor) {\n blueButton->setProperty(\"selected\", true);\n } else if (currentColor == yellowColor) {\n yellowButton->setProperty(\"selected\", true);\n } else if (currentColor == greenColor) {\n greenButton->setProperty(\"selected\", true);\n } else if (currentColor == QColor(\"#000000\")) {\n blackButton->setProperty(\"selected\", true);\n } else if (currentColor == QColor(\"#FFFFFF\")) {\n whiteButton->setProperty(\"selected\", true);\n }\n \n // Force style update\n redButton->style()->unpolish(redButton);\n redButton->style()->polish(redButton);\n blueButton->style()->unpolish(blueButton);\n blueButton->style()->polish(blueButton);\n yellowButton->style()->unpolish(yellowButton);\n yellowButton->style()->polish(yellowButton);\n greenButton->style()->unpolish(greenButton);\n greenButton->style()->polish(greenButton);\n blackButton->style()->unpolish(blackButton);\n blackButton->style()->polish(blackButton);\n whiteButton->style()->unpolish(whiteButton);\n whiteButton->style()->polish(whiteButton);\n}\n void selectColorButton(QPushButton* selectedButton) {\n updateColorButtonStates();\n}\n void updateStraightLineButtonState() {\n // Check if there's a current canvas\n if (!currentCanvas()) return;\n \n // Update the button state to match the canvas straight line mode\n bool isEnabled = currentCanvas()->isStraightLineMode();\n \n // Set visual indicator that the button is active/inactive\n if (straightLineToggleButton) {\n straightLineToggleButton->setProperty(\"selected\", isEnabled);\n \n // Force style update\n straightLineToggleButton->style()->unpolish(straightLineToggleButton);\n straightLineToggleButton->style()->polish(straightLineToggleButton);\n }\n}\n void updateRopeToolButtonState() {\n // Check if there's a current canvas\n if (!currentCanvas()) return;\n\n // Update the button state to match the canvas rope tool mode\n bool isEnabled = currentCanvas()->isRopeToolMode();\n\n // Set visual indicator that the button is active/inactive\n if (ropeToolButton) {\n ropeToolButton->setProperty(\"selected\", isEnabled);\n\n // Force style update\n ropeToolButton->style()->unpolish(ropeToolButton);\n ropeToolButton->style()->polish(ropeToolButton);\n }\n}\n void updateMarkdownButtonState() {\n // Check if there's a current canvas\n if (!currentCanvas()) return;\n\n // Update the button state to match the canvas markdown selection mode\n bool isEnabled = currentCanvas()->isMarkdownSelectionMode();\n\n // Set visual indicator that the button is active/inactive\n if (markdownButton) {\n markdownButton->setProperty(\"selected\", isEnabled);\n\n // Force style update\n markdownButton->style()->unpolish(markdownButton);\n markdownButton->style()->polish(markdownButton);\n }\n}\n void setPenTool() {\n if (!currentCanvas()) return;\n currentCanvas()->setTool(ToolType::Pen);\n updateToolButtonStates();\n updateThicknessSliderForCurrentTool();\n updateDialDisplay();\n}\n void setMarkerTool() {\n if (!currentCanvas()) return;\n currentCanvas()->setTool(ToolType::Marker);\n updateToolButtonStates();\n updateThicknessSliderForCurrentTool();\n updateDialDisplay();\n}\n void setEraserTool() {\n if (!currentCanvas()) return;\n currentCanvas()->setTool(ToolType::Eraser);\n updateToolButtonStates();\n updateThicknessSliderForCurrentTool();\n updateDialDisplay();\n}\n QColor getContrastingTextColor(const QColor &backgroundColor) {\n // Calculate relative luminance using the formula from WCAG 2.0\n double r = backgroundColor.redF();\n double g = backgroundColor.greenF();\n double b = backgroundColor.blueF();\n \n // Gamma correction\n r = (r <= 0.03928) ? r/12.92 : pow((r + 0.055)/1.055, 2.4);\n g = (g <= 0.03928) ? g/12.92 : pow((g + 0.055)/1.055, 2.4);\n b = (b <= 0.03928) ? b/12.92 : pow((b + 0.055)/1.055, 2.4);\n \n // Calculate luminance\n double luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;\n \n // Use white text for darker backgrounds\n return (luminance < 0.5) ? Qt::white : Qt::black;\n}\n void updateCustomColorButtonStyle(const QColor &color) {\n QColor textColor = getContrastingTextColor(color);\n customColorButton->setStyleSheet(QString(\"background-color: %1; color: %2\")\n .arg(color.name())\n .arg(textColor.name()));\n customColorButton->setText(QString(\"%1\").arg(color.name()).toUpper());\n}\n void openRecentNotebooksDialog() {\n RecentNotebooksDialog dialog(this, recentNotebooksManager, this);\n dialog.exec();\n}\n void showPendingTooltip() {\n // This function is now unused since we disabled tablet tracking\n // Tooltips will work through normal mouse hover events instead\n // Keeping the function for potential future use\n}\n void showRopeSelectionMenu(const QPoint &position) {\n // Create context menu for rope tool selection\n QMenu *contextMenu = new QMenu(this);\n contextMenu->setAttribute(Qt::WA_DeleteOnClose);\n \n // Add Copy action\n QAction *copyAction = contextMenu->addAction(tr(\"Copy\"));\n copyAction->setIcon(loadThemedIcon(\"copy\"));\n connect(copyAction, &QAction::triggered, this, [this]() {\n if (currentCanvas()) {\n currentCanvas()->copyRopeSelection();\n }\n });\n \n // Add Delete action\n QAction *deleteAction = contextMenu->addAction(tr(\"Delete\"));\n deleteAction->setIcon(loadThemedIcon(\"trash\"));\n connect(deleteAction, &QAction::triggered, this, [this]() {\n if (currentCanvas()) {\n currentCanvas()->deleteRopeSelection();\n }\n });\n \n // Add Cancel action\n QAction *cancelAction = contextMenu->addAction(tr(\"Cancel\"));\n cancelAction->setIcon(loadThemedIcon(\"cross\"));\n connect(cancelAction, &QAction::triggered, this, [this]() {\n if (currentCanvas()) {\n currentCanvas()->cancelRopeSelection();\n }\n });\n \n // Convert position from canvas coordinates to global coordinates\n QPoint globalPos = currentCanvas()->mapToGlobal(position);\n \n // Show the menu at the specified position\n contextMenu->popup(globalPos);\n}\n void toggleOutlineSidebar() {\n outlineSidebarVisible = !outlineSidebarVisible;\n \n // Hide bookmarks sidebar if it's visible when opening outline\n if (outlineSidebarVisible && bookmarksSidebar && bookmarksSidebar->isVisible()) {\n bookmarksSidebar->setVisible(false);\n bookmarksSidebarVisible = false;\n // Update bookmarks button state\n if (toggleBookmarksButton) {\n toggleBookmarksButton->setProperty(\"selected\", false);\n toggleBookmarksButton->style()->unpolish(toggleBookmarksButton);\n toggleBookmarksButton->style()->polish(toggleBookmarksButton);\n }\n }\n \n outlineSidebar->setVisible(outlineSidebarVisible);\n \n // Update button toggle state\n if (toggleOutlineButton) {\n toggleOutlineButton->setProperty(\"selected\", outlineSidebarVisible);\n toggleOutlineButton->style()->unpolish(toggleOutlineButton);\n toggleOutlineButton->style()->polish(toggleOutlineButton);\n }\n \n // Load PDF outline when showing sidebar for the first time\n if (outlineSidebarVisible) {\n loadPdfOutline();\n }\n}\n void onOutlineItemClicked(QTreeWidgetItem *item, int column) {\n Q_UNUSED(column);\n \n if (!item) return;\n \n // Get the page number stored in the item data\n QVariant pageData = item->data(0, Qt::UserRole);\n if (pageData.isValid()) {\n int pageNumber = pageData.toInt();\n if (pageNumber >= 0) {\n // Switch to the selected page (convert from 0-based to 1-based)\n switchPage(pageNumber + 1);\n pageInput->setValue(pageNumber + 1);\n }\n }\n}\n void loadPdfOutline() {\n if (!outlineTree) return;\n \n outlineTree->clear();\n \n // Get current PDF document\n Poppler::Document* pdfDoc = getPdfDocument();\n if (!pdfDoc) return;\n \n // Get the outline from the PDF document\n QVector outlineItems = pdfDoc->outline();\n \n if (outlineItems.isEmpty()) {\n // If no outline exists, show page numbers as fallback\n int pageCount = pdfDoc->numPages();\n for (int i = 0; i < pageCount; ++i) {\n QTreeWidgetItem* item = new QTreeWidgetItem(outlineTree);\n item->setText(0, QString(tr(\"Page %1\")).arg(i + 1));\n item->setData(0, Qt::UserRole, i); // Store 0-based page index\n }\n } else {\n // Process the actual PDF outline\n for (const Poppler::OutlineItem& outlineItem : outlineItems) {\n addOutlineItem(outlineItem, nullptr);\n }\n }\n \n // Expand the first level by default\n outlineTree->expandToDepth(0);\n}\n void addOutlineItem(const Poppler::OutlineItem& outlineItem, QTreeWidgetItem* parentItem) {\n if (outlineItem.isNull()) return;\n \n QTreeWidgetItem* item;\n if (parentItem) {\n item = new QTreeWidgetItem(parentItem);\n } else {\n item = new QTreeWidgetItem(outlineTree);\n }\n \n // Set the title\n item->setText(0, outlineItem.name());\n \n // Try to get the page number from the destination\n int pageNumber = -1;\n auto destination = outlineItem.destination();\n if (destination) {\n pageNumber = destination->pageNumber();\n }\n \n // Store the page number (1-based) in the item data\n if (pageNumber >= 0) {\n item->setData(0, Qt::UserRole, pageNumber + 1); // Convert to 1-based\n }\n \n // Add child items recursively\n if (outlineItem.hasChildren()) {\n QVector children = outlineItem.children();\n for (const Poppler::OutlineItem& child : children) {\n addOutlineItem(child, item);\n }\n }\n}\n Poppler::Document* getPdfDocument();\n void toggleBookmarksSidebar() {\n if (!bookmarksSidebar) return;\n \n bool isVisible = bookmarksSidebar->isVisible();\n \n // Hide outline sidebar if it's visible\n if (!isVisible && outlineSidebar && outlineSidebar->isVisible()) {\n outlineSidebar->setVisible(false);\n outlineSidebarVisible = false;\n // Update outline button state\n if (toggleOutlineButton) {\n toggleOutlineButton->setProperty(\"selected\", false);\n toggleOutlineButton->style()->unpolish(toggleOutlineButton);\n toggleOutlineButton->style()->polish(toggleOutlineButton);\n }\n }\n \n bookmarksSidebar->setVisible(!isVisible);\n bookmarksSidebarVisible = !isVisible;\n \n // Update button toggle state\n if (toggleBookmarksButton) {\n toggleBookmarksButton->setProperty(\"selected\", bookmarksSidebarVisible);\n toggleBookmarksButton->style()->unpolish(toggleBookmarksButton);\n toggleBookmarksButton->style()->polish(toggleBookmarksButton);\n }\n \n if (bookmarksSidebarVisible) {\n loadBookmarks(); // Refresh bookmarks when opening\n }\n}\n void onBookmarkItemClicked(QTreeWidgetItem *item, int column) {\n Q_UNUSED(column);\n if (!item) return;\n \n // Get the page number from the item data\n bool ok;\n int pageNumber = item->data(0, Qt::UserRole).toInt(&ok);\n if (ok && pageNumber > 0) {\n // Navigate to the bookmarked page\n switchPageWithDirection(pageNumber, (pageNumber > getCurrentPageForCanvas(currentCanvas()) + 1) ? 1 : -1);\n pageInput->setValue(pageNumber);\n }\n}\n void loadBookmarks() {\n if (!bookmarksTree || !currentCanvas()) return;\n \n bookmarksTree->clear();\n \n // Get the current notebook's save folder\n QString saveFolder = currentCanvas()->getSaveFolder();\n if (saveFolder.isEmpty()) return;\n \n QString bookmarksFile = saveFolder + \"/.bookmarks.txt\";\n QFile file(bookmarksFile);\n \n bookmarks.clear();\n \n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n while (!in.atEnd()) {\n QString line = in.readLine().trimmed();\n if (line.isEmpty()) continue;\n \n QStringList parts = line.split('\\t', Qt::KeepEmptyParts);\n if (parts.size() >= 2) {\n bool ok;\n int pageNum = parts[0].toInt(&ok);\n if (ok) {\n QString title = parts[1];\n bookmarks[pageNum] = title;\n }\n }\n }\n file.close();\n }\n \n // Populate the tree widget\n for (auto it = bookmarks.begin(); it != bookmarks.end(); ++it) {\n QTreeWidgetItem *item = new QTreeWidgetItem(bookmarksTree);\n \n // Create a custom widget for each bookmark item\n QWidget *itemWidget = new QWidget();\n QHBoxLayout *itemLayout = new QHBoxLayout(itemWidget);\n itemLayout->setContentsMargins(5, 2, 5, 2);\n itemLayout->setSpacing(5);\n \n // Page number label (fixed width)\n QLabel *pageLabel = new QLabel(QString(tr(\"Page %1\")).arg(it.key()));\n pageLabel->setFixedWidth(60);\n pageLabel->setStyleSheet(\"font-weight: bold; color: #666;\");\n itemLayout->addWidget(pageLabel);\n \n // Editable title (supports Windows handwriting if available)\n QLineEdit *titleEdit = new QLineEdit(it.value());\n titleEdit->setPlaceholderText(\"Enter bookmark title...\");\n titleEdit->setProperty(\"pageNumber\", it.key()); // Store page number for saving\n \n // Enable IME support for multi-language input\n titleEdit->setAttribute(Qt::WA_InputMethodEnabled, true);\n titleEdit->setInputMethodHints(Qt::ImhNone); // Allow all input methods\n titleEdit->installEventFilter(this); // Install event filter for IME handling\n \n // Connect to save when editing is finished\n connect(titleEdit, &QLineEdit::editingFinished, this, [this, titleEdit]() {\n int pageNum = titleEdit->property(\"pageNumber\").toInt();\n QString newTitle = titleEdit->text().trimmed();\n \n if (newTitle.isEmpty()) {\n // Remove bookmark if title is empty\n bookmarks.remove(pageNum);\n } else {\n // Update bookmark title\n bookmarks[pageNum] = newTitle;\n }\n saveBookmarks();\n updateBookmarkButtonState(); // Update button state\n });\n \n itemLayout->addWidget(titleEdit, 1);\n \n // Store page number in item data for navigation\n item->setData(0, Qt::UserRole, it.key());\n \n // Set the custom widget\n bookmarksTree->setItemWidget(item, 0, itemWidget);\n \n // Set item height\n item->setSizeHint(0, QSize(0, 30));\n }\n \n updateBookmarkButtonState(); // Update button state after loading\n}\n void saveBookmarks() {\n if (!currentCanvas()) return;\n \n QString saveFolder = currentCanvas()->getSaveFolder();\n if (saveFolder.isEmpty()) return;\n \n QString bookmarksFile = saveFolder + \"/.bookmarks.txt\";\n QFile file(bookmarksFile);\n \n if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {\n QTextStream out(&file);\n \n // Sort bookmarks by page number\n QList sortedPages = bookmarks.keys();\n std::sort(sortedPages.begin(), sortedPages.end());\n \n for (int pageNum : sortedPages) {\n out << pageNum << '\\t' << bookmarks[pageNum] << '\\n';\n }\n \n file.close();\n }\n}\n void toggleCurrentPageBookmark() {\n if (!currentCanvas()) return;\n \n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1; // Convert to 1-based\n \n if (bookmarks.contains(currentPage)) {\n // Remove bookmark\n bookmarks.remove(currentPage);\n } else {\n // Add bookmark with default title\n QString defaultTitle = QString(tr(\"Bookmark %1\")).arg(currentPage);\n bookmarks[currentPage] = defaultTitle;\n }\n \n saveBookmarks();\n updateBookmarkButtonState();\n \n // Refresh bookmarks view if visible\n if (bookmarksSidebarVisible) {\n loadBookmarks();\n }\n}\n void updateBookmarkButtonState() {\n if (!toggleBookmarkButton || !currentCanvas()) return;\n \n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1; // Convert to 1-based\n bool isBookmarked = bookmarks.contains(currentPage);\n \n toggleBookmarkButton->setProperty(\"selected\", isBookmarked);\n \n // Update tooltip\n if (isBookmarked) {\n toggleBookmarkButton->setToolTip(tr(\"Remove Bookmark\"));\n } else {\n toggleBookmarkButton->setToolTip(tr(\"Add Bookmark\"));\n }\n \n // Force style update\n toggleBookmarkButton->style()->unpolish(toggleBookmarkButton);\n toggleBookmarkButton->style()->polish(toggleBookmarkButton);\n}\n private:\n InkCanvas *canvas;\n QPushButton *benchmarkButton;\n QLabel *benchmarkLabel;\n QTimer *benchmarkTimer;\n bool benchmarking;\n QPushButton *exportNotebookButton;\n QPushButton *importNotebookButton;\n QPushButton *redButton;\n QPushButton *blueButton;\n QPushButton *yellowButton;\n QPushButton *greenButton;\n QPushButton *blackButton;\n QPushButton *whiteButton;\n QLineEdit *customColorInput;\n QPushButton *customColorButton;\n QPushButton *thicknessButton;\n QSlider *thicknessSlider;\n QFrame *thicknessFrame;\n QComboBox *toolSelector;\n QPushButton *penToolButton;\n QPushButton *markerToolButton;\n QPushButton *eraserToolButton;\n QPushButton *deletePageButton;\n QPushButton *selectFolderButton;\n QPushButton *saveButton;\n QPushButton *saveAnnotatedButton;\n QPushButton *fullscreenButton;\n QPushButton *openControlPanelButton;\n QPushButton *openRecentNotebooksButton;\n QPushButton *loadPdfButton;\n QPushButton *clearPdfButton;\n QPushButton *pdfTextSelectButton;\n QPushButton *toggleTabBarButton;\n QMap pageMap;\n QPushButton *backgroundButton;\n QPushButton *straightLineToggleButton;\n QPushButton *ropeToolButton;\n QPushButton *markdownButton;\n QSlider *zoomSlider;\n QPushButton *zoomButton;\n QFrame *zoomFrame;\n QPushButton *dezoomButton;\n QPushButton *zoom50Button;\n QPushButton *zoom200Button;\n QWidget *zoomContainer;\n QLineEdit *zoomInput;\n QScrollBar *panXSlider;\n QScrollBar *panYSlider;\n QListWidget *tabList;\n QStackedWidget *canvasStack;\n QPushButton *addTabButton;\n QWidget *tabBarContainer;\n QWidget *outlineSidebar;\n QTreeWidget *outlineTree;\n QPushButton *toggleOutlineButton;\n bool outlineSidebarVisible = false;\n QWidget *bookmarksSidebar;\n QTreeWidget *bookmarksTree;\n QPushButton *toggleBookmarksButton;\n QPushButton *toggleBookmarkButton;\n QPushButton *touchGesturesButton;\n bool bookmarksSidebarVisible = false;\n QMap bookmarks;\n QPushButton *jumpToPageButton;\n QWidget *dialContainer = nullptr;\n QDial *pageDial = nullptr;\n QDial *modeDial = nullptr;\n QPushButton *dialToggleButton;\n bool fastForwardMode = false;\n QPushButton *fastForwardButton;\n int lastAngle = 0;\n int startAngle = 0;\n bool tracking = false;\n int accumulatedRotation = 0;\n QSoundEffect *dialClickSound = nullptr;\n int grossTotalClicks = 0;\n DialMode currentDialMode = PanAndPageScroll;\n DialMode temporaryDialMode = None;\n QComboBox *dialModeSelector;\n QPushButton *colorPreview;\n QLabel *dialDisplay = nullptr;\n QFrame *dialColorPreview;\n QLabel *dialIconView;\n QFont pixelFont;\n QPushButton *btnPageSwitch;\n QPushButton *btnZoom;\n QPushButton *btnThickness;\n QPushButton *btnTool;\n QPushButton *btnPresets;\n QPushButton *btnPannScroll;\n int tempClicks = 0;\n QPushButton *dialHiddenButton;\n QQueue colorPresets;\n QPushButton *addPresetButton;\n int currentPresetIndex = 0;\n bool useBrighterPalette = false;\n qreal initialDpr = 1.0;\n QWidget *sidebarContainer;\n QWidget *controlBar;\n void setTemporaryDialMode(DialMode mode) {\n if (temporaryDialMode == None) {\n temporaryDialMode = currentDialMode;\n }\n changeDialMode(mode);\n}\n void clearTemporaryDialMode() {\n if (temporaryDialMode != None) {\n changeDialMode(temporaryDialMode);\n temporaryDialMode = None;\n }\n}\n bool controlBarVisible = true;\n void toggleControlBar() {\n // Proper fullscreen toggle: handle both sidebar and control bar\n \n if (controlBarVisible) {\n // Going into fullscreen mode\n \n // First, remember current tab bar state\n sidebarWasVisibleBeforeFullscreen = tabBarContainer->isVisible();\n \n // Hide tab bar if it's visible\n if (tabBarContainer->isVisible()) {\n tabBarContainer->setVisible(false);\n }\n \n // Hide control bar\n controlBarVisible = false;\n controlBar->setVisible(false);\n \n // Hide floating popup widgets when control bar is hidden to prevent stacking\n if (zoomFrame && zoomFrame->isVisible()) zoomFrame->hide();\n if (thicknessFrame && thicknessFrame->isVisible()) thicknessFrame->hide();\n \n // Hide orphaned widgets that are not added to any layout\n if (colorPreview) colorPreview->hide();\n if (thicknessButton) thicknessButton->hide();\n if (jumpToPageButton) jumpToPageButton->hide();\n\n if (toolSelector) toolSelector->hide();\n if (zoomButton) zoomButton->hide();\n if (customColorInput) customColorInput->hide();\n \n // Find and hide local widgets that might be orphaned\n QList comboBoxes = findChildren();\n for (QComboBox* combo : comboBoxes) {\n if (combo->parent() == this && !combo->isVisible()) {\n // Already hidden, keep it hidden\n } else if (combo->parent() == this) {\n // This might be the orphaned dialModeSelector or similar\n combo->hide();\n }\n }\n } else {\n // Coming out of fullscreen mode\n \n // Restore control bar\n controlBarVisible = true;\n controlBar->setVisible(true);\n \n // Restore tab bar to its previous state\n tabBarContainer->setVisible(sidebarWasVisibleBeforeFullscreen);\n \n // Show orphaned widgets when control bar is visible\n // Note: These are kept hidden normally since they're not in the layout\n // Only show them if they were specifically intended to be visible\n }\n \n // Update dial display to reflect new status\n updateDialDisplay();\n \n // Force layout update to recalculate space\n if (auto *canvas = currentCanvas()) {\n QTimer::singleShot(0, this, [this, canvas]() {\n canvas->setMaximumSize(canvas->getCanvasSize());\n });\n }\n}\n void cycleZoomLevels() {\n if (!zoomSlider) return;\n \n int currentZoom = zoomSlider->value();\n int targetZoom;\n \n // Calculate the scaled zoom levels based on initial DPR\n int zoom50 = 50 / initialDpr;\n int zoom100 = 100 / initialDpr;\n int zoom200 = 200 / initialDpr;\n \n // Cycle through 0.5x -> 1x -> 2x -> 0.5x...\n if (currentZoom <= zoom50 + 5) { // Close to 0.5x (with small tolerance)\n targetZoom = zoom100; // Go to 1x\n } else if (currentZoom <= zoom100 + 5) { // Close to 1x\n targetZoom = zoom200; // Go to 2x\n } else { // Any other zoom level or close to 2x\n targetZoom = zoom50; // Go to 0.5x\n }\n \n zoomSlider->setValue(targetZoom);\n updateZoom();\n updateDialDisplay();\n}\n bool sidebarWasVisibleBeforeFullscreen = true;\n int accumulatedRotationAfterLimit = 0;\n int pendingPageFlip = 0;\n QMap buttonHoldMapping;\n QMap buttonPressMapping;\n QMap buttonPressActionMapping;\n QMap keyboardMappings;\n QMap keyboardActionMapping;\n QTimer *tooltipTimer;\n QWidget *lastHoveredWidget;\n QPoint pendingTooltipPos;\n void handleButtonHeld(const QString &buttonName) {\n QString mode = buttonHoldMapping.value(buttonName, \"None\");\n if (mode != \"None\") {\n setTemporaryDialMode(dialModeFromString(mode));\n return;\n }\n}\n void handleButtonReleased(const QString &buttonName) {\n QString mode = buttonHoldMapping.value(buttonName, \"None\");\n if (mode != \"None\") {\n clearTemporaryDialMode();\n }\n}\n void handleControllerButton(const QString &buttonName) { // This is for single press functions\n ControllerAction action = buttonPressActionMapping.value(buttonName, ControllerAction::None);\n\n switch (action) {\n case ControllerAction::ToggleFullscreen:\n fullscreenButton->click();\n break;\n case ControllerAction::ToggleDial:\n toggleDial();\n break;\n case ControllerAction::Zoom50:\n zoom50Button->click();\n break;\n case ControllerAction::ZoomOut:\n dezoomButton->click();\n break;\n case ControllerAction::Zoom200:\n zoom200Button->click();\n break;\n case ControllerAction::AddPreset:\n addPresetButton->click();\n break;\n case ControllerAction::DeletePage:\n deletePageButton->click(); // assuming you have this\n break;\n case ControllerAction::FastForward:\n fastForwardButton->click(); // assuming you have this\n break;\n case ControllerAction::OpenControlPanel:\n openControlPanelButton->click();\n break;\n case ControllerAction::RedColor:\n redButton->click();\n break;\n case ControllerAction::BlueColor:\n blueButton->click();\n break;\n case ControllerAction::YellowColor:\n yellowButton->click();\n break;\n case ControllerAction::GreenColor:\n greenButton->click();\n break;\n case ControllerAction::BlackColor:\n blackButton->click();\n break;\n case ControllerAction::WhiteColor:\n whiteButton->click();\n break;\n case ControllerAction::CustomColor:\n customColorButton->click();\n break;\n case ControllerAction::ToggleSidebar:\n toggleTabBarButton->click();\n break;\n case ControllerAction::Save:\n saveButton->click();\n break;\n case ControllerAction::StraightLineTool:\n straightLineToggleButton->click();\n break;\n case ControllerAction::RopeTool:\n ropeToolButton->click();\n break;\n case ControllerAction::SetPenTool:\n setPenTool();\n break;\n case ControllerAction::SetMarkerTool:\n setMarkerTool();\n break;\n case ControllerAction::SetEraserTool:\n setEraserTool();\n break;\n case ControllerAction::TogglePdfTextSelection:\n pdfTextSelectButton->click();\n break;\n case ControllerAction::ToggleOutline:\n toggleOutlineButton->click();\n break;\n case ControllerAction::ToggleBookmarks:\n toggleBookmarksButton->click();\n break;\n case ControllerAction::AddBookmark:\n toggleBookmarkButton->click();\n break;\n case ControllerAction::ToggleTouchGestures:\n touchGesturesButton->click();\n break;\n default:\n break;\n }\n}\n void handleKeyboardShortcut(const QString &keySequence) {\n ControllerAction action = keyboardActionMapping.value(keySequence, ControllerAction::None);\n \n // Use the same handler as Joy-Con buttons\n switch (action) {\n case ControllerAction::ToggleFullscreen:\n fullscreenButton->click();\n break;\n case ControllerAction::ToggleDial:\n toggleDial();\n break;\n case ControllerAction::Zoom50:\n zoom50Button->click();\n break;\n case ControllerAction::ZoomOut:\n dezoomButton->click();\n break;\n case ControllerAction::Zoom200:\n zoom200Button->click();\n break;\n case ControllerAction::AddPreset:\n addPresetButton->click();\n break;\n case ControllerAction::DeletePage:\n deletePageButton->click();\n break;\n case ControllerAction::FastForward:\n fastForwardButton->click();\n break;\n case ControllerAction::OpenControlPanel:\n openControlPanelButton->click();\n break;\n case ControllerAction::RedColor:\n redButton->click();\n break;\n case ControllerAction::BlueColor:\n blueButton->click();\n break;\n case ControllerAction::YellowColor:\n yellowButton->click();\n break;\n case ControllerAction::GreenColor:\n greenButton->click();\n break;\n case ControllerAction::BlackColor:\n blackButton->click();\n break;\n case ControllerAction::WhiteColor:\n whiteButton->click();\n break;\n case ControllerAction::CustomColor:\n customColorButton->click();\n break;\n case ControllerAction::ToggleSidebar:\n toggleTabBarButton->click();\n break;\n case ControllerAction::Save:\n saveButton->click();\n break;\n case ControllerAction::StraightLineTool:\n straightLineToggleButton->click();\n break;\n case ControllerAction::RopeTool:\n ropeToolButton->click();\n break;\n case ControllerAction::SetPenTool:\n setPenTool();\n break;\n case ControllerAction::SetMarkerTool:\n setMarkerTool();\n break;\n case ControllerAction::SetEraserTool:\n setEraserTool();\n break;\n case ControllerAction::TogglePdfTextSelection:\n pdfTextSelectButton->click();\n break;\n case ControllerAction::ToggleOutline:\n toggleOutlineButton->click();\n break;\n case ControllerAction::ToggleBookmarks:\n toggleBookmarksButton->click();\n break;\n case ControllerAction::AddBookmark:\n toggleBookmarkButton->click();\n break;\n case ControllerAction::ToggleTouchGestures:\n touchGesturesButton->click();\n break;\n default:\n break;\n }\n}\n void saveKeyboardMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.beginGroup(\"KeyboardMappings\");\n for (auto it = keyboardMappings.begin(); it != keyboardMappings.end(); ++it) {\n settings.setValue(it.key(), it.value());\n }\n settings.endGroup();\n}\n void loadKeyboardMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.beginGroup(\"KeyboardMappings\");\n QStringList keys = settings.allKeys();\n \n // List of IME-related shortcuts that should not be intercepted\n QStringList imeShortcuts = {\n \"Ctrl+Space\", // Primary IME toggle\n \"Ctrl+Shift\", // Language switching\n \"Ctrl+Alt\", // IME functions\n \"Shift+Alt\", // Alternative language switching\n \"Alt+Shift\" // Alternative language switching (reversed)\n };\n \n for (const QString &key : keys) {\n // Skip IME-related shortcuts\n if (imeShortcuts.contains(key)) {\n // Remove from settings if it exists\n settings.remove(key);\n continue;\n }\n \n QString value = settings.value(key).toString();\n keyboardMappings[key] = value;\n keyboardActionMapping[key] = stringToAction(value);\n }\n settings.endGroup();\n \n // Save settings to persist the removal of IME shortcuts\n settings.sync();\n}\n void ensureTabHasUniqueSaveFolder(InkCanvas* canvas) {\n if (!canvas) return;\n\n if (canvasStack->count() == 0) return;\n\n QString currentFolder = canvas->getSaveFolder();\n QString tempFolder = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\";\n\n if (currentFolder.isEmpty() || currentFolder == tempFolder) {\n\n QDir sourceDir(tempFolder);\n QStringList pageFiles = sourceDir.entryList(QStringList() << \"*.png\", QDir::Files);\n\n // No pages to save → skip prompting\n if (pageFiles.isEmpty()) {\n return;\n }\n\n QMessageBox::warning(this, tr(\"Unsaved Notebook\"),\n tr(\"This notebook is still using a temporary session folder.\\nPlease select a permanent folder to avoid data loss.\"));\n\n QString selectedFolder = QFileDialog::getExistingDirectory(this, tr(\"Select Save Folder\"));\n if (selectedFolder.isEmpty()) return;\n\n QDir destDir(selectedFolder);\n if (!destDir.exists()) {\n QDir().mkpath(selectedFolder);\n }\n\n // Copy contents from temp to selected folder\n for (const QString &file : sourceDir.entryList(QDir::Files)) {\n QString srcFilePath = tempFolder + \"/\" + file;\n QString dstFilePath = selectedFolder + \"/\" + file;\n\n // If file already exists at destination, remove it to avoid rename failure\n if (QFile::exists(dstFilePath)) {\n QFile::remove(dstFilePath);\n }\n\n QFile::rename(srcFilePath, dstFilePath); // This moves the file\n }\n\n canvas->setSaveFolder(selectedFolder);\n // updateTabLabel(); // No longer needed here, handled by the close button lambda\n }\n\n return;\n}\n RecentNotebooksManager *recentNotebooksManager;\n int pdfRenderDPI = 192;\n void setupUi() {\n \n // Ensure IME is properly enabled for the application\n QInputMethod *inputMethod = QGuiApplication::inputMethod();\n if (inputMethod) {\n inputMethod->show();\n inputMethod->reset();\n }\n \n // Create theme-aware button style\n bool darkMode = isDarkMode();\n QString buttonStyle = createButtonStyle(darkMode);\n\n\n loadPdfButton = new QPushButton(this);\n clearPdfButton = new QPushButton(this);\n loadPdfButton->setFixedSize(26, 30);\n clearPdfButton->setFixedSize(26, 30);\n QIcon pdfIcon(loadThemedIcon(\"pdf\")); // Path to your icon in resources\n QIcon pdfDeleteIcon(loadThemedIcon(\"pdfdelete\")); // Path to your icon in resources\n loadPdfButton->setIcon(pdfIcon);\n clearPdfButton->setIcon(pdfDeleteIcon);\n loadPdfButton->setStyleSheet(buttonStyle);\n clearPdfButton->setStyleSheet(buttonStyle);\n loadPdfButton->setToolTip(tr(\"Load PDF\"));\n clearPdfButton->setToolTip(tr(\"Clear PDF\"));\n connect(loadPdfButton, &QPushButton::clicked, this, &MainWindow::loadPdf);\n connect(clearPdfButton, &QPushButton::clicked, this, &MainWindow::clearPdf);\n\n pdfTextSelectButton = new QPushButton(this);\n pdfTextSelectButton->setFixedSize(26, 30);\n QIcon pdfTextIcon(loadThemedIcon(\"ibeam\"));\n pdfTextSelectButton->setIcon(pdfTextIcon);\n pdfTextSelectButton->setStyleSheet(buttonStyle);\n pdfTextSelectButton->setToolTip(tr(\"Toggle PDF Text Selection\"));\n connect(pdfTextSelectButton, &QPushButton::clicked, this, [this]() {\n if (!currentCanvas()) return;\n \n bool newMode = !currentCanvas()->isPdfTextSelectionEnabled();\n currentCanvas()->setPdfTextSelectionEnabled(newMode);\n updatePdfTextSelectButtonState();\n updateBookmarkButtonState();\n \n // Clear any existing selection when toggling\n if (!newMode) {\n currentCanvas()->clearPdfTextSelection();\n }\n });\n\n exportNotebookButton = new QPushButton(this);\n exportNotebookButton->setFixedSize(26, 30);\n QIcon exportIcon(loadThemedIcon(\"export\")); // Path to your icon in resources\n exportNotebookButton->setIcon(exportIcon);\n exportNotebookButton->setStyleSheet(buttonStyle);\n exportNotebookButton->setToolTip(tr(\"Export Notebook Into .SNPKG File\"));\n importNotebookButton = new QPushButton(this);\n importNotebookButton->setFixedSize(26, 30);\n QIcon importIcon(loadThemedIcon(\"import\")); // Path to your icon in resources\n importNotebookButton->setIcon(importIcon);\n importNotebookButton->setStyleSheet(buttonStyle);\n importNotebookButton->setToolTip(tr(\"Import Notebook From .SNPKG File\"));\n\n connect(exportNotebookButton, &QPushButton::clicked, this, [=]() {\n QString filename = QFileDialog::getSaveFileName(this, tr(\"Export Notebook\"), \"\", \"SpeedyNote Package (*.snpkg)\");\n if (!filename.isEmpty()) {\n if (!filename.endsWith(\".snpkg\")) filename += \".snpkg\";\n currentCanvas()->exportNotebook(filename);\n }\n });\n \n connect(importNotebookButton, &QPushButton::clicked, this, [=]() {\n QString filename = QFileDialog::getOpenFileName(this, tr(\"Import Notebook\"), \"\", \"SpeedyNote Package (*.snpkg)\");\n if (!filename.isEmpty()) {\n currentCanvas()->importNotebook(filename);\n }\n });\n\n benchmarkButton = new QPushButton(this);\n QIcon benchmarkIcon(loadThemedIcon(\"benchmark\")); // Path to your icon in resources\n benchmarkButton->setIcon(benchmarkIcon);\n benchmarkButton->setFixedSize(26, 30); // Make the benchmark button smaller\n benchmarkButton->setStyleSheet(buttonStyle);\n benchmarkButton->setToolTip(tr(\"Toggle Benchmark\"));\n benchmarkLabel = new QLabel(\"PR:N/A\", this);\n benchmarkLabel->setFixedHeight(30); // Make the benchmark bar smaller\n\n toggleTabBarButton = new QPushButton(this);\n toggleTabBarButton->setIcon(loadThemedIcon(\"tabs\")); // You can design separate icons for \"show\" and \"hide\"\n toggleTabBarButton->setToolTip(tr(\"Show/Hide Tab Bar\"));\n toggleTabBarButton->setFixedSize(26, 30);\n toggleTabBarButton->setStyleSheet(buttonStyle);\n toggleTabBarButton->setProperty(\"selected\", true); // Initially visible\n \n // PDF Outline Toggle Button\n toggleOutlineButton = new QPushButton(this);\n toggleOutlineButton->setIcon(loadThemedIcon(\"outline\")); // Icon to be added later\n toggleOutlineButton->setToolTip(tr(\"Show/Hide PDF Outline\"));\n toggleOutlineButton->setFixedSize(26, 30);\n toggleOutlineButton->setStyleSheet(buttonStyle);\n toggleOutlineButton->setProperty(\"selected\", false); // Initially hidden\n \n // Bookmarks Toggle Button\n toggleBookmarksButton = new QPushButton(this);\n toggleBookmarksButton->setIcon(loadThemedIcon(\"bookmark\")); // Using bookpage icon for bookmarks\n toggleBookmarksButton->setToolTip(tr(\"Show/Hide Bookmarks\"));\n toggleBookmarksButton->setFixedSize(26, 30);\n toggleBookmarksButton->setStyleSheet(buttonStyle);\n toggleBookmarksButton->setProperty(\"selected\", false); // Initially hidden\n \n // Add/Remove Bookmark Toggle Button\n toggleBookmarkButton = new QPushButton(this);\n toggleBookmarkButton->setIcon(loadThemedIcon(\"star\"));\n toggleBookmarkButton->setToolTip(tr(\"Add/Remove Bookmark\"));\n toggleBookmarkButton->setFixedSize(26, 30);\n toggleBookmarkButton->setStyleSheet(buttonStyle);\n toggleBookmarkButton->setProperty(\"selected\", false); // For toggle state styling\n\n // Touch Gestures Toggle Button\n touchGesturesButton = new QPushButton(this);\n touchGesturesButton->setIcon(loadThemedIcon(\"hand\")); // Using hand icon for touch/gesture\n touchGesturesButton->setToolTip(tr(\"Toggle Touch Gestures\"));\n touchGesturesButton->setFixedSize(26, 30);\n touchGesturesButton->setStyleSheet(buttonStyle);\n touchGesturesButton->setProperty(\"selected\", touchGesturesEnabled); // For toggle state styling\n\n selectFolderButton = new QPushButton(this);\n selectFolderButton->setFixedSize(26, 30);\n QIcon folderIcon(loadThemedIcon(\"folder\")); // Path to your icon in resources\n selectFolderButton->setIcon(folderIcon);\n selectFolderButton->setStyleSheet(buttonStyle);\n selectFolderButton->setToolTip(tr(\"Select Save Folder\"));\n connect(selectFolderButton, &QPushButton::clicked, this, &MainWindow::selectFolder);\n \n \n saveButton = new QPushButton(this);\n saveButton->setFixedSize(26, 30);\n QIcon saveIcon(loadThemedIcon(\"save\")); // Path to your icon in resources\n saveButton->setIcon(saveIcon);\n saveButton->setStyleSheet(buttonStyle);\n saveButton->setToolTip(tr(\"Save Current Page\"));\n connect(saveButton, &QPushButton::clicked, this, &MainWindow::saveCurrentPage);\n \n saveAnnotatedButton = new QPushButton(this);\n saveAnnotatedButton->setFixedSize(26, 30);\n QIcon saveAnnotatedIcon(loadThemedIcon(\"saveannotated\")); // Path to your icon in resources\n saveAnnotatedButton->setIcon(saveAnnotatedIcon);\n saveAnnotatedButton->setStyleSheet(buttonStyle);\n saveAnnotatedButton->setToolTip(tr(\"Save Page with Background\"));\n connect(saveAnnotatedButton, &QPushButton::clicked, this, &MainWindow::saveAnnotated);\n\n fullscreenButton = new QPushButton(this);\n fullscreenButton->setIcon(loadThemedIcon(\"fullscreen\")); // Load from resources\n fullscreenButton->setFixedSize(26, 30);\n fullscreenButton->setToolTip(tr(\"Toggle Fullscreen\"));\n fullscreenButton->setStyleSheet(buttonStyle);\n\n // ✅ Connect button click to toggleFullscreen() function\n connect(fullscreenButton, &QPushButton::clicked, this, &MainWindow::toggleFullscreen);\n\n // Use the darkMode variable already declared at the beginning of setupUi()\n\n redButton = new QPushButton(this);\n redButton->setFixedSize(18, 30); // Half width\n QString redIconPath = darkMode ? \":/resources/icons/pen_light_red.png\" : \":/resources/icons/pen_dark_red.png\";\n QIcon redIcon(redIconPath);\n redButton->setIcon(redIcon);\n redButton->setStyleSheet(buttonStyle);\n connect(redButton, &QPushButton::clicked, [this]() { \n handleColorButtonClick();\n currentCanvas()->setPenColor(getPaletteColor(\"red\")); \n updateDialDisplay(); \n updateColorButtonStates();\n });\n \n blueButton = new QPushButton(this);\n blueButton->setFixedSize(18, 30); // Half width\n QString blueIconPath = darkMode ? \":/resources/icons/pen_light_blue.png\" : \":/resources/icons/pen_dark_blue.png\";\n QIcon blueIcon(blueIconPath);\n blueButton->setIcon(blueIcon);\n blueButton->setStyleSheet(buttonStyle);\n connect(blueButton, &QPushButton::clicked, [this]() { \n handleColorButtonClick();\n currentCanvas()->setPenColor(getPaletteColor(\"blue\")); \n updateDialDisplay(); \n updateColorButtonStates();\n });\n\n yellowButton = new QPushButton(this);\n yellowButton->setFixedSize(18, 30); // Half width\n QString yellowIconPath = darkMode ? \":/resources/icons/pen_light_yellow.png\" : \":/resources/icons/pen_dark_yellow.png\";\n QIcon yellowIcon(yellowIconPath);\n yellowButton->setIcon(yellowIcon);\n yellowButton->setStyleSheet(buttonStyle);\n connect(yellowButton, &QPushButton::clicked, [this]() { \n handleColorButtonClick();\n currentCanvas()->setPenColor(getPaletteColor(\"yellow\")); \n updateDialDisplay(); \n updateColorButtonStates();\n });\n\n greenButton = new QPushButton(this);\n greenButton->setFixedSize(18, 30); // Half width\n QString greenIconPath = darkMode ? \":/resources/icons/pen_light_green.png\" : \":/resources/icons/pen_dark_green.png\";\n QIcon greenIcon(greenIconPath);\n greenButton->setIcon(greenIcon);\n greenButton->setStyleSheet(buttonStyle);\n connect(greenButton, &QPushButton::clicked, [this]() { \n handleColorButtonClick();\n currentCanvas()->setPenColor(getPaletteColor(\"green\")); \n updateDialDisplay(); \n updateColorButtonStates();\n });\n\n blackButton = new QPushButton(this);\n blackButton->setFixedSize(18, 30); // Half width\n QString blackIconPath = darkMode ? \":/resources/icons/pen_light_black.png\" : \":/resources/icons/pen_dark_black.png\";\n QIcon blackIcon(blackIconPath);\n blackButton->setIcon(blackIcon);\n blackButton->setStyleSheet(buttonStyle);\n connect(blackButton, &QPushButton::clicked, [this]() { \n handleColorButtonClick();\n currentCanvas()->setPenColor(QColor(\"#000000\")); \n updateDialDisplay(); \n updateColorButtonStates();\n });\n\n whiteButton = new QPushButton(this);\n whiteButton->setFixedSize(18, 30); // Half width\n QString whiteIconPath = darkMode ? \":/resources/icons/pen_light_white.png\" : \":/resources/icons/pen_dark_white.png\";\n QIcon whiteIcon(whiteIconPath);\n whiteButton->setIcon(whiteIcon);\n whiteButton->setStyleSheet(buttonStyle);\n connect(whiteButton, &QPushButton::clicked, [this]() { \n handleColorButtonClick();\n currentCanvas()->setPenColor(QColor(\"#FFFFFF\")); \n updateDialDisplay(); \n updateColorButtonStates();\n });\n \n customColorInput = new QLineEdit(this);\n customColorInput->setPlaceholderText(\"Custom HEX\");\n customColorInput->setFixedSize(85, 30);\n \n // Enable IME support for multi-language input\n customColorInput->setAttribute(Qt::WA_InputMethodEnabled, true);\n customColorInput->setInputMethodHints(Qt::ImhNone); // Allow all input methods\n customColorInput->installEventFilter(this); // Install event filter for IME handling\n \n connect(customColorInput, &QLineEdit::returnPressed, this, &MainWindow::applyCustomColor);\n\n \n thicknessButton = new QPushButton(this);\n thicknessButton->setIcon(loadThemedIcon(\"thickness\"));\n thicknessButton->setFixedSize(26, 30);\n thicknessButton->setStyleSheet(buttonStyle);\n connect(thicknessButton, &QPushButton::clicked, this, &MainWindow::toggleThicknessSlider);\n\n thicknessFrame = new QFrame(this);\n thicknessFrame->setFrameShape(QFrame::StyledPanel);\n thicknessFrame->setStyleSheet(R\"(\n background-color: black;\n border: 1px solid black;\n padding: 5px;\n )\");\n thicknessFrame->setVisible(false);\n thicknessFrame->setFixedSize(220, 40); // Adjust width/height as needed\n\n thicknessSlider = new QSlider(Qt::Horizontal, this);\n thicknessSlider->setRange(1, 50);\n thicknessSlider->setValue(5);\n thicknessSlider->setMaximumWidth(200);\n\n\n connect(thicknessSlider, &QSlider::valueChanged, this, &MainWindow::updateThickness);\n\n QVBoxLayout *popupLayoutThickness = new QVBoxLayout();\n popupLayoutThickness->setContentsMargins(10, 5, 10, 5);\n popupLayoutThickness->addWidget(thicknessSlider);\n thicknessFrame->setLayout(popupLayoutThickness);\n\n\n toolSelector = new QComboBox(this);\n toolSelector->addItem(loadThemedIcon(\"pen\"), \"\");\n toolSelector->addItem(loadThemedIcon(\"marker\"), \"\");\n toolSelector->addItem(loadThemedIcon(\"eraser\"), \"\");\n toolSelector->setFixedWidth(43);\n toolSelector->setFixedHeight(30);\n connect(toolSelector, QOverload::of(&QComboBox::currentIndexChanged), this, &MainWindow::changeTool);\n\n // ✅ Individual tool buttons\n penToolButton = new QPushButton(this);\n penToolButton->setFixedSize(26, 30);\n penToolButton->setIcon(loadThemedIcon(\"pen\"));\n penToolButton->setStyleSheet(buttonStyle);\n penToolButton->setToolTip(tr(\"Pen Tool\"));\n connect(penToolButton, &QPushButton::clicked, this, &MainWindow::setPenTool);\n\n markerToolButton = new QPushButton(this);\n markerToolButton->setFixedSize(26, 30);\n markerToolButton->setIcon(loadThemedIcon(\"marker\"));\n markerToolButton->setStyleSheet(buttonStyle);\n markerToolButton->setToolTip(tr(\"Marker Tool\"));\n connect(markerToolButton, &QPushButton::clicked, this, &MainWindow::setMarkerTool);\n\n eraserToolButton = new QPushButton(this);\n eraserToolButton->setFixedSize(26, 30);\n eraserToolButton->setIcon(loadThemedIcon(\"eraser\"));\n eraserToolButton->setStyleSheet(buttonStyle);\n eraserToolButton->setToolTip(tr(\"Eraser Tool\"));\n connect(eraserToolButton, &QPushButton::clicked, this, &MainWindow::setEraserTool);\n\n backgroundButton = new QPushButton(this);\n backgroundButton->setFixedSize(26, 30);\n QIcon bgIcon(loadThemedIcon(\"background\")); // Path to your icon in resources\n backgroundButton->setIcon(bgIcon);\n backgroundButton->setStyleSheet(buttonStyle);\n backgroundButton->setToolTip(tr(\"Set Background Pic\"));\n connect(backgroundButton, &QPushButton::clicked, this, &MainWindow::selectBackground);\n\n // Initialize straight line toggle button\n straightLineToggleButton = new QPushButton(this);\n straightLineToggleButton->setFixedSize(26, 30);\n QIcon straightLineIcon(loadThemedIcon(\"straightLine\")); // Make sure this icon exists or use a different one\n straightLineToggleButton->setIcon(straightLineIcon);\n straightLineToggleButton->setStyleSheet(buttonStyle);\n straightLineToggleButton->setToolTip(tr(\"Toggle Straight Line Mode\"));\n connect(straightLineToggleButton, &QPushButton::clicked, this, [this]() {\n if (!currentCanvas()) return;\n \n // If we're turning on straight line mode, first disable rope tool\n if (!currentCanvas()->isStraightLineMode()) {\n currentCanvas()->setRopeToolMode(false);\n updateRopeToolButtonState();\n }\n \n bool newMode = !currentCanvas()->isStraightLineMode();\n currentCanvas()->setStraightLineMode(newMode);\n updateStraightLineButtonState();\n });\n \n ropeToolButton = new QPushButton(this);\n ropeToolButton->setFixedSize(26, 30);\n QIcon ropeToolIcon(loadThemedIcon(\"rope\")); // Make sure this icon exists\n ropeToolButton->setIcon(ropeToolIcon);\n ropeToolButton->setStyleSheet(buttonStyle);\n ropeToolButton->setToolTip(tr(\"Toggle Rope Tool Mode\"));\n connect(ropeToolButton, &QPushButton::clicked, this, [this]() {\n if (!currentCanvas()) return;\n \n // If we're turning on rope tool mode, first disable straight line\n if (!currentCanvas()->isRopeToolMode()) {\n currentCanvas()->setStraightLineMode(false);\n updateStraightLineButtonState();\n }\n \n bool newMode = !currentCanvas()->isRopeToolMode();\n currentCanvas()->setRopeToolMode(newMode);\n updateRopeToolButtonState();\n });\n \n markdownButton = new QPushButton(this);\n markdownButton->setFixedSize(26, 30);\n QIcon markdownIcon(loadThemedIcon(\"markdown\")); // Using text icon for markdown\n markdownButton->setIcon(markdownIcon);\n markdownButton->setStyleSheet(buttonStyle);\n markdownButton->setToolTip(tr(\"Add Markdown Window\"));\n connect(markdownButton, &QPushButton::clicked, this, [this]() {\n if (!currentCanvas()) return;\n \n // Toggle markdown selection mode\n bool newMode = !currentCanvas()->isMarkdownSelectionMode();\n currentCanvas()->setMarkdownSelectionMode(newMode);\n updateMarkdownButtonState();\n });\n \n deletePageButton = new QPushButton(this);\n deletePageButton->setFixedSize(26, 30);\n QIcon trashIcon(loadThemedIcon(\"trash\")); // Path to your icon in resources\n deletePageButton->setIcon(trashIcon);\n deletePageButton->setStyleSheet(buttonStyle);\n deletePageButton->setToolTip(tr(\"Delete Current Page\"));\n connect(deletePageButton, &QPushButton::clicked, this, &MainWindow::deleteCurrentPage);\n\n zoomButton = new QPushButton(this);\n zoomButton->setIcon(loadThemedIcon(\"zoom\"));\n zoomButton->setFixedSize(26, 30);\n zoomButton->setStyleSheet(buttonStyle);\n connect(zoomButton, &QPushButton::clicked, this, &MainWindow::toggleZoomSlider);\n\n // ✅ Create the floating frame (Initially Hidden)\n zoomFrame = new QFrame(this);\n zoomFrame->setFrameShape(QFrame::StyledPanel);\n zoomFrame->setStyleSheet(R\"(\n background-color: black;\n border: 1px solid black;\n padding: 5px;\n )\");\n zoomFrame->setVisible(false);\n zoomFrame->setFixedSize(440, 40); // Adjust width/height as needed\n\n zoomSlider = new QSlider(Qt::Horizontal, this);\n zoomSlider->setRange(10, 400);\n zoomSlider->setValue(100);\n zoomSlider->setMaximumWidth(405);\n\n connect(zoomSlider, &QSlider::valueChanged, this, &MainWindow::onZoomSliderChanged);\n\n QVBoxLayout *popupLayout = new QVBoxLayout();\n popupLayout->setContentsMargins(10, 5, 10, 5);\n popupLayout->addWidget(zoomSlider);\n zoomFrame->setLayout(popupLayout);\n \n\n zoom50Button = new QPushButton(\"0.5x\", this);\n zoom50Button->setFixedSize(35, 30);\n zoom50Button->setStyleSheet(buttonStyle);\n zoom50Button->setToolTip(tr(\"Set Zoom to 50%\"));\n connect(zoom50Button, &QPushButton::clicked, [this]() { zoomSlider->setValue(50 / initialDpr); updateDialDisplay(); });\n\n dezoomButton = new QPushButton(\"1x\", this);\n dezoomButton->setFixedSize(26, 30);\n dezoomButton->setStyleSheet(buttonStyle);\n dezoomButton->setToolTip(tr(\"Set Zoom to 100%\"));\n connect(dezoomButton, &QPushButton::clicked, [this]() { zoomSlider->setValue(100 / initialDpr); updateDialDisplay(); });\n\n zoom200Button = new QPushButton(\"2x\", this);\n zoom200Button->setFixedSize(31, 30);\n zoom200Button->setStyleSheet(buttonStyle);\n zoom200Button->setToolTip(tr(\"Set Zoom to 200%\"));\n connect(zoom200Button, &QPushButton::clicked, [this]() { zoomSlider->setValue(200 / initialDpr); updateDialDisplay(); });\n\n panXSlider = new QScrollBar(Qt::Horizontal, this);\n panYSlider = new QScrollBar(Qt::Vertical, this);\n panYSlider->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);\n \n // Set scrollbar styling\n QString scrollBarStyle = R\"(\n QScrollBar {\n background: rgba(200, 200, 200, 80);\n border: none;\n margin: 0px;\n }\n QScrollBar:hover {\n background: rgba(200, 200, 200, 120);\n }\n QScrollBar:horizontal {\n height: 16px !important; /* Force narrow height */\n max-height: 16px !important;\n }\n QScrollBar:vertical {\n width: 16px !important; /* Force narrow width */\n max-width: 16px !important;\n }\n QScrollBar::handle {\n background: rgba(100, 100, 100, 150);\n border-radius: 2px;\n min-height: 120px; /* Longer handle for vertical scrollbar */\n min-width: 120px; /* Longer handle for horizontal scrollbar */\n }\n QScrollBar::handle:hover {\n background: rgba(80, 80, 80, 210);\n }\n /* Hide scroll buttons */\n QScrollBar::add-line, \n QScrollBar::sub-line {\n width: 0px;\n height: 0px;\n background: none;\n border: none;\n }\n /* Disable scroll page buttons */\n QScrollBar::add-page, \n QScrollBar::sub-page {\n background: transparent;\n }\n )\";\n \n panXSlider->setStyleSheet(scrollBarStyle);\n panYSlider->setStyleSheet(scrollBarStyle);\n \n // Force fixed dimensions programmatically\n panXSlider->setFixedHeight(16);\n panYSlider->setFixedWidth(16);\n \n // Set up auto-hiding\n panXSlider->setMouseTracking(true);\n panYSlider->setMouseTracking(true);\n panXSlider->installEventFilter(this);\n panYSlider->installEventFilter(this);\n panXSlider->setVisible(false);\n panYSlider->setVisible(false);\n \n // Create timer for auto-hiding\n scrollbarHideTimer = new QTimer(this);\n scrollbarHideTimer->setSingleShot(true);\n scrollbarHideTimer->setInterval(200); // Hide after 0.2 seconds\n connect(scrollbarHideTimer, &QTimer::timeout, this, [this]() {\n panXSlider->setVisible(false);\n panYSlider->setVisible(false);\n scrollbarsVisible = false;\n });\n \n // panXSlider->setFixedHeight(30);\n // panYSlider->setFixedWidth(30);\n\n connect(panXSlider, &QScrollBar::valueChanged, this, &MainWindow::updatePanX);\n \n connect(panYSlider, &QScrollBar::valueChanged, this, &MainWindow::updatePanY);\n\n\n\n\n // 🌟 PDF Outline Sidebar\n outlineSidebar = new QWidget(this);\n outlineSidebar->setFixedWidth(250);\n outlineSidebar->setVisible(false); // Hidden by default\n \n QVBoxLayout *outlineLayout = new QVBoxLayout(outlineSidebar);\n outlineLayout->setContentsMargins(5, 5, 5, 5);\n \n QLabel *outlineLabel = new QLabel(tr(\"PDF Outline\"), outlineSidebar);\n outlineLabel->setStyleSheet(\"font-weight: bold; padding: 5px;\");\n outlineLayout->addWidget(outlineLabel);\n \n outlineTree = new QTreeWidget(outlineSidebar);\n outlineTree->setHeaderHidden(true);\n outlineTree->setRootIsDecorated(true);\n outlineTree->setIndentation(15);\n outlineLayout->addWidget(outlineTree);\n \n // Connect outline tree item clicks\n connect(outlineTree, &QTreeWidget::itemClicked, this, &MainWindow::onOutlineItemClicked);\n \n // 🌟 Bookmarks Sidebar\n bookmarksSidebar = new QWidget(this);\n bookmarksSidebar->setFixedWidth(250);\n bookmarksSidebar->setVisible(false); // Hidden by default\n \n QVBoxLayout *bookmarksLayout = new QVBoxLayout(bookmarksSidebar);\n bookmarksLayout->setContentsMargins(5, 5, 5, 5);\n \n QLabel *bookmarksLabel = new QLabel(tr(\"Bookmarks\"), bookmarksSidebar);\n bookmarksLabel->setStyleSheet(\"font-weight: bold; padding: 5px;\");\n bookmarksLayout->addWidget(bookmarksLabel);\n \n bookmarksTree = new QTreeWidget(bookmarksSidebar);\n bookmarksTree->setHeaderHidden(true);\n bookmarksTree->setRootIsDecorated(false);\n bookmarksTree->setIndentation(0);\n bookmarksLayout->addWidget(bookmarksTree);\n \n // Connect bookmarks tree item clicks\n connect(bookmarksTree, &QTreeWidget::itemClicked, this, &MainWindow::onBookmarkItemClicked);\n\n // 🌟 Horizontal Tab Bar (like modern web browsers)\n tabList = new QListWidget(this);\n tabList->setFlow(QListView::LeftToRight); // Make it horizontal\n tabList->setFixedHeight(32); // Increased to accommodate scrollbar below tabs\n tabList->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);\n tabList->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n tabList->setSelectionMode(QAbstractItemView::SingleSelection);\n\n // Style the tab bar like a modern browser with transparent scrollbar\n tabList->setStyleSheet(R\"(\n QListWidget {\n background-color: rgba(240, 240, 240, 255);\n border: none;\n border-bottom: 1px solid rgba(200, 200, 200, 255);\n outline: none;\n }\n QListWidget::item {\n background-color: rgba(220, 220, 220, 255);\n border: 1px solid rgba(180, 180, 180, 255);\n border-bottom: none;\n margin-right: 1px;\n margin-top: 2px;\n padding: 0px;\n min-width: 80px;\n max-width: 120px;\n }\n QListWidget::item:selected {\n background-color: white;\n border: 1px solid rgba(180, 180, 180, 255);\n border-bottom: 1px solid white;\n margin-top: 1px;\n }\n QListWidget::item:hover:!selected {\n background-color: rgba(230, 230, 230, 255);\n }\n QScrollBar:horizontal {\n background: rgba(240, 240, 240, 255);\n height: 8px;\n border: none;\n margin: 0px;\n border-top: 1px solid rgba(200, 200, 200, 255);\n }\n QScrollBar::handle:horizontal {\n background: rgba(150, 150, 150, 120);\n border-radius: 4px;\n min-width: 20px;\n margin: 1px;\n }\n QScrollBar::handle:horizontal:hover {\n background: rgba(120, 120, 120, 200);\n }\n QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal {\n width: 0px;\n height: 0px;\n background: none;\n border: none;\n }\n QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {\n background: transparent;\n }\n )\");\n\n // 🌟 Add Button for New Tab (styled like browser + button)\n addTabButton = new QPushButton(this);\n QIcon addTab(loadThemedIcon(\"addtab\")); // Path to your icon in resources\n addTabButton->setIcon(addTab);\n addTabButton->setFixedSize(30, 30); // Even smaller to match thinner layout\n addTabButton->setStyleSheet(R\"(\n QPushButton {\n background-color: rgba(220, 220, 220, 255);\n border: 1px solid rgba(180, 180, 180, 255);\n border-radius: 15px;\n margin: 2px;\n }\n QPushButton:hover {\n background-color: rgba(200, 200, 200, 255);\n }\n QPushButton:pressed {\n background-color: rgba(180, 180, 180, 255);\n }\n )\");\n addTabButton->setToolTip(tr(\"Add New Tab\"));\n connect(addTabButton, &QPushButton::clicked, this, &MainWindow::addNewTab);\n\n if (!canvasStack) {\n canvasStack = new QStackedWidget(this);\n }\n\n connect(tabList, &QListWidget::currentRowChanged, this, &MainWindow::switchTab);\n\n // Create horizontal tab container\n tabBarContainer = new QWidget(this);\n tabBarContainer->setObjectName(\"tabBarContainer\");\n tabBarContainer->setFixedHeight(38); // Increased to accommodate scrollbar below tabs\n \n QHBoxLayout *tabBarLayout = new QHBoxLayout(tabBarContainer);\n tabBarLayout->setContentsMargins(5, 5, 5, 5);\n tabBarLayout->setSpacing(5);\n tabBarLayout->addWidget(tabList, 1); // Tab list takes most space\n tabBarLayout->addWidget(addTabButton, 0); // Add button stays at the end\n\n connect(toggleTabBarButton, &QPushButton::clicked, this, [=]() {\n bool isVisible = tabBarContainer->isVisible();\n tabBarContainer->setVisible(!isVisible);\n \n // Update button toggle state\n toggleTabBarButton->setProperty(\"selected\", !isVisible);\n toggleTabBarButton->style()->unpolish(toggleTabBarButton);\n toggleTabBarButton->style()->polish(toggleTabBarButton);\n\n QTimer::singleShot(0, this, [this]() {\n if (auto *canvas = currentCanvas()) {\n canvas->setMaximumSize(canvas->getCanvasSize());\n }\n });\n });\n \n connect(toggleOutlineButton, &QPushButton::clicked, this, &MainWindow::toggleOutlineSidebar);\n connect(toggleBookmarksButton, &QPushButton::clicked, this, &MainWindow::toggleBookmarksSidebar);\n connect(toggleBookmarkButton, &QPushButton::clicked, this, &MainWindow::toggleCurrentPageBookmark);\n connect(touchGesturesButton, &QPushButton::clicked, this, [this]() {\n setTouchGesturesEnabled(!touchGesturesEnabled);\n touchGesturesButton->setProperty(\"selected\", touchGesturesEnabled);\n touchGesturesButton->style()->unpolish(touchGesturesButton);\n touchGesturesButton->style()->polish(touchGesturesButton);\n });\n\n \n\n\n // Previous page button\n prevPageButton = new QPushButton(this);\n prevPageButton->setFixedSize(26, 30);\n prevPageButton->setText(\"◀\");\n prevPageButton->setStyleSheet(buttonStyle);\n prevPageButton->setToolTip(tr(\"Previous Page\"));\n connect(prevPageButton, &QPushButton::clicked, this, &MainWindow::goToPreviousPage);\n\n pageInput = new QSpinBox(this);\n pageInput->setFixedSize(42, 30);\n pageInput->setMinimum(1);\n pageInput->setMaximum(9999);\n pageInput->setValue(1);\n pageInput->setMaximumWidth(100);\n connect(pageInput, QOverload::of(&QSpinBox::valueChanged), this, &MainWindow::onPageInputChanged);\n\n // Next page button\n nextPageButton = new QPushButton(this);\n nextPageButton->setFixedSize(26, 30);\n nextPageButton->setText(\"▶\");\n nextPageButton->setStyleSheet(buttonStyle);\n nextPageButton->setToolTip(tr(\"Next Page\"));\n connect(nextPageButton, &QPushButton::clicked, this, &MainWindow::goToNextPage);\n\n jumpToPageButton = new QPushButton(this);\n // QIcon jumpIcon(\":/resources/icons/bookpage.png\"); // Path to your icon in resources\n jumpToPageButton->setFixedSize(26, 30);\n jumpToPageButton->setStyleSheet(buttonStyle);\n jumpToPageButton->setIcon(loadThemedIcon(\"bookpage\"));\n connect(jumpToPageButton, &QPushButton::clicked, this, &MainWindow::showJumpToPageDialog);\n\n // ✅ Dial Toggle Button\n dialToggleButton = new QPushButton(this);\n dialToggleButton->setIcon(loadThemedIcon(\"dial\")); // Icon for dial\n dialToggleButton->setFixedSize(26, 30);\n dialToggleButton->setToolTip(tr(\"Toggle Magic Dial\"));\n dialToggleButton->setStyleSheet(buttonStyle);\n\n // ✅ Connect to toggle function\n connect(dialToggleButton, &QPushButton::clicked, this, &MainWindow::toggleDial);\n\n // toggleDial();\n\n \n\n fastForwardButton = new QPushButton(this);\n fastForwardButton->setFixedSize(26, 30);\n // QIcon ffIcon(\":/resources/icons/fastforward.png\"); // Path to your icon in resources\n fastForwardButton->setIcon(loadThemedIcon(\"fastforward\"));\n fastForwardButton->setToolTip(tr(\"Toggle Fast Forward 8x\"));\n fastForwardButton->setStyleSheet(buttonStyle);\n\n // ✅ Toggle fast-forward mode\n connect(fastForwardButton, &QPushButton::clicked, [this]() {\n fastForwardMode = !fastForwardMode;\n updateFastForwardButtonState();\n });\n\n QComboBox *dialModeSelector = new QComboBox(this);\n dialModeSelector->addItem(\"Page Switch\", PageSwitching);\n dialModeSelector->addItem(\"Zoom\", ZoomControl);\n dialModeSelector->addItem(\"Thickness\", ThicknessControl);\n\n dialModeSelector->addItem(\"Tool Switch\", ToolSwitching);\n dialModeSelector->setFixedWidth(120);\n\n connect(dialModeSelector, QOverload::of(&QComboBox::currentIndexChanged), this,\n [this](int index) { changeDialMode(static_cast(index)); });\n\n\n\n colorPreview = new QPushButton(this);\n colorPreview->setFixedSize(26, 30);\n colorPreview->setStyleSheet(\"border-radius: 15px; border: 1px solid gray;\");\n colorPreview->setEnabled(false); // ✅ Prevents it from being clicked\n\n btnPageSwitch = new QPushButton(loadThemedIcon(\"bookpage\"), \"\", this);\n btnPageSwitch->setStyleSheet(buttonStyle);\n btnPageSwitch->setFixedSize(26, 30);\n btnPageSwitch->setToolTip(tr(\"Set Dial Mode to Page Switching\"));\n btnZoom = new QPushButton(loadThemedIcon(\"zoom\"), \"\", this);\n btnZoom->setStyleSheet(buttonStyle);\n btnZoom->setFixedSize(26, 30);\n btnZoom->setToolTip(tr(\"Set Dial Mode to Zoom Ctrl\"));\n btnThickness = new QPushButton(loadThemedIcon(\"thickness\"), \"\", this);\n btnThickness->setStyleSheet(buttonStyle);\n btnThickness->setFixedSize(26, 30);\n btnThickness->setToolTip(tr(\"Set Dial Mode to Pen Tip Thickness Ctrl\"));\n\n btnTool = new QPushButton(loadThemedIcon(\"pen\"), \"\", this);\n btnTool->setStyleSheet(buttonStyle);\n btnTool->setFixedSize(26, 30);\n btnTool->setToolTip(tr(\"Set Dial Mode to Tool Switching\"));\n btnPresets = new QPushButton(loadThemedIcon(\"preset\"), \"\", this);\n btnPresets->setStyleSheet(buttonStyle);\n btnPresets->setFixedSize(26, 30);\n btnPresets->setToolTip(tr(\"Set Dial Mode to Color Preset Selection\"));\n btnPannScroll = new QPushButton(loadThemedIcon(\"scroll\"), \"\", this);\n btnPannScroll->setStyleSheet(buttonStyle);\n btnPannScroll->setFixedSize(26, 30);\n btnPannScroll->setToolTip(tr(\"Slide and turn pages with the dial\"));\n\n connect(btnPageSwitch, &QPushButton::clicked, this, [this]() { changeDialMode(PageSwitching); });\n connect(btnZoom, &QPushButton::clicked, this, [this]() { changeDialMode(ZoomControl); });\n connect(btnThickness, &QPushButton::clicked, this, [this]() { changeDialMode(ThicknessControl); });\n\n connect(btnTool, &QPushButton::clicked, this, [this]() { changeDialMode(ToolSwitching); });\n connect(btnPresets, &QPushButton::clicked, this, [this]() { changeDialMode(PresetSelection); }); \n connect(btnPannScroll, &QPushButton::clicked, this, [this]() { changeDialMode(PanAndPageScroll); });\n\n\n // ✅ Initialize color presets based on palette mode (will be updated after UI setup)\n colorPresets.enqueue(getDefaultPenColor());\n colorPresets.enqueue(QColor(\"#AA0000\")); // Temporary - will be updated later\n colorPresets.enqueue(QColor(\"#997700\"));\n colorPresets.enqueue(QColor(\"#0000AA\"));\n colorPresets.enqueue(QColor(\"#007700\"));\n colorPresets.enqueue(QColor(\"#000000\"));\n colorPresets.enqueue(QColor(\"#FFFFFF\"));\n\n // ✅ Button to add current color to presets\n addPresetButton = new QPushButton(loadThemedIcon(\"savepreset\"), \"\", this);\n addPresetButton->setStyleSheet(buttonStyle);\n addPresetButton->setToolTip(tr(\"Add Current Color to Presets\"));\n addPresetButton->setFixedSize(26, 30);\n connect(addPresetButton, &QPushButton::clicked, this, &MainWindow::addColorPreset);\n\n\n\n\n openControlPanelButton = new QPushButton(this);\n openControlPanelButton->setIcon(loadThemedIcon(\"settings\")); // Replace with your actual settings icon\n openControlPanelButton->setStyleSheet(buttonStyle);\n openControlPanelButton->setToolTip(tr(\"Open Control Panel\"));\n openControlPanelButton->setFixedSize(26, 30); // Adjust to match your other buttons\n\n connect(openControlPanelButton, &QPushButton::clicked, this, [=]() {\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n ControlPanelDialog dialog(this, canvas, this);\n dialog.exec(); // Modal\n }\n });\n\n openRecentNotebooksButton = new QPushButton(this); // Create button\n openRecentNotebooksButton->setIcon(loadThemedIcon(\"recent\")); // Replace with actual icon if available\n openRecentNotebooksButton->setStyleSheet(buttonStyle);\n openRecentNotebooksButton->setToolTip(tr(\"Open Recent Notebooks\"));\n openRecentNotebooksButton->setFixedSize(26, 30);\n connect(openRecentNotebooksButton, &QPushButton::clicked, this, &MainWindow::openRecentNotebooksDialog);\n\n customColorButton = new QPushButton(this);\n customColorButton->setFixedSize(62, 30);\n QColor initialColor = getDefaultPenColor(); // Theme-aware default color\n customColorButton->setText(initialColor.name().toUpper());\n\n if (currentCanvas()) {\n initialColor = currentCanvas()->getPenColor();\n }\n\n updateCustomColorButtonStyle(initialColor);\n\n QTimer::singleShot(0, this, [=]() {\n connect(customColorButton, &QPushButton::clicked, this, [=]() {\n if (!currentCanvas()) return;\n \n handleColorButtonClick();\n \n // Get the current custom color from the button text\n QString buttonText = customColorButton->text();\n QColor customColor(buttonText);\n \n // Check if the custom color is already the current pen color\n if (currentCanvas()->getPenColor() == customColor) {\n // Second click - show color picker dialog\n QColor chosen = QColorDialog::getColor(currentCanvas()->getPenColor(), this, \"Select Pen Color\");\n if (chosen.isValid()) {\n currentCanvas()->setPenColor(chosen);\n updateCustomColorButtonStyle(chosen);\n updateDialDisplay();\n updateColorButtonStates();\n }\n } else {\n // First click - apply the custom color\n currentCanvas()->setPenColor(customColor);\n updateDialDisplay();\n updateColorButtonStates();\n }\n });\n });\n\n QHBoxLayout *controlLayout = new QHBoxLayout;\n \n controlLayout->addWidget(toggleOutlineButton);\n controlLayout->addWidget(toggleBookmarksButton);\n controlLayout->addWidget(toggleBookmarkButton);\n controlLayout->addWidget(touchGesturesButton);\n controlLayout->addWidget(toggleTabBarButton);\n controlLayout->addWidget(selectFolderButton);\n\n controlLayout->addWidget(exportNotebookButton);\n controlLayout->addWidget(importNotebookButton);\n controlLayout->addWidget(loadPdfButton);\n controlLayout->addWidget(clearPdfButton);\n controlLayout->addWidget(pdfTextSelectButton);\n controlLayout->addWidget(backgroundButton);\n controlLayout->addWidget(saveButton);\n controlLayout->addWidget(saveAnnotatedButton);\n controlLayout->addWidget(openControlPanelButton);\n controlLayout->addWidget(openRecentNotebooksButton); // Add button to layout\n controlLayout->addWidget(redButton);\n controlLayout->addWidget(blueButton);\n controlLayout->addWidget(yellowButton);\n controlLayout->addWidget(greenButton);\n controlLayout->addWidget(blackButton);\n controlLayout->addWidget(whiteButton);\n controlLayout->addWidget(customColorButton);\n controlLayout->addWidget(straightLineToggleButton);\n controlLayout->addWidget(ropeToolButton); // Add rope tool button to layout\n controlLayout->addWidget(markdownButton); // Add markdown button to layout\n // controlLayout->addWidget(colorPreview);\n // controlLayout->addWidget(thicknessButton);\n // controlLayout->addWidget(jumpToPageButton);\n controlLayout->addWidget(dialToggleButton);\n controlLayout->addWidget(fastForwardButton);\n // controlLayout->addWidget(channelSelector);\n controlLayout->addWidget(btnPageSwitch);\n controlLayout->addWidget(btnPannScroll);\n controlLayout->addWidget(btnZoom);\n controlLayout->addWidget(btnThickness);\n\n controlLayout->addWidget(btnTool);\n controlLayout->addWidget(btnPresets);\n controlLayout->addWidget(addPresetButton);\n // controlLayout->addWidget(dialModeSelector);\n // controlLayout->addStretch();\n \n // controlLayout->addWidget(toolSelector);\n controlLayout->addWidget(fullscreenButton);\n // controlLayout->addWidget(zoomButton);\n controlLayout->addWidget(zoom50Button);\n controlLayout->addWidget(dezoomButton);\n controlLayout->addWidget(zoom200Button);\n controlLayout->addStretch();\n \n \n controlLayout->addWidget(prevPageButton);\n controlLayout->addWidget(pageInput);\n controlLayout->addWidget(nextPageButton);\n controlLayout->addWidget(benchmarkButton);\n controlLayout->addWidget(benchmarkLabel);\n controlLayout->addWidget(deletePageButton);\n \n \n \n controlBar = new QWidget; // Use member variable instead of local\n controlBar->setObjectName(\"controlBar\");\n // controlBar->setLayout(controlLayout); // Commented out - responsive layout will handle this\n controlBar->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);\n\n // Theme will be applied later in loadUserSettings -> updateTheme()\n controlBar->setStyleSheet(\"\");\n\n \n \n\n canvasStack = new QStackedWidget();\n canvasStack->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);\n\n // Create a container for the canvas and scrollbars with relative positioning\n QWidget *canvasContainer = new QWidget;\n QVBoxLayout *canvasLayout = new QVBoxLayout(canvasContainer);\n canvasLayout->setContentsMargins(0, 0, 0, 0);\n canvasLayout->addWidget(canvasStack);\n\n // Enable context menu for the workaround\n canvasContainer->setContextMenuPolicy(Qt::CustomContextMenu);\n \n // Set up the scrollbars to overlay the canvas\n panXSlider->setParent(canvasContainer);\n panYSlider->setParent(canvasContainer);\n \n // Raise scrollbars to ensure they're visible above the canvas\n panXSlider->raise();\n panYSlider->raise();\n \n // Handle scrollbar intersection\n connect(canvasContainer, &QWidget::customContextMenuRequested, this, [this]() {\n // This connection is just to make sure the container exists\n // and can receive signals - a workaround for some Qt versions\n });\n \n // Position the scrollbars at the bottom and right edges\n canvasContainer->installEventFilter(this);\n \n // Update scrollbar positions initially\n QTimer::singleShot(0, this, [this, canvasContainer]() {\n updateScrollbarPositions();\n });\n\n // Main layout: toolbar -> tab bar -> canvas (vertical stack)\n QWidget *container = new QWidget;\n container->setObjectName(\"container\");\n QVBoxLayout *mainLayout = new QVBoxLayout(container);\n mainLayout->setContentsMargins(0, 0, 0, 0); // ✅ Remove extra margins\n mainLayout->setSpacing(0); // ✅ Remove spacing between components\n \n // Add components in vertical order\n mainLayout->addWidget(controlBar); // Toolbar at top\n mainLayout->addWidget(tabBarContainer); // Tab bar below toolbar\n \n // Content area with sidebars and canvas\n QHBoxLayout *contentLayout = new QHBoxLayout;\n contentLayout->setContentsMargins(0, 0, 0, 0);\n contentLayout->setSpacing(0);\n contentLayout->addWidget(outlineSidebar, 0); // Fixed width outline sidebar\n contentLayout->addWidget(bookmarksSidebar, 0); // Fixed width bookmarks sidebar\n contentLayout->addWidget(canvasContainer, 1); // Canvas takes remaining space\n \n QWidget *contentWidget = new QWidget;\n contentWidget->setLayout(contentLayout);\n mainLayout->addWidget(contentWidget, 1);\n\n setCentralWidget(container);\n\n benchmarkTimer = new QTimer(this);\n connect(benchmarkButton, &QPushButton::clicked, this, &MainWindow::toggleBenchmark);\n connect(benchmarkTimer, &QTimer::timeout, this, &MainWindow::updateBenchmarkDisplay);\n\n QString tempDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\";\n QDir dir(tempDir);\n\n // Remove all contents (but keep the directory itself)\n if (dir.exists()) {\n dir.removeRecursively(); // Careful: this wipes everything inside\n }\n QDir().mkpath(tempDir); // Recreate clean directory\n\n addNewTab();\n\n // Initialize responsive toolbar layout\n createSingleRowLayout(); // Start with single row layout\n \n // Now that all UI components are created, update the color palette\n updateColorPalette();\n\n}\n void loadUserSettings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n\n // Load low-res toggle\n lowResPreviewEnabled = settings.value(\"lowResPreviewEnabled\", true).toBool();\n setLowResPreviewEnabled(lowResPreviewEnabled);\n\n \n zoomButtonsVisible = settings.value(\"zoomButtonsVisible\", true).toBool();\n setZoomButtonsVisible(zoomButtonsVisible);\n\n scrollOnTopEnabled = settings.value(\"scrollOnTopEnabled\", true).toBool();\n setScrollOnTopEnabled(scrollOnTopEnabled);\n\n touchGesturesEnabled = settings.value(\"touchGesturesEnabled\", true).toBool();\n setTouchGesturesEnabled(touchGesturesEnabled);\n \n // Update button visual state to match loaded setting\n touchGesturesButton->setProperty(\"selected\", touchGesturesEnabled);\n touchGesturesButton->style()->unpolish(touchGesturesButton);\n touchGesturesButton->style()->polish(touchGesturesButton);\n \n // Initialize default background settings if they don't exist\n if (!settings.contains(\"defaultBackgroundStyle\")) {\n saveDefaultBackgroundSettings(BackgroundStyle::Grid, Qt::white, 30);\n }\n \n // Load keyboard mappings\n loadKeyboardMappings();\n \n // Load theme settings\n loadThemeSettings();\n}\n bool scrollbarsVisible = false;\n QTimer *scrollbarHideTimer = nullptr;\n bool eventFilter(QObject *obj, QEvent *event) override {\n static bool dragging = false;\n static QPoint lastMousePos;\n static QTimer *longPressTimer = nullptr;\n\n // Handle IME focus events for text input widgets\n QLineEdit *lineEdit = qobject_cast(obj);\n if (lineEdit) {\n if (event->type() == QEvent::FocusIn) {\n // Ensure IME is enabled when text field gets focus\n lineEdit->setAttribute(Qt::WA_InputMethodEnabled, true);\n QInputMethod *inputMethod = QGuiApplication::inputMethod();\n if (inputMethod) {\n inputMethod->show();\n }\n }\n else if (event->type() == QEvent::FocusOut) {\n // Keep IME available but reset state\n QInputMethod *inputMethod = QGuiApplication::inputMethod();\n if (inputMethod) {\n inputMethod->reset();\n }\n }\n }\n\n // Handle resize events for canvas container\n QWidget *container = canvasStack ? canvasStack->parentWidget() : nullptr;\n if (obj == container && event->type() == QEvent::Resize) {\n updateScrollbarPositions();\n return false; // Let the event propagate\n }\n\n // Handle scrollbar visibility\n if (obj == panXSlider || obj == panYSlider) {\n if (event->type() == QEvent::Enter) {\n // Mouse entered scrollbar area\n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n return false;\n } \n else if (event->type() == QEvent::Leave) {\n // Mouse left scrollbar area - start timer to hide\n if (!scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->start();\n }\n return false;\n }\n }\n\n // Check if this is a canvas event for scrollbar handling\n InkCanvas* canvas = qobject_cast(obj);\n if (canvas) {\n // Handle mouse movement for scrollbar visibility\n if (event->type() == QEvent::MouseMove) {\n QMouseEvent* mouseEvent = static_cast(event);\n handleEdgeProximity(canvas, mouseEvent->pos());\n }\n // Handle tablet events for stylus hover (safely)\n else if (event->type() == QEvent::TabletMove) {\n try {\n QTabletEvent* tabletEvent = static_cast(event);\n handleEdgeProximity(canvas, tabletEvent->position().toPoint());\n } catch (...) {\n // Ignore tablet event errors to prevent crashes\n }\n }\n // Handle mouse button press events for forward/backward navigation\n else if (event->type() == QEvent::MouseButtonPress) {\n QMouseEvent* mouseEvent = static_cast(event);\n \n // Mouse button 4 (Back button) - Previous page\n if (mouseEvent->button() == Qt::BackButton) {\n if (prevPageButton) {\n prevPageButton->click();\n }\n return true; // Consume the event\n }\n // Mouse button 5 (Forward button) - Next page\n else if (mouseEvent->button() == Qt::ForwardButton) {\n if (nextPageButton) {\n nextPageButton->click();\n }\n return true; // Consume the event\n }\n }\n // Handle wheel events for scrolling\n else if (event->type() == QEvent::Wheel) {\n QWheelEvent* wheelEvent = static_cast(event);\n \n // Check if we need scrolling\n bool needHorizontalScroll = panXSlider->maximum() > 0;\n bool needVerticalScroll = panYSlider->maximum() > 0;\n \n // Handle vertical scrolling (Y axis)\n if (wheelEvent->angleDelta().y() != 0 && needVerticalScroll) {\n // Calculate scroll amount (negative because wheel up should scroll up)\n int scrollDelta = -wheelEvent->angleDelta().y() / 8; // Convert from 1/8 degree units\n scrollDelta = scrollDelta / 15; // Convert to steps (typical wheel step is 15 degrees)\n \n // Much faster base scroll speed - aim for ~3-5 scrolls to reach bottom\n int baseScrollAmount = panYSlider->maximum() / 8; // 1/8 of total range per scroll\n scrollDelta = scrollDelta * qMax(baseScrollAmount, 50); // Minimum 50 units per scroll\n \n // Apply the scroll\n int currentPan = panYSlider->value();\n int newPan = qBound(panYSlider->minimum(), currentPan + scrollDelta, panYSlider->maximum());\n panYSlider->setValue(newPan);\n \n // Show scrollbar temporarily\n panYSlider->setVisible(true);\n scrollbarsVisible = true;\n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n scrollbarHideTimer->start();\n \n // Consume the event\n return true;\n }\n \n // Handle horizontal scrolling (X axis) - for completeness\n if (wheelEvent->angleDelta().x() != 0 && needHorizontalScroll) {\n // Calculate scroll amount\n int scrollDelta = wheelEvent->angleDelta().x() / 8; // Convert from 1/8 degree units\n scrollDelta = scrollDelta / 15; // Convert to steps\n \n // Much faster base scroll speed - same logic as vertical\n int baseScrollAmount = panXSlider->maximum() / 8; // 1/8 of total range per scroll\n scrollDelta = scrollDelta * qMax(baseScrollAmount, 50); // Minimum 50 units per scroll\n \n // Apply the scroll\n int currentPan = panXSlider->value();\n int newPan = qBound(panXSlider->minimum(), currentPan + scrollDelta, panXSlider->maximum());\n panXSlider->setValue(newPan);\n \n // Show scrollbar temporarily\n panXSlider->setVisible(true);\n scrollbarsVisible = true;\n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n scrollbarHideTimer->start();\n \n // Consume the event\n return true;\n }\n \n // If no scrolling was needed, let the event propagate\n return false;\n }\n }\n\n // Handle dial container drag events\n if (obj == dialContainer) {\n if (event->type() == QEvent::MouseButtonPress) {\n QMouseEvent *mouseEvent = static_cast(event);\n lastMousePos = mouseEvent->globalPos();\n dragging = false;\n\n if (!longPressTimer) {\n longPressTimer = new QTimer(this);\n longPressTimer->setSingleShot(true);\n connect(longPressTimer, &QTimer::timeout, [this]() {\n dragging = true; // ✅ Allow movement after long press\n });\n }\n longPressTimer->start(1500); // ✅ Start long press timer (500ms)\n return true;\n }\n\n if (event->type() == QEvent::MouseMove && dragging) {\n QMouseEvent *mouseEvent = static_cast(event);\n QPoint delta = mouseEvent->globalPos() - lastMousePos;\n dialContainer->move(dialContainer->pos() + delta);\n lastMousePos = mouseEvent->globalPos();\n return true;\n }\n\n if (event->type() == QEvent::MouseButtonRelease) {\n if (longPressTimer) longPressTimer->stop();\n dragging = false; // ✅ Stop dragging on release\n return true;\n }\n }\n\n return QObject::eventFilter(obj, event);\n}\n void updateScrollbarPositions() {\n QWidget *container = canvasStack->parentWidget();\n if (!container || !panXSlider || !panYSlider) return;\n \n // Add small margins for better visibility\n const int margin = 3;\n \n // Get scrollbar dimensions\n const int scrollbarWidth = panYSlider->width();\n const int scrollbarHeight = panXSlider->height();\n \n // Calculate sizes based on container\n int containerWidth = container->width();\n int containerHeight = container->height();\n \n // Leave a bit of space for the corner\n int cornerOffset = 15;\n \n // Position horizontal scrollbar at top\n panXSlider->setGeometry(\n cornerOffset + margin, // Leave space at left corner\n margin,\n containerWidth - cornerOffset - margin*2, // Full width minus corner and right margin\n scrollbarHeight\n );\n \n // Position vertical scrollbar at left\n panYSlider->setGeometry(\n margin,\n cornerOffset + margin, // Leave space at top corner\n scrollbarWidth,\n containerHeight - cornerOffset - margin*2 // Full height minus corner and bottom margin\n );\n}\n void handleEdgeProximity(InkCanvas* canvas, const QPoint& pos) {\n if (!canvas) return;\n \n // Get canvas dimensions\n int canvasWidth = canvas->width();\n int canvasHeight = canvas->height();\n \n // Edge detection zones - show scrollbars when pointer is within 50px of edges\n bool nearLeftEdge = pos.x() < 25; // For vertical scrollbar\n bool nearTopEdge = pos.y() < 25; // For horizontal scrollbar - entire top edge\n \n // Only show scrollbars if canvas is larger than viewport\n bool needHorizontalScroll = panXSlider->maximum() > 0;\n bool needVerticalScroll = panYSlider->maximum() > 0;\n \n // Show/hide scrollbars based on pointer position\n if (nearLeftEdge && needVerticalScroll) {\n panYSlider->setVisible(true);\n scrollbarsVisible = true;\n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n scrollbarHideTimer->start();\n }\n \n if (nearTopEdge && needHorizontalScroll) {\n panXSlider->setVisible(true);\n scrollbarsVisible = true;\n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n scrollbarHideTimer->start();\n }\n}\n bool isToolbarTwoRows = false;\n QVBoxLayout *controlLayoutVertical = nullptr;\n QHBoxLayout *controlLayoutSingle = nullptr;\n QHBoxLayout *controlLayoutFirstRow = nullptr;\n QHBoxLayout *controlLayoutSecondRow = nullptr;\n void updateToolbarLayout() {\n // Calculate scaled width using device pixel ratio\n QScreen *screen = QGuiApplication::primaryScreen();\n // qreal dpr = screen ? screen->devicePixelRatio() : 1.0;\n int scaledWidth = width();\n \n // Dynamic threshold based on zoom button visibility\n int threshold = areZoomButtonsVisible() ? 1548 : 1438;\n \n // Debug output to understand what's happening\n // qDebug() << \"Window width:\" << scaledWidth << \"Threshold:\" << threshold << \"Zoom buttons visible:\" << areZoomButtonsVisible();\n \n bool shouldBeTwoRows = scaledWidth <= threshold;\n \n // qDebug() << \"Should be two rows:\" << shouldBeTwoRows << \"Currently is two rows:\" << isToolbarTwoRows;\n \n if (shouldBeTwoRows != isToolbarTwoRows) {\n isToolbarTwoRows = shouldBeTwoRows;\n \n // qDebug() << \"Switching to\" << (isToolbarTwoRows ? \"two rows\" : \"single row\");\n \n if (isToolbarTwoRows) {\n createTwoRowLayout();\n } else {\n createSingleRowLayout();\n }\n }\n}\n void createSingleRowLayout() {\n // Delete separator line if it exists (from previous 2-row layout)\n if (separatorLine) {\n delete separatorLine;\n separatorLine = nullptr;\n }\n \n // Create new single row layout first\n QHBoxLayout *newLayout = new QHBoxLayout;\n \n // Add all widgets to single row (same order as before)\n newLayout->addWidget(toggleTabBarButton);\n newLayout->addWidget(toggleOutlineButton);\n newLayout->addWidget(toggleBookmarksButton);\n newLayout->addWidget(toggleBookmarkButton);\n newLayout->addWidget(touchGesturesButton);\n newLayout->addWidget(selectFolderButton);\n newLayout->addWidget(exportNotebookButton);\n newLayout->addWidget(importNotebookButton);\n newLayout->addWidget(loadPdfButton);\n newLayout->addWidget(clearPdfButton);\n newLayout->addWidget(pdfTextSelectButton);\n newLayout->addWidget(backgroundButton);\n newLayout->addWidget(saveButton);\n newLayout->addWidget(saveAnnotatedButton);\n newLayout->addWidget(openControlPanelButton);\n newLayout->addWidget(openRecentNotebooksButton);\n newLayout->addWidget(redButton);\n newLayout->addWidget(blueButton);\n newLayout->addWidget(yellowButton);\n newLayout->addWidget(greenButton);\n newLayout->addWidget(blackButton);\n newLayout->addWidget(whiteButton);\n newLayout->addWidget(customColorButton);\n newLayout->addWidget(penToolButton);\n newLayout->addWidget(markerToolButton);\n newLayout->addWidget(eraserToolButton);\n newLayout->addWidget(straightLineToggleButton);\n newLayout->addWidget(ropeToolButton);\n newLayout->addWidget(markdownButton);\n newLayout->addWidget(dialToggleButton);\n newLayout->addWidget(fastForwardButton);\n newLayout->addWidget(btnPageSwitch);\n newLayout->addWidget(btnPannScroll);\n newLayout->addWidget(btnZoom);\n newLayout->addWidget(btnThickness);\n\n newLayout->addWidget(btnTool);\n newLayout->addWidget(btnPresets);\n newLayout->addWidget(addPresetButton);\n newLayout->addWidget(fullscreenButton);\n \n // Only add zoom buttons if they're visible\n if (areZoomButtonsVisible()) {\n newLayout->addWidget(zoom50Button);\n newLayout->addWidget(dezoomButton);\n newLayout->addWidget(zoom200Button);\n }\n \n newLayout->addStretch();\n newLayout->addWidget(prevPageButton);\n newLayout->addWidget(pageInput);\n newLayout->addWidget(nextPageButton);\n newLayout->addWidget(benchmarkButton);\n newLayout->addWidget(benchmarkLabel);\n newLayout->addWidget(deletePageButton);\n \n // Safely replace the layout\n QLayout* oldLayout = controlBar->layout();\n if (oldLayout) {\n // Remove all items from old layout (but don't delete widgets)\n QLayoutItem* item;\n while ((item = oldLayout->takeAt(0)) != nullptr) {\n // Just removing, not deleting widgets\n }\n delete oldLayout;\n }\n \n // Set the new layout\n controlBar->setLayout(newLayout);\n controlLayoutSingle = newLayout;\n \n // Clean up other layout pointers\n controlLayoutVertical = nullptr;\n controlLayoutFirstRow = nullptr;\n controlLayoutSecondRow = nullptr;\n \n // Update pan range after layout change\n updatePanRange();\n}\n void createTwoRowLayout() {\n // Create new layouts first\n QVBoxLayout *newVerticalLayout = new QVBoxLayout;\n QHBoxLayout *newFirstRowLayout = new QHBoxLayout;\n QHBoxLayout *newSecondRowLayout = new QHBoxLayout;\n \n // Add comfortable spacing and margins for 2-row layout\n newFirstRowLayout->setContentsMargins(8, 8, 8, 6); // More generous margins\n newFirstRowLayout->setSpacing(3); // Add spacing between buttons for less cramped feel\n newSecondRowLayout->setContentsMargins(8, 6, 8, 8); // More generous margins\n newSecondRowLayout->setSpacing(3); // Add spacing between buttons for less cramped feel\n \n // First row: up to customColorButton\n newFirstRowLayout->addWidget(toggleTabBarButton);\n newFirstRowLayout->addWidget(toggleOutlineButton);\n newFirstRowLayout->addWidget(toggleBookmarksButton);\n newFirstRowLayout->addWidget(toggleBookmarkButton);\n newFirstRowLayout->addWidget(touchGesturesButton);\n newFirstRowLayout->addWidget(selectFolderButton);\n newFirstRowLayout->addWidget(exportNotebookButton);\n newFirstRowLayout->addWidget(importNotebookButton);\n newFirstRowLayout->addWidget(loadPdfButton);\n newFirstRowLayout->addWidget(clearPdfButton);\n newFirstRowLayout->addWidget(pdfTextSelectButton);\n newFirstRowLayout->addWidget(backgroundButton);\n newFirstRowLayout->addWidget(saveButton);\n newFirstRowLayout->addWidget(saveAnnotatedButton);\n newFirstRowLayout->addWidget(openControlPanelButton);\n newFirstRowLayout->addWidget(openRecentNotebooksButton);\n newFirstRowLayout->addWidget(redButton);\n newFirstRowLayout->addWidget(blueButton);\n newFirstRowLayout->addWidget(yellowButton);\n newFirstRowLayout->addWidget(greenButton);\n newFirstRowLayout->addWidget(blackButton);\n newFirstRowLayout->addWidget(whiteButton);\n newFirstRowLayout->addWidget(customColorButton);\n newFirstRowLayout->addWidget(penToolButton);\n newFirstRowLayout->addWidget(markerToolButton);\n newFirstRowLayout->addWidget(eraserToolButton);\n newFirstRowLayout->addStretch();\n \n // Create a separator line\n if (!separatorLine) {\n separatorLine = new QFrame();\n separatorLine->setFrameShape(QFrame::HLine);\n separatorLine->setFrameShadow(QFrame::Sunken);\n separatorLine->setLineWidth(1);\n separatorLine->setStyleSheet(\"QFrame { color: rgba(255, 255, 255, 255); }\");\n }\n \n // Second row: everything after customColorButton\n newSecondRowLayout->addWidget(straightLineToggleButton);\n newSecondRowLayout->addWidget(ropeToolButton);\n newSecondRowLayout->addWidget(markdownButton);\n newSecondRowLayout->addWidget(dialToggleButton);\n newSecondRowLayout->addWidget(fastForwardButton);\n newSecondRowLayout->addWidget(btnPageSwitch);\n newSecondRowLayout->addWidget(btnPannScroll);\n newSecondRowLayout->addWidget(btnZoom);\n newSecondRowLayout->addWidget(btnThickness);\n\n newSecondRowLayout->addWidget(btnTool);\n newSecondRowLayout->addWidget(btnPresets);\n newSecondRowLayout->addWidget(addPresetButton);\n newSecondRowLayout->addWidget(fullscreenButton);\n \n // Only add zoom buttons if they're visible\n if (areZoomButtonsVisible()) {\n newSecondRowLayout->addWidget(zoom50Button);\n newSecondRowLayout->addWidget(dezoomButton);\n newSecondRowLayout->addWidget(zoom200Button);\n }\n \n newSecondRowLayout->addStretch();\n newSecondRowLayout->addWidget(prevPageButton);\n newSecondRowLayout->addWidget(pageInput);\n newSecondRowLayout->addWidget(nextPageButton);\n newSecondRowLayout->addWidget(benchmarkButton);\n newSecondRowLayout->addWidget(benchmarkLabel);\n newSecondRowLayout->addWidget(deletePageButton);\n \n // Add layouts to vertical layout with separator\n newVerticalLayout->addLayout(newFirstRowLayout);\n newVerticalLayout->addWidget(separatorLine);\n newVerticalLayout->addLayout(newSecondRowLayout);\n newVerticalLayout->setContentsMargins(0, 0, 0, 0);\n newVerticalLayout->setSpacing(0); // No spacing since we have our own separator\n \n // Safely replace the layout\n QLayout* oldLayout = controlBar->layout();\n if (oldLayout) {\n // Remove all items from old layout (but don't delete widgets)\n QLayoutItem* item;\n while ((item = oldLayout->takeAt(0)) != nullptr) {\n // Just removing, not deleting widgets\n }\n delete oldLayout;\n }\n \n // Set the new layout\n controlBar->setLayout(newVerticalLayout);\n controlLayoutVertical = newVerticalLayout;\n controlLayoutFirstRow = newFirstRowLayout;\n controlLayoutSecondRow = newSecondRowLayout;\n \n // Clean up other layout pointer\n controlLayoutSingle = nullptr;\n \n // Update pan range after layout change\n updatePanRange();\n}\n QString elideTabText(const QString &text, int maxWidth) {\n // Create a font metrics object using the default font\n QFontMetrics fontMetrics(QApplication::font());\n \n // Elide the text from the right (showing the beginning)\n return fontMetrics.elidedText(text, Qt::ElideRight, maxWidth);\n}\n QTimer *layoutUpdateTimer = nullptr;\n QFrame *separatorLine = nullptr;\n protected:\n void resizeEvent(QResizeEvent *event) override {\n QMainWindow::resizeEvent(event);\n \n // Use a timer to delay layout updates during resize to prevent excessive switching\n if (!layoutUpdateTimer) {\n layoutUpdateTimer = new QTimer(this);\n layoutUpdateTimer->setSingleShot(true);\n connect(layoutUpdateTimer, &QTimer::timeout, this, [this]() {\n updateToolbarLayout();\n // Also reposition dial after resize finishes\n if (dialContainer && dialContainer->isVisible()) {\n positionDialContainer();\n }\n });\n }\n \n layoutUpdateTimer->stop();\n layoutUpdateTimer->start(100); // Wait 100ms after resize stops\n}\n void keyPressEvent(QKeyEvent *event) override {\n // Don't intercept keyboard events when text input widgets have focus\n // This prevents conflicts with Windows TextInputFramework\n QWidget *focusWidget = QApplication::focusWidget();\n if (focusWidget) {\n bool isTextInputWidget = qobject_cast(focusWidget) || \n qobject_cast(focusWidget) || \n qobject_cast(focusWidget) ||\n qobject_cast(focusWidget) ||\n qobject_cast(focusWidget);\n \n if (isTextInputWidget) {\n // Let text input widgets handle their own keyboard events\n QMainWindow::keyPressEvent(event);\n return;\n }\n }\n \n // Don't intercept IME-related keyboard shortcuts\n // These are reserved for Windows Input Method Editor\n if (event->modifiers() & Qt::ControlModifier) {\n if (event->key() == Qt::Key_Space || // Ctrl+Space (IME toggle)\n event->key() == Qt::Key_Shift || // Ctrl+Shift (language switch)\n event->key() == Qt::Key_Alt) { // Ctrl+Alt (IME functions)\n // Let Windows handle IME shortcuts\n QMainWindow::keyPressEvent(event);\n return;\n }\n }\n \n // Don't intercept Shift+Alt (another common IME shortcut)\n if ((event->modifiers() & Qt::ShiftModifier) && (event->modifiers() & Qt::AltModifier)) {\n QMainWindow::keyPressEvent(event);\n return;\n }\n \n // Build key sequence string\n QStringList modifiers;\n \n if (event->modifiers() & Qt::ControlModifier) modifiers << \"Ctrl\";\n if (event->modifiers() & Qt::ShiftModifier) modifiers << \"Shift\";\n if (event->modifiers() & Qt::AltModifier) modifiers << \"Alt\";\n if (event->modifiers() & Qt::MetaModifier) modifiers << \"Meta\";\n \n QString keyString = QKeySequence(event->key()).toString();\n \n QString fullSequence;\n if (!modifiers.isEmpty()) {\n fullSequence = modifiers.join(\"+\") + \"+\" + keyString;\n } else {\n fullSequence = keyString;\n }\n \n // Check if this sequence is mapped\n if (keyboardMappings.contains(fullSequence)) {\n handleKeyboardShortcut(fullSequence);\n event->accept();\n return;\n }\n \n // If not handled, pass to parent\n QMainWindow::keyPressEvent(event);\n}\n void tabletEvent(QTabletEvent *event) override {\n // Since tablet tracking is disabled to prevent crashes, we now only handle\n // basic tablet events that come through when stylus is touching the surface\n if (!event) {\n return;\n }\n \n // Just pass tablet events to parent safely without custom hover handling\n // (hover tooltips will work through normal mouse events instead)\n try {\n QMainWindow::tabletEvent(event);\n } catch (...) {\n // Catch any exceptions and just accept the event\n event->accept();\n }\n}\n void inputMethodEvent(QInputMethodEvent *event) override {\n // Forward IME events to the focused widget\n QWidget *focusWidget = QApplication::focusWidget();\n if (focusWidget && focusWidget != this) {\n QApplication::sendEvent(focusWidget, event);\n event->accept();\n return;\n }\n \n // Default handling\n QMainWindow::inputMethodEvent(event);\n}\n QVariant inputMethodQuery(Qt::InputMethodQuery query) const override {\n // Forward IME queries to the focused widget\n QWidget *focusWidget = QApplication::focusWidget();\n if (focusWidget && focusWidget != this) {\n return focusWidget->inputMethodQuery(query);\n }\n \n // Default handling\n return QMainWindow::inputMethodQuery(query);\n}\n};"], ["/SpeedyNote/source/ControlPanelDialog.h", "class ControlPanelDialog {\n Q_OBJECT\n\npublic:\n explicit ControlPanelDialog(MainWindow *mainWindow, InkCanvas *targetCanvas, QWidget *parent = nullptr);\n private:\n void applyChanges() {\n if (!canvas) return;\n\n BackgroundStyle style = static_cast(\n styleCombo->currentData().toInt()\n );\n\n canvas->setBackgroundStyle(style);\n canvas->setBackgroundColor(selectedColor);\n canvas->setBackgroundDensity(densitySpin->value());\n canvas->update();\n canvas->saveBackgroundMetadata();\n\n // ✅ Save these settings as defaults for new tabs\n if (mainWindowRef) {\n mainWindowRef->saveDefaultBackgroundSettings(style, selectedColor, densitySpin->value());\n }\n\n // ✅ Apply button mappings back to MainWindow with internal keys\n if (mainWindowRef) {\n for (const QString &buttonKey : holdMappingCombos.keys()) {\n QString displayString = holdMappingCombos[buttonKey]->currentText();\n QString internalKey = ButtonMappingHelper::displayToInternalKey(displayString, true); // true = isDialMode\n mainWindowRef->setHoldMapping(buttonKey, internalKey);\n }\n for (const QString &buttonKey : pressMappingCombos.keys()) {\n QString displayString = pressMappingCombos[buttonKey]->currentText();\n QString internalKey = ButtonMappingHelper::displayToInternalKey(displayString, false); // false = isAction\n mainWindowRef->setPressMapping(buttonKey, internalKey);\n }\n\n // ✅ Save to persistent settings\n mainWindowRef->saveButtonMappings();\n \n // ✅ Apply theme settings\n mainWindowRef->setUseCustomAccentColor(useCustomAccentCheckbox->isChecked());\n if (selectedAccentColor.isValid()) {\n mainWindowRef->setCustomAccentColor(selectedAccentColor);\n }\n \n // ✅ Apply color palette setting\n mainWindowRef->setUseBrighterPalette(useBrighterPaletteCheckbox->isChecked());\n }\n}\n void chooseColor() {\n QColor chosen = QColorDialog::getColor(selectedColor, this, tr(\"Select Background Color\"));\n if (chosen.isValid()) {\n selectedColor = chosen;\n colorButton->setStyleSheet(QString(\"background-color: %1\").arg(selectedColor.name()));\n }\n}\n void addKeyboardMapping() {\n // Step 1: Capture key sequence\n KeyCaptureDialog captureDialog(this);\n if (captureDialog.exec() != QDialog::Accepted) {\n return;\n }\n \n QString keySequence = captureDialog.getCapturedKeySequence();\n if (keySequence.isEmpty()) {\n return;\n }\n \n // Check if key sequence already exists\n if (mainWindowRef && mainWindowRef->getKeyboardMappings().contains(keySequence)) {\n QMessageBox::warning(this, tr(\"Key Already Mapped\"), \n tr(\"The key sequence '%1' is already mapped. Please choose a different key combination.\").arg(keySequence));\n return;\n }\n \n // Step 2: Choose action\n QStringList actions = ButtonMappingHelper::getTranslatedActions();\n bool ok;\n QString selectedAction = QInputDialog::getItem(this, tr(\"Select Action\"), \n tr(\"Choose the action to perform when '%1' is pressed:\").arg(keySequence), \n actions, 0, false, &ok);\n \n if (!ok || selectedAction.isEmpty()) {\n return;\n }\n \n // Convert display name to internal key\n QString internalKey = ButtonMappingHelper::displayToInternalKey(selectedAction, false);\n \n // Add the mapping\n if (mainWindowRef) {\n mainWindowRef->addKeyboardMapping(keySequence, internalKey);\n \n // Update table\n int row = keyboardTable->rowCount();\n keyboardTable->insertRow(row);\n keyboardTable->setItem(row, 0, new QTableWidgetItem(keySequence));\n keyboardTable->setItem(row, 1, new QTableWidgetItem(selectedAction));\n }\n}\n void removeKeyboardMapping() {\n int currentRow = keyboardTable->currentRow();\n if (currentRow < 0) {\n QMessageBox::information(this, tr(\"No Selection\"), tr(\"Please select a mapping to remove.\"));\n return;\n }\n \n QTableWidgetItem *keyItem = keyboardTable->item(currentRow, 0);\n if (!keyItem) return;\n \n QString keySequence = keyItem->text();\n \n // Confirm removal\n int ret = QMessageBox::question(this, tr(\"Remove Mapping\"), \n tr(\"Are you sure you want to remove the keyboard shortcut '%1'?\").arg(keySequence),\n QMessageBox::Yes | QMessageBox::No, QMessageBox::No);\n \n if (ret == QMessageBox::Yes) {\n // Remove from MainWindow\n if (mainWindowRef) {\n mainWindowRef->removeKeyboardMapping(keySequence);\n }\n \n // Remove from table\n keyboardTable->removeRow(currentRow);\n }\n}\n void openControllerMapping() {\n if (!mainWindowRef) {\n QMessageBox::warning(this, tr(\"Error\"), tr(\"MainWindow reference not available.\"));\n return;\n }\n \n SDLControllerManager *controllerManager = mainWindowRef->getControllerManager();\n if (!controllerManager) {\n QMessageBox::warning(this, tr(\"Controller Not Available\"), \n tr(\"Controller manager is not available. Please ensure a controller is connected and restart the application.\"));\n return;\n }\n \n if (!controllerManager->getJoystick()) {\n QMessageBox::warning(this, tr(\"No Controller Detected\"), \n tr(\"No controller is currently connected. Please connect your controller and restart the application.\"));\n return;\n }\n \n ControllerMappingDialog dialog(controllerManager, this);\n dialog.exec();\n}\n void reconnectController() {\n if (!mainWindowRef) {\n QMessageBox::warning(this, tr(\"Error\"), tr(\"MainWindow reference not available.\"));\n return;\n }\n \n SDLControllerManager *controllerManager = mainWindowRef->getControllerManager();\n if (!controllerManager) {\n QMessageBox::warning(this, tr(\"Controller Not Available\"), \n tr(\"Controller manager is not available.\"));\n return;\n }\n \n // Show reconnecting message\n controllerStatusLabel->setText(tr(\"🔄 Reconnecting...\"));\n controllerStatusLabel->setStyleSheet(\"color: orange;\");\n \n // Force the UI to update immediately\n QApplication::processEvents();\n \n // Attempt to reconnect using thread-safe method\n QMetaObject::invokeMethod(controllerManager, \"reconnect\", Qt::BlockingQueuedConnection);\n \n // Update status after reconnection attempt\n updateControllerStatus();\n \n // Show result message\n if (controllerManager->getJoystick()) {\n // Reconnect the controller signals in MainWindow\n mainWindowRef->reconnectControllerSignals();\n \n QMessageBox::information(this, tr(\"Reconnection Successful\"), \n tr(\"Controller has been successfully reconnected!\"));\n } else {\n QMessageBox::warning(this, tr(\"Reconnection Failed\"), \n tr(\"Failed to reconnect controller. Please ensure your controller is powered on and in pairing mode, then try again.\"));\n }\n}\n private:\n InkCanvas *canvas;\n QTabWidget *tabWidget;\n QWidget *backgroundTab;\n QComboBox *styleCombo;\n QPushButton *colorButton;\n QSpinBox *densitySpin;\n QPushButton *applyButton;\n QPushButton *okButton;\n QPushButton *cancelButton;\n QColor selectedColor;\n void createBackgroundTab() {\n backgroundTab = new QWidget(this);\n\n QLabel *styleLabel = new QLabel(tr(\"Background Style:\"));\n styleCombo = new QComboBox();\n styleCombo->addItem(tr(\"None\"), static_cast(BackgroundStyle::None));\n styleCombo->addItem(tr(\"Grid\"), static_cast(BackgroundStyle::Grid));\n styleCombo->addItem(tr(\"Lines\"), static_cast(BackgroundStyle::Lines));\n\n QLabel *colorLabel = new QLabel(tr(\"Background Color:\"));\n colorButton = new QPushButton();\n connect(colorButton, &QPushButton::clicked, this, &ControlPanelDialog::chooseColor);\n\n QLabel *densityLabel = new QLabel(tr(\"Density:\"));\n densitySpin = new QSpinBox();\n densitySpin->setRange(10, 200);\n densitySpin->setSuffix(\" px\");\n densitySpin->setSingleStep(5);\n\n QGridLayout *layout = new QGridLayout(backgroundTab);\n layout->addWidget(styleLabel, 0, 0);\n layout->addWidget(styleCombo, 0, 1);\n layout->addWidget(colorLabel, 1, 0);\n layout->addWidget(colorButton, 1, 1);\n layout->addWidget(densityLabel, 2, 0);\n layout->addWidget(densitySpin, 2, 1);\n // layout->setColumnStretch(1, 1); // Stretch the second column\n layout->setRowStretch(3, 1); // Stretch the last row\n}\n void loadFromCanvas() {\n styleCombo->setCurrentIndex(static_cast(canvas->getBackgroundStyle()));\n densitySpin->setValue(canvas->getBackgroundDensity());\n selectedColor = canvas->getBackgroundColor();\n\n colorButton->setStyleSheet(QString(\"background-color: %1\").arg(selectedColor.name()));\n\n if (mainWindowRef) {\n for (const QString &buttonKey : holdMappingCombos.keys()) {\n QString internalKey = mainWindowRef->getHoldMapping(buttonKey);\n QString displayString = ButtonMappingHelper::internalKeyToDisplay(internalKey, true); // true = isDialMode\n int index = holdMappingCombos[buttonKey]->findText(displayString);\n if (index >= 0) holdMappingCombos[buttonKey]->setCurrentIndex(index);\n }\n\n for (const QString &buttonKey : pressMappingCombos.keys()) {\n QString internalKey = mainWindowRef->getPressMapping(buttonKey);\n QString displayString = ButtonMappingHelper::internalKeyToDisplay(internalKey, false); // false = isAction\n int index = pressMappingCombos[buttonKey]->findText(displayString);\n if (index >= 0) pressMappingCombos[buttonKey]->setCurrentIndex(index);\n }\n \n // Load theme settings\n useCustomAccentCheckbox->setChecked(mainWindowRef->isUsingCustomAccentColor());\n \n // Get the stored custom accent color\n selectedAccentColor = mainWindowRef->getCustomAccentColor();\n \n accentColorButton->setStyleSheet(QString(\"background-color: %1\").arg(selectedAccentColor.name()));\n accentColorButton->setEnabled(useCustomAccentCheckbox->isChecked());\n \n // Load color palette setting\n useBrighterPaletteCheckbox->setChecked(mainWindowRef->isUsingBrighterPalette());\n }\n}\n MainWindow *mainWindowRef;\n InkCanvas *canvasRef;\n QWidget *performanceTab;\n QWidget *toolbarTab;\n void createToolbarTab() {\n toolbarTab = new QWidget(this);\n QVBoxLayout *toolbarLayout = new QVBoxLayout(toolbarTab);\n\n // ✅ Checkbox to show/hide benchmark controls\n QCheckBox *benchmarkVisibilityCheckbox = new QCheckBox(tr(\"Show Benchmark Controls\"), toolbarTab);\n benchmarkVisibilityCheckbox->setChecked(mainWindowRef->areBenchmarkControlsVisible());\n toolbarLayout->addWidget(benchmarkVisibilityCheckbox);\n QLabel *benchmarkNote = new QLabel(tr(\"This will show/hide the benchmark controls on the toolbar. Press the clock button to start/stop the benchmark.\"));\n benchmarkNote->setWordWrap(true);\n benchmarkNote->setStyleSheet(\"color: gray; font-size: 10px;\");\n toolbarLayout->addWidget(benchmarkNote);\n\n // ✅ Checkbox to show/hide zoom buttons\n QCheckBox *zoomButtonsVisibilityCheckbox = new QCheckBox(tr(\"Show Zoom Buttons\"), toolbarTab);\n zoomButtonsVisibilityCheckbox->setChecked(mainWindowRef->areZoomButtonsVisible());\n toolbarLayout->addWidget(zoomButtonsVisibilityCheckbox);\n QLabel *zoomButtonsNote = new QLabel(tr(\"This will show/hide the 0.5x, 1x, and 2x zoom buttons on the toolbar\"));\n zoomButtonsNote->setWordWrap(true);\n zoomButtonsNote->setStyleSheet(\"color: gray; font-size: 10px;\");\n toolbarLayout->addWidget(zoomButtonsNote);\n\n QCheckBox *scrollOnTopCheckBox = new QCheckBox(tr(\"Scroll on Top after Page Switching\"), toolbarTab);\n scrollOnTopCheckBox->setChecked(mainWindowRef->isScrollOnTopEnabled());\n toolbarLayout->addWidget(scrollOnTopCheckBox);\n QLabel *scrollNote = new QLabel(tr(\"Enabling this will make the page scroll to the top after switching to a new page.\"));\n scrollNote->setWordWrap(true);\n scrollNote->setStyleSheet(\"color: gray; font-size: 10px;\");\n toolbarLayout->addWidget(scrollNote);\n \n toolbarLayout->addStretch();\n toolbarTab->setLayout(toolbarLayout);\n tabWidget->addTab(toolbarTab, tr(\"Features\"));\n\n\n // Connect the checkbox\n connect(benchmarkVisibilityCheckbox, &QCheckBox::toggled, mainWindowRef, &MainWindow::setBenchmarkControlsVisible);\n connect(zoomButtonsVisibilityCheckbox, &QCheckBox::toggled, mainWindowRef, &MainWindow::setZoomButtonsVisible);\n connect(scrollOnTopCheckBox, &QCheckBox::toggled, mainWindowRef, &MainWindow::setScrollOnTopEnabled);\n}\n void createPerformanceTab() {\n performanceTab = new QWidget();\n QVBoxLayout *layout = new QVBoxLayout(performanceTab);\n\n QCheckBox *previewToggle = new QCheckBox(tr(\"Enable Low-Resolution PDF Previews\"));\n previewToggle->setChecked(mainWindowRef->isLowResPreviewEnabled());\n\n connect(previewToggle, &QCheckBox::toggled, mainWindowRef, &MainWindow::setLowResPreviewEnabled);\n\n QLabel *note = new QLabel(tr(\"Disabling this may improve dial smoothness on low-end devices.\"));\n note->setWordWrap(true);\n note->setStyleSheet(\"color: gray; font-size: 10px;\");\n\n QLabel *dpiLabel = new QLabel(tr(\"PDF Rendering DPI:\"));\n QComboBox *dpiSelector = new QComboBox();\n dpiSelector->addItems({\"96\", \"192\", \"288\", \"384\", \"480\"});\n dpiSelector->setCurrentText(QString::number(mainWindowRef->getPdfDPI()));\n\n connect(dpiSelector, &QComboBox::currentTextChanged, this, [=](const QString &value) {\n mainWindowRef->setPdfDPI(value.toInt());\n });\n\n QLabel *notePDF = new QLabel(tr(\"Adjust how the PDF is rendered. Higher DPI means better quality but slower performance. DO NOT CHANGE THIS OPTION WHEN MULTIPLE TABS ARE OPEN. THIS MAY LEAD TO UNDEFINED BEHAVIOR!\"));\n notePDF->setWordWrap(true);\n notePDF->setStyleSheet(\"color: gray; font-size: 10px;\");\n\n\n layout->addWidget(previewToggle);\n layout->addWidget(note);\n layout->addWidget(dpiLabel);\n layout->addWidget(dpiSelector);\n layout->addWidget(notePDF);\n\n layout->addStretch();\n\n // return performanceTab;\n}\n QWidget *controllerMappingTab;\n QPushButton *reconnectButton;\n QLabel *controllerStatusLabel;\n QMap holdMappingCombos;\n QMap pressMappingCombos;\n void createButtonMappingTab() {\n QWidget *buttonTab = new QWidget(this);\n QVBoxLayout *layout = new QVBoxLayout(buttonTab);\n\n QStringList buttonKeys = ButtonMappingHelper::getInternalButtonKeys();\n QStringList buttonDisplayNames = ButtonMappingHelper::getTranslatedButtons();\n QStringList dialModes = ButtonMappingHelper::getTranslatedDialModes();\n QStringList actions = ButtonMappingHelper::getTranslatedActions();\n\n for (int i = 0; i < buttonKeys.size(); ++i) {\n const QString &buttonKey = buttonKeys[i];\n const QString &buttonDisplayName = buttonDisplayNames[i];\n \n QHBoxLayout *h = new QHBoxLayout();\n h->addWidget(new QLabel(buttonDisplayName)); // Use translated button name\n\n QComboBox *holdCombo = new QComboBox();\n holdCombo->addItems(dialModes); // Add translated dial mode names\n holdMappingCombos[buttonKey] = holdCombo;\n h->addWidget(new QLabel(tr(\"Hold:\")));\n h->addWidget(holdCombo);\n\n QComboBox *pressCombo = new QComboBox();\n pressCombo->addItems(actions); // Add translated action names\n pressMappingCombos[buttonKey] = pressCombo;\n h->addWidget(new QLabel(tr(\"Press:\")));\n h->addWidget(pressCombo);\n\n layout->addLayout(h);\n }\n\n layout->addStretch();\n buttonTab->setLayout(layout);\n tabWidget->addTab(buttonTab, tr(\"Button Mapping\"));\n}\n void createControllerMappingTab() {\n controllerMappingTab = new QWidget(this);\n QVBoxLayout *layout = new QVBoxLayout(controllerMappingTab);\n \n // Instructions\n QLabel *instructionLabel = new QLabel(tr(\"Configure physical controller button mappings for your Joy-Con or other controller:\"), controllerMappingTab);\n instructionLabel->setWordWrap(true);\n layout->addWidget(instructionLabel);\n \n QLabel *noteLabel = new QLabel(tr(\"Note: This maps your physical controller buttons to the logical Joy-Con functions used by the application. \"\n \"After setting up the physical mapping, you can configure what actions each logical button performs in the 'Button Mapping' tab.\"), controllerMappingTab);\n noteLabel->setWordWrap(true);\n noteLabel->setStyleSheet(\"color: gray; font-size: 10px; margin-bottom: 10px;\");\n layout->addWidget(noteLabel);\n \n // Button to open controller mapping dialog\n QPushButton *openMappingButton = new QPushButton(tr(\"Configure Controller Mapping\"), controllerMappingTab);\n openMappingButton->setMinimumHeight(40);\n connect(openMappingButton, &QPushButton::clicked, this, &ControlPanelDialog::openControllerMapping);\n layout->addWidget(openMappingButton);\n \n // Button to reconnect controller\n reconnectButton = new QPushButton(tr(\"Reconnect Controller\"), controllerMappingTab);\n reconnectButton->setMinimumHeight(40);\n reconnectButton->setStyleSheet(\"QPushButton { background-color: #4CAF50; color: white; font-weight: bold; }\");\n connect(reconnectButton, &QPushButton::clicked, this, &ControlPanelDialog::reconnectController);\n layout->addWidget(reconnectButton);\n \n // Status information\n QLabel *statusLabel = new QLabel(tr(\"Current controller status:\"), controllerMappingTab);\n statusLabel->setStyleSheet(\"font-weight: bold; margin-top: 20px;\");\n layout->addWidget(statusLabel);\n \n // Dynamic status label\n controllerStatusLabel = new QLabel(controllerMappingTab);\n updateControllerStatus();\n layout->addWidget(controllerStatusLabel);\n \n layout->addStretch();\n \n tabWidget->addTab(controllerMappingTab, tr(\"Controller Mapping\"));\n}\n void createKeyboardMappingTab() {\n keyboardTab = new QWidget(this);\n QVBoxLayout *layout = new QVBoxLayout(keyboardTab);\n \n // Instructions\n QLabel *instructionLabel = new QLabel(tr(\"Configure custom keyboard shortcuts for application actions:\"), keyboardTab);\n instructionLabel->setWordWrap(true);\n layout->addWidget(instructionLabel);\n \n // Table to show current mappings\n keyboardTable = new QTableWidget(0, 2, keyboardTab);\n keyboardTable->setHorizontalHeaderLabels({tr(\"Key Sequence\"), tr(\"Action\")});\n keyboardTable->horizontalHeader()->setStretchLastSection(true);\n keyboardTable->setSelectionBehavior(QAbstractItemView::SelectRows);\n keyboardTable->setEditTriggers(QAbstractItemView::NoEditTriggers);\n layout->addWidget(keyboardTable);\n \n // Buttons\n QHBoxLayout *buttonLayout = new QHBoxLayout();\n addKeyboardMappingButton = new QPushButton(tr(\"Add Mapping\"), keyboardTab);\n removeKeyboardMappingButton = new QPushButton(tr(\"Remove Mapping\"), keyboardTab);\n \n buttonLayout->addWidget(addKeyboardMappingButton);\n buttonLayout->addWidget(removeKeyboardMappingButton);\n buttonLayout->addStretch();\n \n layout->addLayout(buttonLayout);\n \n // Connections\n connect(addKeyboardMappingButton, &QPushButton::clicked, this, &ControlPanelDialog::addKeyboardMapping);\n connect(removeKeyboardMappingButton, &QPushButton::clicked, this, &ControlPanelDialog::removeKeyboardMapping);\n \n // Load current mappings\n if (mainWindowRef) {\n QMap mappings = mainWindowRef->getKeyboardMappings();\n keyboardTable->setRowCount(mappings.size());\n int row = 0;\n for (auto it = mappings.begin(); it != mappings.end(); ++it) {\n keyboardTable->setItem(row, 0, new QTableWidgetItem(it.key()));\n QString displayAction = ButtonMappingHelper::internalKeyToDisplay(it.value(), false);\n keyboardTable->setItem(row, 1, new QTableWidgetItem(displayAction));\n row++;\n }\n }\n \n tabWidget->addTab(keyboardTab, tr(\"Keyboard Shortcuts\"));\n}\n QWidget *keyboardTab;\n QTableWidget *keyboardTable;\n QPushButton *addKeyboardMappingButton;\n QPushButton *removeKeyboardMappingButton;\n QWidget *themeTab;\n QCheckBox *useCustomAccentCheckbox;\n QPushButton *accentColorButton;\n QColor selectedAccentColor;\n QCheckBox *useBrighterPaletteCheckbox;\n void createThemeTab() {\n themeTab = new QWidget(this);\n QVBoxLayout *layout = new QVBoxLayout(themeTab);\n \n // Custom accent color\n useCustomAccentCheckbox = new QCheckBox(tr(\"Use Custom Accent Color\"), themeTab);\n layout->addWidget(useCustomAccentCheckbox);\n \n QLabel *accentColorLabel = new QLabel(tr(\"Accent Color:\"), themeTab);\n accentColorButton = new QPushButton(themeTab);\n accentColorButton->setFixedSize(100, 30);\n connect(accentColorButton, &QPushButton::clicked, this, &ControlPanelDialog::chooseAccentColor);\n \n QHBoxLayout *accentColorLayout = new QHBoxLayout();\n accentColorLayout->addWidget(accentColorLabel);\n accentColorLayout->addWidget(accentColorButton);\n accentColorLayout->addStretch();\n layout->addLayout(accentColorLayout);\n \n QLabel *accentColorNote = new QLabel(tr(\"When enabled, use a custom accent color instead of the system accent color for the toolbar, dial, and tab selection.\"));\n accentColorNote->setWordWrap(true);\n accentColorNote->setStyleSheet(\"color: gray; font-size: 10px;\");\n layout->addWidget(accentColorNote);\n \n // Enable/disable accent color button based on checkbox\n connect(useCustomAccentCheckbox, &QCheckBox::toggled, accentColorButton, &QPushButton::setEnabled);\n connect(useCustomAccentCheckbox, &QCheckBox::toggled, accentColorLabel, &QLabel::setEnabled);\n \n // Color palette preference\n useBrighterPaletteCheckbox = new QCheckBox(tr(\"Use Brighter Color Palette\"), themeTab);\n layout->addWidget(useBrighterPaletteCheckbox);\n \n QLabel *paletteNote = new QLabel(tr(\"When enabled, use brighter colors (good for dark PDF backgrounds). When disabled, use darker colors (good for light PDF backgrounds). This setting is independent of the UI theme.\"));\n paletteNote->setWordWrap(true);\n paletteNote->setStyleSheet(\"color: gray; font-size: 10px;\");\n layout->addWidget(paletteNote);\n \n layout->addStretch();\n \n tabWidget->addTab(themeTab, tr(\"Theme\"));\n}\n void chooseAccentColor() {\n QColor chosen = QColorDialog::getColor(selectedAccentColor, this, tr(\"Select Accent Color\"));\n if (chosen.isValid()) {\n selectedAccentColor = chosen;\n accentColorButton->setStyleSheet(QString(\"background-color: %1\").arg(selectedAccentColor.name()));\n }\n}\n void updateControllerStatus() {\n if (!mainWindowRef || !controllerStatusLabel) return;\n \n SDLControllerManager *controllerManager = mainWindowRef->getControllerManager();\n if (!controllerManager) {\n controllerStatusLabel->setText(tr(\"✗ Controller manager not available\"));\n controllerStatusLabel->setStyleSheet(\"color: red;\");\n return;\n }\n \n if (controllerManager->getJoystick()) {\n controllerStatusLabel->setText(tr(\"✓ Controller connected\"));\n controllerStatusLabel->setStyleSheet(\"color: green; font-weight: bold;\");\n } else {\n controllerStatusLabel->setText(tr(\"✗ No controller detected\"));\n controllerStatusLabel->setStyleSheet(\"color: red; font-weight: bold;\");\n }\n}\n};"], ["/SpeedyNote/source/PdfOpenDialog.h", "class PdfOpenDialog {\n Q_OBJECT\n\npublic:\n enum Result {\n Cancel,\n CreateNewFolder,\n UseExistingFolder\n };\n explicit PdfOpenDialog(const QString &pdfPath, QWidget *parent = nullptr) {\n setWindowTitle(tr(\"Open PDF with SpeedyNote\"));\n setWindowIcon(QIcon(\":/resources/icons/mainicon.png\"));\n setModal(true);\n \n // Remove setFixedSize and use proper size management instead\n // Calculate size based on DPI\n QScreen *screen = QGuiApplication::primaryScreen();\n qreal dpr = screen ? screen->devicePixelRatio() : 1.0;\n \n // Set minimum and maximum sizes instead of fixed size\n int baseWidth = 500;\n int baseHeight = 200;\n \n // Scale sizes appropriately for DPI\n int scaledWidth = static_cast(baseWidth * qMax(1.0, dpr * 0.8));\n int scaledHeight = static_cast(baseHeight * qMax(1.0, dpr * 0.8));\n \n setMinimumSize(scaledWidth, scaledHeight);\n setMaximumSize(scaledWidth + 100, scaledHeight + 50); // Allow some flexibility\n \n // Set size policy to prevent unwanted resizing\n setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);\n \n setupUI();\n \n // Ensure the dialog is properly sized after UI setup\n adjustSize();\n \n // Center the dialog on parent or screen\n if (parent) {\n move(parent->geometry().center() - rect().center());\n } else {\n move(screen->geometry().center() - rect().center());\n }\n}\n static bool hasValidNotebookFolder(const QString &pdfPath, QString &folderPath) {\n QFileInfo fileInfo(pdfPath);\n QString suggestedFolderName = fileInfo.baseName(); // Filename without extension\n QString pdfDir = fileInfo.absolutePath(); // Directory containing the PDF\n QString potentialFolderPath = pdfDir + \"/\" + suggestedFolderName;\n \n if (isValidNotebookFolder(potentialFolderPath, pdfPath)) {\n folderPath = potentialFolderPath;\n return true;\n }\n \n return false;\n}\n protected:\n void resizeEvent(QResizeEvent *event) override {\n // Handle resize events smoothly to prevent jitter during window dragging\n if (event->size() != event->oldSize()) {\n // Only process if size actually changed\n QDialog::resizeEvent(event);\n \n // Ensure the dialog stays within reasonable bounds\n QSize newSize = event->size();\n QSize minSize = minimumSize();\n QSize maxSize = maximumSize();\n \n // Clamp the size to prevent unwanted resizing\n newSize = newSize.expandedTo(minSize).boundedTo(maxSize);\n \n if (newSize != event->size()) {\n // If size needs to be adjusted, do it without triggering another resize event\n resize(newSize);\n }\n } else {\n // If size hasn't changed, just call parent implementation\n QDialog::resizeEvent(event);\n }\n}\n private:\n void onCreateNewFolder() {\n QFileInfo fileInfo(pdfPath);\n QString suggestedFolderName = fileInfo.baseName();\n \n // Get the directory where the PDF is located\n QString pdfDir = fileInfo.absolutePath();\n QString newFolderPath = pdfDir + \"/\" + suggestedFolderName;\n \n // Check if folder already exists\n if (QDir(newFolderPath).exists()) {\n QMessageBox::StandardButton reply = QMessageBox::question(\n this, \n tr(\"Folder Exists\"), \n tr(\"A folder named \\\"%1\\\" already exists in the same directory as the PDF.\\n\\nDo you want to use this existing folder?\").arg(suggestedFolderName),\n QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel\n );\n \n if (reply == QMessageBox::Yes) {\n selectedFolder = newFolderPath;\n result = UseExistingFolder;\n accept();\n return;\n } else if (reply == QMessageBox::Cancel) {\n return; // Stay in dialog\n }\n // If No, continue to create with different name\n \n // Try to create with incremented name\n int counter = 1;\n do {\n newFolderPath = pdfDir + \"/\" + suggestedFolderName + QString(\"_%1\").arg(counter);\n counter++;\n } while (QDir(newFolderPath).exists() && counter < 100);\n \n if (counter >= 100) {\n QMessageBox::warning(this, tr(\"Error\"), tr(\"Could not create a unique folder name.\"));\n return;\n }\n }\n \n // Create the new folder\n QDir dir;\n if (dir.mkpath(newFolderPath)) {\n selectedFolder = newFolderPath;\n result = CreateNewFolder;\n accept();\n } else {\n QMessageBox::warning(this, tr(\"Error\"), tr(\"Failed to create folder: %1\").arg(newFolderPath));\n }\n}\n void onUseExistingFolder() {\n QString folder = QFileDialog::getExistingDirectory(\n this, \n tr(\"Select Existing Notebook Folder\"), \n QFileInfo(pdfPath).absolutePath()\n );\n \n if (!folder.isEmpty()) {\n selectedFolder = folder;\n result = UseExistingFolder;\n accept();\n }\n}\n void onCancel() {\n result = Cancel;\n reject();\n}\n private:\n void setupUI() {\n QVBoxLayout *mainLayout = new QVBoxLayout(this);\n mainLayout->setSpacing(15);\n mainLayout->setContentsMargins(20, 20, 20, 20);\n \n // Set layout size constraint to prevent unwanted resizing\n mainLayout->setSizeConstraint(QLayout::SetMinAndMaxSize);\n \n // Icon and title\n QHBoxLayout *headerLayout = new QHBoxLayout();\n headerLayout->setSpacing(10);\n \n QLabel *iconLabel = new QLabel();\n QPixmap icon = QIcon(\":/resources/icons/mainicon.png\").pixmap(48, 48);\n iconLabel->setPixmap(icon);\n iconLabel->setFixedSize(48, 48);\n iconLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);\n \n QLabel *titleLabel = new QLabel(tr(\"Open PDF with SpeedyNote\"));\n titleLabel->setStyleSheet(\"font-size: 16px; font-weight: bold;\");\n titleLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);\n \n headerLayout->addWidget(iconLabel);\n headerLayout->addWidget(titleLabel);\n headerLayout->addStretch();\n \n mainLayout->addLayout(headerLayout);\n \n // PDF file info\n QFileInfo fileInfo(pdfPath);\n QString fileName = fileInfo.fileName();\n QString folderName = fileInfo.baseName(); // Filename without extension\n \n QLabel *messageLabel = new QLabel(tr(\"PDF File: %1\\n\\nHow would you like to open this PDF?\").arg(fileName));\n messageLabel->setWordWrap(true);\n messageLabel->setStyleSheet(\"font-size: 12px; color: #666;\");\n messageLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);\n \n mainLayout->addWidget(messageLabel);\n \n // Buttons\n QVBoxLayout *buttonLayout = new QVBoxLayout();\n buttonLayout->setSpacing(10);\n \n // Create new folder button\n QPushButton *createFolderBtn = new QPushButton(tr(\"Create New Notebook Folder (\\\"%1\\\")\").arg(folderName));\n createFolderBtn->setIcon(QApplication::style()->standardIcon(QStyle::SP_DirIcon));\n createFolderBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);\n createFolderBtn->setMinimumHeight(40);\n createFolderBtn->setStyleSheet(R\"(\n QPushButton {\n text-align: left;\n padding: 10px;\n border: 1px solid palette(mid);\n border-radius: 5px;\n background: palette(button);\n }\n QPushButton:hover {\n background: palette(light);\n border-color: palette(dark);\n }\n QPushButton:pressed {\n background: palette(midlight);\n }\n )\");\n connect(createFolderBtn, &QPushButton::clicked, this, &PdfOpenDialog::onCreateNewFolder);\n \n // Use existing folder button\n QPushButton *existingFolderBtn = new QPushButton(tr(\"Use Existing Notebook Folder...\"));\n existingFolderBtn->setIcon(QApplication::style()->standardIcon(QStyle::SP_DirOpenIcon));\n existingFolderBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);\n existingFolderBtn->setMinimumHeight(40);\n existingFolderBtn->setStyleSheet(R\"(\n QPushButton {\n text-align: left;\n padding: 10px;\n border: 1px solid palette(mid);\n border-radius: 5px;\n background: palette(button);\n }\n QPushButton:hover {\n background: palette(light);\n border-color: palette(dark);\n }\n QPushButton:pressed {\n background: palette(midlight);\n }\n )\");\n connect(existingFolderBtn, &QPushButton::clicked, this, &PdfOpenDialog::onUseExistingFolder);\n \n buttonLayout->addWidget(createFolderBtn);\n buttonLayout->addWidget(existingFolderBtn);\n \n mainLayout->addLayout(buttonLayout);\n \n // Cancel button\n QHBoxLayout *cancelLayout = new QHBoxLayout();\n cancelLayout->addStretch();\n \n QPushButton *cancelBtn = new QPushButton(tr(\"Cancel\"));\n cancelBtn->setIcon(QApplication::style()->standardIcon(QStyle::SP_DialogCancelButton));\n cancelBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);\n cancelBtn->setMinimumSize(80, 30);\n cancelBtn->setStyleSheet(R\"(\n QPushButton {\n padding: 8px 20px;\n border: 1px solid palette(mid);\n border-radius: 3px;\n background: palette(button);\n }\n QPushButton:hover {\n background: palette(light);\n }\n QPushButton:pressed {\n background: palette(midlight);\n }\n )\");\n connect(cancelBtn, &QPushButton::clicked, this, &PdfOpenDialog::onCancel);\n \n cancelLayout->addWidget(cancelBtn);\n mainLayout->addLayout(cancelLayout);\n}\n static bool isValidNotebookFolder(const QString &folderPath, const QString &pdfPath) {\n QDir folder(folderPath);\n if (!folder.exists()) {\n return false;\n }\n \n // Priority 1: Check for .pdf_path.txt file with matching PDF path\n QString pdfPathFile = folderPath + \"/.pdf_path.txt\";\n if (QFile::exists(pdfPathFile)) {\n QFile file(pdfPathFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString storedPdfPath = in.readLine().trimmed();\n file.close();\n \n if (!storedPdfPath.isEmpty()) {\n // Compare absolute paths to handle relative path differences\n QFileInfo currentPdf(pdfPath);\n QFileInfo storedPdf(storedPdfPath);\n \n // Check if the stored PDF file still exists and matches\n if (storedPdf.exists() && \n currentPdf.absoluteFilePath() == storedPdf.absoluteFilePath()) {\n return true;\n }\n }\n }\n }\n \n // Priority 2: Check for .notebook_id.txt file (SpeedyNote notebook folder)\n QString notebookIdFile = folderPath + \"/.notebook_id.txt\";\n if (QFile::exists(notebookIdFile)) {\n // Additional check: ensure this folder has some notebook content\n QStringList contentFiles = folder.entryList(\n QStringList() << \"*.png\" << \".pdf_path.txt\" << \".bookmarks.txt\" << \".background_config.txt\", \n QDir::Files\n );\n \n // If it has notebook-related files, it's likely a valid SpeedyNote folder\n // but not necessarily for this specific PDF\n if (!contentFiles.isEmpty()) {\n // This is a SpeedyNote notebook, but for a different PDF\n // Return false so the user gets the dialog to choose what to do\n return false;\n }\n }\n \n return false;\n}\n Result result;\n QString selectedFolder;\n QString pdfPath;\n};"], ["/SpeedyNote/source/InkCanvas.h", "class MarkdownWindowManager {\n Q_OBJECT\n\nsignals:\n void zoomChanged(int newZoom);\n void panChanged(int panX, int panY);\n void touchGestureEnded();\n void ropeSelectionCompleted(const QPoint &position);\n void pdfLinkClicked(int targetPage);\n void pdfTextSelected(const QString &text);\n void pdfLoaded();\n void markdownSelectionModeChanged(bool enabled);\n public:\n explicit InkCanvas(QWidget *parent = nullptr) { \n \n // Set theme-aware default pen color\n MainWindow *mainWindow = qobject_cast(parent);\n if (mainWindow) {\n penColor = mainWindow->getDefaultPenColor();\n } \n setAttribute(Qt::WA_StaticContents);\n setTabletTracking(true);\n setAttribute(Qt::WA_AcceptTouchEvents); // Enable touch events\n\n // Enable immediate updates for smoother animation\n setAttribute(Qt::WA_OpaquePaintEvent);\n setAttribute(Qt::WA_NoSystemBackground);\n \n // Detect screen resolution and set canvas size\n QScreen *screen = QGuiApplication::primaryScreen();\n if (screen) {\n QSize logicalSize = screen->availableGeometry().size() * 0.89;\n setMaximumSize(logicalSize); // Optional\n setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);\n } else {\n setFixedSize(1920, 1080); // Fallback size\n }\n \n initializeBuffer();\n QCache pdfCache(10);\n pdfCache.setMaxCost(10); // ✅ Ensures the cache holds at most 5 pages\n // No need to set auto-delete, QCache will handle deletion automatically\n \n // Initialize PDF text selection throttling timer (60 FPS = ~16.67ms)\n pdfTextSelectionTimer = new QTimer(this);\n pdfTextSelectionTimer->setSingleShot(true);\n pdfTextSelectionTimer->setInterval(16); // ~60 FPS\n connect(pdfTextSelectionTimer, &QTimer::timeout, this, &InkCanvas::processPendingTextSelection);\n \n // Initialize PDF cache timer (will be created on-demand)\n pdfCacheTimer = nullptr;\n currentCachedPage = -1;\n \n // Initialize note page cache system\n noteCache.setMaxCost(15); // Cache up to 15 note pages (more than PDF since they're smaller)\n noteCacheTimer = nullptr;\n currentCachedNotePage = -1;\n \n // Initialize markdown manager\n markdownManager = new MarkdownWindowManager(this, this);\n \n // Connect pan/zoom signals to update markdown window positions\n connect(this, &InkCanvas::panChanged, markdownManager, &MarkdownWindowManager::updateAllWindowPositions);\n connect(this, &InkCanvas::zoomChanged, markdownManager, &MarkdownWindowManager::updateAllWindowPositions);\n}\n virtual ~InkCanvas() {\n // Cleanup if needed\n}\n void startBenchmark() {\n benchmarking = true;\n processedTimestamps.clear();\n benchmarkTimer.start();\n}\n void stopBenchmark() {\n benchmarking = false;\n}\n int getProcessedRate() {\n qint64 now = benchmarkTimer.elapsed();\n while (!processedTimestamps.empty() && now - processedTimestamps.front() > 1000) {\n processedTimestamps.pop_front();\n }\n return static_cast(processedTimestamps.size());\n}\n void setPenColor(const QColor &color) {\n penColor = color;\n}\n void setPenThickness(qreal thickness) {\n // Set thickness for the current tool\n switch (currentTool) {\n case ToolType::Pen:\n penToolThickness = thickness;\n break;\n case ToolType::Marker:\n markerToolThickness = thickness;\n break;\n case ToolType::Eraser:\n eraserToolThickness = thickness;\n break;\n }\n \n // Update the current thickness for efficient drawing\n penThickness = thickness;\n}\n void adjustAllToolThicknesses(qreal zoomRatio) {\n // Adjust thickness for all tools to maintain visual consistency\n penToolThickness *= zoomRatio;\n markerToolThickness *= zoomRatio;\n eraserToolThickness *= zoomRatio;\n \n // Update the current thickness based on the current tool\n switch (currentTool) {\n case ToolType::Pen:\n penThickness = penToolThickness;\n break;\n case ToolType::Marker:\n penThickness = markerToolThickness;\n break;\n case ToolType::Eraser:\n penThickness = eraserToolThickness;\n break;\n }\n}\n void setTool(ToolType tool) {\n currentTool = tool;\n \n // Switch to the thickness for the new tool\n switch (currentTool) {\n case ToolType::Pen:\n penThickness = penToolThickness;\n break;\n case ToolType::Marker:\n penThickness = markerToolThickness;\n break;\n case ToolType::Eraser:\n penThickness = eraserToolThickness;\n break;\n }\n}\n void setSaveFolder(const QString &folderPath) {\n saveFolder = folderPath;\n clearPdfNoDelete(); \n\n if (!saveFolder.isEmpty()) {\n QDir().mkpath(saveFolder);\n loadNotebookId(); // ✅ Load notebook ID when save folder is set\n }\n\n QString bgMetaFile = saveFolder + \"/.background_config.txt\"; // This metadata is for background styles, not to be confused with pdf directories. \n if (QFile::exists(bgMetaFile)) {\n QFile file(bgMetaFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n while (!in.atEnd()) {\n QString line = in.readLine().trimmed();\n if (line.startsWith(\"style=\")) {\n QString val = line.mid(6);\n if (val == \"Grid\") backgroundStyle = BackgroundStyle::Grid;\n else if (val == \"Lines\") backgroundStyle = BackgroundStyle::Lines;\n else backgroundStyle = BackgroundStyle::None;\n } else if (line.startsWith(\"color=\")) {\n backgroundColor = QColor(line.mid(6));\n } else if (line.startsWith(\"density=\")) {\n backgroundDensity = line.mid(8).toInt();\n }\n }\n file.close();\n }\n }\n\n // ✅ Check if the folder has a saved PDF path\n QString metadataFile = saveFolder + \"/.pdf_path.txt\";\n if (!QFile::exists(metadataFile)) {\n return;\n }\n\n\n QFile file(metadataFile);\n if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n return;\n }\n\n QTextStream in(&file);\n QString storedPdfPath = in.readLine().trimmed();\n file.close();\n\n if (storedPdfPath.isEmpty()) {\n return;\n }\n\n\n // ✅ Ensure the stored PDF file still exists before loading\n if (!QFile::exists(storedPdfPath)) {\n return;\n }\n loadPdf(storedPdfPath);\n}\n void saveToFile(int pageNumber) {\n if (saveFolder.isEmpty()) {\n return;\n }\n QString filePath = saveFolder + QString(\"/%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n\n // ✅ If no file exists and the buffer is empty, do nothing\n \n if (!edited) {\n return;\n }\n\n QImage image(buffer.size(), QImage::Format_ARGB32);\n image.fill(Qt::transparent);\n QPainter painter(&image);\n painter.drawPixmap(0, 0, buffer);\n image.save(filePath, \"PNG\");\n edited = false;\n \n // Save markdown windows for this page\n if (markdownManager) {\n markdownManager->saveWindowsForPage(pageNumber);\n }\n \n // Update note cache with the saved buffer\n noteCache.insert(pageNumber, new QPixmap(buffer));\n}\n void saveCurrentPage() {\n MainWindow *mainWin = qobject_cast(parentWidget()); // ✅ Get main window\n if (!mainWin) return;\n \n int currentPage = mainWin->getCurrentPageForCanvas(this); // ✅ Get correct page\n saveToFile(currentPage);\n}\n void loadPage(int pageNumber) {\n if (saveFolder.isEmpty()) return;\n\n // Hide any markdown windows from the previous page BEFORE loading the new page content.\n // This ensures the correct repaint area and stops the transparency timer.\n if (markdownManager) {\n markdownManager->hideAllWindows();\n }\n\n // Update current note page tracker\n currentCachedNotePage = pageNumber;\n\n // Check if note page is already cached\n bool loadedFromCache = false;\n if (noteCache.contains(pageNumber)) {\n // Use cached note page immediately\n buffer = *noteCache.object(pageNumber);\n loadedFromCache = true;\n } else {\n // Load note page from disk and cache it\n loadNotePageToCache(pageNumber);\n \n // Use the newly cached page or initialize buffer if loading failed\n if (noteCache.contains(pageNumber)) {\n buffer = *noteCache.object(pageNumber);\n loadedFromCache = true;\n } else {\n initializeBuffer(); // Clear the canvas if no file exists\n loadedFromCache = false;\n }\n }\n \n // Reset edited state when loading a new page\n edited = false;\n \n // Handle background image loading (PDF or custom background)\n if (isPdfLoaded && pdfDocument && pageNumber >= 0 && pageNumber < pdfDocument->numPages()) {\n // Use PDF as background (should already be cached by loadPdfPage)\n if (pdfCache.contains(pageNumber)) {\n backgroundImage = *pdfCache.object(pageNumber);\n \n // Resize canvas buffer to match PDF page size if needed\n if (backgroundImage.size() != buffer.size()) {\n QPixmap newBuffer(backgroundImage.size());\n newBuffer.fill(Qt::transparent);\n\n // Copy existing drawings\n QPainter painter(&newBuffer);\n painter.drawPixmap(0, 0, buffer);\n\n buffer = newBuffer;\n // Don't constrain widget size - let it expand to fill available space\n // The paintEvent will center the PDF content within the widget\n \n // Update cache with resized buffer\n noteCache.insert(pageNumber, new QPixmap(buffer));\n }\n }\n } else {\n // Handle custom background images\n QString bgFileName = saveFolder + QString(\"/bg_%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n QString metadataFile = saveFolder + QString(\"/.%1_bgsize_%2.txt\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n\n int bgWidth = 0, bgHeight = 0;\n if (QFile::exists(metadataFile)) {\n QFile file(metadataFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n in >> bgWidth >> bgHeight;\n file.close();\n }\n }\n\n if (QFile::exists(bgFileName)) {\n QImage bgImage(bgFileName);\n backgroundImage = QPixmap::fromImage(bgImage);\n\n // Resize canvas **only if background resolution is different**\n if (bgWidth > 0 && bgHeight > 0 && (bgWidth != width() || bgHeight != height())) {\n // Create a new buffer\n QPixmap newBuffer(bgWidth, bgHeight);\n newBuffer.fill(Qt::transparent);\n\n // Copy existing drawings to the new buffer\n QPainter painter(&newBuffer);\n painter.drawPixmap(0, 0, buffer);\n\n // Assign the new buffer\n buffer = newBuffer;\n setMaximumSize(bgWidth, bgHeight);\n \n // Update cache with resized buffer\n noteCache.insert(pageNumber, new QPixmap(buffer));\n }\n } else {\n backgroundImage = QPixmap(); // No background for this page\n // Only apply device pixel ratio fix if buffer was NOT loaded from cache\n // This prevents resizing cached buffers that might already be correctly sized\n if (!loadedFromCache) {\n QScreen *screen = QGuiApplication::primaryScreen();\n qreal dpr = screen ? screen->devicePixelRatio() : 1.0;\n QSize logicalSize = screen ? screen->size() : QSize(1440, 900);\n QSize expectedPixelSize = logicalSize * dpr;\n \n if (buffer.size() != expectedPixelSize) {\n // Buffer is wrong size, need to resize it properly\n QPixmap newBuffer(expectedPixelSize);\n newBuffer.fill(Qt::transparent);\n \n // Copy existing drawings if buffer was smaller\n if (!buffer.isNull()) {\n QPainter painter(&newBuffer);\n painter.drawPixmap(0, 0, buffer);\n }\n \n buffer = newBuffer;\n setMaximumSize(expectedPixelSize);\n }\n }\n }\n }\n\n // Cache adjacent note pages after delay for faster navigation\n checkAndCacheAdjacentNotePages(pageNumber);\n\n update();\n adjustSize(); // Force the widget to update its size\n parentWidget()->update();\n \n // Load markdown windows AFTER canvas is fully rendered and sized\n // Use a single-shot timer to ensure the canvas is fully updated\n QTimer::singleShot(0, this, [this, pageNumber]() {\n if (markdownManager) {\n markdownManager->loadWindowsForPage(pageNumber);\n }\n });\n}\n void deletePage(int pageNumber) {\n if (saveFolder.isEmpty()) {\n return;\n }\n QString fileName = saveFolder + QString(\"/%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n QString bgFileName = saveFolder + QString(\"/bg_%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n QString metadataFileName = saveFolder + QString(\"/.%1_bgsize_%2.txt\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n \n #ifdef Q_OS_WIN\n // Remove hidden attribute before deleting in Windows\n SetFileAttributesW(reinterpret_cast(metadataFileName.utf16()), FILE_ATTRIBUTE_NORMAL);\n #endif\n \n QFile::remove(fileName);\n QFile::remove(bgFileName);\n QFile::remove(metadataFileName);\n\n // Remove deleted page from note cache\n noteCache.remove(pageNumber);\n\n // Delete markdown windows for this page\n if (markdownManager) {\n markdownManager->deleteWindowsForPage(pageNumber);\n }\n\n if (pdfDocument){\n loadPdfPage(pageNumber);\n }\n else{\n loadPage(pageNumber);\n }\n\n}\n void setBackground(const QString &filePath, int pageNumber) {\n if (saveFolder.isEmpty()) {\n return; // No save folder set\n }\n\n // Construct full path inside save folder\n QString bgFileName = saveFolder + QString(\"/bg_%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n\n // Copy the file to the save folder\n QFile::copy(filePath, bgFileName);\n\n // Load the background image\n QImage bgImage(bgFileName);\n\n if (!bgImage.isNull()) {\n // Save background resolution in metadata file\n QString metadataFile = saveFolder + QString(\"/.%1_bgsize_%2.txt\")\n .arg(notebookId)\n .arg(pageNumber, 5, 10, QChar('0'));\n QFile file(metadataFile);\n if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {\n QTextStream out(&file);\n out << bgImage.width() << \" \" << bgImage.height();\n file.close();\n }\n\n #ifdef Q_OS_WIN\n // Set hidden attribute for metadata on Windows\n SetFileAttributesW(reinterpret_cast(metadataFile.utf16()), FILE_ATTRIBUTE_HIDDEN);\n #endif \n\n // Only resize if the background size is different\n if (bgImage.width() != width() || bgImage.height() != height()) {\n // Create a new buffer with the new size\n QPixmap newBuffer(bgImage.width(), bgImage.height());\n newBuffer.fill(Qt::transparent);\n\n // Copy existing drawings\n QPainter painter(&newBuffer);\n painter.drawPixmap(0, 0, buffer);\n\n // Assign new buffer and update canvas size\n buffer = newBuffer;\n setMaximumSize(bgImage.width(), bgImage.height());\n }\n\n backgroundImage = QPixmap::fromImage(bgImage);\n \n update();\n adjustSize();\n parentWidget()->update();\n }\n\n update(); // Refresh canvas\n}\n void saveAnnotated(int pageNumber) {\n if (saveFolder.isEmpty()) return;\n\n QString filePath = saveFolder + QString(\"/annotated_%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n\n // Use the buffer size to ensure correct resolution\n QImage image(buffer.size(), QImage::Format_ARGB32);\n image.fill(Qt::transparent);\n QPainter painter(&image);\n \n if (!backgroundImage.isNull()) {\n painter.drawPixmap(0, 0, backgroundImage.scaled(buffer.size(), Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation));\n }\n \n painter.drawPixmap(0, 0, buffer);\n image.save(filePath, \"PNG\");\n}\n void setZoom(int zoomLevel) {\n int newZoom = qMax(10, qMin(zoomLevel, 400)); // Limit zoom to 10%-400%\n if (zoomFactor != newZoom) {\n zoomFactor = newZoom;\n internalZoomFactor = zoomFactor; // Sync internal zoom\n update();\n emit zoomChanged(zoomFactor);\n }\n}\n int getZoom() const {\n return zoomFactor;\n}\n void updatePanOffsets(int xOffset, int yOffset) {\n panOffsetX = xOffset;\n panOffsetY = yOffset;\n update();\n}\n int getPanOffsetX() const {\n return panOffsetX;\n}\n int getPanOffsetY() const {\n return panOffsetY;\n}\n void setPanX(int xOffset) {\n if (panOffsetX != value) {\n panOffsetX = value;\n update();\n emit panChanged(panOffsetX, panOffsetY);\n }\n}\n void setPanY(int yOffset) {\n if (panOffsetY != value) {\n panOffsetY = value;\n update();\n emit panChanged(panOffsetX, panOffsetY);\n }\n}\n void loadPdf(const QString &pdfPath) {\n pdfDocument = Poppler::Document::load(pdfPath);\n if (pdfDocument && !pdfDocument->isLocked()) {\n // Enable anti-aliasing rendering hints for better text quality\n pdfDocument->setRenderHint(Poppler::Document::Antialiasing, true);\n pdfDocument->setRenderHint(Poppler::Document::TextAntialiasing, true);\n pdfDocument->setRenderHint(Poppler::Document::TextHinting, true);\n pdfDocument->setRenderHint(Poppler::Document::TextSlightHinting, true);\n \n totalPdfPages = pdfDocument->numPages();\n isPdfLoaded = true;\n totalPdfPages = pdfDocument->numPages();\n loadPdfPage(0); // Load first page\n // ✅ Save the PDF path in the metadata file\n if (!saveFolder.isEmpty()) {\n QString metadataFile = saveFolder + \"/.pdf_path.txt\";\n QFile file(metadataFile);\n if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {\n QTextStream out(&file);\n out << pdfPath; // Store the absolute path of the PDF\n file.close();\n }\n }\n // Emit signal that PDF was loaded\n emit pdfLoaded();\n }\n}\n void loadPdfPage(int pageNumber) {\n if (!pdfDocument) return;\n\n // Update current page tracker\n currentCachedPage = pageNumber;\n\n // Check if target page is already cached\n if (pdfCache.contains(pageNumber)) {\n // Display the cached page immediately\n backgroundImage = *pdfCache.object(pageNumber);\n loadPage(pageNumber); // Load annotations\n loadPdfTextBoxes(pageNumber); // Load text boxes for PDF text selection\n update();\n \n // Check and cache adjacent pages after delay\n checkAndCacheAdjacentPages(pageNumber);\n return;\n }\n\n // Target page not in cache - render it immediately\n renderPdfPageToCache(pageNumber);\n \n // Display the newly rendered page\n if (pdfCache.contains(pageNumber)) {\n backgroundImage = *pdfCache.object(pageNumber);\n } else {\n backgroundImage = QPixmap(); // Clear background if rendering failed\n }\n \n loadPage(pageNumber); // Load existing canvas annotations\n loadPdfTextBoxes(pageNumber); // Load text boxes for PDF text selection\n update();\n \n // Cache adjacent pages after delay\n checkAndCacheAdjacentPages(pageNumber);\n}\n bool isPdfLoadedFunc() const {\n return isPdfLoaded;\n}\n int getTotalPdfPages() const {\n return totalPdfPages;\n}\n Poppler::Document* getPdfDocument() const;\n void clearPdf() {\n pdfDocument.reset();\n pdfDocument = nullptr;\n isPdfLoaded = false;\n totalPdfPages = 0;\n pdfCache.clear();\n \n // Reset cache system state\n currentCachedPage = -1;\n if (pdfCacheTimer && pdfCacheTimer->isActive()) {\n pdfCacheTimer->stop();\n }\n \n // Cancel and clean up any active PDF watchers\n for (QFutureWatcher* watcher : activePdfWatchers) {\n if (watcher && !watcher->isFinished()) {\n watcher->cancel();\n }\n watcher->deleteLater();\n }\n activePdfWatchers.clear();\n\n // ✅ Remove the PDF path file when clearing the PDF\n if (!saveFolder.isEmpty()) {\n QString metadataFile = saveFolder + \"/.pdf_path.txt\";\n QFile::remove(metadataFile);\n }\n}\n void clearPdfNoDelete() {\n pdfDocument.reset();\n pdfDocument = nullptr;\n isPdfLoaded = false;\n totalPdfPages = 0;\n pdfCache.clear();\n \n // Reset cache system state\n currentCachedPage = -1;\n if (pdfCacheTimer && pdfCacheTimer->isActive()) {\n pdfCacheTimer->stop();\n }\n \n // Cancel and clean up any active PDF watchers\n for (QFutureWatcher* watcher : activePdfWatchers) {\n if (watcher && !watcher->isFinished()) {\n watcher->cancel();\n }\n watcher->deleteLater();\n }\n activePdfWatchers.clear();\n}\n QString getSaveFolder() const {\n return saveFolder;\n}\n QColor getPenColor() {\n return penColor;\n}\n qreal getPenThickness() {\n return penThickness;\n}\n ToolType getCurrentTool() {\n return currentTool;\n}\n void loadPdfPreviewAsync(int pageNumber) {\n if (!pdfDocument || pageNumber < 0 || pageNumber >= pdfDocument->numPages()) return;\n\n QFutureWatcher *watcher = new QFutureWatcher(this);\n\n connect(watcher, &QFutureWatcher::finished, this, [this, watcher]() {\n QPixmap result = watcher->result();\n if (!result.isNull()) {\n backgroundImage = result;\n update(); // trigger repaint\n }\n watcher->deleteLater(); // Clean up\n });\n\n QFuture future = QtConcurrent::run([=]() -> QPixmap {\n std::unique_ptr page(pdfDocument->page(pageNumber));\n if (!page) return QPixmap();\n\n // Render with document-level anti-aliasing settings\n QImage pdfImage = page->renderToImage(96, 96);\n if (pdfImage.isNull()) return QPixmap();\n\n QImage upscaled = pdfImage.scaled(pdfImage.width() * (pdfRenderDPI / 96),\n pdfImage.height() * (pdfRenderDPI / 96),\n Qt::KeepAspectRatio,\n Qt::SmoothTransformation);\n\n return QPixmap::fromImage(upscaled);\n });\n\n watcher->setFuture(future);\n}\n void setBackgroundStyle(BackgroundStyle style) {\n backgroundStyle = style;\n update(); // Trigger repaint\n}\n void setBackgroundColor(const QColor &color) {\n backgroundColor = color;\n update();\n}\n void setBackgroundDensity(int density) {\n backgroundDensity = density;\n update();\n}\n void saveBackgroundMetadata() {\n if (saveFolder.isEmpty()) return;\n\n QString bgMetaFile = saveFolder + \"/.background_config.txt\";\n QFile file(bgMetaFile);\n if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {\n QTextStream out(&file);\n QString styleStr = \"None\";\n if (backgroundStyle == BackgroundStyle::Grid) styleStr = \"Grid\";\n else if (backgroundStyle == BackgroundStyle::Lines) styleStr = \"Lines\";\n\n out << \"style=\" << styleStr << \"\\n\";\n out << \"color=\" << backgroundColor.name().toUpper() << \"\\n\";\n out << \"density=\" << backgroundDensity << \"\\n\";\n file.close();\n }\n}\n void exportNotebook(const QString &destinationFile) {\n if (destinationFile.isEmpty()) {\n QMessageBox::warning(nullptr, tr(\"Export Error\"), tr(\"No export file specified.\"));\n return;\n }\n\n if (saveFolder.isEmpty()) {\n QMessageBox::warning(nullptr, tr(\"Export Error\"), tr(\"No notebook loaded (saveFolder is empty)\"));\n return;\n }\n\n QStringList files;\n\n // Collect all files from saveFolder\n QDir dir(saveFolder);\n QDirIterator it(saveFolder, QDir::Files, QDirIterator::Subdirectories);\n while (it.hasNext()) {\n QString filePath = it.next();\n QString relativePath = dir.relativeFilePath(filePath);\n files << relativePath;\n }\n\n if (files.isEmpty()) {\n QMessageBox::warning(nullptr, tr(\"Export Error\"), tr(\"No files found to export.\"));\n return;\n }\n\n // Generate temporary file list\n QString tempFileList = saveFolder + \"/filelist.txt\";\n QFile listFile(tempFileList);\n if (listFile.open(QIODevice::WriteOnly | QIODevice::Text)) {\n QTextStream out(&listFile);\n for (const QString &file : files) {\n out << file << \"\\n\";\n }\n listFile.close();\n } else {\n QMessageBox::warning(nullptr, tr(\"Export Error\"), tr(\"Failed to create temporary file list.\"));\n return;\n }\n\n#ifdef _WIN32\n QString tarExe = QCoreApplication::applicationDirPath() + \"/bsdtar.exe\";\n#else\n QString tarExe = \"tar\";\n#endif\n\n QStringList args;\n args << \"-cf\" << QDir::toNativeSeparators(destinationFile);\n\n for (const QString &file : files) {\n args << QDir::toNativeSeparators(file);\n }\n\n QProcess process;\n process.setWorkingDirectory(saveFolder);\n\n process.start(tarExe, args);\n if (!process.waitForFinished()) {\n QMessageBox::warning(nullptr, tr(\"Export Error\"), tr(\"Tar process failed to finish.\"));\n QFile::remove(tempFileList);\n return;\n }\n\n QFile::remove(tempFileList);\n\n if (process.exitStatus() != QProcess::NormalExit || process.exitCode() != 0) {\n QMessageBox::warning(nullptr, tr(\"Export Error\"), tr(\"Tar process failed.\"));\n return;\n }\n\n QMessageBox::information(nullptr, tr(\"Export\"), tr(\"Notebook exported successfully.\"));\n}\n void importNotebook(const QString &packageFile) {\n\n // Ask user for destination working folder\n QString destFolder = QFileDialog::getExistingDirectory(nullptr, tr(\"Select Destination Folder for Imported Notebook\"));\n\n if (destFolder.isEmpty()) {\n QMessageBox::warning(nullptr, tr(\"Import Canceled\"), tr(\"No destination folder selected.\"));\n return;\n }\n\n // Check if destination folder is empty (optional, good practice)\n QDir destDir(destFolder);\n if (!destDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot).isEmpty()) {\n QMessageBox::StandardButton reply = QMessageBox::question(nullptr, tr(\"Destination Not Empty\"),\n tr(\"The selected folder is not empty. Files may be overwritten. Continue?\"),\n QMessageBox::Yes | QMessageBox::No);\n if (reply != QMessageBox::Yes) {\n return;\n }\n }\n\n#ifdef _WIN32\n QString tarExe = QCoreApplication::applicationDirPath() + \"/bsdtar.exe\";\n#else\n QString tarExe = \"tar\";\n#endif\n\n // Extract package\n QStringList args;\n args << \"-xf\" << packageFile;\n\n QProcess process;\n process.setWorkingDirectory(destFolder);\n process.start(tarExe, args);\n process.waitForFinished();\n\n // Switch notebook folder\n setSaveFolder(destFolder);\n loadPage(0);\n\n QMessageBox::information(nullptr, tr(\"Import Complete\"), tr(\"Notebook imported successfully.\"));\n}\n void importNotebookTo(const QString &packageFile, const QString &destFolder) {\n\n #ifdef _WIN32\n QString tarExe = QCoreApplication::applicationDirPath() + \"/bsdtar.exe\";\n #else\n QString tarExe = \"tar\";\n #endif\n \n QStringList args;\n args << \"-xf\" << packageFile;\n \n QProcess process;\n process.setWorkingDirectory(destFolder);\n process.start(tarExe, args);\n process.waitForFinished();\n \n setSaveFolder(destFolder);\n loadNotebookId();\n loadPage(0);\n\n QMessageBox::information(nullptr, tr(\"Import\"), tr(\"Notebook imported successfully.\"));\n }\n void deleteRopeSelection() {\n if (!selectionBuffer.isNull() && !selectionRect.isEmpty()) {\n // If the selection area hasn't been cleared from the buffer yet, clear it now for deletion\n if (!selectionAreaCleared && !selectionMaskPath.isEmpty()) {\n QPainter painter(&buffer);\n painter.setCompositionMode(QPainter::CompositionMode_Clear);\n painter.fillPath(selectionMaskPath, Qt::transparent);\n painter.end();\n }\n \n // Clear the selection state\n selectionBuffer = QPixmap();\n selectionRect = QRect();\n exactSelectionRectF = QRectF();\n movingSelection = false;\n selectingWithRope = false;\n selectionJustCopied = false;\n selectionAreaCleared = false;\n selectionMaskPath = QPainterPath();\n selectionBufferRect = QRectF();\n \n // Mark as edited since we deleted content\n if (!edited) {\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n \n // Update the entire canvas to remove selection visuals\n update();\n }\n}\n void cancelRopeSelection() {\n if (!selectionBuffer.isNull() && !selectionRect.isEmpty()) {\n // Paste the selection back to its current location (where user moved it)\n QPainter painter(&buffer);\n // Explicitly set composition mode to draw on top of existing content\n painter.setCompositionMode(QPainter::CompositionMode_SourceOver);\n // Use the current selection position\n QPointF currentTopLeft = exactSelectionRectF.isEmpty() ? selectionRect.topLeft() : exactSelectionRectF.topLeft();\n QPointF bufferDest = mapLogicalWidgetToPhysicalBuffer(currentTopLeft);\n painter.drawPixmap(bufferDest.toPoint(), selectionBuffer);\n painter.end();\n \n // Store selection buffer size for update calculation before clearing it\n QSize selectionSize = selectionBuffer.size();\n QRect updateRect = QRect(currentTopLeft.toPoint(), selectionSize);\n \n // Clear the selection state\n selectionBuffer = QPixmap();\n selectionRect = QRect();\n exactSelectionRectF = QRectF();\n movingSelection = false;\n selectingWithRope = false;\n selectionJustCopied = false;\n selectionAreaCleared = false;\n selectionMaskPath = QPainterPath();\n selectionBufferRect = QRectF();\n \n // Update the restored area\n update(updateRect.adjusted(-5, -5, 5, 5));\n }\n}\n void copyRopeSelection() {\n if (!selectionBuffer.isNull() && !selectionRect.isEmpty()) {\n // Get current selection position\n QPointF currentTopLeft = exactSelectionRectF.isEmpty() ? selectionRect.topLeft() : exactSelectionRectF.topLeft();\n \n // Calculate new position (right next to the original), but ensure it stays within canvas bounds\n QPointF newTopLeft = currentTopLeft + QPointF(selectionRect.width() + 5, 0); // 5 pixels gap\n \n // Check if the new position would extend beyond buffer boundaries and adjust if needed\n QPointF currentBufferDest = mapLogicalWidgetToPhysicalBuffer(currentTopLeft);\n QPointF newBufferDest = mapLogicalWidgetToPhysicalBuffer(newTopLeft);\n \n // Ensure the copy stays within buffer bounds\n if (newBufferDest.x() + selectionBuffer.width() > buffer.width()) {\n // If it would extend beyond right edge, place it to the left of the original\n newTopLeft = currentTopLeft - QPointF(selectionRect.width() + 5, 0);\n newBufferDest = mapLogicalWidgetToPhysicalBuffer(newTopLeft);\n \n // If it still doesn't fit on the left, place it below the original\n if (newBufferDest.x() < 0) {\n newTopLeft = currentTopLeft + QPointF(0, selectionRect.height() + 5);\n newBufferDest = mapLogicalWidgetToPhysicalBuffer(newTopLeft);\n \n // If it doesn't fit below either, place it above\n if (newBufferDest.y() + selectionBuffer.height() > buffer.height()) {\n newTopLeft = currentTopLeft - QPointF(0, selectionRect.height() + 5);\n newBufferDest = mapLogicalWidgetToPhysicalBuffer(newTopLeft);\n \n // If none of the positions work, just offset slightly and let it extend\n if (newBufferDest.y() < 0) {\n newTopLeft = currentTopLeft + QPointF(10, 10);\n newBufferDest = mapLogicalWidgetToPhysicalBuffer(newTopLeft);\n }\n }\n }\n }\n if (newBufferDest.y() + selectionBuffer.height() > buffer.height()) {\n // If it would extend beyond bottom edge, place it above the original\n newTopLeft = currentTopLeft - QPointF(0, selectionRect.height() + 5);\n newBufferDest = mapLogicalWidgetToPhysicalBuffer(newTopLeft);\n }\n \n // First, paste the selection back to its current location to restore the original\n QPainter painter(&buffer);\n // Explicitly set composition mode to draw on top of existing content\n painter.setCompositionMode(QPainter::CompositionMode_SourceOver);\n painter.drawPixmap(currentBufferDest.toPoint(), selectionBuffer);\n \n // Then, paste the copy to the new location\n // We need to handle the case where the copy extends beyond buffer boundaries\n QRect targetRect(newBufferDest.toPoint(), selectionBuffer.size());\n QRect bufferBounds(0, 0, buffer.width(), buffer.height());\n QRect clippedRect = targetRect.intersected(bufferBounds);\n \n if (!clippedRect.isEmpty()) {\n // Calculate which part of the selectionBuffer to draw\n QRect sourceRect = QRect(\n clippedRect.x() - targetRect.x(),\n clippedRect.y() - targetRect.y(),\n clippedRect.width(),\n clippedRect.height()\n );\n \n painter.drawPixmap(clippedRect, selectionBuffer, sourceRect);\n }\n \n // For the selection buffer, we keep the FULL content, even if parts extend beyond canvas\n // This way when the user drags it back, the full content is preserved\n QPixmap newSelectionBuffer = selectionBuffer; // Keep the full original content\n \n // DON'T clear the copied area immediately - leave both original and copy on the canvas\n // The copy will only be cleared when the user actually starts moving the selection\n // This way, if the user cancels without moving, both original and copy remain permanently\n painter.end();\n \n // Update the selection buffer and position\n selectionBuffer = newSelectionBuffer;\n selectionRect = QRect(newTopLeft.toPoint(), selectionRect.size());\n exactSelectionRectF = QRectF(newTopLeft, selectionRect.size());\n selectionJustCopied = true; // Mark that this selection was just copied\n \n // Mark as edited since we added content\n if (!edited) {\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n \n // Update the entire affected area (original + copy + gap)\n QRect updateArea = QRect(currentTopLeft.toPoint(), selectionRect.size())\n .united(selectionRect)\n .adjusted(-10, -10, 10, 10);\n update(updateArea);\n }\n}\n void setMarkdownSelectionMode(bool enabled) {\n markdownSelectionMode = enabled;\n \n if (markdownManager) {\n markdownManager->setSelectionMode(enabled);\n }\n \n if (!enabled) {\n markdownSelecting = false;\n }\n \n // Update cursor\n setCursor(enabled ? Qt::CrossCursor : Qt::ArrowCursor);\n \n // Notify signal\n emit markdownSelectionModeChanged(enabled);\n}\n bool isMarkdownSelectionMode() const {\n return markdownSelectionMode;\n}\n void clearPdfTextSelection() {\n // Clear selection state\n selectedTextBoxes.clear();\n pdfTextSelecting = false;\n \n // Cancel any pending throttled updates\n if (pdfTextSelectionTimer && pdfTextSelectionTimer->isActive()) {\n pdfTextSelectionTimer->stop();\n }\n hasPendingSelection = false;\n \n // Refresh display\n update();\n}\n QString getSelectedPdfText() const {\n if (selectedTextBoxes.isEmpty()) {\n return QString();\n }\n \n // Pre-allocate string with estimated size for efficiency\n QString selectedText;\n selectedText.reserve(selectedTextBoxes.size() * 20); // Estimate ~20 chars per text box\n \n // Build text with space separators\n for (const Poppler::TextBox* textBox : selectedTextBoxes) {\n if (textBox && !textBox->text().isEmpty()) {\n if (!selectedText.isEmpty()) {\n selectedText += \" \";\n }\n selectedText += textBox->text();\n }\n }\n \n return selectedText;\n}\n QPointF mapWidgetToCanvas(const QPointF &widgetPoint) const {\n QPointF topLeft = mapWidgetToCanvas(widgetRect.topLeft());\n QPointF bottomRight = mapWidgetToCanvas(widgetRect.bottomRight());\n \n return QRect(topLeft.toPoint(), bottomRight.toPoint());\n}\n QPointF mapCanvasToWidget(const QPointF &canvasPoint) const {\n QPointF topLeft = mapCanvasToWidget(canvasRect.topLeft());\n QPointF bottomRight = mapCanvasToWidget(canvasRect.bottomRight());\n \n return QRect(topLeft.toPoint(), bottomRight.toPoint());\n}\n QRect mapWidgetToCanvas(const QRect &widgetRect) const {\n QPointF topLeft = mapWidgetToCanvas(widgetRect.topLeft());\n QPointF bottomRight = mapWidgetToCanvas(widgetRect.bottomRight());\n \n return QRect(topLeft.toPoint(), bottomRight.toPoint());\n}\n QRect mapCanvasToWidget(const QRect &canvasRect) const {\n QPointF topLeft = mapCanvasToWidget(canvasRect.topLeft());\n QPointF bottomRight = mapCanvasToWidget(canvasRect.bottomRight());\n \n return QRect(topLeft.toPoint(), bottomRight.toPoint());\n}\n protected:\n void paintEvent(QPaintEvent *event) override {\n QPainter painter(this);\n \n // Save the painter state before transformations\n painter.save();\n \n // Calculate the scaled canvas size\n qreal scaledCanvasWidth = buffer.width() * (internalZoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (internalZoomFactor / 100.0);\n \n // Calculate centering offsets\n qreal centerOffsetX = 0;\n qreal centerOffsetY = 0;\n \n // Center horizontally if canvas is smaller than widget\n if (scaledCanvasWidth < width()) {\n centerOffsetX = (width() - scaledCanvasWidth) / 2.0;\n }\n \n // Center vertically if canvas is smaller than widget\n if (scaledCanvasHeight < height()) {\n centerOffsetY = (height() - scaledCanvasHeight) / 2.0;\n }\n \n // Apply centering offset first\n painter.translate(centerOffsetX, centerOffsetY);\n \n // Use internal zoom factor for smoother animation\n painter.scale(internalZoomFactor / 100.0, internalZoomFactor / 100.0);\n\n // Pan offset needs to be reversed because painter works in transformed coordinates\n painter.translate(-panOffsetX, -panOffsetY);\n\n // Set clipping rectangle to canvas bounds to prevent painting outside\n painter.setClipRect(0, 0, buffer.width(), buffer.height());\n\n // 🟨 Notebook-style background rendering\n if (backgroundImage.isNull()) {\n painter.save();\n \n // Always apply background color regardless of style\n painter.fillRect(QRectF(0, 0, buffer.width(), buffer.height()), backgroundColor);\n\n // Only draw grid/lines if not \"None\" style\n if (backgroundStyle != BackgroundStyle::None) {\n QPen linePen(QColor(100, 100, 100, 100)); // Subtle gray lines\n linePen.setWidthF(1.0);\n painter.setPen(linePen);\n\n qreal scaledDensity = backgroundDensity;\n\n if (devicePixelRatioF() > 1.0)\n scaledDensity *= devicePixelRatioF(); // Optional DPI handling\n\n if (backgroundStyle == BackgroundStyle::Lines || backgroundStyle == BackgroundStyle::Grid) {\n for (int y = 0; y < buffer.height(); y += scaledDensity)\n painter.drawLine(0, y, buffer.width(), y);\n }\n if (backgroundStyle == BackgroundStyle::Grid) {\n for (int x = 0; x < buffer.width(); x += scaledDensity)\n painter.drawLine(x, 0, x, buffer.height());\n }\n }\n\n painter.restore();\n }\n\n // ✅ Draw loaded image or PDF background if available\n if (!backgroundImage.isNull()) {\n painter.drawPixmap(0, 0, backgroundImage);\n }\n\n // ✅ Draw user's strokes from the buffer (transparent overlay)\n painter.drawPixmap(0, 0, buffer);\n \n // Draw straight line preview if in straight line mode and drawing\n // Skip preview for eraser tool\n if (straightLineMode && drawing && currentTool != ToolType::Eraser) {\n // Save the current state before applying the eraser mode\n painter.save();\n \n // Store current pressure - ensure minimum is 0.5 for consistent preview\n qreal pressure = qMax(0.5, painter.device()->devicePixelRatioF() > 1.0 ? 0.8 : 1.0);\n \n // Set up the pen based on tool type\n if (currentTool == ToolType::Marker) {\n qreal thickness = penThickness * 8.0;\n QColor markerColor = penColor;\n // Increase alpha for better visibility in straight line mode\n // Using a higher value (80) instead of the regular 4 to compensate for single-pass drawing\n markerColor.setAlpha(80);\n QPen pen(markerColor, thickness, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);\n painter.setPen(pen);\n } else { // Default Pen\n // Match the exact same thickness calculation as in drawStroke\n qreal scaledThickness = penThickness * pressure;\n QPen pen(penColor, scaledThickness, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);\n painter.setPen(pen);\n }\n \n // Use the same coordinate transformation logic as in drawStroke\n // to ensure the preview line appears at the exact same position\n QPointF bufferStart, bufferEnd;\n \n // Convert screen coordinates to buffer coordinates using the same calculations as drawStroke\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n QPointF adjustedStart = straightLineStartPoint - QPointF(centerOffsetX, centerOffsetY);\n QPointF adjustedEnd = lastPoint - QPointF(centerOffsetX, centerOffsetY);\n \n bufferStart = (adjustedStart / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n bufferEnd = (adjustedEnd / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n \n // Draw the preview line using the same coordinates that will be used for the final line\n painter.drawLine(bufferStart, bufferEnd);\n \n // Restore the original painter state\n painter.restore();\n }\n\n // Draw selection rectangle if in rope tool mode and selecting, moving, or has a selection\n if (ropeToolMode && (selectingWithRope || movingSelection || (!selectionBuffer.isNull() && !selectionRect.isEmpty()))) {\n painter.save(); // Save painter state for overlays\n painter.resetTransform(); // Reset transform to draw directly in logical widget coordinates\n \n if (selectingWithRope && !lassoPathPoints.isEmpty()) {\n QPen selectionPen(Qt::DashLine);\n selectionPen.setColor(Qt::blue);\n selectionPen.setWidthF(1.5); // Width in logical pixels\n painter.setPen(selectionPen);\n painter.drawPolygon(lassoPathPoints); // lassoPathPoints are logical widget coordinates\n } else if (!selectionBuffer.isNull() && !selectionRect.isEmpty()) {\n // selectionRect is in logical widget coordinates.\n // selectionBuffer is in buffer coordinates, we need to handle scaling correctly\n QPixmap scaledBuffer = selectionBuffer;\n \n // Calculate the current zoom factor\n qreal currentZoom = internalZoomFactor / 100.0;\n \n // Scale the selection buffer to match the current zoom level\n if (currentZoom != 1.0) {\n QSize scaledSize = QSize(\n qRound(scaledBuffer.width() * currentZoom),\n qRound(scaledBuffer.height() * currentZoom)\n );\n scaledBuffer = scaledBuffer.scaled(scaledSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);\n }\n \n // Draw it at the logical position\n // Use exactSelectionRectF for smoother movement if available\n QPointF topLeft = exactSelectionRectF.isEmpty() ? selectionRect.topLeft() : exactSelectionRectF.topLeft();\n painter.drawPixmap(topLeft, scaledBuffer);\n\n QPen selectionBorderPen(Qt::DashLine);\n selectionBorderPen.setColor(Qt::darkCyan);\n selectionBorderPen.setWidthF(1.5); // Width in logical pixels\n painter.setPen(selectionBorderPen);\n \n // Use exactSelectionRectF for drawing the selection border if available\n if (!exactSelectionRectF.isEmpty()) {\n painter.drawRect(exactSelectionRectF);\n } else {\n painter.drawRect(selectionRect);\n }\n }\n painter.restore(); // Restore painter state to what it was for drawing the main buffer\n }\n \n\n \n\n \n // Restore the painter state\n painter.restore();\n \n // Fill the area outside the canvas with the widget's background color\n QRect widgetRect = rect();\n QRectF canvasRect(\n centerOffsetX - panOffsetX * (internalZoomFactor / 100.0),\n centerOffsetY - panOffsetY * (internalZoomFactor / 100.0),\n buffer.width() * (internalZoomFactor / 100.0),\n buffer.height() * (internalZoomFactor / 100.0)\n );\n \n // Create regions for areas outside the canvas\n QRegion outsideRegion(widgetRect);\n outsideRegion -= QRegion(canvasRect.toRect());\n \n // Fill the outside region with the background color\n painter.setClipRegion(outsideRegion);\n painter.fillRect(widgetRect, palette().window().color());\n \n // Reset clipping for overlay elements that should appear on top\n painter.setClipping(false);\n \n // Draw markdown selection overlay\n if (markdownSelectionMode && markdownSelecting) {\n painter.save();\n QPen selectionPen(Qt::DashLine);\n selectionPen.setColor(Qt::green);\n selectionPen.setWidthF(2.0);\n painter.setPen(selectionPen);\n \n QBrush selectionBrush(QColor(0, 255, 0, 30)); // Semi-transparent green\n painter.setBrush(selectionBrush);\n \n QRect selectionRect = QRect(markdownSelectionStart, markdownSelectionEnd).normalized();\n painter.drawRect(selectionRect);\n painter.restore();\n }\n \n // Draw PDF text selection overlay on top of everything\n if (pdfTextSelectionEnabled && isPdfLoaded) {\n painter.save(); // Save painter state for PDF text overlay\n painter.resetTransform(); // Reset transform to draw directly in logical widget coordinates\n \n // Draw selection rectangle if actively selecting\n if (pdfTextSelecting) {\n QPen selectionPen(Qt::DashLine);\n selectionPen.setColor(QColor(0, 120, 215)); // Blue selection rectangle\n selectionPen.setWidthF(2.0); // Make it more visible\n painter.setPen(selectionPen);\n \n QBrush selectionBrush(QColor(0, 120, 215, 30)); // Semi-transparent blue fill\n painter.setBrush(selectionBrush);\n \n QRectF selectionRect(pdfSelectionStart, pdfSelectionEnd);\n selectionRect = selectionRect.normalized();\n painter.drawRect(selectionRect);\n }\n \n // Draw highlights for selected text boxes\n if (!selectedTextBoxes.isEmpty()) {\n QColor highlightColor = QColor(255, 255, 0, 100); // Semi-transparent yellow\n painter.setBrush(highlightColor);\n painter.setPen(Qt::NoPen);\n \n // Draw highlight rectangles for selected text boxes\n for (const Poppler::TextBox* textBox : selectedTextBoxes) {\n if (textBox) {\n // Convert PDF coordinates to widget coordinates\n QRectF pdfRect = textBox->boundingBox();\n QPointF topLeft = mapPdfToWidgetCoordinates(pdfRect.topLeft());\n QPointF bottomRight = mapPdfToWidgetCoordinates(pdfRect.bottomRight());\n QRectF widgetRect(topLeft, bottomRight);\n widgetRect = widgetRect.normalized();\n \n painter.drawRect(widgetRect);\n }\n }\n }\n \n painter.restore(); // Restore painter state\n }\n}\n void tabletEvent(QTabletEvent *event) override {\n // ✅ PRIORITY: Handle PDF text selection with stylus when enabled\n // This redirects stylus input to text selection instead of drawing\n if (pdfTextSelectionEnabled && isPdfLoaded) {\n if (event->type() == QEvent::TabletPress) {\n pdfTextSelecting = true;\n pdfSelectionStart = event->position();\n pdfSelectionEnd = pdfSelectionStart;\n \n // Clear any existing selected text boxes without resetting pdfTextSelecting\n selectedTextBoxes.clear();\n \n setCursor(Qt::IBeamCursor); // Ensure cursor is correct\n update(); // Refresh display\n event->accept();\n return;\n } else if (event->type() == QEvent::TabletMove && pdfTextSelecting) {\n pdfSelectionEnd = event->position();\n \n // Store pending selection for throttled processing (60 FPS throttling)\n pendingSelectionStart = pdfSelectionStart;\n pendingSelectionEnd = pdfSelectionEnd;\n hasPendingSelection = true;\n \n // Start timer if not already running (throttled to 60 FPS)\n if (!pdfTextSelectionTimer->isActive()) {\n pdfTextSelectionTimer->start();\n }\n \n // NOTE: No direct update() call here - let the timer handle updates at 60 FPS\n event->accept();\n return;\n } else if (event->type() == QEvent::TabletRelease && pdfTextSelecting) {\n pdfSelectionEnd = event->position();\n \n // Process any pending selection immediately on release\n if (pdfTextSelectionTimer && pdfTextSelectionTimer->isActive()) {\n pdfTextSelectionTimer->stop();\n if (hasPendingSelection) {\n updatePdfTextSelection(pendingSelectionStart, pendingSelectionEnd);\n hasPendingSelection = false;\n }\n } else {\n // Update selection with final position\n updatePdfTextSelection(pdfSelectionStart, pdfSelectionEnd);\n }\n \n pdfTextSelecting = false;\n \n // Check for link clicks if no text was selected\n QString selectedText = getSelectedPdfText();\n if (selectedText.isEmpty()) {\n handlePdfLinkClick(event->position());\n } else {\n // Show context menu for text selection\n QPoint globalPos = mapToGlobal(event->position().toPoint());\n showPdfTextSelectionMenu(globalPos);\n }\n \n event->accept();\n return;\n }\n }\n \n // ✅ NORMAL STYLUS BEHAVIOR: Only reached when PDF text selection is OFF\n // Hardware eraser detection\n static bool hardwareEraserActive = false;\n bool wasUsingHardwareEraser = false;\n \n // Track hardware eraser state\n if (event->pointerType() == QPointingDevice::PointerType::Eraser) {\n // Hardware eraser is being used\n wasUsingHardwareEraser = true;\n \n if (event->type() == QEvent::TabletPress) {\n // Start of eraser stroke - save current tool and switch to eraser\n hardwareEraserActive = true;\n previousTool = currentTool;\n currentTool = ToolType::Eraser;\n }\n }\n \n // Maintain hardware eraser state across move events\n if (hardwareEraserActive && event->type() != QEvent::TabletRelease) {\n wasUsingHardwareEraser = true;\n }\n\n // Determine if we're in eraser mode (either hardware eraser or tool set to eraser)\n bool isErasing = (currentTool == ToolType::Eraser);\n\n if (event->type() == QEvent::TabletPress) {\n drawing = true;\n lastPoint = event->posF(); // Logical widget coordinates\n if (straightLineMode) {\n straightLineStartPoint = lastPoint;\n }\n if (ropeToolMode) {\n if (!selectionBuffer.isNull() && selectionRect.contains(lastPoint.toPoint())) {\n // Start moving an existing selection (or continue if already moving)\n movingSelection = true;\n selectingWithRope = false;\n lastMovePoint = lastPoint;\n // Initialize the exact floating-point rect if it's empty\n if (exactSelectionRectF.isEmpty()) {\n exactSelectionRectF = QRectF(selectionRect);\n }\n \n // If this selection was just copied, clear the area now that user is moving it\n if (selectionJustCopied) {\n QPainter painter(&buffer);\n painter.setCompositionMode(QPainter::CompositionMode_Clear);\n QPointF bufferDest = mapLogicalWidgetToPhysicalBuffer(selectionRect.topLeft());\n QRect clearRect(bufferDest.toPoint(), selectionBuffer.size());\n // Only clear the part that's within buffer bounds\n QRect bufferBounds(0, 0, buffer.width(), buffer.height());\n QRect clippedClearRect = clearRect.intersected(bufferBounds);\n if (!clippedClearRect.isEmpty()) {\n painter.fillRect(clippedClearRect, Qt::transparent);\n }\n painter.end();\n selectionJustCopied = false; // Clear the flag\n }\n \n // If the selection area hasn't been cleared from the buffer yet, clear it now\n if (!selectionAreaCleared && !selectionMaskPath.isEmpty()) {\n QPainter painter(&buffer);\n painter.setCompositionMode(QPainter::CompositionMode_Clear);\n painter.fillPath(selectionMaskPath, Qt::transparent);\n painter.end();\n selectionAreaCleared = true;\n }\n // selectionBuffer already has the content.\n // The original area in 'buffer' was already cleared when selection was made.\n } else {\n // Start a new selection or cancel existing one\n if (!selectionBuffer.isNull()) { // If there's an active selection, a tap outside cancels it\n selectionBuffer = QPixmap();\n selectionRect = QRect();\n lassoPathPoints.clear();\n movingSelection = false;\n selectingWithRope = false;\n selectionJustCopied = false;\n selectionAreaCleared = false;\n selectionMaskPath = QPainterPath();\n selectionBufferRect = QRectF();\n update(); // Full update to remove old selection visuals\n drawing = false; // Consumed this press for cancel\n return;\n }\n selectingWithRope = true;\n movingSelection = false;\n selectionJustCopied = false;\n selectionAreaCleared = false;\n selectionMaskPath = QPainterPath();\n selectionBufferRect = QRectF();\n lassoPathPoints.clear();\n lassoPathPoints << lastPoint; // Start the lasso path\n selectionRect = QRect();\n selectionBuffer = QPixmap();\n }\n }\n } else if (event->type() == QEvent::TabletMove && drawing) {\n if (ropeToolMode) {\n if (selectingWithRope) {\n QRectF oldPreviewBoundingRect = lassoPathPoints.boundingRect();\n lassoPathPoints << event->posF();\n lastPoint = event->posF();\n QRectF newPreviewBoundingRect = lassoPathPoints.boundingRect();\n // Update the area of the selection rectangle preview (logical widget coordinates)\n update(oldPreviewBoundingRect.united(newPreviewBoundingRect).toRect().adjusted(-5,-5,5,5));\n } else if (movingSelection) {\n QPointF delta = event->posF() - lastMovePoint; // Delta in logical widget coordinates\n QRect oldWidgetSelectionRect = selectionRect;\n \n // Update the exact floating-point rectangle first\n exactSelectionRectF.translate(delta);\n \n // Convert back to integer rect, but only when the position actually changes\n QRect newRect = exactSelectionRectF.toRect();\n if (newRect != selectionRect) {\n selectionRect = newRect;\n // Update the combined area of the old and new selection positions (logical widget coordinates)\n update(oldWidgetSelectionRect.united(selectionRect).adjusted(-2,-2,2,2));\n } else {\n // Even if the integer position didn't change, we still need to update\n // to make movement feel smoother, especially with slow movements\n update(selectionRect.adjusted(-2,-2,2,2));\n }\n \n lastMovePoint = event->posF();\n if (!edited){\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n }\n } else if (straightLineMode && !isErasing) {\n // For straight line mode with non-eraser tools, just update the last position\n // and trigger a repaint of only the affected area for preview\n static QElapsedTimer updateTimer;\n static bool timerInitialized = false;\n \n if (!timerInitialized) {\n updateTimer.start();\n timerInitialized = true;\n }\n \n // Throttle updates based on time for high CPU usage tools\n bool shouldUpdate = true;\n \n // Apply throttling for marker which can be CPU intensive\n if (currentTool == ToolType::Marker) {\n shouldUpdate = updateTimer.elapsed() > 16; // Only update every 16ms (approx 60fps)\n }\n \n if (shouldUpdate) {\n QPointF oldLastPoint = lastPoint;\n lastPoint = event->posF();\n \n // Calculate affected rectangle that needs updating\n QRectF updateRect = calculatePreviewRect(straightLineStartPoint, oldLastPoint, lastPoint);\n update(updateRect.toRect());\n \n // Reset timer\n updateTimer.restart();\n } else {\n // Just update the last point without redrawing\n lastPoint = event->posF();\n }\n } else if (straightLineMode && isErasing) {\n // For eraser in straight line mode, continuously erase from start to current point\n // This gives immediate visual feedback and smoother erasing experience\n \n // Store current point\n QPointF currentPoint = event->posF();\n \n // Clear previous stroke by redrawing with transparency\n QRectF updateRect = QRectF(straightLineStartPoint, lastPoint).normalized().adjusted(-20, -20, 20, 20);\n update(updateRect.toRect());\n \n // Erase from start point to current position\n eraseStroke(straightLineStartPoint, currentPoint, event->pressure());\n \n // Update last point\n lastPoint = currentPoint;\n \n // Only track benchmarking when enabled\n if (benchmarking) {\n processedTimestamps.push_back(benchmarkTimer.elapsed());\n }\n } else {\n // Normal drawing mode OR eraser regardless of straight line mode\n if (isErasing) {\n eraseStroke(lastPoint, event->posF(), event->pressure());\n } else {\n drawStroke(lastPoint, event->posF(), event->pressure());\n }\n lastPoint = event->posF();\n \n // Only track benchmarking when enabled\n if (benchmarking) {\n processedTimestamps.push_back(benchmarkTimer.elapsed());\n }\n }\n } else if (event->type() == QEvent::TabletRelease) {\n if (straightLineMode && !isErasing) {\n // Draw the final line on release with the current pressure\n qreal pressure = event->pressure();\n \n // Always use at least a minimum pressure\n pressure = qMax(pressure, 0.5);\n \n drawStroke(straightLineStartPoint, event->posF(), pressure);\n \n // Only track benchmarking when enabled\n if (benchmarking) {\n processedTimestamps.push_back(benchmarkTimer.elapsed());\n }\n \n // Force repaint to clear the preview line\n update();\n if (!edited){\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n } else if (straightLineMode && isErasing) {\n // For erasing in straight line mode, most of the work is done during movement\n // Just ensure one final erasing pass from start to end point\n qreal pressure = qMax(event->pressure(), 0.5);\n \n // Final pass to ensure the entire line is erased\n eraseStroke(straightLineStartPoint, event->posF(), pressure);\n \n // Force update to clear any remaining artifacts\n update();\n if (!edited){\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n }\n \n drawing = false;\n \n // Reset tool state if we were using the hardware eraser\n if (wasUsingHardwareEraser) {\n currentTool = previousTool;\n hardwareEraserActive = false; // Reset hardware eraser tracking\n }\n\n if (ropeToolMode) {\n if (selectingWithRope) {\n if (lassoPathPoints.size() > 2) { // Need at least 3 points for a polygon\n lassoPathPoints << lassoPathPoints.first(); // Close the polygon\n \n if (!lassoPathPoints.boundingRect().isEmpty()) {\n // 1. Create a QPolygonF in buffer coordinates using proper transformation\n QPolygonF bufferLassoPath;\n for (const QPointF& p_widget_logical : qAsConst(lassoPathPoints)) {\n bufferLassoPath << mapLogicalWidgetToPhysicalBuffer(p_widget_logical);\n }\n\n // 2. Get the bounding box of this path on the buffer\n QRectF bufferPathBoundingRect = bufferLassoPath.boundingRect();\n\n // 3. Copy that part of the main buffer\n QPixmap originalPiece = buffer.copy(bufferPathBoundingRect.toRect());\n\n // 4. Create the selectionBuffer (same size as originalPiece) and fill transparent\n selectionBuffer = QPixmap(originalPiece.size());\n selectionBuffer.fill(Qt::transparent);\n \n // 5. Create a mask from the lasso path\n QPainterPath maskPath;\n // The lasso path for the mask needs to be relative to originalPiece.topLeft()\n maskPath.addPolygon(bufferLassoPath.translated(-bufferPathBoundingRect.topLeft()));\n \n // 6. Paint the originalPiece onto selectionBuffer, using the mask\n QPainter selectionPainter(&selectionBuffer);\n selectionPainter.setClipPath(maskPath);\n selectionPainter.drawPixmap(0,0, originalPiece);\n selectionPainter.end();\n\n // 7. DON'T clear the selected area from the main buffer yet\n // The area will only be cleared when the user actually starts moving the selection\n // This way, if the user cancels without moving, the original content remains\n selectionAreaCleared = false;\n \n // Store the mask path and buffer rect for later clearing when movement starts\n selectionMaskPath = maskPath.translated(bufferPathBoundingRect.topLeft());\n selectionBufferRect = bufferPathBoundingRect;\n \n // 8. Calculate the correct selectionRect in logical widget coordinates\n QRectF logicalSelectionRect = mapRectBufferToWidgetLogical(bufferPathBoundingRect);\n selectionRect = logicalSelectionRect.toRect();\n exactSelectionRectF = logicalSelectionRect;\n \n // Update the area of the selection on screen\n update(logicalSelectionRect.adjusted(-2,-2,2,2).toRect());\n \n // Emit signal for context menu at the center of the selection with a delay\n // This allows the user to immediately start moving the selection if desired\n QPoint menuPosition = selectionRect.center();\n QTimer::singleShot(500, this, [this, menuPosition]() {\n // Only show menu if selection still exists and hasn't been moved\n if (!selectionBuffer.isNull() && !selectionRect.isEmpty() && !movingSelection) {\n emit ropeSelectionCompleted(menuPosition);\n }\n });\n }\n }\n lassoPathPoints.clear(); // Ready for next selection, or move\n selectingWithRope = false;\n // Now, if the user presses inside selectionRect, movingSelection will become true.\n } else if (movingSelection) {\n if (!selectionBuffer.isNull() && !selectionRect.isEmpty()) {\n QPainter painter(&buffer);\n // Explicitly set composition mode to draw on top of existing content\n painter.setCompositionMode(QPainter::CompositionMode_SourceOver);\n // Use exact floating-point position if available for more precise placement\n QPointF topLeft = exactSelectionRectF.isEmpty() ? selectionRect.topLeft() : exactSelectionRectF.topLeft();\n // Use proper coordinate transformation to get buffer coordinates\n QPointF bufferDest = mapLogicalWidgetToPhysicalBuffer(topLeft);\n painter.drawPixmap(bufferDest.toPoint(), selectionBuffer);\n painter.end();\n \n // Update the pasted area\n QRectF bufferPasteRect(bufferDest, selectionBuffer.size());\n update(mapRectBufferToWidgetLogical(bufferPasteRect).adjusted(-2,-2,2,2));\n \n // Clear selection after pasting, making it permanent\n selectionBuffer = QPixmap();\n selectionRect = QRect();\n exactSelectionRectF = QRectF();\n movingSelection = false;\n selectionJustCopied = false;\n selectionAreaCleared = false;\n selectionMaskPath = QPainterPath();\n selectionBufferRect = QRectF();\n }\n }\n }\n \n\n }\n event->accept();\n}\n void mousePressEvent(QMouseEvent *event) override {\n // Handle markdown selection when enabled\n if (markdownSelectionMode && event->button() == Qt::LeftButton) {\n markdownSelecting = true;\n markdownSelectionStart = event->pos();\n markdownSelectionEnd = markdownSelectionStart;\n event->accept();\n return;\n }\n \n // Handle PDF text selection when enabled (mouse/touch fallback - stylus handled in tabletEvent)\n if (pdfTextSelectionEnabled && isPdfLoaded) {\n if (event->button() == Qt::LeftButton) {\n pdfTextSelecting = true;\n pdfSelectionStart = event->position();\n pdfSelectionEnd = pdfSelectionStart;\n \n // Clear any existing selected text boxes without resetting pdfTextSelecting\n selectedTextBoxes.clear();\n \n setCursor(Qt::IBeamCursor); // Ensure cursor is correct\n update(); // Refresh display\n event->accept();\n return;\n }\n }\n \n // Ignore mouse/touch input on canvas for drawing (drawing only works with tablet/stylus)\n event->ignore();\n}\n void mouseMoveEvent(QMouseEvent *event) override {\n // Handle markdown selection when enabled\n if (markdownSelectionMode && markdownSelecting) {\n markdownSelectionEnd = event->pos();\n update(); // Refresh to show selection rectangle\n event->accept();\n return;\n }\n \n // Handle PDF text selection when enabled (mouse/touch fallback - stylus handled in tabletEvent)\n if (pdfTextSelectionEnabled && isPdfLoaded && pdfTextSelecting) {\n pdfSelectionEnd = event->position();\n \n // Store pending selection for throttled processing\n pendingSelectionStart = pdfSelectionStart;\n pendingSelectionEnd = pdfSelectionEnd;\n hasPendingSelection = true;\n \n // Start timer if not already running (throttled to 60 FPS)\n if (!pdfTextSelectionTimer->isActive()) {\n pdfTextSelectionTimer->start();\n }\n \n event->accept();\n return;\n }\n \n // Update cursor based on mode when not actively selecting\n if (pdfTextSelectionEnabled && isPdfLoaded && !pdfTextSelecting) {\n setCursor(Qt::IBeamCursor);\n }\n \n event->ignore();\n}\n void mouseReleaseEvent(QMouseEvent *event) override {\n // Handle markdown selection when enabled\n if (markdownSelectionMode && markdownSelecting && event->button() == Qt::LeftButton) {\n markdownSelecting = false;\n \n // Create markdown window if selection is valid\n QRect selectionRect = QRect(markdownSelectionStart, markdownSelectionEnd).normalized();\n if (selectionRect.width() > 50 && selectionRect.height() > 50 && markdownManager) {\n markdownManager->createMarkdownWindow(selectionRect);\n }\n \n // Exit selection mode\n setMarkdownSelectionMode(false);\n \n // Force screen update to clear the green selection overlay\n update();\n \n event->accept();\n return;\n }\n \n // Handle PDF text selection when enabled (mouse/touch fallback - stylus handled in tabletEvent)\n if (pdfTextSelectionEnabled && isPdfLoaded && pdfTextSelecting) {\n if (event->button() == Qt::LeftButton) {\n pdfSelectionEnd = event->position();\n \n // Process any pending selection immediately on release\n if (pdfTextSelectionTimer && pdfTextSelectionTimer->isActive()) {\n pdfTextSelectionTimer->stop();\n if (hasPendingSelection) {\n updatePdfTextSelection(pendingSelectionStart, pendingSelectionEnd);\n hasPendingSelection = false;\n }\n } else {\n // Update selection with final position\n updatePdfTextSelection(pdfSelectionStart, pdfSelectionEnd);\n }\n \n pdfTextSelecting = false;\n \n // Check for link clicks if no text was selected\n QString selectedText = getSelectedPdfText();\n if (selectedText.isEmpty()) {\n handlePdfLinkClick(event->position());\n } else {\n // Show context menu for text selection\n QPoint globalPos = mapToGlobal(event->position().toPoint());\n showPdfTextSelectionMenu(globalPos);\n }\n \n event->accept();\n return;\n }\n }\n \n\n \n event->ignore();\n}\n void resizeEvent(QResizeEvent *event) override {\n // Don't resize the buffer when the widget resizes\n // The buffer size should be determined by the PDF/document content, not the widget size\n // The paintEvent will handle centering the buffer content within the widget\n \n QWidget::resizeEvent(event);\n}\n bool event(QEvent *event) override {\n if (!touchGesturesEnabled) {\n return QWidget::event(event);\n }\n\n if (event->type() == QEvent::TouchBegin || \n event->type() == QEvent::TouchUpdate || \n event->type() == QEvent::TouchEnd) {\n \n QTouchEvent *touchEvent = static_cast(event);\n const QList touchPoints = touchEvent->points();\n \n activeTouchPoints = touchPoints.count();\n\n if (activeTouchPoints == 1) {\n // Single finger pan\n const QTouchEvent::TouchPoint &touchPoint = touchPoints.first();\n \n if (event->type() == QEvent::TouchBegin) {\n isPanning = true;\n lastTouchPos = touchPoint.position();\n } else if (event->type() == QEvent::TouchUpdate && isPanning) {\n QPointF delta = touchPoint.position() - lastTouchPos;\n \n // Make panning more responsive by using floating-point calculations\n qreal scaledDeltaX = delta.x() / (internalZoomFactor / 100.0);\n qreal scaledDeltaY = delta.y() / (internalZoomFactor / 100.0);\n \n // Calculate new pan positions with sub-pixel precision\n qreal newPanX = panOffsetX - scaledDeltaX;\n qreal newPanY = panOffsetY - scaledDeltaY;\n \n // Clamp pan values when canvas is smaller than viewport\n qreal scaledCanvasWidth = buffer.width() * (internalZoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (internalZoomFactor / 100.0);\n \n // If canvas is smaller than widget, lock pan to 0 (centered)\n if (scaledCanvasWidth < width()) {\n newPanX = 0;\n }\n if (scaledCanvasHeight < height()) {\n newPanY = 0;\n }\n \n // Emit signal with integer values for compatibility\n emit panChanged(qRound(newPanX), qRound(newPanY));\n \n lastTouchPos = touchPoint.position();\n }\n } else if (activeTouchPoints == 2) {\n // Two finger pinch zoom\n isPanning = false;\n \n const QTouchEvent::TouchPoint &touch1 = touchPoints[0];\n const QTouchEvent::TouchPoint &touch2 = touchPoints[1];\n \n // Calculate distance between touch points with higher precision\n qreal currentDist = QLineF(touch1.position(), touch2.position()).length();\n qreal startDist = QLineF(touch1.pressPosition(), touch2.pressPosition()).length();\n \n if (event->type() == QEvent::TouchBegin) {\n lastPinchScale = 1.0;\n // Store the starting internal zoom\n internalZoomFactor = zoomFactor;\n } else if (event->type() == QEvent::TouchUpdate && startDist > 0) {\n qreal scale = currentDist / startDist;\n \n // Use exponential scaling for more natural feel\n qreal scaleChange = scale / lastPinchScale;\n \n // Apply scale with higher sensitivity\n internalZoomFactor *= scaleChange;\n internalZoomFactor = qBound(10.0, internalZoomFactor, 400.0);\n \n // Calculate zoom center (midpoint between two fingers)\n QPointF center = (touch1.position() + touch2.position()) / 2.0;\n \n // Account for centering offset\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n // Adjust center point for centering offset\n QPointF adjustedCenter = center - QPointF(centerOffsetX, centerOffsetY);\n \n // Always update zoom for smooth animation\n int newZoom = qRound(internalZoomFactor);\n \n // Calculate pan adjustment to keep the zoom centered at pinch point\n QPointF bufferCenter = adjustedCenter / (zoomFactor / 100.0) + QPointF(panOffsetX, panOffsetY);\n \n // Update zoom factor before emitting\n qreal oldZoomFactor = zoomFactor;\n zoomFactor = newZoom;\n \n // Emit zoom change even for small changes\n emit zoomChanged(newZoom);\n \n // Adjust pan to keep center point fixed with sub-pixel precision\n qreal newPanX = bufferCenter.x() - adjustedCenter.x() / (internalZoomFactor / 100.0);\n qreal newPanY = bufferCenter.y() - adjustedCenter.y() / (internalZoomFactor / 100.0);\n \n // After zoom, check if we need to center\n qreal newScaledCanvasWidth = buffer.width() * (internalZoomFactor / 100.0);\n qreal newScaledCanvasHeight = buffer.height() * (internalZoomFactor / 100.0);\n \n if (newScaledCanvasWidth < width()) {\n newPanX = 0;\n }\n if (newScaledCanvasHeight < height()) {\n newPanY = 0;\n }\n \n emit panChanged(qRound(newPanX), qRound(newPanY));\n \n lastPinchScale = scale;\n \n // Request update only for visible area\n update();\n }\n } else {\n // More than 2 fingers - ignore\n isPanning = false;\n }\n \n if (event->type() == QEvent::TouchEnd) {\n isPanning = false;\n lastPinchScale = 1.0;\n activeTouchPoints = 0;\n // Sync internal zoom with actual zoom\n internalZoomFactor = zoomFactor;\n \n // Emit signal that touch gesture has ended\n emit touchGestureEnded();\n }\n \n event->accept();\n return true;\n }\n \n return QWidget::event(event);\n}\n private:\n QPointF mapLogicalWidgetToPhysicalBuffer(const QPointF& logicalWidgetPoint) {\n // Use the same coordinate transformation logic as drawStroke for consistency\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n // Convert widget position to buffer position, accounting for centering\n QPointF adjustedPoint = logicalWidgetPoint - QPointF(centerOffsetX, centerOffsetY);\n QPointF bufferPoint = (adjustedPoint / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n \n return bufferPoint;\n}\n QRect mapRectBufferToWidgetLogical(const QRectF& physicalBufferRect) {\n // Use the same coordinate transformation logic as drawStroke for consistency\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n // Convert buffer coordinates back to widget coordinates\n QRectF widgetRect = QRectF(\n (physicalBufferRect.topLeft() - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY),\n physicalBufferRect.size() * (zoomFactor / 100.0)\n );\n \n return widgetRect.toRect();\n}\n QPixmap buffer;\n QImage background;\n QPointF lastPoint;\n QPointF straightLineStartPoint;\n bool drawing;\n QColor penColor;\n qreal penThickness;\n ToolType currentTool;\n ToolType previousTool;\n qreal penToolThickness = 5.0;\n qreal markerToolThickness = 5.0;\n qreal eraserToolThickness = 5.0;\n QString saveFolder;\n QPixmap backgroundImage;\n bool straightLineMode = false;\n bool ropeToolMode = false;\n QPixmap selectionBuffer;\n QRect selectionRect;\n QRectF exactSelectionRectF;\n QPolygonF lassoPathPoints;\n bool selectingWithRope = false;\n bool movingSelection = false;\n bool selectionJustCopied = false;\n bool selectionAreaCleared = false;\n QPainterPath selectionMaskPath;\n QRectF selectionBufferRect;\n QPointF lastMovePoint;\n int zoomFactor;\n int panOffsetX;\n int panOffsetY;\n qreal internalZoomFactor = 100.0;\n void initializeBuffer() {\n QScreen *screen = QGuiApplication::primaryScreen();\n qreal dpr = screen ? screen->devicePixelRatio() : 1.0;\n\n // Get logical screen size\n QSize logicalSize = screen ? screen->size() : QSize(1440, 900);\n QSize pixelSize = logicalSize * dpr;\n\n buffer = QPixmap(pixelSize);\n buffer.fill(Qt::transparent);\n\n setMaximumSize(pixelSize); // 🔥 KEY LINE to make full canvas drawable\n}\n void drawStroke(const QPointF &start, const QPointF &end, qreal pressure) {\n if (buffer.isNull()) {\n initializeBuffer();\n }\n\n if (!edited){\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n\n QPainter painter(&buffer);\n painter.setRenderHint(QPainter::Antialiasing);\n\n qreal thickness = penThickness;\n\n qreal updatePadding = (currentTool == ToolType::Marker) ? thickness * 4.0 : 10;\n\n if (currentTool == ToolType::Marker) {\n thickness *= 8.0;\n QColor markerColor = penColor;\n // Adjust alpha based on whether we're in straight line mode\n if (straightLineMode) {\n // For straight line mode, use higher alpha to make it more visible\n markerColor.setAlpha(40);\n } else {\n // For regular drawing, use lower alpha for the usual marker effect\n markerColor.setAlpha(4);\n }\n QPen pen(markerColor, thickness, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);\n painter.setPen(pen);\n } else { // Default Pen\n qreal scaledThickness = thickness * pressure; // **Linear pressure scaling**\n QPen pen(penColor, scaledThickness, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);\n painter.setPen(pen);\n }\n\n // Calculate centering offsets\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n // Convert screen position to buffer position, accounting for centering\n QPointF adjustedStart = start - QPointF(centerOffsetX, centerOffsetY);\n QPointF adjustedEnd = end - QPointF(centerOffsetX, centerOffsetY);\n \n QPointF bufferStart = (adjustedStart / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n QPointF bufferEnd = (adjustedEnd / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n\n painter.drawLine(bufferStart, bufferEnd);\n\n QRectF updateRect = QRectF(bufferStart, bufferEnd)\n .normalized()\n .adjusted(-updatePadding, -updatePadding, updatePadding, updatePadding);\n\n QRect scaledUpdateRect = QRect(\n ((updateRect.topLeft() - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY)).toPoint(),\n ((updateRect.bottomRight() - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY)).toPoint()\n );\n update(scaledUpdateRect);\n}\n void eraseStroke(const QPointF &start, const QPointF &end, qreal pressure) {\n if (buffer.isNull()) {\n initializeBuffer();\n }\n\n if (!edited){\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n\n QPainter painter(&buffer);\n painter.setCompositionMode(QPainter::CompositionMode_Clear);\n\n qreal eraserThickness = penThickness * 6.0;\n QPen eraserPen(Qt::transparent, eraserThickness, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);\n painter.setPen(eraserPen);\n\n // Calculate centering offsets\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n // Convert screen position to buffer position, accounting for centering\n QPointF adjustedStart = start - QPointF(centerOffsetX, centerOffsetY);\n QPointF adjustedEnd = end - QPointF(centerOffsetX, centerOffsetY);\n \n QPointF bufferStart = (adjustedStart / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n QPointF bufferEnd = (adjustedEnd / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n\n painter.drawLine(bufferStart, bufferEnd);\n\n qreal updatePadding = eraserThickness / 2.0 + 5.0; // Half the eraser thickness plus some extra padding\n QRectF updateRect = QRectF(bufferStart, bufferEnd)\n .normalized()\n .adjusted(-updatePadding, -updatePadding, updatePadding, updatePadding);\n\n QRect scaledUpdateRect = QRect(\n ((updateRect.topLeft() - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY)).toPoint(),\n ((updateRect.bottomRight() - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY)).toPoint()\n );\n update(scaledUpdateRect);\n}\n QRectF calculatePreviewRect(const QPointF &start, const QPointF &oldEnd, const QPointF &newEnd) {\n // Calculate centering offsets - use the same calculation as in paintEvent\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n // Calculate the buffer coordinates for our points (same as in drawStroke)\n QPointF adjustedStart = start - QPointF(centerOffsetX, centerOffsetY);\n QPointF adjustedOldEnd = oldEnd - QPointF(centerOffsetX, centerOffsetY);\n QPointF adjustedNewEnd = newEnd - QPointF(centerOffsetX, centerOffsetY);\n \n QPointF bufferStart = (adjustedStart / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n QPointF bufferOldEnd = (adjustedOldEnd / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n QPointF bufferNewEnd = (adjustedNewEnd / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n \n // Now convert from buffer coordinates to screen coordinates\n QPointF screenStart = (bufferStart - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY);\n QPointF screenOldEnd = (bufferOldEnd - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY);\n QPointF screenNewEnd = (bufferNewEnd - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY);\n \n // Create rectangles for both the old and new lines\n QRectF oldLineRect = QRectF(screenStart, screenOldEnd).normalized();\n QRectF newLineRect = QRectF(screenStart, screenNewEnd).normalized();\n \n // Calculate padding based on pen thickness and device pixel ratio\n qreal dpr = devicePixelRatioF();\n qreal padding;\n \n if (currentTool == ToolType::Eraser) {\n padding = penThickness * 6.0 * dpr;\n } else if (currentTool == ToolType::Marker) {\n padding = penThickness * 8.0 * dpr;\n } else {\n padding = penThickness * dpr;\n }\n \n // Ensure minimum padding\n padding = qMax(padding, 15.0);\n \n // Combine rectangles with appropriate padding\n QRectF combinedRect = oldLineRect.united(newLineRect);\n return combinedRect.adjusted(-padding, -padding, padding, padding);\n}\n QCache pdfCache;\n std::unique_ptr pdfDocument;\n int currentPdfPage;\n bool isPdfLoaded = false;\n int totalPdfPages = 0;\n int lastActivePage = 0;\n int lastZoomLevel = 100;\n int lastPanX = 0;\n int lastPanY = 0;\n bool edited = false;\n bool benchmarking;\n std::deque processedTimestamps;\n QElapsedTimer benchmarkTimer;\n QString notebookId;\n void loadNotebookId() {\n QString idFile = saveFolder + \"/.notebook_id.txt\";\n if (QFile::exists(idFile)) {\n QFile file(idFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n notebookId = in.readLine().trimmed();\n }\n } else {\n // No ID file → create new random ID\n notebookId = QUuid::createUuid().toString(QUuid::WithoutBraces).replace(\"-\", \"\");\n saveNotebookId();\n }\n}\n void saveNotebookId() {\n QString idFile = saveFolder + \"/.notebook_id.txt\";\n QFile file(idFile);\n if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {\n QTextStream out(&file);\n out << notebookId;\n }\n}\n int pdfRenderDPI = 192;\n bool touchGesturesEnabled = false;\n QPointF lastTouchPos;\n qreal lastPinchScale = 1.0;\n bool isPanning = false;\n int activeTouchPoints = 0;\n BackgroundStyle backgroundStyle = BackgroundStyle::None;\n QColor backgroundColor = Qt::white;\n int backgroundDensity = 40;\n bool pdfTextSelectionEnabled = false;\n bool pdfTextSelecting = false;\n QPointF pdfSelectionStart;\n QPointF pdfSelectionEnd;\n QList currentPdfTextBoxes;\n QList selectedTextBoxes;\n std::unique_ptr currentPdfPageForText;\n QTimer* pdfTextSelectionTimer = nullptr;\n QPointF pendingSelectionStart;\n QPointF pendingSelectionEnd;\n bool hasPendingSelection = false;\n QTimer* pdfCacheTimer = nullptr;\n int currentCachedPage = -1;\n int pendingCacheTargetPage = -1;\n QList*> activePdfWatchers;\n QCache noteCache;\n QTimer* noteCacheTimer = nullptr;\n int currentCachedNotePage = -1;\n int pendingNoteCacheTargetPage = -1;\n QList*> activeNoteWatchers;\n MarkdownWindowManager* markdownManager = nullptr;\n bool markdownSelectionMode = false;\n QPoint markdownSelectionStart;\n QPoint markdownSelectionEnd;\n bool markdownSelecting = false;\n void loadPdfTextBoxes(int pageNumber) {\n // Clear existing text boxes\n qDeleteAll(currentPdfTextBoxes);\n currentPdfTextBoxes.clear();\n \n if (!pdfDocument || pageNumber < 0 || pageNumber >= pdfDocument->numPages()) {\n return;\n }\n \n // Get the page for text operations\n currentPdfPageForText = std::unique_ptr(pdfDocument->page(pageNumber));\n if (!currentPdfPageForText) {\n return;\n }\n \n // Load text boxes for the page\n auto textBoxVector = currentPdfPageForText->textList();\n currentPdfTextBoxes.clear();\n for (auto& textBox : textBoxVector) {\n currentPdfTextBoxes.append(textBox.release()); // Transfer ownership to QList\n }\n}\n QPointF mapWidgetToPdfCoordinates(const QPointF &widgetPoint) {\n if (!currentPdfPageForText || backgroundImage.isNull()) {\n return QPointF();\n }\n \n // Use the same zoom factor as in paintEvent (internalZoomFactor for smooth animations)\n qreal zoom = internalZoomFactor / 100.0;\n \n // Calculate the scaled canvas size (same as in paintEvent)\n qreal scaledCanvasWidth = buffer.width() * zoom;\n qreal scaledCanvasHeight = buffer.height() * zoom;\n \n // Calculate centering offsets (same as in paintEvent)\n qreal centerOffsetX = 0;\n qreal centerOffsetY = 0;\n \n // Center horizontally if canvas is smaller than widget\n if (scaledCanvasWidth < width()) {\n centerOffsetX = (width() - scaledCanvasWidth) / 2.0;\n }\n \n // Center vertically if canvas is smaller than widget\n if (scaledCanvasHeight < height()) {\n centerOffsetY = (height() - scaledCanvasHeight) / 2.0;\n }\n \n // Reverse the transformations applied in paintEvent\n QPointF adjustedPoint = widgetPoint;\n adjustedPoint -= QPointF(centerOffsetX, centerOffsetY);\n adjustedPoint /= zoom;\n adjustedPoint += QPointF(panOffsetX, panOffsetY);\n \n // Convert to PDF coordinates\n // Since Poppler renders the PDF in Qt coordinate system (top-left origin),\n // we don't need to flip the Y coordinate\n QSizeF pdfPageSize = currentPdfPageForText->pageSizeF();\n QSizeF imageSize = backgroundImage.size();\n \n // Scale from image coordinates to PDF coordinates\n qreal scaleX = pdfPageSize.width() / imageSize.width();\n qreal scaleY = pdfPageSize.height() / imageSize.height();\n \n QPointF pdfPoint;\n pdfPoint.setX(adjustedPoint.x() * scaleX);\n pdfPoint.setY(adjustedPoint.y() * scaleY); // No Y-axis flipping needed\n \n return pdfPoint;\n}\n QPointF mapPdfToWidgetCoordinates(const QPointF &pdfPoint) {\n if (!currentPdfPageForText || backgroundImage.isNull()) {\n return QPointF();\n }\n \n // Convert from PDF coordinates to image coordinates\n QSizeF pdfPageSize = currentPdfPageForText->pageSizeF();\n QSizeF imageSize = backgroundImage.size();\n \n // Scale from PDF coordinates to image coordinates\n qreal scaleX = imageSize.width() / pdfPageSize.width();\n qreal scaleY = imageSize.height() / pdfPageSize.height();\n \n QPointF imagePoint;\n imagePoint.setX(pdfPoint.x() * scaleX);\n imagePoint.setY(pdfPoint.y() * scaleY); // No Y-axis flipping needed\n \n // Use the same zoom factor as in paintEvent (internalZoomFactor for smooth animations)\n qreal zoom = internalZoomFactor / 100.0;\n \n // Apply the same transformations as in paintEvent\n QPointF widgetPoint = imagePoint;\n widgetPoint -= QPointF(panOffsetX, panOffsetY);\n widgetPoint *= zoom;\n \n // Calculate the scaled canvas size (same as in paintEvent)\n qreal scaledCanvasWidth = buffer.width() * zoom;\n qreal scaledCanvasHeight = buffer.height() * zoom;\n \n // Calculate centering offsets (same as in paintEvent)\n qreal centerOffsetX = 0;\n qreal centerOffsetY = 0;\n \n // Center horizontally if canvas is smaller than widget\n if (scaledCanvasWidth < width()) {\n centerOffsetX = (width() - scaledCanvasWidth) / 2.0;\n }\n \n // Center vertically if canvas is smaller than widget\n if (scaledCanvasHeight < height()) {\n centerOffsetY = (height() - scaledCanvasHeight) / 2.0;\n }\n \n widgetPoint += QPointF(centerOffsetX, centerOffsetY);\n \n return widgetPoint;\n}\n void updatePdfTextSelection(const QPointF &start, const QPointF &end) {\n // Early return if PDF is not loaded or no text boxes available\n if (!isPdfLoaded || currentPdfTextBoxes.isEmpty()) {\n return;\n }\n \n // Clear previous selection efficiently\n selectedTextBoxes.clear();\n \n // Create normalized selection rectangle in widget coordinates\n QRectF widgetSelectionRect(start, end);\n widgetSelectionRect = widgetSelectionRect.normalized();\n \n // Convert to PDF coordinate space\n QPointF pdfTopLeft = mapWidgetToPdfCoordinates(widgetSelectionRect.topLeft());\n QPointF pdfBottomRight = mapWidgetToPdfCoordinates(widgetSelectionRect.bottomRight());\n QRectF pdfSelectionRect(pdfTopLeft, pdfBottomRight);\n pdfSelectionRect = pdfSelectionRect.normalized();\n \n // Reserve space for efficiency if we expect many selections\n selectedTextBoxes.reserve(qMin(currentPdfTextBoxes.size(), 50));\n \n // Find intersecting text boxes with optimized loop\n for (const Poppler::TextBox* textBox : currentPdfTextBoxes) {\n if (textBox && textBox->boundingBox().intersects(pdfSelectionRect)) {\n selectedTextBoxes.append(const_cast(textBox));\n }\n }\n \n // Only emit signal and update if we have selected text\n if (!selectedTextBoxes.isEmpty()) {\n QString selectedText = getSelectedPdfText();\n if (!selectedText.isEmpty()) {\n emit pdfTextSelected(selectedText);\n }\n }\n \n // Trigger repaint to show selection\n update();\n}\n void handlePdfLinkClick(const QPointF &clickPoint) {\n if (!isPdfLoaded || !currentPdfPageForText) {\n return;\n }\n \n // Convert widget coordinates to PDF coordinates\n QPointF pdfPoint = mapWidgetToPdfCoordinates(position);\n \n // Get PDF page size for reference\n QSizeF pdfPageSize = currentPdfPageForText->pageSizeF();\n \n // Convert to normalized coordinates (0.0 to 1.0) to match Poppler's link coordinate system\n QPointF normalizedPoint(pdfPoint.x() / pdfPageSize.width(), pdfPoint.y() / pdfPageSize.height());\n \n // Get links for the current page\n auto links = currentPdfPageForText->links();\n \n for (const auto& link : links) {\n QRectF linkArea = link->linkArea();\n \n // Normalize the rectangle to handle negative width/height\n QRectF normalizedLinkArea = linkArea.normalized();\n \n // Check if the normalized rectangle contains the normalized point\n if (normalizedLinkArea.contains(normalizedPoint)) {\n // Handle different types of links\n if (link->linkType() == Poppler::Link::Goto) {\n Poppler::LinkGoto* gotoLink = static_cast(link.get());\n if (gotoLink && gotoLink->destination().pageNumber() >= 0) {\n int targetPage = gotoLink->destination().pageNumber() - 1; // Convert to 0-based\n emit pdfLinkClicked(targetPage);\n return;\n }\n }\n // Add other link types as needed (URI, etc.)\n }\n }\n}\n void showPdfTextSelectionMenu(const QPoint &position) {\n QString selectedText = getSelectedPdfText();\n if (selectedText.isEmpty()) {\n return; // No text selected, don't show menu\n }\n \n // Create context menu\n QMenu *contextMenu = new QMenu(this);\n contextMenu->setAttribute(Qt::WA_DeleteOnClose);\n \n // Add Copy action\n QAction *copyAction = contextMenu->addAction(tr(\"Copy\"));\n copyAction->setIcon(QIcon(\":/resources/icons/copy.png\")); // You may need to add this icon\n connect(copyAction, &QAction::triggered, this, [selectedText]() {\n QClipboard *clipboard = QGuiApplication::clipboard();\n clipboard->setText(selectedText);\n });\n \n // Add separator\n contextMenu->addSeparator();\n \n // Add Cancel action\n QAction *cancelAction = contextMenu->addAction(tr(\"Cancel\"));\n cancelAction->setIcon(QIcon(\":/resources/icons/cross.png\"));\n connect(cancelAction, &QAction::triggered, this, [this]() {\n clearPdfTextSelection();\n });\n \n // Show the menu at the specified position\n contextMenu->popup(position);\n}\n QList getTextBoxesInSelection(const QPointF &start, const QPointF &end) {\n QList selectedBoxes;\n \n if (!currentPdfPageForText) {\n // qDebug() << \"PDF text selection: No current page for text\";\n return selectedBoxes;\n }\n \n // Convert widget coordinates to PDF coordinates\n QPointF pdfStart = mapWidgetToPdfCoordinates(start);\n QPointF pdfEnd = mapWidgetToPdfCoordinates(end);\n \n // qDebug() << \"PDF text selection: Widget coords\" << start << \"to\" << end;\n // qDebug() << \"PDF text selection: PDF coords\" << pdfStart << \"to\" << pdfEnd;\n \n // Create selection rectangle in PDF coordinates\n QRectF selectionRect(pdfStart, pdfEnd);\n selectionRect = selectionRect.normalized();\n \n // qDebug() << \"PDF text selection: Selection rect in PDF coords:\" << selectionRect;\n \n // Find text boxes that intersect with the selection\n int intersectionCount = 0;\n for (Poppler::TextBox* textBox : currentPdfTextBoxes) {\n if (textBox) {\n QRectF textBoxRect = textBox->boundingBox();\n bool intersects = textBoxRect.intersects(selectionRect);\n \n if (intersects) {\n selectedBoxes.append(textBox);\n intersectionCount++;\n // qDebug() << \"PDF text selection: Text box intersects:\" << textBox->text() \n // << \"at\" << textBoxRect;\n }\n }\n }\n \n // qDebug() << \"PDF text selection: Found\" << intersectionCount << \"intersecting text boxes\";\n \n return selectedBoxes;\n}\n void renderPdfPageToCache(int pageNumber) {\n if (!pdfDocument || !isValidPageNumber(pageNumber)) {\n return;\n }\n \n // Check if already cached\n if (pdfCache.contains(pageNumber)) {\n return;\n }\n \n // Ensure the cache holds only 10 pages max\n if (pdfCache.count() >= 10) {\n auto oldestKey = pdfCache.keys().first();\n pdfCache.remove(oldestKey);\n }\n \n // Render the page and store it in the cache\n std::unique_ptr page(pdfDocument->page(pageNumber));\n if (page) {\n // Render with document-level anti-aliasing settings\n QImage pdfImage = page->renderToImage(pdfRenderDPI, pdfRenderDPI);\n if (!pdfImage.isNull()) {\n QPixmap cachedPixmap = QPixmap::fromImage(pdfImage);\n pdfCache.insert(pageNumber, new QPixmap(cachedPixmap));\n }\n }\n}\n void checkAndCacheAdjacentPages(int targetPage) {\n if (!pdfDocument || !isValidPageNumber(targetPage)) {\n return;\n }\n \n // Calculate adjacent pages\n int prevPage = targetPage - 1;\n int nextPage = targetPage + 1;\n \n // Check what needs to be cached\n bool needPrevPage = isValidPageNumber(prevPage) && !pdfCache.contains(prevPage);\n bool needCurrentPage = !pdfCache.contains(targetPage);\n bool needNextPage = isValidPageNumber(nextPage) && !pdfCache.contains(nextPage);\n \n // If all pages are cached, nothing to do\n if (!needPrevPage && !needCurrentPage && !needNextPage) {\n return;\n }\n \n // Stop any existing timer\n if (pdfCacheTimer && pdfCacheTimer->isActive()) {\n pdfCacheTimer->stop();\n }\n \n // Create timer if it doesn't exist\n if (!pdfCacheTimer) {\n pdfCacheTimer = new QTimer(this);\n pdfCacheTimer->setSingleShot(true);\n connect(pdfCacheTimer, &QTimer::timeout, this, &InkCanvas::cacheAdjacentPages);\n }\n \n // Store the target page for validation when timer fires\n pendingCacheTargetPage = targetPage;\n \n // Start 1-second delay timer\n pdfCacheTimer->start(1000);\n}\n bool isValidPageNumber(int pageNumber) const {\n return (pageNumber >= 0 && pageNumber < totalPdfPages);\n}\n void loadNotePageToCache(int pageNumber) {\n // Check if already cached\n if (noteCache.contains(pageNumber)) {\n return;\n }\n \n QString filePath = getNotePageFilePath(pageNumber);\n if (filePath.isEmpty()) {\n return;\n }\n \n // Ensure the cache doesn't exceed its limit\n if (noteCache.count() >= 15) {\n // QCache will automatically remove least recently used items\n // but we can be explicit about it\n auto keys = noteCache.keys();\n if (!keys.isEmpty()) {\n noteCache.remove(keys.first());\n }\n }\n \n // Load note page from disk if it exists\n if (QFile::exists(filePath)) {\n QPixmap notePixmap;\n if (notePixmap.load(filePath)) {\n noteCache.insert(pageNumber, new QPixmap(notePixmap));\n }\n }\n // If file doesn't exist, we don't cache anything - loadPage will handle initialization\n}\n void checkAndCacheAdjacentNotePages(int targetPage) {\n if (saveFolder.isEmpty()) {\n return;\n }\n \n // Calculate adjacent pages\n int prevPage = targetPage - 1;\n int nextPage = targetPage + 1;\n \n // Check what needs to be cached (we don't have a max page limit for notes)\n bool needPrevPage = (prevPage >= 0) && !noteCache.contains(prevPage);\n bool needCurrentPage = !noteCache.contains(targetPage);\n bool needNextPage = !noteCache.contains(nextPage); // No upper limit check for notes\n \n // If all nearby pages are cached, nothing to do\n if (!needPrevPage && !needCurrentPage && !needNextPage) {\n return;\n }\n \n // Stop any existing timer\n if (noteCacheTimer && noteCacheTimer->isActive()) {\n noteCacheTimer->stop();\n }\n \n // Create timer if it doesn't exist\n if (!noteCacheTimer) {\n noteCacheTimer = new QTimer(this);\n noteCacheTimer->setSingleShot(true);\n connect(noteCacheTimer, &QTimer::timeout, this, &InkCanvas::cacheAdjacentNotePages);\n }\n \n // Store the target page for validation when timer fires\n pendingNoteCacheTargetPage = targetPage;\n \n // Start 1-second delay timer\n noteCacheTimer->start(1000);\n}\n QString getNotePageFilePath(int pageNumber) const {\n if (saveFolder.isEmpty() || notebookId.isEmpty()) {\n return QString();\n }\n return saveFolder + QString(\"/%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n}\n void invalidateCurrentPageCache() {\n if (currentCachedNotePage >= 0) {\n noteCache.remove(currentCachedNotePage);\n }\n}\n private:\n void processPendingTextSelection() {\n if (!hasPendingSelection) {\n return;\n }\n \n // Process the pending selection update\n updatePdfTextSelection(pendingSelectionStart, pendingSelectionEnd);\n hasPendingSelection = false;\n}\n void cacheAdjacentPages() {\n if (!pdfDocument || currentCachedPage < 0) {\n return;\n }\n \n // Check if the user has moved to a different page since the timer was started\n // If so, skip caching adjacent pages as they're no longer relevant\n if (pendingCacheTargetPage != currentCachedPage) {\n return; // User switched pages, don't cache adjacent pages for old page\n }\n \n int targetPage = currentCachedPage;\n int prevPage = targetPage - 1;\n int nextPage = targetPage + 1;\n \n // Create list of pages to cache asynchronously\n QList pagesToCache;\n \n // Add previous page if needed\n if (isValidPageNumber(prevPage) && !pdfCache.contains(prevPage)) {\n pagesToCache.append(prevPage);\n }\n \n // Add next page if needed\n if (isValidPageNumber(nextPage) && !pdfCache.contains(nextPage)) {\n pagesToCache.append(nextPage);\n }\n \n // Cache pages asynchronously\n for (int pageNum : pagesToCache) {\n QFutureWatcher *watcher = new QFutureWatcher(this);\n \n // Track the watcher for cleanup\n activePdfWatchers.append(watcher);\n \n connect(watcher, &QFutureWatcher::finished, this, [this, watcher]() {\n // Remove from active list and delete\n activePdfWatchers.removeOne(watcher);\n watcher->deleteLater();\n });\n \n // Capture pageNum by value to avoid issues with lambda capture\n QFuture future = QtConcurrent::run([this, pageNum]() {\n renderPdfPageToCache(pageNum);\n });\n \n watcher->setFuture(future);\n }\n}\n void cacheAdjacentNotePages() {\n if (saveFolder.isEmpty() || currentCachedNotePage < 0) {\n return;\n }\n \n // Check if the user has moved to a different page since the timer was started\n // If so, skip caching adjacent pages as they're no longer relevant\n if (pendingNoteCacheTargetPage != currentCachedNotePage) {\n return; // User switched pages, don't cache adjacent pages for old page\n }\n \n int targetPage = currentCachedNotePage;\n int prevPage = targetPage - 1;\n int nextPage = targetPage + 1;\n \n // Create list of note pages to cache asynchronously\n QList notePagesToCache;\n \n // Add previous page if needed (check for >= 0 since notes can start from page 0)\n if (prevPage >= 0 && !noteCache.contains(prevPage)) {\n notePagesToCache.append(prevPage);\n }\n \n // Add next page if needed (no upper limit check for notes)\n if (!noteCache.contains(nextPage)) {\n notePagesToCache.append(nextPage);\n }\n \n // Cache note pages asynchronously\n for (int pageNum : notePagesToCache) {\n QFutureWatcher *watcher = new QFutureWatcher(this);\n \n // Track the watcher for cleanup\n activeNoteWatchers.append(watcher);\n \n connect(watcher, &QFutureWatcher::finished, this, [this, watcher]() {\n // Remove from active list and delete\n activeNoteWatchers.removeOne(watcher);\n watcher->deleteLater();\n });\n \n // Capture pageNum by value to avoid issues with lambda capture\n QFuture future = QtConcurrent::run([this, pageNum]() {\n loadNotePageToCache(pageNum);\n });\n \n watcher->setFuture(future);\n }\n}\n};"], ["/SpeedyNote/source/RecentNotebooksManager.h", "class InkCanvas {\n Q_OBJECT\n\npublic:\n explicit RecentNotebooksManager(QObject *parent = nullptr);\n void addRecentNotebook(const QString& folderPath, InkCanvas* canvasForPreview = nullptr) {\n if (folderPath.isEmpty()) return;\n\n // Remove if already exists to move it to the front\n recentNotebookPaths.removeAll(folderPath);\n recentNotebookPaths.prepend(folderPath);\n\n // Trim the list if it exceeds the maximum size\n while (recentNotebookPaths.size() > MAX_RECENT_NOTEBOOKS) {\n recentNotebookPaths.removeLast();\n }\n\n generateAndSaveCoverPreview(folderPath, canvasForPreview);\n saveRecentNotebooks();\n}\n QStringList getRecentNotebooks() const {\n return recentNotebookPaths;\n}\n QString getCoverImagePathForNotebook(const QString& folderPath) const {\n QString coverDir = getCoverImageDir();\n QString coverFileName = sanitizeFolderName(folderPath) + \"_cover.png\";\n QString coverFilePath = coverDir + coverFileName;\n if (QFile::exists(coverFilePath)) {\n return coverFilePath;\n }\n return \"\"; // Return empty if no cover exists\n}\n QString getNotebookDisplayName(const QString& folderPath) const {\n // Check for PDF metadata first\n QString metadataFile = folderPath + \"/.pdf_path.txt\";\n if (QFile::exists(metadataFile)) {\n QFile file(metadataFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString pdfPath = in.readLine().trimmed();\n file.close();\n if (!pdfPath.isEmpty()) {\n return QFileInfo(pdfPath).fileName();\n }\n }\n }\n // Fallback to folder name\n return QFileInfo(folderPath).fileName();\n}\n void generateAndSaveCoverPreview(const QString& folderPath, InkCanvas* optionalCanvas = nullptr) {\n QString coverDir = getCoverImageDir();\n QString coverFileName = sanitizeFolderName(folderPath) + \"_cover.png\";\n QString coverFilePath = coverDir + coverFileName;\n\n QImage coverImage(400, 300, QImage::Format_ARGB32_Premultiplied);\n coverImage.fill(Qt::white); // Default background\n QPainter painter(&coverImage);\n painter.setRenderHint(QPainter::SmoothPixmapTransform);\n\n if (optionalCanvas && optionalCanvas->width() > 0 && optionalCanvas->height() > 0) {\n int logicalCanvasWidth = optionalCanvas->width();\n int logicalCanvasHeight = optionalCanvas->height();\n\n double targetAspectRatio = 4.0 / 3.0;\n double canvasAspectRatio = (double)logicalCanvasWidth / logicalCanvasHeight;\n\n int grabWidth, grabHeight;\n int xOffset = 0, yOffset = 0;\n\n if (canvasAspectRatio > targetAspectRatio) { // Canvas is wider than target 4:3\n grabHeight = logicalCanvasHeight;\n grabWidth = qRound(logicalCanvasHeight * targetAspectRatio);\n xOffset = (logicalCanvasWidth - grabWidth) / 2;\n } else { // Canvas is taller than or equal to target 4:3\n grabWidth = logicalCanvasWidth;\n grabHeight = qRound(logicalCanvasWidth / targetAspectRatio);\n yOffset = (logicalCanvasHeight - grabHeight) / 2;\n }\n\n if (grabWidth > 0 && grabHeight > 0) {\n QRect grabRect(xOffset, yOffset, grabWidth, grabHeight);\n QPixmap capturedView = optionalCanvas->grab(grabRect);\n painter.drawPixmap(coverImage.rect(), capturedView, capturedView.rect());\n } else {\n // Fallback if calculated grab dimensions are invalid, draw placeholder or fill\n // This case should ideally not be hit if canvas width/height > 0\n painter.fillRect(coverImage.rect(), Qt::lightGray);\n painter.setPen(Qt::black);\n painter.drawText(coverImage.rect(), Qt::AlignCenter, tr(\"Preview Error\"));\n }\n } else {\n // Fallback: check for a saved \"annotated_..._00000.png\" or the first page\n // This part remains the same as it deals with pre-rendered images.\n QString notebookIdStr;\n InkCanvas tempCanvas(nullptr); // Temporary canvas to access potential notebookId property logic if it were there\n // However, notebookId is specific to an instance with a saveFolder.\n // For a generic fallback, we might need a different way or assume a common naming if notebookId is unknown.\n // For now, let's assume a simple naming or improve this fallback if needed.\n \n // Attempt to get notebookId if folderPath is a valid notebook with an ID file\n QFile idFile(folderPath + \"/.notebook_id.txt\");\n if (idFile.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&idFile);\n notebookIdStr = in.readLine().trimmed();\n idFile.close();\n }\n\n QString firstPagePath, firstAnnotatedPagePath;\n if (!notebookIdStr.isEmpty()) {\n firstPagePath = folderPath + QString(\"/%1_00000.png\").arg(notebookIdStr);\n firstAnnotatedPagePath = folderPath + QString(\"/annotated_%1_00000.png\").arg(notebookIdStr);\n } else {\n // Fallback if no ID, try a generic name (less ideal)\n // This situation should be rare if notebooks are managed properly\n // For robustness, one might iterate files or use a known default page name\n // For this example, we'll stick to a pattern that might not always work without an ID\n // Consider that `InkCanvas(nullptr).property(\"notebookId\")` was problematic as `notebookId` is instance specific.\n }\n\n QImage pageImage;\n if (!firstAnnotatedPagePath.isEmpty() && QFile::exists(firstAnnotatedPagePath)) {\n pageImage.load(firstAnnotatedPagePath);\n } else if (!firstPagePath.isEmpty() && QFile::exists(firstPagePath)) {\n pageImage.load(firstPagePath);\n }\n\n if (!pageImage.isNull()) {\n painter.drawImage(coverImage.rect(), pageImage, pageImage.rect());\n } else {\n // If no image found, draw a placeholder\n painter.fillRect(coverImage.rect(), Qt::darkGray);\n painter.setPen(Qt::white);\n painter.drawText(coverImage.rect(), Qt::AlignCenter, tr(\"No Page 0 Preview\"));\n }\n }\n coverImage.save(coverFilePath, \"PNG\");\n}\n private:\n void loadRecentNotebooks() {\n recentNotebookPaths = settings.value(\"recentNotebooks\").toStringList();\n}\n void saveRecentNotebooks() {\n settings.setValue(\"recentNotebooks\", recentNotebookPaths);\n}\n QString getCoverImageDir() const {\n return QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/RecentCovers/\";\n}\n QString sanitizeFolderName(const QString& folderPath) const {\n return QFileInfo(folderPath).baseName().replace(QRegularExpression(\"[^a-zA-Z0-9_]\"), \"_\");\n}\n QStringList recentNotebookPaths;\n const int MAX_RECENT_NOTEBOOKS = 16;\n QSettings settings;\n};"], ["/SpeedyNote/source/ControllerMappingDialog.h", "class SDLControllerManager {\n Q_OBJECT\n\npublic:\n explicit ControllerMappingDialog(SDLControllerManager *controllerManager, QWidget *parent = nullptr);\n private:\n void startButtonMapping(const QString &logicalButton) {\n if (!controller) return;\n \n // Disable all mapping buttons during mapping\n for (auto button : mappingButtons) {\n button->setEnabled(false);\n }\n \n // Update the current button being mapped\n currentMappingButton = logicalButton;\n mappingButtons[logicalButton]->setText(tr(\"Press button...\"));\n \n // Start button detection mode\n controller->startButtonDetection();\n \n // Start timeout timer\n mappingTimeoutTimer->start();\n \n // Show status message\n QApplication::setOverrideCursor(Qt::WaitCursor);\n}\n void onRawButtonPressed(int sdlButton, const QString &buttonName) {\n if (currentMappingButton.isEmpty()) return;\n \n // Stop detection and timeout\n controller->stopButtonDetection();\n mappingTimeoutTimer->stop();\n QApplication::restoreOverrideCursor();\n \n // Check if this button is already mapped to another function\n QMap currentMappings = controller->getAllPhysicalMappings();\n QString conflictingButton;\n for (auto it = currentMappings.begin(); it != currentMappings.end(); ++it) {\n if (it.value() == sdlButton && it.key() != currentMappingButton) {\n conflictingButton = it.key();\n break;\n }\n }\n \n if (!conflictingButton.isEmpty()) {\n int ret = QMessageBox::question(this, tr(\"Button Conflict\"), \n tr(\"The button '%1' is already mapped to '%2'.\\n\\nDo you want to reassign it to '%3'?\")\n .arg(buttonName).arg(conflictingButton).arg(currentMappingButton),\n QMessageBox::Yes | QMessageBox::No);\n \n if (ret != QMessageBox::Yes) {\n // Reset UI and return\n mappingButtons[currentMappingButton]->setText(tr(\"Map\"));\n for (auto button : mappingButtons) {\n button->setEnabled(true);\n }\n currentMappingButton.clear();\n return;\n }\n \n // Clear the conflicting mapping\n controller->setPhysicalButtonMapping(conflictingButton, -1);\n currentMappingLabels[conflictingButton]->setText(\"Not mapped\");\n currentMappingLabels[conflictingButton]->setStyleSheet(\"color: gray;\");\n }\n \n // Set the new mapping\n controller->setPhysicalButtonMapping(currentMappingButton, sdlButton);\n \n // Get appropriate text color for current theme\n QString textColor = isDarkMode() ? \"white\" : \"black\";\n \n // Update UI\n currentMappingLabels[currentMappingButton]->setText(buttonName);\n currentMappingLabels[currentMappingButton]->setStyleSheet(QString(\"color: %1; font-weight: bold;\").arg(textColor));\n mappingButtons[currentMappingButton]->setText(tr(\"Map\"));\n \n // Re-enable all buttons\n for (auto button : mappingButtons) {\n button->setEnabled(true);\n }\n \n currentMappingButton.clear();\n \n QMessageBox::information(this, tr(\"Mapping Complete\"), \n tr(\"Button '%1' has been successfully mapped!\").arg(buttonName));\n}\n void resetToDefaults() {\n int ret = QMessageBox::question(this, tr(\"Reset to Defaults\"), \n tr(\"Are you sure you want to reset all button mappings to their default values?\\n\\nThis will overwrite your current configuration.\"),\n QMessageBox::Yes | QMessageBox::No);\n \n if (ret == QMessageBox::Yes) {\n // Get default mappings and apply them\n QMap defaults = controller->getDefaultMappings();\n for (auto it = defaults.begin(); it != defaults.end(); ++it) {\n controller->setPhysicalButtonMapping(it.key(), it.value());\n }\n \n // Update display\n updateMappingDisplay();\n \n QMessageBox::information(this, tr(\"Reset Complete\"), \n tr(\"All button mappings have been reset to their default values.\"));\n }\n}\n void applyMappings() {\n // Mappings are already applied in real-time, just close the dialog\n accept();\n}\n private:\n SDLControllerManager *controller;\n QGridLayout *mappingLayout;\n QMap buttonLabels;\n QMap currentMappingLabels;\n QMap mappingButtons;\n QPushButton *resetButton;\n QPushButton *applyButton;\n QPushButton *cancelButton;\n QString currentMappingButton;\n QTimer *mappingTimeoutTimer;\n void setupUI() {\n QVBoxLayout *mainLayout = new QVBoxLayout(this);\n \n // Instructions\n QLabel *instructionLabel = new QLabel(tr(\"Map your physical controller buttons to Joy-Con functions.\\n\"\n \"Click 'Map' next to each function, then press the corresponding button on your controller.\"), this);\n instructionLabel->setWordWrap(true);\n instructionLabel->setStyleSheet(\"font-weight: bold; margin-bottom: 10px;\");\n mainLayout->addWidget(instructionLabel);\n \n // Mapping grid\n QWidget *mappingWidget = new QWidget(this);\n mappingLayout = new QGridLayout(mappingWidget);\n \n // Headers\n mappingLayout->addWidget(new QLabel(tr(\"Joy-Con Function\"), this), 0, 0);\n mappingLayout->addWidget(new QLabel(tr(\"Description\"), this), 0, 1);\n mappingLayout->addWidget(new QLabel(tr(\"Current Mapping\"), this), 0, 2);\n mappingLayout->addWidget(new QLabel(tr(\"Action\"), this), 0, 3);\n \n // Get logical button descriptions\n QMap descriptions = getLogicalButtonDescriptions();\n \n // Create mapping rows for each logical button\n QStringList logicalButtons = {\"LEFTSHOULDER\", \"RIGHTSHOULDER\", \"PADDLE2\", \"PADDLE4\", \n \"Y\", \"A\", \"B\", \"X\", \"LEFTSTICK\", \"START\", \"GUIDE\"};\n \n int row = 1;\n for (const QString &logicalButton : logicalButtons) {\n // Function name\n QLabel *functionLabel = new QLabel(logicalButton, this);\n functionLabel->setStyleSheet(\"font-weight: bold;\");\n buttonLabels[logicalButton] = functionLabel;\n mappingLayout->addWidget(functionLabel, row, 0);\n \n // Description\n QLabel *descLabel = new QLabel(descriptions.value(logicalButton, \"Unknown\"), this);\n descLabel->setWordWrap(true);\n mappingLayout->addWidget(descLabel, row, 1);\n \n // Current mapping display\n QLabel *currentLabel = new QLabel(\"Not mapped\", this);\n currentLabel->setStyleSheet(\"color: gray;\");\n currentMappingLabels[logicalButton] = currentLabel;\n mappingLayout->addWidget(currentLabel, row, 2);\n \n // Map button\n QPushButton *mapButton = new QPushButton(tr(\"Map\"), this);\n mappingButtons[logicalButton] = mapButton;\n connect(mapButton, &QPushButton::clicked, this, [this, logicalButton]() {\n startButtonMapping(logicalButton);\n });\n mappingLayout->addWidget(mapButton, row, 3);\n \n row++;\n }\n \n mainLayout->addWidget(mappingWidget);\n \n // Buttons\n QHBoxLayout *buttonLayout = new QHBoxLayout();\n \n resetButton = new QPushButton(tr(\"Reset to Defaults\"), this);\n connect(resetButton, &QPushButton::clicked, this, &ControllerMappingDialog::resetToDefaults);\n buttonLayout->addWidget(resetButton);\n \n buttonLayout->addStretch();\n \n applyButton = new QPushButton(tr(\"Apply\"), this);\n connect(applyButton, &QPushButton::clicked, this, &ControllerMappingDialog::applyMappings);\n buttonLayout->addWidget(applyButton);\n \n cancelButton = new QPushButton(tr(\"Cancel\"), this);\n connect(cancelButton, &QPushButton::clicked, this, &QDialog::reject);\n buttonLayout->addWidget(cancelButton);\n \n mainLayout->addLayout(buttonLayout);\n}\n QMap getLogicalButtonDescriptions() const {\n QMap descriptions;\n descriptions[\"LEFTSHOULDER\"] = tr(\"L Button (Left Shoulder)\");\n descriptions[\"RIGHTSHOULDER\"] = tr(\"ZL Button (Left Trigger)\");\n descriptions[\"PADDLE2\"] = tr(\"SL Button (Side Left)\");\n descriptions[\"PADDLE4\"] = tr(\"SR Button (Side Right)\");\n descriptions[\"Y\"] = tr(\"Up Arrow (D-Pad Up)\");\n descriptions[\"A\"] = tr(\"Down Arrow (D-Pad Down)\");\n descriptions[\"B\"] = tr(\"Left Arrow (D-Pad Left)\");\n descriptions[\"X\"] = tr(\"Right Arrow (D-Pad Right)\");\n descriptions[\"LEFTSTICK\"] = tr(\"Analog Stick Press\");\n descriptions[\"START\"] = tr(\"Minus Button (-)\");\n descriptions[\"GUIDE\"] = tr(\"Screenshot Button\");\n return descriptions;\n}\n void loadCurrentMappings() {\n QMap currentMappings = controller->getAllPhysicalMappings();\n \n // Get appropriate text color for current theme\n QString textColor = isDarkMode() ? \"white\" : \"black\";\n \n for (auto it = currentMappings.begin(); it != currentMappings.end(); ++it) {\n const QString &logicalButton = it.key();\n int physicalButton = it.value();\n \n if (currentMappingLabels.contains(logicalButton)) {\n QString physicalName = controller->getPhysicalButtonName(physicalButton);\n currentMappingLabels[logicalButton]->setText(physicalName);\n currentMappingLabels[logicalButton]->setStyleSheet(QString(\"color: %1; font-weight: bold;\").arg(textColor));\n }\n }\n}\n void updateMappingDisplay() {\n loadCurrentMappings();\n}\n bool isDarkMode() const {\n // Same logic as MainWindow::isDarkMode()\n QColor bg = palette().color(QPalette::Window);\n return bg.lightness() < 128; // Lightness scale: 0 (black) - 255 (white)\n}\n};"], ["/SpeedyNote/source/MarkdownWindowManager.h", "class MarkdownWindow {\n Q_OBJECT\n\npublic:\n explicit MarkdownWindowManager(InkCanvas *canvas, QObject *parent = nullptr);\n ~MarkdownWindowManager() {\n clearAllWindows();\n}\n MarkdownWindow* createMarkdownWindow(const QRect &rect);\n void removeMarkdownWindow(MarkdownWindow *window) {\n if (!window) return;\n \n // Remove from current windows\n currentWindows.removeAll(window);\n \n // Remove from all page windows\n for (auto it = pageWindows.begin(); it != pageWindows.end(); ++it) {\n it.value().removeAll(window);\n }\n \n emit windowRemoved(window);\n \n // Delete the window\n window->deleteLater();\n}\n void clearAllWindows() {\n // Stop transparency timer\n transparencyTimer->stop();\n currentlyFocusedWindow = nullptr;\n windowsAreTransparent = false;\n \n // Clear current windows\n for (MarkdownWindow *window : currentWindows) {\n window->deleteLater();\n }\n currentWindows.clear();\n \n // Clear page windows\n for (auto it = pageWindows.begin(); it != pageWindows.end(); ++it) {\n for (MarkdownWindow *window : it.value()) {\n window->deleteLater();\n }\n }\n pageWindows.clear();\n}\n void saveWindowsForPage(int pageNumber) {\n if (!canvas || currentWindows.isEmpty()) return;\n \n // Update page windows map\n pageWindows[pageNumber] = currentWindows;\n \n // Save to file\n saveWindowData(pageNumber, currentWindows);\n}\n void loadWindowsForPage(int pageNumber) {\n if (!canvas) return;\n\n // qDebug() << \"MarkdownWindowManager::loadWindowsForPage(\" << pageNumber << \")\";\n\n // This method is now only responsible for loading and showing the\n // windows for the specified page. Hiding of old windows is handled before this.\n\n QList newPageWindows;\n\n // Check if we have windows for this page in memory\n if (pageWindows.contains(pageNumber)) {\n // qDebug() << \"Found windows in memory for page\" << pageNumber;\n newPageWindows = pageWindows[pageNumber];\n } else {\n // qDebug() << \"Loading windows from file for page\" << pageNumber;\n // Load from file\n newPageWindows = loadWindowData(pageNumber);\n\n // Update page windows map\n if (!newPageWindows.isEmpty()) {\n pageWindows[pageNumber] = newPageWindows;\n }\n }\n\n // qDebug() << \"Loaded\" << newPageWindows.size() << \"windows for page\" << pageNumber;\n\n // Update the current window list and show the windows\n currentWindows = newPageWindows;\n for (MarkdownWindow *window : currentWindows) {\n // Validate that the window is within canvas bounds\n if (!window->isValidForCanvas()) {\n // qDebug() << \"Warning: Markdown window at\" << window->getCanvasRect() \n // << \"is outside canvas bounds\" << canvas->getCanvasRect();\n // Optionally adjust the window position to fit within bounds\n QRect canvasBounds = canvas->getCanvasRect();\n QRect windowRect = window->getCanvasRect();\n \n // Clamp the window position to canvas bounds\n int newX = qMax(0, qMin(windowRect.x(), canvasBounds.width() - windowRect.width()));\n int newY = qMax(0, qMin(windowRect.y(), canvasBounds.height() - windowRect.height()));\n \n if (newX != windowRect.x() || newY != windowRect.y()) {\n QRect adjustedRect(newX, newY, windowRect.width(), windowRect.height());\n window->setCanvasRect(adjustedRect);\n // qDebug() << \"Adjusted window position to\" << adjustedRect;\n }\n }\n \n // Ensure canvas connections are set up for loaded windows\n window->ensureCanvasConnections();\n \n window->show();\n window->updateScreenPosition();\n // Make sure window is not transparent when loaded\n window->setTransparent(false);\n }\n \n // Start transparency timer if there are windows but none are focused\n if (!currentWindows.isEmpty()) {\n // qDebug() << \"Starting transparency timer for\" << currentWindows.size() << \"windows\";\n resetTransparencyTimer();\n } else {\n // qDebug() << \"No windows to show, not starting timer\";\n }\n}\n void deleteWindowsForPage(int pageNumber) {\n // Remove windows from memory\n if (pageWindows.contains(pageNumber)) {\n QList windows = pageWindows[pageNumber];\n for (MarkdownWindow *window : windows) {\n window->deleteLater();\n }\n pageWindows.remove(pageNumber);\n }\n \n // Delete file\n QString filePath = getWindowDataFilePath(pageNumber);\n if (QFile::exists(filePath)) {\n QFile::remove(filePath);\n }\n \n // Clear current windows if they belong to this page\n if (pageWindows.value(pageNumber) == currentWindows) {\n currentWindows.clear();\n }\n}\n void setSelectionMode(bool enabled) {\n selectionMode = enabled;\n \n // Change cursor for canvas\n if (canvas) {\n canvas->setCursor(enabled ? Qt::CrossCursor : Qt::ArrowCursor);\n }\n}\n QList getCurrentPageWindows() const {\n return currentWindows;\n}\n void resetTransparencyTimer() {\n // qDebug() << \"MarkdownWindowManager::resetTransparencyTimer() called\";\n transparencyTimer->stop();\n \n // DON'T make all windows opaque here - only stop the timer\n // The focused window should be made opaque by the caller if needed\n windowsAreTransparent = false; // Reset the state\n \n // Start the timer again\n transparencyTimer->start();\n // qDebug() << \"Transparency timer started for 10 seconds\";\n}\n void setWindowsTransparent(bool transparent) {\n if (windowsAreTransparent == transparent) return;\n \n // qDebug() << \"MarkdownWindowManager::setWindowsTransparent(\" << transparent << \")\";\n // qDebug() << \"Current windows count:\" << currentWindows.size();\n // qDebug() << \"Currently focused window:\" << currentlyFocusedWindow;\n \n windowsAreTransparent = transparent;\n \n // Apply transparency logic:\n // - If transparent=true: make all windows except focused one transparent\n // - If transparent=false: make all windows opaque\n for (MarkdownWindow *window : currentWindows) {\n if (transparent) {\n // When making transparent, only make non-focused windows transparent\n if (window != currentlyFocusedWindow) {\n // qDebug() << \"Setting unfocused window\" << window << \"transparent: true\";\n window->setTransparent(true);\n } else {\n // qDebug() << \"Keeping focused window\" << window << \"opaque\";\n window->setTransparent(false);\n }\n } else {\n // When making opaque, make all windows opaque\n // qDebug() << \"Setting window\" << window << \"transparent: false\";\n window->setTransparent(false);\n }\n }\n}\n void hideAllWindows() {\n // Stop transparency timer when hiding windows\n transparencyTimer->stop();\n currentlyFocusedWindow = nullptr;\n windowsAreTransparent = false;\n \n // Hide all current windows\n for (MarkdownWindow *window : currentWindows) {\n window->hide();\n window->setTransparent(false); // Reset transparency state\n }\n}\n void windowCreated(MarkdownWindow *window);\n void windowRemoved(MarkdownWindow *window);\n private:\n void onWindowDeleteRequested(MarkdownWindow *window) {\n removeMarkdownWindow(window);\n \n // Mark canvas as edited since we deleted a markdown window\n if (canvas) {\n canvas->setEdited(true);\n }\n \n // Save current state\n if (canvas) {\n MainWindow *mainWindow = qobject_cast(canvas->parent());\n if (mainWindow) {\n int currentPage = mainWindow->getCurrentPageForCanvas(canvas);\n saveWindowsForPage(currentPage);\n }\n }\n}\n void onWindowFocusChanged(MarkdownWindow *window, bool focused) {\n // qDebug() << \"MarkdownWindowManager::onWindowFocusChanged(\" << window << \", \" << focused << \")\";\n \n if (focused) {\n // A window gained focus - make it opaque immediately and reset timer\n // qDebug() << \"Window gained focus, setting as currently focused\";\n currentlyFocusedWindow = window;\n \n // Make the focused window opaque immediately\n window->setTransparent(false);\n \n // Reset timer to start counting down for making other windows transparent\n resetTransparencyTimer();\n } else {\n // A window lost focus\n // qDebug() << \"Window lost focus\";\n if (currentlyFocusedWindow == window) {\n // qDebug() << \"Clearing currently focused window\";\n currentlyFocusedWindow = nullptr;\n }\n \n // Check if any window still has focus\n bool anyWindowFocused = false;\n for (MarkdownWindow *w : currentWindows) {\n if (w->isEditorFocused()) {\n // qDebug() << \"Found another focused window:\" << w;\n anyWindowFocused = true;\n currentlyFocusedWindow = w;\n // Make the newly focused window opaque\n w->setTransparent(false);\n break;\n }\n }\n \n if (!anyWindowFocused) {\n // qDebug() << \"No window has focus, starting transparency timer\";\n // No window has focus, start transparency timer\n resetTransparencyTimer();\n } else {\n // qDebug() << \"Another window still has focus, resetting timer\";\n // Another window has focus, reset timer\n resetTransparencyTimer();\n }\n }\n}\n void onWindowContentChanged(MarkdownWindow *window) {\n // qDebug() << \"MarkdownWindowManager::onWindowContentChanged(\" << window << \")\";\n \n // Content changed, make this window the focused one and reset transparency timer\n currentlyFocusedWindow = window;\n window->setTransparent(false); // Make the active window opaque\n \n // Reset transparency timer\n resetTransparencyTimer();\n}\n void onTransparencyTimerTimeout() {\n // qDebug() << \"MarkdownWindowManager::onTransparencyTimerTimeout() - Timer expired!\";\n // Make all windows except the focused one semi-transparent\n setWindowsTransparent(true);\n}\n private:\n InkCanvas *canvas;\n bool selectionMode = false;\n QMap> pageWindows;\n QList currentWindows;\n QTimer *transparencyTimer;\n MarkdownWindow *currentlyFocusedWindow = nullptr;\n bool windowsAreTransparent = false;\n QString getWindowDataFilePath(int pageNumber) const {\n QString saveFolder = getSaveFolder();\n QString notebookId = getNotebookId();\n \n if (saveFolder.isEmpty() || notebookId.isEmpty()) {\n return QString();\n }\n \n return saveFolder + QString(\"/.%1_markdown_%2.json\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n}\n void saveWindowData(int pageNumber, const QList &windows) {\n QString filePath = getWindowDataFilePath(pageNumber);\n if (filePath.isEmpty()) return;\n \n QJsonArray windowsArray;\n for (MarkdownWindow *window : windows) {\n QVariantMap windowData = window->serialize();\n windowsArray.append(QJsonObject::fromVariantMap(windowData));\n }\n \n QJsonDocument doc(windowsArray);\n \n QFile file(filePath);\n if (file.open(QIODevice::WriteOnly)) {\n file.write(doc.toJson());\n file.close();\n \n #ifdef Q_OS_WIN\n // Set hidden attribute on Windows\n SetFileAttributesW(reinterpret_cast(filePath.utf16()), FILE_ATTRIBUTE_HIDDEN);\n #endif\n }\n}\n QList loadWindowData(int pageNumber) {\n QList windows;\n \n QString filePath = getWindowDataFilePath(pageNumber);\n if (filePath.isEmpty() || !QFile::exists(filePath)) {\n return windows;\n }\n \n QFile file(filePath);\n if (!file.open(QIODevice::ReadOnly)) {\n return windows;\n }\n \n QByteArray data = file.readAll();\n file.close();\n \n QJsonParseError error;\n QJsonDocument doc = QJsonDocument::fromJson(data, &error);\n if (error.error != QJsonParseError::NoError) {\n qWarning() << \"Failed to parse markdown window data:\" << error.errorString();\n return windows;\n }\n \n QJsonArray windowsArray = doc.array();\n for (const QJsonValue &value : windowsArray) {\n QJsonObject windowObj = value.toObject();\n QVariantMap windowData = windowObj.toVariantMap();\n \n // Create window with default rect (will be updated by deserialize)\n MarkdownWindow *window = new MarkdownWindow(QRect(0, 0, 300, 200), canvas);\n window->deserialize(windowData);\n \n // Connect signals\n connectWindowSignals(window);\n \n windows.append(window);\n window->show();\n }\n \n return windows;\n}\n QString getSaveFolder() const {\n return canvas ? canvas->getSaveFolder() : QString();\n}\n QString getNotebookId() const {\n if (!canvas) return QString();\n \n QString saveFolder = canvas->getSaveFolder();\n if (saveFolder.isEmpty()) return QString();\n \n QString idFile = saveFolder + \"/.notebook_id.txt\";\n if (QFile::exists(idFile)) {\n QFile file(idFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString notebookId = in.readLine().trimmed();\n file.close();\n return notebookId;\n }\n }\n \n return \"notebook\"; // Default fallback\n}\n QRect convertScreenToCanvasRect(const QRect &screenRect) const {\n if (!canvas) {\n // qDebug() << \"MarkdownWindowManager::convertScreenToCanvasRect() - No canvas, returning screen rect:\" << screenRect;\n return screenRect;\n }\n \n // Use the new coordinate conversion methods from InkCanvas\n QRect canvasRect = canvas->mapWidgetToCanvas(screenRect);\n // qDebug() << \"MarkdownWindowManager::convertScreenToCanvasRect() - Screen rect:\" << screenRect << \"-> Canvas rect:\" << canvasRect;\n // qDebug() << \" Canvas size:\" << canvas->getCanvasSize() << \"Zoom:\" << canvas->getZoomFactor() << \"Pan:\" << canvas->getPanOffset();\n return canvasRect;\n}\n void connectWindowSignals(MarkdownWindow *window) {\n // qDebug() << \"MarkdownWindowManager::connectWindowSignals() - Connecting signals for window\" << window;\n \n // Connect existing signals\n connect(window, &MarkdownWindow::deleteRequested, this, &MarkdownWindowManager::onWindowDeleteRequested);\n connect(window, &MarkdownWindow::contentChanged, this, [this, window]() {\n onWindowContentChanged(window);\n \n // Mark canvas as edited since markdown content changed\n if (canvas) {\n canvas->setEdited(true);\n \n // Get current page and save windows\n MainWindow *mainWindow = qobject_cast(canvas->parent());\n if (mainWindow) {\n int currentPage = mainWindow->getCurrentPageForCanvas(canvas);\n saveWindowsForPage(currentPage);\n }\n }\n });\n connect(window, &MarkdownWindow::windowMoved, this, [this, window](MarkdownWindow*) {\n // qDebug() << \"Window moved:\" << window;\n \n // Window was moved, make it the focused one and reset transparency timer\n currentlyFocusedWindow = window;\n window->setTransparent(false); // Make the active window opaque\n resetTransparencyTimer();\n \n // Mark canvas as edited since window was moved\n if (canvas) {\n canvas->setEdited(true);\n }\n });\n connect(window, &MarkdownWindow::windowResized, this, [this, window](MarkdownWindow*) {\n // qDebug() << \"Window resized:\" << window;\n \n // Window was resized, make it the focused one and reset transparency timer\n currentlyFocusedWindow = window;\n window->setTransparent(false); // Make the active window opaque\n resetTransparencyTimer();\n \n // Mark canvas as edited since window was resized\n if (canvas) {\n canvas->setEdited(true);\n }\n });\n \n // Connect new transparency-related signals\n connect(window, &MarkdownWindow::focusChanged, this, &MarkdownWindowManager::onWindowFocusChanged);\n connect(window, &MarkdownWindow::editorFocusChanged, this, &MarkdownWindowManager::onWindowFocusChanged);\n connect(window, &MarkdownWindow::windowInteracted, this, [this, window](MarkdownWindow*) {\n // qDebug() << \"Window interacted:\" << window;\n \n // Window was clicked/interacted with, make it the focused one and reset transparency timer\n currentlyFocusedWindow = window;\n window->setTransparent(false); // Make the active window opaque\n resetTransparencyTimer();\n });\n \n // qDebug() << \"All signals connected for window\" << window;\n}\n public:\n void updateAllWindowPositions() {\n // Update positions of all current windows\n for (MarkdownWindow *window : currentWindows) {\n if (window) {\n window->updateScreenPosition();\n }\n }\n}\n};"], ["/SpeedyNote/source/MarkdownWindow.h", "class QMarkdownTextEdit {\n Q_OBJECT\n\npublic:\n explicit MarkdownWindow(const QRect &rect, QWidget *parent = nullptr);\n ~MarkdownWindow() = default;\n QString getMarkdownContent() const {\n return markdownEditor ? markdownEditor->toPlainText() : QString();\n}\n void setMarkdownContent(const QString &content) {\n if (markdownEditor) {\n markdownEditor->setPlainText(content);\n }\n}\n QRect getWindowRect() const {\n return geometry();\n}\n void setWindowRect(const QRect &rect) {\n setGeometry(rect);\n}\n QRect getCanvasRect() const {\n return canvasRect;\n}\n void setCanvasRect(const QRect &canvasRect) {\n canvasRect = rect;\n updateScreenPosition();\n}\n void updateScreenPosition() {\n // Prevent recursive updates\n if (isUpdatingPosition) return;\n isUpdatingPosition = true;\n \n // Debug: Log when this is called due to external changes (not during mouse movement)\n if (!dragging && !resizing) {\n // qDebug() << \"MarkdownWindow::updateScreenPosition() called for window\" << this << \"Canvas rect:\" << canvasRect;\n }\n \n // Get the canvas parent to access coordinate conversion methods\n if (QWidget *canvas = parentWidget()) {\n // Try to cast to InkCanvas to use the new coordinate methods\n if (InkCanvas *inkCanvas = qobject_cast(canvas)) {\n // Use the new coordinate conversion methods\n QRect screenRect = inkCanvas->mapCanvasToWidget(canvasRect);\n // qDebug() << \"MarkdownWindow::updateScreenPosition() - Canvas rect:\" << canvasRect << \"-> Screen rect:\" << screenRect;\n // qDebug() << \" Canvas size:\" << inkCanvas->getCanvasSize() << \"Zoom:\" << inkCanvas->getZoomFactor() << \"Pan:\" << inkCanvas->getPanOffset();\n setGeometry(screenRect);\n } else {\n // Fallback: use canvas coordinates directly\n // qDebug() << \"MarkdownWindow::updateScreenPosition() - No InkCanvas parent, using canvas rect directly:\" << canvasRect;\n setGeometry(canvasRect);\n }\n } else {\n // No parent, use canvas coordinates directly\n // qDebug() << \"MarkdownWindow::updateScreenPosition() - No parent, using canvas rect directly:\" << canvasRect;\n setGeometry(canvasRect);\n }\n \n isUpdatingPosition = false;\n}\n QVariantMap serialize() const {\n QVariantMap data;\n data[\"canvas_x\"] = canvasRect.x();\n data[\"canvas_y\"] = canvasRect.y();\n data[\"canvas_width\"] = canvasRect.width();\n data[\"canvas_height\"] = canvasRect.height();\n data[\"content\"] = getMarkdownContent();\n \n // Add canvas size information for debugging and consistency checks\n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n QSize canvasSize = inkCanvas->getCanvasSize();\n data[\"canvas_buffer_width\"] = canvasSize.width();\n data[\"canvas_buffer_height\"] = canvasSize.height();\n data[\"zoom_factor\"] = inkCanvas->getZoomFactor();\n QPointF panOffset = inkCanvas->getPanOffset();\n data[\"pan_x\"] = panOffset.x();\n data[\"pan_y\"] = panOffset.y();\n }\n \n return data;\n}\n void deserialize(const QVariantMap &data) {\n int x = data.value(\"canvas_x\", 0).toInt();\n int y = data.value(\"canvas_y\", 0).toInt();\n int width = data.value(\"canvas_width\", 300).toInt();\n int height = data.value(\"canvas_height\", 200).toInt();\n QString content = data.value(\"content\", \"# New Markdown Window\").toString();\n \n QRect loadedRect = QRect(x, y, width, height);\n // qDebug() << \"MarkdownWindow::deserialize() - Loaded canvas rect:\" << loadedRect;\n // qDebug() << \" Original canvas size:\" << data.value(\"canvas_buffer_width\", -1).toInt() << \"x\" << data.value(\"canvas_buffer_height\", -1).toInt();\n \n // Apply bounds checking to loaded coordinates\n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n QRect canvasBounds = inkCanvas->getCanvasRect();\n \n // Ensure window stays within canvas bounds\n int maxX = canvasBounds.width() - loadedRect.width();\n int maxY = canvasBounds.height() - loadedRect.height();\n \n loadedRect.setX(qMax(0, qMin(loadedRect.x(), maxX)));\n loadedRect.setY(qMax(0, qMin(loadedRect.y(), maxY)));\n \n if (loadedRect != QRect(x, y, width, height)) {\n // qDebug() << \" Bounds-corrected canvas rect:\" << loadedRect << \"Canvas bounds:\" << canvasBounds;\n }\n }\n \n canvasRect = loadedRect;\n setMarkdownContent(content);\n \n // Ensure canvas connections are set up\n ensureCanvasConnections();\n \n updateScreenPosition();\n}\n void focusEditor() {\n if (markdownEditor) {\n markdownEditor->setFocus();\n }\n}\n bool isEditorFocused() const {\n return markdownEditor && markdownEditor->hasFocus();\n}\n void setTransparent(bool transparent) {\n if (isTransparentState == transparent) return;\n \n // qDebug() << \"MarkdownWindow::setTransparent(\" << transparent << \") for window\" << this;\n isTransparentState = transparent;\n \n // Apply transparency effect by changing the background style\n if (transparent) {\n // qDebug() << \"Setting window background to semi-transparent\";\n applyTransparentStyle();\n } else {\n // qDebug() << \"Setting window background to opaque\";\n applyStyle(); // Restore normal style\n }\n}\n bool isTransparent() const {\n return isTransparentState;\n}\n bool isValidForCanvas() const {\n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n QRect canvasBounds = inkCanvas->getCanvasRect();\n \n // Check if the window is at least partially within the canvas bounds\n return canvasBounds.intersects(canvasRect);\n }\n \n // If no canvas parent, assume valid\n return true;\n}\n QString getCoordinateInfo() const {\n QString info;\n info += QString(\"Canvas Coordinates: (%1, %2) %3x%4\\n\")\n .arg(canvasRect.x()).arg(canvasRect.y())\n .arg(canvasRect.width()).arg(canvasRect.height());\n \n QRect screenRect = geometry();\n info += QString(\"Screen Coordinates: (%1, %2) %3x%4\\n\")\n .arg(screenRect.x()).arg(screenRect.y())\n .arg(screenRect.width()).arg(screenRect.height());\n \n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n QSize canvasSize = inkCanvas->getCanvasSize();\n info += QString(\"Canvas Size: %1x%2\\n\")\n .arg(canvasSize.width()).arg(canvasSize.height());\n \n info += QString(\"Zoom Factor: %1\\n\").arg(inkCanvas->getZoomFactor());\n \n QPointF panOffset = inkCanvas->getPanOffset();\n info += QString(\"Pan Offset: (%1, %2)\\n\")\n .arg(panOffset.x()).arg(panOffset.y());\n \n info += QString(\"Valid for Canvas: %1\\n\").arg(isValidForCanvas() ? \"Yes\" : \"No\");\n } else {\n info += \"No InkCanvas parent found\\n\";\n }\n \n return info;\n}\n void ensureCanvasConnections() {\n // Connect to canvas pan/zoom changes to update position\n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n // Disconnect any existing connections to avoid duplicates\n disconnect(inkCanvas, &InkCanvas::panChanged, this, &MarkdownWindow::updateScreenPosition);\n disconnect(inkCanvas, &InkCanvas::zoomChanged, this, &MarkdownWindow::updateScreenPosition);\n \n // Reconnect\n connect(inkCanvas, &InkCanvas::panChanged, this, &MarkdownWindow::updateScreenPosition);\n connect(inkCanvas, &InkCanvas::zoomChanged, this, &MarkdownWindow::updateScreenPosition);\n \n // Install event filter to handle canvas resize events (for layout changes)\n inkCanvas->installEventFilter(this);\n \n // qDebug() << \"MarkdownWindow::ensureCanvasConnections() - Connected to canvas signals for window\" << this;\n } else {\n // qDebug() << \"MarkdownWindow::ensureCanvasConnections() - No InkCanvas parent found for window\" << this;\n }\n}\n void deleteRequested(MarkdownWindow *window);\n void contentChanged();\n void windowMoved(MarkdownWindow *window);\n void windowResized(MarkdownWindow *window);\n void focusChanged(MarkdownWindow *window, bool focused);\n void editorFocusChanged(MarkdownWindow *window, bool focused);\n void windowInteracted(MarkdownWindow *window);\n protected:\n void mousePressEvent(QMouseEvent *event) override {\n if (event->button() == Qt::LeftButton) {\n // Emit signal to indicate window interaction\n emit windowInteracted(this);\n \n ResizeHandle handle = getResizeHandle(event->pos());\n \n if (handle != None) {\n // Start resizing\n resizing = true;\n isUserInteracting = true;\n currentResizeHandle = handle;\n resizeStartPosition = event->globalPosition().toPoint();\n resizeStartRect = geometry();\n } else if (event->pos().y() < 24) { // Header area\n // Start dragging\n dragging = true;\n isUserInteracting = true;\n dragStartPosition = event->globalPosition().toPoint();\n windowStartPosition = pos();\n }\n }\n \n QWidget::mousePressEvent(event);\n}\n void mouseMoveEvent(QMouseEvent *event) override {\n if (resizing) {\n QPoint delta = event->globalPosition().toPoint() - resizeStartPosition;\n QRect newRect = resizeStartRect;\n \n // Apply resize based on the stored handle\n switch (currentResizeHandle) {\n case TopLeft:\n newRect.setTopLeft(newRect.topLeft() + delta);\n break;\n case TopRight:\n newRect.setTopRight(newRect.topRight() + delta);\n break;\n case BottomLeft:\n newRect.setBottomLeft(newRect.bottomLeft() + delta);\n break;\n case BottomRight:\n newRect.setBottomRight(newRect.bottomRight() + delta);\n break;\n case Top:\n newRect.setTop(newRect.top() + delta.y());\n break;\n case Bottom:\n newRect.setBottom(newRect.bottom() + delta.y());\n break;\n case Left:\n newRect.setLeft(newRect.left() + delta.x());\n break;\n case Right:\n newRect.setRight(newRect.right() + delta.x());\n break;\n default:\n break;\n }\n \n // Enforce minimum size\n newRect.setSize(newRect.size().expandedTo(QSize(200, 150)));\n \n // Keep resized window within canvas bounds\n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n // Convert to canvas coordinates to check bounds\n QRect tempCanvasRect = inkCanvas->mapWidgetToCanvas(newRect);\n QRect canvasBounds = inkCanvas->getCanvasRect();\n \n // Apply canvas bounds constraints\n int maxCanvasX = canvasBounds.width() - tempCanvasRect.width();\n int maxCanvasY = canvasBounds.height() - tempCanvasRect.height();\n \n tempCanvasRect.setX(qMax(0, qMin(tempCanvasRect.x(), maxCanvasX)));\n tempCanvasRect.setY(qMax(0, qMin(tempCanvasRect.y(), maxCanvasY)));\n \n // Also ensure the window doesn't get resized beyond canvas bounds\n if (tempCanvasRect.right() > canvasBounds.width()) {\n tempCanvasRect.setWidth(canvasBounds.width() - tempCanvasRect.x());\n }\n if (tempCanvasRect.bottom() > canvasBounds.height()) {\n tempCanvasRect.setHeight(canvasBounds.height() - tempCanvasRect.y());\n }\n \n // Convert back to screen coordinates for the constrained geometry\n newRect = inkCanvas->mapCanvasToWidget(tempCanvasRect);\n }\n \n // Update the widget geometry directly during resizing\n setGeometry(newRect);\n \n // Convert screen coordinates back to canvas coordinates\n convertScreenToCanvasRect(newRect);\n emit windowResized(this);\n } else if (dragging) {\n QPoint delta = event->globalPosition().toPoint() - dragStartPosition;\n QPoint newPos = windowStartPosition + delta;\n \n // Keep window within canvas bounds (not just parent widget bounds)\n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n // Convert current position to canvas coordinates to check bounds\n QRect tempScreenRect(newPos, size());\n QRect tempCanvasRect = inkCanvas->mapWidgetToCanvas(tempScreenRect);\n QRect canvasBounds = inkCanvas->getCanvasRect();\n \n // Apply canvas bounds constraints\n int maxCanvasX = canvasBounds.width() - tempCanvasRect.width();\n int maxCanvasY = canvasBounds.height() - tempCanvasRect.height();\n \n tempCanvasRect.setX(qMax(0, qMin(tempCanvasRect.x(), maxCanvasX)));\n tempCanvasRect.setY(qMax(0, qMin(tempCanvasRect.y(), maxCanvasY)));\n \n // Convert back to screen coordinates for the constrained position\n QRect constrainedScreenRect = inkCanvas->mapCanvasToWidget(tempCanvasRect);\n newPos = constrainedScreenRect.topLeft();\n \n // Debug: Log when position is constrained\n if (tempCanvasRect != inkCanvas->mapWidgetToCanvas(QRect(windowStartPosition + delta, size()))) {\n // qDebug() << \"MarkdownWindow: Constraining position to canvas bounds. Canvas rect:\" << tempCanvasRect;\n }\n } else {\n // Fallback: Keep window within parent bounds\n if (parentWidget()) {\n QRect parentRect = parentWidget()->rect();\n newPos.setX(qMax(0, qMin(newPos.x(), parentRect.width() - width())));\n newPos.setY(qMax(0, qMin(newPos.y(), parentRect.height() - height())));\n }\n }\n \n // Update the widget position directly during dragging\n move(newPos);\n \n // Convert screen position back to canvas coordinates\n QRect newScreenRect(newPos, size());\n convertScreenToCanvasRect(newScreenRect);\n emit windowMoved(this);\n } else {\n // Update cursor for resize handles\n updateCursor(event->pos());\n }\n \n QWidget::mouseMoveEvent(event);\n}\n void mouseReleaseEvent(QMouseEvent *event) override {\n if (event->button() == Qt::LeftButton) {\n resizing = false;\n dragging = false;\n isUserInteracting = false;\n currentResizeHandle = None;\n }\n \n QWidget::mouseReleaseEvent(event);\n}\n void resizeEvent(QResizeEvent *event) override {\n QWidget::resizeEvent(event);\n \n // Emit windowResized if this is a user-initiated resize or if we're not updating position due to canvas changes\n if (isUserInteracting || !isUpdatingPosition) {\n emit windowResized(this);\n }\n}\n void paintEvent(QPaintEvent *event) override {\n QWidget::paintEvent(event);\n \n // Draw resize handles\n QPainter painter(this);\n painter.setRenderHint(QPainter::Antialiasing);\n \n QColor handleColor = hasFocus() ? QColor(74, 144, 226) : QColor(180, 180, 180);\n painter.setPen(QPen(handleColor, 2));\n painter.setBrush(QBrush(handleColor));\n \n // Draw corner handles\n int handleSize = 6;\n painter.drawEllipse(0, 0, handleSize, handleSize); // Top-left\n painter.drawEllipse(width() - handleSize, 0, handleSize, handleSize); // Top-right\n painter.drawEllipse(0, height() - handleSize, handleSize, handleSize); // Bottom-left\n painter.drawEllipse(width() - handleSize, height() - handleSize, handleSize, handleSize); // Bottom-right\n}\n void focusInEvent(QFocusEvent *event) override {\n // qDebug() << \"MarkdownWindow::focusInEvent() - Window\" << this << \"gained focus\";\n QWidget::focusInEvent(event);\n emit focusChanged(this, true);\n}\n void focusOutEvent(QFocusEvent *event) override {\n // qDebug() << \"MarkdownWindow::focusOutEvent() - Window\" << this << \"lost focus\";\n QWidget::focusOutEvent(event);\n emit focusChanged(this, false);\n}\n bool eventFilter(QObject *obj, QEvent *event) override {\n if (obj == markdownEditor) {\n if (event->type() == QEvent::FocusIn) {\n // qDebug() << \"MarkdownWindow::eventFilter() - Editor gained focus in window\" << this;\n emit editorFocusChanged(this, true);\n } else if (event->type() == QEvent::FocusOut) {\n // qDebug() << \"MarkdownWindow::eventFilter() - Editor lost focus in window\" << this;\n emit editorFocusChanged(this, false);\n }\n } else if (obj == parentWidget() && event->type() == QEvent::Resize) {\n // Canvas widget was resized (likely due to layout changes like showing/hiding sidebars)\n // Update our screen position to maintain canvas position\n QTimer::singleShot(0, this, [this]() {\n updateScreenPosition();\n });\n }\n return QWidget::eventFilter(obj, event);\n}\n private:\n void onDeleteClicked() {\n emit deleteRequested(this);\n}\n void onMarkdownTextChanged() {\n emit contentChanged();\n}\n private:\n enum ResizeHandle {\n None,\n TopLeft,\n TopRight,\n BottomLeft,\n BottomRight,\n Top,\n Bottom,\n Left,\n Right\n };\n QMarkdownTextEdit *markdownEditor;\n QPushButton *deleteButton;\n QLabel *titleLabel;\n QVBoxLayout *mainLayout;\n QHBoxLayout *headerLayout;\n bool dragging = false;\n QPoint dragStartPosition;\n QPoint windowStartPosition;\n bool resizing = false;\n QPoint resizeStartPosition;\n QRect resizeStartRect;\n ResizeHandle currentResizeHandle = None;\n QRect canvasRect;\n bool isTransparentState = false;\n bool isUpdatingPosition = false;\n bool isUserInteracting = false;\n ResizeHandle getResizeHandle(const QPoint &pos) const {\n const int handleSize = 8;\n const QRect rect = this->rect();\n \n // Check corner handles first\n if (QRect(0, 0, handleSize, handleSize).contains(pos))\n return TopLeft;\n if (QRect(rect.width() - handleSize, 0, handleSize, handleSize).contains(pos))\n return TopRight;\n if (QRect(0, rect.height() - handleSize, handleSize, handleSize).contains(pos))\n return BottomLeft;\n if (QRect(rect.width() - handleSize, rect.height() - handleSize, handleSize, handleSize).contains(pos))\n return BottomRight;\n \n // Check edge handles\n if (QRect(0, 0, rect.width(), handleSize).contains(pos))\n return Top;\n if (QRect(0, rect.height() - handleSize, rect.width(), handleSize).contains(pos))\n return Bottom;\n if (QRect(0, 0, handleSize, rect.height()).contains(pos))\n return Left;\n if (QRect(rect.width() - handleSize, 0, handleSize, rect.height()).contains(pos))\n return Right;\n \n return None;\n}\n void updateCursor(const QPoint &pos) {\n ResizeHandle handle = getResizeHandle(pos);\n \n switch (handle) {\n case TopLeft:\n case BottomRight:\n setCursor(Qt::SizeFDiagCursor);\n break;\n case TopRight:\n case BottomLeft:\n setCursor(Qt::SizeBDiagCursor);\n break;\n case Top:\n case Bottom:\n setCursor(Qt::SizeVerCursor);\n break;\n case Left:\n case Right:\n setCursor(Qt::SizeHorCursor);\n break;\n default:\n if (pos.y() < 24) { // Header area\n setCursor(Qt::SizeAllCursor);\n } else {\n setCursor(Qt::ArrowCursor);\n }\n break;\n }\n}\n void setupUI() {\n mainLayout = new QVBoxLayout(this);\n mainLayout->setContentsMargins(2, 2, 2, 2);\n mainLayout->setSpacing(0);\n \n // Header with title and delete button\n headerLayout = new QHBoxLayout();\n headerLayout->setContentsMargins(4, 2, 4, 2);\n headerLayout->setSpacing(4);\n \n titleLabel = new QLabel(\"Markdown\", this);\n titleLabel->setStyleSheet(\"font-weight: bold; color: #333;\");\n \n deleteButton = new QPushButton(\"×\", this);\n deleteButton->setFixedSize(16, 16);\n deleteButton->setStyleSheet(R\"(\n QPushButton {\n background-color: #ff4444;\n color: white;\n border: none;\n border-radius: 8px;\n font-weight: bold;\n font-size: 10px;\n }\n QPushButton:hover {\n background-color: #ff6666;\n }\n QPushButton:pressed {\n background-color: #cc2222;\n }\n )\");\n \n connect(deleteButton, &QPushButton::clicked, this, &MarkdownWindow::onDeleteClicked);\n \n headerLayout->addWidget(titleLabel);\n headerLayout->addStretch();\n headerLayout->addWidget(deleteButton);\n \n // Markdown editor\n markdownEditor = new QMarkdownTextEdit(this);\n markdownEditor->setPlainText(\"\"); // Start with empty content\n \n connect(markdownEditor, &QMarkdownTextEdit::textChanged, this, &MarkdownWindow::onMarkdownTextChanged);\n \n // Connect editor focus events using event filter\n markdownEditor->installEventFilter(this);\n \n mainLayout->addLayout(headerLayout);\n mainLayout->addWidget(markdownEditor);\n}\n void applyStyle() {\n // Detect dark mode using the same method as MainWindow\n bool isDarkMode = palette().color(QPalette::Window).lightness() < 128;\n \n QString backgroundColor = isDarkMode ? \"#2b2b2b\" : \"white\";\n QString borderColor = isDarkMode ? \"#555555\" : \"#cccccc\";\n QString headerBackgroundColor = isDarkMode ? \"#3c3c3c\" : \"#f0f0f0\";\n QString focusBorderColor = isDarkMode ? \"#6ca9dc\" : \"#4a90e2\";\n \n setStyleSheet(QString(R\"(\n MarkdownWindow {\n background-color: %1;\n border: 2px solid %2;\n border-radius: 4px;\n }\n MarkdownWindow:focus {\n border-color: %3;\n }\n )\").arg(backgroundColor, borderColor, focusBorderColor));\n \n // Style the header\n if (headerLayout && headerLayout->parentWidget()) {\n headerLayout->parentWidget()->setStyleSheet(QString(R\"(\n background-color: %1;\n border-bottom: 1px solid %2;\n )\").arg(headerBackgroundColor, borderColor));\n }\n \n // Reset the markdown editor style to default (opaque)\n if (markdownEditor) {\n markdownEditor->setStyleSheet(\"\"); // Clear any custom styles\n }\n}\n void applyTransparentStyle() {\n // Detect dark mode using the same method as MainWindow\n bool isDarkMode = palette().color(QPalette::Window).lightness() < 128;\n \n QString backgroundColor = isDarkMode ? \"rgba(43, 43, 43, 0.3)\" : \"rgba(255, 255, 255, 0.3)\"; // 30% opacity\n QString borderColor = isDarkMode ? \"#555555\" : \"#cccccc\";\n QString headerBackgroundColor = isDarkMode ? \"rgba(60, 60, 60, 0.3)\" : \"rgba(240, 240, 240, 0.3)\"; // 30% opacity\n QString focusBorderColor = isDarkMode ? \"#6ca9dc\" : \"#4a90e2\";\n \n setStyleSheet(QString(R\"(\n MarkdownWindow {\n background-color: %1;\n border: 2px solid %2;\n border-radius: 4px;\n }\n MarkdownWindow:focus {\n border-color: %3;\n }\n )\").arg(backgroundColor, borderColor, focusBorderColor));\n \n // Style the header with transparency\n if (headerLayout && headerLayout->parentWidget()) {\n headerLayout->parentWidget()->setStyleSheet(QString(R\"(\n background-color: %1;\n border-bottom: 1px solid %2;\n )\").arg(headerBackgroundColor, borderColor));\n }\n \n // Make the markdown editor background semi-transparent too\n if (markdownEditor) {\n QString editorBg = isDarkMode ? \"rgba(43, 43, 43, 0.3)\" : \"rgba(255, 255, 255, 0.3)\";\n markdownEditor->setStyleSheet(QString(R\"(\n QMarkdownTextEdit {\n background-color: %1;\n border: none;\n }\n )\").arg(editorBg));\n }\n}\n void convertScreenToCanvasRect(const QRect &screenRect) {\n // Get the canvas parent to access coordinate conversion methods\n if (QWidget *canvas = parentWidget()) {\n // Try to cast to InkCanvas to use the new coordinate methods\n if (InkCanvas *inkCanvas = qobject_cast(canvas)) {\n // Use the new coordinate conversion methods\n QRect oldCanvasRect = canvasRect;\n QRect newCanvasRect = inkCanvas->mapWidgetToCanvas(screenRect);\n \n // Store the converted canvas coordinates without bounds checking\n // Bounds checking should only happen during user interaction (dragging/resizing)\n canvasRect = newCanvasRect;\n // Only log if there was a significant change (and not during mouse movement)\n if ((canvasRect.topLeft() - oldCanvasRect.topLeft()).manhattanLength() > 10 && !dragging && !resizing) {\n // qDebug() << \"MarkdownWindow::convertScreenToCanvasRect() - Screen rect:\" << screenRect << \"-> Canvas rect:\" << canvasRect;\n // qDebug() << \" Old canvas rect:\" << oldCanvasRect;\n }\n } else {\n // Fallback: use screen coordinates directly\n // qDebug() << \"MarkdownWindow::convertScreenToCanvasRect() - No InkCanvas parent, using screen rect directly:\" << screenRect;\n canvasRect = screenRect;\n }\n } else {\n // No parent, use screen coordinates directly\n // qDebug() << \"MarkdownWindow::convertScreenToCanvasRect() - No parent, using screen rect directly:\" << screenRect;\n canvasRect = screenRect;\n }\n}\n};"], ["/SpeedyNote/markdown/qmarkdowntextedit.h", "class LineNumArea {\n Q_OBJECT\n Q_PROPERTY(\n bool highlighting READ highlightingEnabled WRITE setHighlightingEnabled);\n friend class LineNumArea;\n public:\n enum AutoTextOption {\n None = 0x0000,\n\n // inserts closing characters for brackets and Markdown characters\n BracketClosing = 0x0001,\n\n // removes matching brackets and Markdown characters\n BracketRemoval = 0x0002\n };\n Q_DECLARE_FLAGS(AutoTextOptions, AutoTextOption);\n explicit QMarkdownTextEdit(QWidget *parent = nullptr,\n bool initHighlighter = true) {\n installEventFilter(this);\n viewport()->installEventFilter(this);\n _autoTextOptions = AutoTextOption::BracketClosing;\n\n _lineNumArea = new LineNumArea(this);\n updateLineNumberAreaWidth(0);\n\n // Markdown highlighting is enabled by default\n _highlightingEnabled = initHighlighter;\n if (initHighlighter) {\n _highlighter = new MarkdownHighlighter(document());\n }\n\n QFont font = this->font();\n\n // set the tab stop to the width of 4 spaces in the editor\n constexpr int tabStop = 4;\n QFontMetrics metrics(font);\n\n#if QT_VERSION < QT_VERSION_CHECK(5, 11, 0)\n setTabStopWidth(tabStop * metrics.width(' '));\n#else\n setTabStopDistance(tabStop * metrics.horizontalAdvance(QLatin1Char(' ')));\n#endif\n\n // add shortcuts for duplicating text\n // new QShortcut( QKeySequence( \"Ctrl+D\" ), this, SLOT( duplicateText() )\n // ); new QShortcut( QKeySequence( \"Ctrl+Alt+Down\" ), this, SLOT(\n // duplicateText() ) );\n\n // add a layout to the widget\n auto *layout = new QVBoxLayout(this);\n layout->setContentsMargins(0, 0, 0, 0);\n layout->addStretch();\n this->setLayout(layout);\n\n // add the hidden search widget\n _searchWidget = new QPlainTextEditSearchWidget(this);\n this->layout()->addWidget(_searchWidget);\n\n connect(this, &QPlainTextEdit::textChanged, this,\n &QMarkdownTextEdit::adjustRightMargin);\n connect(this, &QPlainTextEdit::cursorPositionChanged, this,\n &QMarkdownTextEdit::centerTheCursor);\n connect(verticalScrollBar(), &QScrollBar::valueChanged, this,\n [this](int) { _lineNumArea->update(); });\n connect(this, &QPlainTextEdit::cursorPositionChanged, this, [this]() {\n _lineNumArea->update();\n\n auto oldArea = blockBoundingGeometry(_textCursor.block())\n .translated(contentOffset());\n _textCursor = textCursor();\n auto newArea = blockBoundingGeometry(_textCursor.block())\n .translated(contentOffset());\n auto areaToUpdate = oldArea | newArea;\n viewport()->update(areaToUpdate.toRect());\n });\n connect(document(), &QTextDocument::blockCountChanged, this,\n &QMarkdownTextEdit::updateLineNumberAreaWidth);\n connect(this, &QPlainTextEdit::updateRequest, this,\n &QMarkdownTextEdit::updateLineNumberArea);\n\n updateSettings();\n\n // workaround for disabled signals up initialization\n QTimer::singleShot(300, this, &QMarkdownTextEdit::adjustRightMargin);\n}\n MarkdownHighlighter *highlighter();\n QPlainTextEditSearchWidget *searchWidget();\n void setIgnoredClickUrlSchemata(QStringList ignoredUrlSchemata) {\n _ignoredClickUrlSchemata = std::move(ignoredUrlSchemata);\n}\n virtual void openUrl(const QString &urlString) {\n qDebug() << \"QMarkdownTextEdit \" << __func__\n << \" - 'urlString': \" << urlString;\n\n QDesktopServices::openUrl(QUrl(urlString));\n}\n QString getMarkdownUrlAtPosition(const QString &text, int position) {\n QString url;\n\n // get a map of parsed Markdown urls with their link texts as key\n const QMap urlMap = parseMarkdownUrlsFromText(text);\n QMap::const_iterator i = urlMap.constBegin();\n for (; i != urlMap.constEnd(); ++i) {\n const QString &linkText = i.key();\n const QString &urlString = i.value();\n\n const int foundPositionStart = text.indexOf(linkText);\n\n if (foundPositionStart >= 0) {\n // calculate end position of found linkText\n const int foundPositionEnd = foundPositionStart + linkText.size();\n\n // check if position is in found string range\n if ((position >= foundPositionStart) &&\n (position <= foundPositionEnd)) {\n url = urlString;\n break;\n }\n }\n }\n\n return url;\n}\n void initSearchFrame(QWidget *searchFrame, bool darkMode = false) {\n _searchFrame = searchFrame;\n\n // remove the search widget from our layout\n layout()->removeWidget(_searchWidget);\n\n QLayout *layout = _searchFrame->layout();\n\n // create a grid layout for the frame and add the search widget to it\n if (layout == nullptr) {\n layout = new QVBoxLayout(_searchFrame);\n layout->setSpacing(0);\n layout->setContentsMargins(0, 0, 0, 0);\n }\n\n _searchWidget->setDarkMode(darkMode);\n layout->addWidget(_searchWidget);\n _searchFrame->setLayout(layout);\n}\n void setAutoTextOptions(AutoTextOptions options) {\n _autoTextOptions = options;\n}\n static bool isValidUrl(const QString &urlString) {\n static QRegularExpression regex(R\"(^\\w+:\\/\\/.+)\");\n const QRegularExpressionMatch match = regex.match(urlString);\n return match.hasMatch();\n}\n void resetMouseCursor() const {\n QWidget *viewPort = viewport();\n viewPort->setCursor(Qt::IBeamCursor);\n}\n void setReadOnly(bool ro) {\n QPlainTextEdit::setReadOnly(ro);\n\n // attempted to fix a problem with Chinese and Japanese input methods\n // @see https://github.com/pbek/QOwnNotes/issues/976\n setAttribute(Qt::WA_InputMethodEnabled, !isReadOnly());\n}\n void doSearch(QString &searchText,\n QPlainTextEditSearchWidget::SearchMode searchMode =\n QPlainTextEditSearchWidget::SearchMode::PlainTextMode) {\n _searchWidget->setSearchText(searchText);\n _searchWidget->setSearchMode(searchMode);\n _searchWidget->doSearchCount();\n _searchWidget->activate(false);\n}\n void hideSearchWidget(bool reset) {\n _searchWidget->deactivate();\n\n if (reset) {\n _searchWidget->reset();\n }\n}\n void updateSettings() {\n // if true: centers the screen if cursor reaches bottom (but not top)\n searchWidget()->setDebounceDelay(_debounceDelay);\n setCenterOnScroll(_centerCursor);\n}\n void setLineNumbersCurrentLineColor(QColor color) {\n _lineNumArea->setCurrentLineColor(std::move(color));\n}\n void setLineNumbersOtherLineColor(QColor color) {\n _lineNumArea->setOtherLineColor(std::move(color));\n}\n void setSearchWidgetDebounceDelay(uint debounceDelay) {\n _debounceDelay = debounceDelay;\n searchWidget()->setDebounceDelay(_debounceDelay);\n}\n void setHighlightingEnabled(bool enabled) {\n if (_highlightingEnabled == enabled || _highlighter == nullptr) {\n return;\n }\n\n _highlightingEnabled = enabled;\n _highlighter->setDocument(enabled ? document() : Q_NULLPTR);\n\n if (enabled) {\n _highlighter->rehighlight();\n }\n}\n [[nodiscard]] bool highlightingEnabled() const {\n return _highlightingEnabled && _highlighter != nullptr;\n}\n void setHighlightCurrentLine(bool set) {\n _highlightCurrentLine = set;\n}\n bool highlightCurrentLine() { return _highlightCurrentLine; }\n void setCurrentLineHighlightColor(const QColor &c) {\n _currentLineHighlightColor = color;\n}\n QColor currentLineHighlightColor() {\n return _currentLineHighlightColor;\n}\n public:\n void duplicateText() {\n if (isReadOnly()) {\n return;\n }\n\n QTextCursor cursor = this->textCursor();\n QString selectedText = cursor.selectedText();\n\n // duplicate line if no text was selected\n if (selectedText.isEmpty()) {\n const int position = cursor.position();\n\n // select the whole line\n cursor.movePosition(QTextCursor::StartOfBlock);\n cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);\n\n const int positionDiff = cursor.position() - position;\n selectedText = \"\\n\" + cursor.selectedText();\n\n // insert text with new line at end of the selected line\n cursor.setPosition(cursor.selectionEnd());\n cursor.insertText(selectedText);\n\n // set the position to same position it was in the duplicated line\n cursor.setPosition(cursor.position() - positionDiff);\n } else {\n // duplicate selected text\n cursor.setPosition(cursor.selectionEnd());\n const int selectionStart = cursor.position();\n\n // insert selected text\n cursor.insertText(selectedText);\n const int selectionEnd = cursor.position();\n\n // select the inserted text\n cursor.setPosition(selectionStart);\n cursor.setPosition(selectionEnd, QTextCursor::KeepAnchor);\n }\n\n this->setTextCursor(cursor);\n}\n void setText(const QString &text) { setPlainText(text); }\n void setPlainText(const QString &text) {\n // clear the dirty blocks vector to increase performance and prevent\n // a possible crash in QSyntaxHighlighter::rehighlightBlock\n if (_highlighter) _highlighter->clearDirtyBlocks();\n\n QPlainTextEdit::setPlainText(text);\n adjustRightMargin();\n}\n void adjustRightMargin() {\n QMargins margins = layout()->contentsMargins();\n const int rightMargin =\n document()->size().height() > viewport()->size().height() ? 24 : 0;\n margins.setRight(rightMargin);\n layout()->setContentsMargins(margins);\n}\n void hide() {\n _searchWidget->hide();\n QWidget::hide();\n}\n bool openLinkAtCursorPosition() {\n QTextCursor cursor = this->textCursor();\n const int clickedPosition = cursor.position();\n\n // select the text in the clicked block and find out on\n // which position we clicked\n cursor.movePosition(QTextCursor::StartOfBlock);\n const int positionFromStart = clickedPosition - cursor.position();\n cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);\n\n const QString selectedText = cursor.selectedText();\n\n // find out which url in the selected text was clicked\n const QString urlString =\n getMarkdownUrlAtPosition(selectedText, positionFromStart);\n const QUrl url = QUrl(urlString);\n const bool isRelativeFileUrl =\n urlString.startsWith(QLatin1String(\"file://..\"));\n const bool isLegacyAttachmentUrl =\n urlString.startsWith(QLatin1String(\"file://attachments\"));\n\n qDebug() << __func__ << \" - 'emit urlClicked( urlString )': \" << urlString;\n\n Q_EMIT urlClicked(urlString);\n\n if ((url.isValid() && isValidUrl(urlString)) || isRelativeFileUrl ||\n isLegacyAttachmentUrl) {\n // ignore some schemata\n if (!(_ignoredClickUrlSchemata.contains(url.scheme()) ||\n isRelativeFileUrl || isLegacyAttachmentUrl)) {\n // open the url\n openUrl(urlString);\n }\n\n return true;\n }\n\n return false;\n}\n bool handleBackspaceEntered() {\n if (!(_autoTextOptions & AutoTextOption::BracketRemoval) || isReadOnly()) {\n return false;\n }\n\n QTextCursor cursor = textCursor();\n\n // return if some text was selected\n if (!cursor.selectedText().isEmpty()) {\n return false;\n }\n\n int position = cursor.position();\n const int positionInBlock = cursor.positionInBlock();\n int block = cursor.block().blockNumber();\n\n if (_highlighter)\n if (_highlighter->isPosInACodeSpan(block, positionInBlock - 1))\n return false;\n\n // return if backspace was pressed at the beginning of a block\n if (positionInBlock == 0) {\n return false;\n }\n\n // get the current text from the block\n const QString text = cursor.block().text();\n\n char charToRemove{};\n\n // current char\n const char charInFront = text.at(positionInBlock - 1).toLatin1();\n\n if (charInFront == '*')\n return handleCharRemoval(MarkdownHighlighter::RangeType::Emphasis,\n block, positionInBlock - 1);\n else if (charInFront == '`')\n return handleCharRemoval(MarkdownHighlighter::RangeType::CodeSpan,\n block, positionInBlock - 1);\n\n // handle removal of \", ', and brackets\n\n // is it opener?\n int pos = _openingCharacters.indexOf(charInFront);\n // for \" and '\n bool isOpener = false;\n bool isCloser = false;\n if (pos == 5 || pos == 6) {\n isOpener = isQuotOpener(positionInBlock - 1, text);\n } else {\n isOpener = pos != -1;\n }\n if (isOpener) {\n charToRemove = _closingCharacters.at(pos);\n } else {\n // is it closer?\n pos = _closingCharacters.indexOf(charInFront);\n if (pos == 5 || pos == 6)\n isCloser = isQuotCloser(positionInBlock - 1, text);\n else\n isCloser = pos != -1;\n if (isCloser)\n charToRemove = _openingCharacters.at(pos);\n else\n return false;\n }\n\n int charToRemoveIndex = -1;\n if (isOpener) {\n bool closer = true;\n charToRemoveIndex = text.indexOf(charToRemove, positionInBlock);\n if (charToRemoveIndex == -1) return false;\n if (pos == 5 || pos == 6)\n closer = isQuotCloser(charToRemoveIndex, text);\n if (!closer) return false;\n cursor.setPosition(position + (charToRemoveIndex - positionInBlock));\n cursor.deleteChar();\n } else if (isCloser) {\n charToRemoveIndex = text.lastIndexOf(charToRemove, positionInBlock - 2);\n if (charToRemoveIndex == -1) return false;\n bool opener = true;\n if (pos == 5 || pos == 6)\n opener = isQuotOpener(charToRemoveIndex, text);\n if (!opener) return false;\n const int pos = position - (positionInBlock - charToRemoveIndex);\n cursor.setPosition(pos);\n cursor.deleteChar();\n position -= 1;\n } else {\n charToRemoveIndex = text.lastIndexOf(charToRemove, positionInBlock - 2);\n if (charToRemoveIndex == -1) return false;\n const int pos = position - (positionInBlock - charToRemoveIndex);\n cursor.setPosition(pos);\n cursor.deleteChar();\n position -= 1;\n }\n\n // moving the cursor back to the old position so the previous character\n // can be removed\n cursor.setPosition(position);\n setTextCursor(cursor);\n return false;\n}\n void centerTheCursor() {\n if (_mouseButtonDown || !_centerCursor) {\n return;\n }\n\n // Centers the cursor every time, but not on the top and bottom,\n // bottom is done by setCenterOnScroll() in updateSettings()\n centerCursor();\n\n /*\n QRect cursor = cursorRect();\n QRect vp = viewport()->rect();\n\n qDebug() << __func__ << \" - 'cursor.top': \" << cursor.top();\n qDebug() << __func__ << \" - 'cursor.bottom': \" << cursor.bottom();\n qDebug() << __func__ << \" - 'vp': \" << vp.bottom();\n\n int bottom = 0;\n int top = 0;\n\n qDebug() << __func__ << \" - 'viewportMargins().top()': \"\n << viewportMargins().top();\n\n qDebug() << __func__ << \" - 'viewportMargins().bottom()': \"\n << viewportMargins().bottom();\n\n int vpBottom = viewportMargins().top() + viewportMargins().bottom() +\n vp.bottom(); int vpCenter = vpBottom / 2; int cBottom = cursor.bottom() +\n viewportMargins().top();\n\n qDebug() << __func__ << \" - 'vpBottom': \" << vpBottom;\n qDebug() << __func__ << \" - 'vpCenter': \" << vpCenter;\n qDebug() << __func__ << \" - 'cBottom': \" << cBottom;\n\n\n if (cBottom >= vpCenter) {\n bottom = cBottom + viewportMargins().top() / 2 +\n viewportMargins().bottom() / 2 - (vp.bottom() / 2);\n // bottom = cBottom - (vp.bottom() / 2);\n // bottom *= 1.5;\n }\n\n // setStyleSheet(QString(\"QPlainTextEdit {padding-bottom:\n %1px;}\").arg(QString::number(bottom)));\n\n // if (cursor.top() < (vp.bottom() / 2)) {\n // top = (vp.bottom() / 2) - cursor.top() + viewportMargins().top() /\n 2 + viewportMargins().bottom() / 2;\n //// top *= -1;\n //// bottom *= 1.5;\n // }\n qDebug() << __func__ << \" - 'top': \" << top;\n qDebug() << __func__ << \" - 'bottom': \" << bottom;\n setViewportMargins(0,top,0, bottom);\n\n\n // QScrollBar* scrollbar = verticalScrollBar();\n //\n // qDebug() << __func__ << \" - 'scrollbar->value();': \" <<\n scrollbar->value();;\n // qDebug() << __func__ << \" - 'scrollbar->maximum();': \"\n // << scrollbar->maximum();;\n\n\n // scrollbar->setValue(scrollbar->value() - offset.y());\n //\n // setViewportMargins\n\n // setViewportMargins(0, 0, 0, bottom);\n */\n}\n void undo() {\n if (isReadOnly()) {\n return;\n }\n\n QTextCursor cursor = textCursor();\n // if no text selected, call undo\n if (!cursor.hasSelection()) {\n QPlainTextEdit::undo();\n return;\n }\n\n // if text is selected and bracket closing was used\n // we retain our selection\n if (_handleBracketClosingUsed) {\n // get the selection\n int selectionEnd = cursor.selectionEnd();\n int selectionStart = cursor.selectionStart();\n // call undo\n QPlainTextEdit::undo();\n // select again\n cursor.setPosition(selectionStart - 1);\n cursor.setPosition(selectionEnd - 1, QTextCursor::KeepAnchor);\n this->setTextCursor(cursor);\n _handleBracketClosingUsed = false;\n } else {\n // if text was selected but bracket closing wasn't used\n // do normal undo\n QPlainTextEdit::undo();\n return;\n }\n}\n void moveTextUpDown(bool up) {\n if (isReadOnly()) {\n return;\n }\n\n QTextCursor cursor = textCursor();\n QTextCursor move = cursor;\n\n move.setVisualNavigation(false);\n\n move.beginEditBlock(); // open an edit block to keep undo operations sane\n bool hasSelection = cursor.hasSelection();\n\n if (hasSelection) {\n // if there's a selection inside the block, we select the whole block\n move.setPosition(cursor.selectionStart());\n move.movePosition(QTextCursor::StartOfBlock);\n move.setPosition(cursor.selectionEnd(), QTextCursor::KeepAnchor);\n move.movePosition(\n move.atBlockStart() ? QTextCursor::Left : QTextCursor::EndOfBlock,\n QTextCursor::KeepAnchor);\n } else {\n move.movePosition(QTextCursor::StartOfBlock);\n move.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);\n }\n\n // get the text of the current block\n QString text = move.selectedText();\n\n move.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor);\n move.removeSelectedText();\n\n if (up) { // up key\n move.movePosition(QTextCursor::PreviousBlock);\n move.insertBlock();\n move.movePosition(QTextCursor::Left);\n } else { // down key\n move.movePosition(QTextCursor::EndOfBlock);\n if (move.atBlockStart()) { // empty block\n move.movePosition(QTextCursor::NextBlock);\n move.insertBlock();\n move.movePosition(QTextCursor::Left);\n } else {\n move.insertBlock();\n }\n }\n\n int start = move.position();\n move.clearSelection();\n move.insertText(text);\n int end = move.position();\n\n // reselect\n if (hasSelection) {\n move.setPosition(end);\n move.setPosition(start, QTextCursor::KeepAnchor);\n } else {\n move.setPosition(start);\n }\n\n move.endEditBlock();\n\n setTextCursor(move);\n}\n void setLineNumberEnabled(bool enabled) {\n _lineNumArea->setLineNumAreaEnabled(enabled);\n updateLineNumberAreaWidth(0);\n}\n protected:\n QTextCursor _textCursor;\n MarkdownHighlighter *_highlighter = nullptr;\n bool _highlightingEnabled;\n QStringList _ignoredClickUrlSchemata;\n QPlainTextEditSearchWidget *_searchWidget;\n QWidget *_searchFrame;\n AutoTextOptions _autoTextOptions;\n bool _mouseButtonDown = false;\n bool _centerCursor = false;\n bool _highlightCurrentLine = false;\n QColor _currentLineHighlightColor = QColor();\n uint _debounceDelay = 0;\n bool eventFilter(QObject *obj, QEvent *event) override {\n // qDebug() << event->type();\n if (event->type() == QEvent::HoverMove) {\n auto *mouseEvent = static_cast(event);\n\n QWidget *viewPort = this->viewport();\n // toggle cursor when control key has been pressed or released\n viewPort->setCursor(\n mouseEvent->modifiers().testFlag(Qt::ControlModifier)\n ? Qt::PointingHandCursor\n : Qt::IBeamCursor);\n } else if (event->type() == QEvent::KeyPress) {\n auto *keyEvent = static_cast(event);\n\n // set cursor to pointing hand if control key was pressed\n if (keyEvent->modifiers().testFlag(Qt::ControlModifier)) {\n QWidget *viewPort = this->viewport();\n viewPort->setCursor(Qt::PointingHandCursor);\n }\n\n // disallow keys if text edit hasn't focus\n if (!this->hasFocus()) {\n return true;\n }\n\n if ((keyEvent->key() == Qt::Key_Escape) && _searchWidget->isVisible()) {\n _searchWidget->deactivate();\n return true;\n } else if (keyEvent->key() == Qt::Key_Insert &&\n keyEvent->modifiers().testFlag(Qt::NoModifier)) {\n setOverwriteMode(!overwriteMode());\n\n // This solves a UI glitch if the visual cursor was not properly\n // updated when characters have different widths\n QTextCursor cursor = this->textCursor();\n cursor.movePosition(QTextCursor::Right);\n setTextCursor(cursor);\n cursor.movePosition(QTextCursor::Left);\n setTextCursor(cursor);\n\n return false;\n } else if ((keyEvent->key() == Qt::Key_Tab) ||\n (keyEvent->key() == Qt::Key_Backtab)) {\n // handle entered tab and reverse tab keys\n return handleTabEntered(keyEvent->key() == Qt::Key_Backtab);\n } else if ((keyEvent->key() == Qt::Key_F) &&\n keyEvent->modifiers().testFlag(Qt::ControlModifier)) {\n _searchWidget->activate();\n return true;\n } else if ((keyEvent->key() == Qt::Key_R) &&\n keyEvent->modifiers().testFlag(Qt::ControlModifier)) {\n _searchWidget->activateReplace();\n return true;\n // } else if (keyEvent->key() == Qt::Key_Delete) {\n } else if (keyEvent->key() == Qt::Key_Backspace) {\n return handleBackspaceEntered();\n } else if (keyEvent->key() == Qt::Key_Asterisk) {\n return handleBracketClosing(QLatin1Char('*'));\n } else if (keyEvent->key() == Qt::Key_QuoteDbl) {\n return quotationMarkCheck(QLatin1Char('\"'));\n // apostrophe bracket closing is temporary disabled because\n // apostrophes are used in different contexts\n // } else if (keyEvent->key() == Qt::Key_Apostrophe) {\n // return handleBracketClosing(\"'\");\n // underline bracket closing is temporary disabled because\n // underlines are used in different contexts\n // } else if (keyEvent->key() == Qt::Key_Underscore) {\n // return handleBracketClosing(\"_\");\n } else if (keyEvent->key() == Qt::Key_QuoteLeft) {\n return quotationMarkCheck(QLatin1Char('`'));\n } else if (keyEvent->key() == Qt::Key_AsciiTilde) {\n return handleBracketClosing(QLatin1Char('~'));\n#ifdef Q_OS_MAC\n } else if (keyEvent->modifiers().testFlag(Qt::AltModifier) &&\n keyEvent->key() == Qt::Key_ParenLeft) {\n // bracket closing for US keyboard on macOS\n return handleBracketClosing(QLatin1Char('{'), QLatin1Char('}'));\n#endif\n } else if (keyEvent->key() == Qt::Key_ParenLeft) {\n return handleBracketClosing(QLatin1Char('('), QLatin1Char(')'));\n } else if (keyEvent->key() == Qt::Key_BraceLeft) {\n return handleBracketClosing(QLatin1Char('{'), QLatin1Char('}'));\n } else if (keyEvent->key() == Qt::Key_BracketLeft) {\n return handleBracketClosing(QLatin1Char('['), QLatin1Char(']'));\n } else if (keyEvent->key() == Qt::Key_Less) {\n return handleBracketClosing(QLatin1Char('<'), QLatin1Char('>'));\n#ifdef Q_OS_MAC\n } else if (keyEvent->modifiers().testFlag(Qt::AltModifier) &&\n keyEvent->key() == Qt::Key_ParenRight) {\n // bracket closing for US keyboard on macOS\n return bracketClosingCheck(QLatin1Char('{'), QLatin1Char('}'));\n#endif\n } else if (keyEvent->key() == Qt::Key_ParenRight) {\n return bracketClosingCheck(QLatin1Char('('), QLatin1Char(')'));\n } else if (keyEvent->key() == Qt::Key_BraceRight) {\n return bracketClosingCheck(QLatin1Char('{'), QLatin1Char('}'));\n } else if (keyEvent->key() == Qt::Key_BracketRight) {\n return bracketClosingCheck(QLatin1Char('['), QLatin1Char(']'));\n } else if (keyEvent->key() == Qt::Key_Greater) {\n return bracketClosingCheck(QLatin1Char('<'), QLatin1Char('>'));\n } else if ((keyEvent->key() == Qt::Key_Return ||\n keyEvent->key() == Qt::Key_Enter) &&\n !isReadOnly() &&\n keyEvent->modifiers().testFlag(Qt::ShiftModifier)) {\n QTextCursor cursor = this->textCursor();\n cursor.insertText(\" \\n\");\n return true;\n } else if ((keyEvent->key() == Qt::Key_Return ||\n keyEvent->key() == Qt::Key_Enter) &&\n !isReadOnly() &&\n keyEvent->modifiers().testFlag(Qt::ControlModifier)) {\n QTextCursor cursor = this->textCursor();\n cursor.movePosition(QTextCursor::EndOfBlock);\n cursor.insertText(QStringLiteral(\"\\n\"));\n setTextCursor(cursor);\n return true;\n } else if (keyEvent == QKeySequence::Copy ||\n keyEvent == QKeySequence::Cut) {\n QTextCursor cursor = this->textCursor();\n if (!cursor.hasSelection()) {\n QString text;\n if (cursor.block().length() <= 1) // no content\n text = \"\\n\";\n else {\n // cursor.select(QTextCursor::BlockUnderCursor); //\n // negative, it will include the previous paragraph\n // separator\n cursor.movePosition(QTextCursor::StartOfBlock);\n cursor.movePosition(QTextCursor::EndOfBlock,\n QTextCursor::KeepAnchor);\n text = cursor.selectedText();\n if (!cursor.atEnd()) {\n text += \"\\n\";\n // this is the paragraph separator\n cursor.movePosition(QTextCursor::NextCharacter,\n QTextCursor::KeepAnchor, 1);\n }\n }\n if (keyEvent == QKeySequence::Cut) {\n if (!cursor.atEnd() && text == \"\\n\")\n cursor.deletePreviousChar();\n else\n cursor.removeSelectedText();\n cursor.movePosition(QTextCursor::StartOfBlock);\n setTextCursor(cursor);\n }\n qApp->clipboard()->setText(text);\n return true;\n }\n } else if ((keyEvent->key() == Qt::Key_Down) &&\n keyEvent->modifiers().testFlag(Qt::ControlModifier) &&\n keyEvent->modifiers().testFlag(Qt::AltModifier)) {\n // duplicate text with `Ctrl + Alt + Down`\n duplicateText();\n return true;\n#ifndef Q_OS_MAC\n } else if ((keyEvent->key() == Qt::Key_Down) &&\n keyEvent->modifiers().testFlag(Qt::ControlModifier) &&\n !keyEvent->modifiers().testFlag(Qt::ShiftModifier)) {\n // scroll the page down\n auto *scrollBar = verticalScrollBar();\n scrollBar->setSliderPosition(scrollBar->sliderPosition() + 1);\n return true;\n } else if ((keyEvent->key() == Qt::Key_Up) &&\n keyEvent->modifiers().testFlag(Qt::ControlModifier) &&\n !keyEvent->modifiers().testFlag(Qt::ShiftModifier)) {\n // scroll the page up\n auto *scrollBar = verticalScrollBar();\n scrollBar->setSliderPosition(scrollBar->sliderPosition() - 1);\n return true;\n#endif\n } else if ((keyEvent->key() == Qt::Key_Down) &&\n keyEvent->modifiers().testFlag(Qt::NoModifier)) {\n // if you are in the last line and press cursor down the cursor will\n // jump to the end of the line\n QTextCursor cursor = textCursor();\n if (cursor.position() >= document()->lastBlock().position()) {\n cursor.movePosition(QTextCursor::EndOfLine);\n\n // check if we are really in the last line, not only in\n // the last block\n if (cursor.atBlockEnd()) {\n setTextCursor(cursor);\n }\n }\n return QPlainTextEdit::eventFilter(obj, event);\n } else if ((keyEvent->key() == Qt::Key_Up) &&\n keyEvent->modifiers().testFlag(Qt::NoModifier)) {\n // if you are in the first line and press cursor up the cursor will\n // jump to the start of the line\n QTextCursor cursor = textCursor();\n QTextBlock block = document()->firstBlock();\n int endOfFirstLinePos = block.position() + block.length();\n\n if (cursor.position() <= endOfFirstLinePos) {\n cursor.movePosition(QTextCursor::StartOfLine);\n\n // check if we are really in the first line, not only in\n // the first block\n if (cursor.atBlockStart()) {\n setTextCursor(cursor);\n }\n }\n return QPlainTextEdit::eventFilter(obj, event);\n } else if (keyEvent->key() == Qt::Key_Return ||\n keyEvent->key() == Qt::Key_Enter) {\n return handleReturnEntered();\n } else if ((keyEvent->key() == Qt::Key_F3)) {\n _searchWidget->doSearch(\n !keyEvent->modifiers().testFlag(Qt::ShiftModifier));\n return true;\n } else if ((keyEvent->key() == Qt::Key_Z) &&\n (keyEvent->modifiers().testFlag(Qt::ControlModifier)) &&\n !(keyEvent->modifiers().testFlag(Qt::ShiftModifier))) {\n undo();\n return true;\n } else if ((keyEvent->key() == Qt::Key_Down) &&\n (keyEvent->modifiers().testFlag(Qt::ControlModifier)) &&\n (keyEvent->modifiers().testFlag(Qt::ShiftModifier))) {\n moveTextUpDown(false);\n return true;\n } else if ((keyEvent->key() == Qt::Key_Up) &&\n (keyEvent->modifiers().testFlag(Qt::ControlModifier)) &&\n (keyEvent->modifiers().testFlag(Qt::ShiftModifier))) {\n moveTextUpDown(true);\n return true;\n#ifdef Q_OS_MAC\n // https://github.com/pbek/QOwnNotes/issues/1593\n // https://github.com/pbek/QOwnNotes/issues/2643\n } else if (keyEvent->key() == Qt::Key_Home) {\n QTextCursor cursor = textCursor();\n // Meta is Control on macOS\n cursor.movePosition(\n keyEvent->modifiers().testFlag(Qt::MetaModifier)\n ? QTextCursor::Start\n : QTextCursor::StartOfLine,\n keyEvent->modifiers().testFlag(Qt::ShiftModifier)\n ? QTextCursor::KeepAnchor\n : QTextCursor::MoveAnchor);\n this->setTextCursor(cursor);\n return true;\n } else if (keyEvent->key() == Qt::Key_End) {\n QTextCursor cursor = textCursor();\n // Meta is Control on macOS\n cursor.movePosition(\n keyEvent->modifiers().testFlag(Qt::MetaModifier)\n ? QTextCursor::End\n : QTextCursor::EndOfLine,\n keyEvent->modifiers().testFlag(Qt::ShiftModifier)\n ? QTextCursor::KeepAnchor\n : QTextCursor::MoveAnchor);\n this->setTextCursor(cursor);\n return true;\n#endif\n }\n\n return QPlainTextEdit::eventFilter(obj, event);\n } else if (event->type() == QEvent::KeyRelease) {\n auto *keyEvent = static_cast(event);\n\n // reset cursor if control key was released\n if (keyEvent->key() == Qt::Key_Control) {\n resetMouseCursor();\n }\n\n return QPlainTextEdit::eventFilter(obj, event);\n } else if (event->type() == QEvent::MouseButtonRelease) {\n _mouseButtonDown = false;\n auto *mouseEvent = static_cast(event);\n\n // track `Ctrl + Click` in the text edit\n if ((obj == this->viewport()) &&\n (mouseEvent->button() == Qt::LeftButton) &&\n (QGuiApplication::keyboardModifiers() == Qt::ExtraButton24)) {\n // open the link (if any) at the current position\n // in the noteTextEdit\n openLinkAtCursorPosition();\n return true;\n }\n } else if (event->type() == QEvent::MouseButtonPress) {\n _mouseButtonDown = true;\n } else if (event->type() == QEvent::MouseButtonDblClick) {\n _mouseButtonDown = true;\n } else if (event->type() == QEvent::Wheel) {\n auto *wheel = dynamic_cast(event);\n\n // emit zoom signals\n if (wheel->modifiers() == Qt::ControlModifier) {\n if (wheel->angleDelta().y() > 0) {\n Q_EMIT zoomIn();\n } else {\n Q_EMIT zoomOut();\n }\n\n return true;\n }\n }\n\n return QPlainTextEdit::eventFilter(obj, event);\n}\n QMargins viewportMargins() {\n return QPlainTextEdit::viewportMargins();\n}\n bool increaseSelectedTextIndention(\n bool reverse,\n const QString &indentCharacters = QChar::fromLatin1('\\t')) {\n QTextCursor cursor = this->textCursor();\n QString selectedText = cursor.selectedText();\n\n if (!selectedText.isEmpty()) {\n // Start the selection at start of the first block of the selection\n int end = cursor.selectionEnd();\n cursor.setPosition(cursor.selectionStart());\n cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor);\n cursor.setPosition(end, QTextCursor::KeepAnchor);\n this->setTextCursor(cursor);\n selectedText = cursor.selectedText();\n\n // we need this strange newline character we are getting in the\n // selected text for newlines\n const QString newLine =\n QString::fromUtf8(QByteArray::fromHex(QByteArrayLiteral(\"e280a9\")));\n QString newText;\n\n if (reverse) {\n // un-indent text\n\n const int indentSize = indentCharacters == QStringLiteral(\"\\t\")\n ? 4\n : indentCharacters.length();\n\n // remove leading \\t or spaces in following lines\n newText = selectedText.replace(\n QRegularExpression(newLine + QStringLiteral(\"(\\\\t| {1,\") +\n QString::number(indentSize) +\n QStringLiteral(\"})\")),\n QStringLiteral(\"\\n\"));\n\n // remove leading \\t or spaces in first line\n newText.remove(QRegularExpression(QStringLiteral(\"^(\\\\t| {1,\") +\n QString::number(indentSize) +\n QStringLiteral(\"})\")));\n } else {\n // replace trailing new line to prevent an indent of the line after\n // the selection\n newText = selectedText.replace(\n QRegularExpression(QRegularExpression::escape(newLine) +\n QStringLiteral(\"$\")),\n QStringLiteral(\"\\n\"));\n\n // indent text\n newText.replace(newLine, QStringLiteral(\"\\n\") + indentCharacters)\n .prepend(indentCharacters);\n\n // remove trailing \\t\n static QRegularExpression regex1(QStringLiteral(\"\\\\t$\"));\n newText.remove(regex1);\n }\n\n // insert the new text\n cursor.insertText(newText);\n\n // update the selection to the new text\n cursor.setPosition(cursor.position() - newText.size(),\n QTextCursor::KeepAnchor);\n this->setTextCursor(cursor);\n\n return true;\n } else if (reverse) {\n const int indentSize = indentCharacters.length();\n\n // do the check as often as we have characters to un-indent\n for (int i = 1; i <= indentSize; i++) {\n // if nothing was selected but we want to reverse the indention\n // check if there is a \\t in front or after the cursor and remove it\n // if so\n const int position = cursor.position();\n\n if (!cursor.atStart()) {\n // get character in front of cursor\n cursor.setPosition(position - 1, QTextCursor::KeepAnchor);\n }\n\n // check for \\t or space in front of cursor\n static QRegularExpression regex1(QStringLiteral(\"[\\\\t ]\"));\n QRegularExpressionMatch match = regex1.match(cursor.selectedText());\n\n if (!match.hasMatch()) {\n // (select to) check for \\t or space after the cursor\n cursor.setPosition(position);\n\n if (!cursor.atEnd()) {\n cursor.setPosition(position + 1, QTextCursor::KeepAnchor);\n }\n }\n\n match = regex1.match(cursor.selectedText());\n\n if (match.hasMatch()) {\n cursor.removeSelectedText();\n }\n\n cursor = this->textCursor();\n }\n\n return true;\n }\n\n // else just insert indentCharacters\n cursor.insertText(indentCharacters);\n\n return true;\n}\n bool handleTabEntered(bool reverse, const QString &indentCharacters =\n QChar::fromLatin1('\\t')) {\n if (isReadOnly()) {\n return true;\n }\n\n QTextCursor cursor = this->textCursor();\n\n // only check for lists if we haven't a text selected\n if (cursor.selectedText().isEmpty()) {\n cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);\n const QString currentLineText = cursor.selectedText();\n\n // check if we want to indent or un-indent an ordered list\n // Valid listCharacters: '+ ', '-' , '* ', '+ [ ] ', '+ [x] ', '- [ ] ',\n // '- [x] ', '- [-] ', '* [ ] ', '* [x] '.\n static QRegularExpression regex1(\n R\"(^(\\s*)([+|\\-|\\*] \\[(x|-| )\\]|[+\\-\\*])(\\s+)$)\");\n QRegularExpressionMatchIterator i = regex1.globalMatch(currentLineText);\n\n if (i.hasNext()) {\n QRegularExpressionMatch match = i.next();\n QString whitespaces = match.captured(1);\n const QString listCharacter = match.captured(2);\n const QString whitespaceCharacter = match.captured(4);\n\n // add or remove one tabulator key\n if (reverse) {\n // remove one set of indentCharacters or a tabulator\n whitespaces.remove(QRegularExpression(\n QStringLiteral(\"^(\\\\t|\") +\n QRegularExpression::escape(indentCharacters) +\n QStringLiteral(\")\")));\n\n } else {\n whitespaces += indentCharacters;\n }\n\n cursor.insertText(whitespaces + listCharacter +\n whitespaceCharacter);\n return true;\n }\n\n // check if we want to indent or un-indent an ordered list\n static QRegularExpression regex2(R\"(^(\\s*)(\\d+)([\\.|\\)])(\\s+)$)\");\n i = regex2.globalMatch(currentLineText);\n\n if (i.hasNext()) {\n const QRegularExpressionMatch match = i.next();\n QString whitespaces = match.captured(1);\n const QString listCharacter = match.captured(2);\n const QString listMarker = match.captured(3);\n const QString whitespaceCharacter = match.captured(4);\n\n // add or remove one tabulator key\n if (reverse) {\n whitespaces.chop(1);\n } else {\n whitespaces += indentCharacters;\n }\n\n cursor.insertText(whitespaces + listCharacter + listMarker +\n whitespaceCharacter);\n return true;\n }\n }\n\n // check if we want to indent the whole text\n return increaseSelectedTextIndention(reverse, indentCharacters);\n}\n QMap parseMarkdownUrlsFromText(const QString &text) {\n QMap urlMap;\n QRegularExpressionMatchIterator iterator;\n\n // match urls like this: \n // re = QRegularExpression(\"(<(.+?:\\\\/\\\\/.+?)>)\");\n static QRegularExpression regex1(QStringLiteral(\"(<(.+?)>)\"));\n iterator = regex1.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString linkText = match.captured(1);\n QString url = match.captured(2);\n urlMap[linkText] = url;\n }\n\n // match urls like this: [this url](http://mylink)\n // QRegularExpression re(\"(\\\\[.*?\\\\]\\\\((.+?:\\\\/\\\\/.+?)\\\\))\");\n static QRegularExpression regex2(R\"((\\[.*?\\]\\((.+?)\\)))\");\n iterator = regex2.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString linkText = match.captured(1);\n QString url = match.captured(2);\n urlMap[linkText] = url;\n }\n\n // match urls like this: http://mylink\n static QRegularExpression regex3(R\"(\\b\\w+?:\\/\\/[^\\s]+[^\\s>\\)])\");\n iterator = regex3.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString url = match.captured(0);\n urlMap[url] = url;\n }\n\n // match urls like this: www.github.com\n static QRegularExpression regex4(R\"(\\bwww\\.[^\\s]+\\.[^\\s]+\\b)\");\n iterator = regex4.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString url = match.captured(0);\n urlMap[url] = QStringLiteral(\"http://\") + url;\n }\n\n // match reference urls like this: [this url][1] with this later:\n // [1]: http://domain\n static QRegularExpression regex5(R\"((\\[.*?\\]\\[(.+?)\\]))\");\n iterator = regex5.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString linkText = match.captured(1);\n QString referenceId = match.captured(2);\n\n // search for the referenced url in the whole text edit\n // QRegularExpression refRegExp(\n // \"\\\\[\" + QRegularExpression::escape(referenceId) +\n // \"\\\\]: (.+?:\\\\/\\\\/.+)\");\n QRegularExpression refRegExp(QStringLiteral(\"\\\\[\") +\n QRegularExpression::escape(referenceId) +\n QStringLiteral(\"\\\\]: (.+)\"));\n QRegularExpressionMatch urlMatch = refRegExp.match(toPlainText());\n\n if (urlMatch.hasMatch()) {\n QString url = urlMatch.captured(1);\n urlMap[linkText] = url;\n }\n }\n\n return urlMap;\n}\n bool handleReturnEntered() {\n if (isReadOnly()) {\n return true;\n }\n\n // This will be the main cursor to add or remove text\n QTextCursor cursor = this->textCursor();\n\n // We need a 2nd cursor to get the text of the current block without moving\n // the main cursor that is used to remove the selected text\n QTextCursor cursor2 = this->textCursor();\n cursor2.select(QTextCursor::BlockUnderCursor);\n const QString currentLineText = cursor2.selectedText().trimmed();\n\n const int position = cursor.position();\n const bool cursorAtBlockStart = cursor.atBlockStart();\n cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);\n const QString currentLinePartialText = cursor.selectedText();\n\n // if return is pressed and there is just an unordered list symbol then we\n // want to remove the list symbol Valid listCharacters: '+ ', '-' , '* ', '+\n // [ ] ', '+ [x] ', '- [ ] ', '- [-] ', '- [x] ', '* [ ] ', '* [x] '.\n static QRegularExpression regex1(\n R\"(^(\\s*)([+|\\-|\\*] \\[(x|-| |)\\]|[+\\-\\*])(\\s+)$)\");\n QRegularExpressionMatchIterator iterator =\n regex1.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n cursor.removeSelectedText();\n return true;\n }\n\n // if return is pressed and there is just an ordered list symbol then we\n // want to remove the list symbol\n static QRegularExpression regex2(R\"(^(\\s*)(\\d+[\\.|\\)])(\\s+)$)\");\n iterator = regex2.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n qDebug() << cursor.selectedText();\n cursor.removeSelectedText();\n return true;\n }\n\n // Check if we are in an unordered list.\n // We are in a list when we have '* ', '- ' or '+ ', possibly with preceding\n // whitespace. If e.g. user has entered '**text**' and pressed enter - we\n // don't want to do more list-stuff.\n QString currentLine = currentLinePartialText.trimmed();\n QChar char0;\n QChar char1;\n if (currentLine.length() >= 1) char0 = currentLine.at(0);\n if (currentLine.length() >= 2) char1 = currentLine.at(1);\n const bool inList =\n ((char0 == QLatin1Char('*') || char0 == QLatin1Char('-') ||\n char0 == QLatin1Char('+')) &&\n char1 == QLatin1Char(' '));\n\n if (inList) {\n // if the current line starts with a list character (possibly after\n // whitespaces) add the whitespaces at the next line too\n // Valid listCharacters: '+ ', '-' , '* ', '+ [ ] ', '+ [x] ', '- [ ] ',\n // '- [x] ', '- [-] ', '* [ ] ', '* [x] '.\n static QRegularExpression regex3(\n R\"(^(\\s*)([+|\\-|\\*] \\[(x|-| |)\\]|[+\\-\\*])(\\s+))\");\n iterator = regex3.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n const QString whitespaces = match.captured(1);\n QString listCharacter = match.captured(2);\n const QString whitespaceCharacter = match.captured(4);\n\n static QRegularExpression regex4(R\"(^([+|\\-|\\*]) \\[(x| |\\-|)\\])\");\n // start new checkbox list item with an unchecked checkbox\n iterator = regex4.globalMatch(listCharacter);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match1 = iterator.next();\n const QString realListCharacter = match1.captured(1);\n listCharacter = realListCharacter + QStringLiteral(\" [ ]\");\n }\n\n cursor.setPosition(position);\n cursor.insertText(\"\\n\" + whitespaces + listCharacter +\n whitespaceCharacter);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n }\n\n // check for ordered lists and increment the list number in the next line\n static QRegularExpression regex5(R\"(^(\\s*)(\\d+)([\\.|\\)])(\\s+))\");\n iterator = regex5.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n const QString whitespaces = match.captured(1);\n const uint listNumber = match.captured(2).toUInt();\n const QString listMarker = match.captured(3);\n const QString whitespaceCharacter = match.captured(4);\n\n cursor.setPosition(position);\n cursor.insertText(\"\\n\" + whitespaces + QString::number(listNumber + 1) +\n listMarker + whitespaceCharacter);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n\n // intent next line with same whitespaces as in current line\n static QRegularExpression regex6(R\"(^(\\s+))\");\n iterator = regex6.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n const QString whitespaces = match.captured(1);\n\n cursor.setPosition(position);\n cursor.insertText(\"\\n\" + whitespaces);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n\n // Add new list item above current line if we are at the start the line of a\n // list item\n if (cursorAtBlockStart) {\n static QRegularExpression regex7(\n R\"(^([+|\\-|\\*] \\[(x|-| |)\\]|[+\\-\\*])(\\s+))\");\n iterator = regex7.globalMatch(currentLineText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n QString listCharacter = match.captured(1);\n const QString whitespaceCharacter = match.captured(3);\n\n static QRegularExpression regex8(R\"(^([+|\\-|\\*]) \\[(x| |\\-|)\\])\");\n // start new checkbox list item with an unchecked checkbox\n iterator = regex8.globalMatch(listCharacter);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match1 = iterator.next();\n const QString realListCharacter = match1.captured(1);\n listCharacter = realListCharacter + QStringLiteral(\" [ ]\");\n }\n\n cursor.setPosition(position);\n // Enter new list item above current line\n cursor.insertText(listCharacter + whitespaceCharacter + \"\\n\");\n // Move the cursor at the end of the new list item\n cursor.movePosition(QTextCursor::Left);\n setTextCursor(cursor);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n }\n\n return false;\n}\n bool handleBracketClosing(const QChar openingCharacter,\n QChar closingCharacter = QChar()) {\n // check if bracket closing or read-only are enabled\n if (!(_autoTextOptions & AutoTextOption::BracketClosing) || isReadOnly()) {\n return false;\n }\n\n QTextCursor cursor = textCursor();\n\n if (closingCharacter.isNull()) {\n closingCharacter = openingCharacter;\n }\n\n const QString selectedText = cursor.selectedText();\n\n // When user currently has text selected, we prepend the openingCharacter\n // and append the closingCharacter. E.g. 'text' -> '(text)'. We keep the\n // current selectedText selected.\n if (!selectedText.isEmpty()) {\n // Insert. The selectedText is overwritten.\n const QString newText =\n openingCharacter + selectedText + closingCharacter;\n cursor.insertText(newText);\n\n // Re-select the selectedText.\n const int selectionEnd = cursor.position() - 1;\n const int selectionStart = selectionEnd - selectedText.length();\n\n cursor.setPosition(selectionStart);\n cursor.setPosition(selectionEnd, QTextCursor::KeepAnchor);\n this->setTextCursor(cursor);\n _handleBracketClosingUsed = true;\n return true;\n }\n\n // get the current text from the block (inserted character not included)\n // Remove whitespace at start of string (e.g. in multilevel-lists).\n static QRegularExpression regex1(\"^\\\\s+\");\n const QString text = cursor.block().text().remove(regex1);\n\n const int pib = cursor.positionInBlock();\n bool isPreviousAsterisk =\n pib > 0 && pib < text.length() && text.at(pib - 1) == '*';\n bool isNextAsterisk = pib < text.length() && text.at(pib) == '*';\n bool isMaybeBold = isPreviousAsterisk && isNextAsterisk;\n if (pib < text.length() && !isMaybeBold && !text.at(pib).isSpace()) {\n return false;\n }\n\n // Default positions to move the cursor back.\n int cursorSubtract = 1;\n // Special handling for `*` opening character, as this could be:\n // - start of a list (or sublist);\n // - start of a bold text;\n if (openingCharacter == QLatin1Char('*')) {\n // don't auto complete in code block\n bool isInCode =\n MarkdownHighlighter::isCodeBlock(cursor.block().userState());\n // we only do auto completion if there is a space before the cursor pos\n bool hasSpaceOrAsteriskBefore = !text.isEmpty() && pib > 0 &&\n (text.at(pib - 1).isSpace() ||\n text.at(pib - 1) == QLatin1Char('*'));\n // This could be the start of a list, don't autocomplete.\n bool isEmpty = text.isEmpty();\n\n if (isInCode || !hasSpaceOrAsteriskBefore || isEmpty) {\n return false;\n }\n\n // bold\n if (isPreviousAsterisk && isNextAsterisk) {\n cursorSubtract = 1;\n }\n\n // User wants: '**'.\n // Not the start of a list, probably bold text. We autocomplete with\n // extra closingCharacter and cursorSubtract to 'catchup'.\n if (text == QLatin1String(\"*\")) {\n cursor.insertText(QStringLiteral(\"*\"));\n cursorSubtract = 2;\n }\n }\n\n // Auto-completion for ``` pair\n if (openingCharacter == QLatin1Char('`')) {\n#if QT_VERSION < QT_VERSION_CHECK(5, 12, 0)\n if (QRegExp(QStringLiteral(\"[^`]*``\")).exactMatch(text)) {\n#else\n if (QRegularExpression(\n QRegularExpression::anchoredPattern(QStringLiteral(\"[^`]*``\")))\n .match(text)\n .hasMatch()) {\n#endif\n cursor.insertText(QStringLiteral(\"``\"));\n cursorSubtract = 3;\n }\n }\n\n // don't auto complete in code block\n if (openingCharacter == QLatin1Char('<') &&\n MarkdownHighlighter::isCodeBlock(cursor.block().userState())) {\n return false;\n }\n\n cursor.beginEditBlock();\n cursor.insertText(openingCharacter);\n cursor.insertText(closingCharacter);\n cursor.setPosition(cursor.position() - cursorSubtract);\n cursor.endEditBlock();\n\n setTextCursor(cursor);\n return true;\n}\n\n/**\n * Checks if the closing character should be output or not\n *\n * @param openingCharacter\n * @param closingCharacter\n * @return\n */\nbool QMarkdownTextEdit::bracketClosingCheck(const QChar openingCharacter,\n QChar closingCharacter) {\n // check if bracket closing or read-only are enabled\n if (!(_autoTextOptions & AutoTextOption::BracketClosing) || isReadOnly()) {\n return false;\n }\n\n if (closingCharacter.isNull()) {\n closingCharacter = openingCharacter;\n }\n\n QTextCursor cursor = textCursor();\n const int positionInBlock = cursor.positionInBlock();\n\n // get the current text from the block\n const QString text = cursor.block().text();\n const int textLength = text.length();\n\n // if we are at the end of the line we just want to enter the character\n if (positionInBlock >= textLength) {\n return false;\n }\n\n const QChar currentChar = text.at(positionInBlock);\n\n // if (closingCharacter == openingCharacter) {\n\n // }\n\n qDebug() << __func__ << \" - 'currentChar': \" << currentChar;\n\n // if the current character is not the closing character we just want to\n // enter the character\n if (currentChar != closingCharacter) {\n return false;\n }\n\n const QString leftText = text.left(positionInBlock);\n const int openingCharacterCount = leftText.count(openingCharacter);\n const int closingCharacterCount = leftText.count(closingCharacter);\n\n // if there were enough opening characters just enter the character\n if (openingCharacterCount < (closingCharacterCount + 1)) {\n return false;\n }\n\n // move the cursor to the right and don't enter the character\n cursor.movePosition(QTextCursor::Right);\n setTextCursor(cursor);\n return true;\n}\n\n/**\n * Checks if the closing character should be output or not or if a closing\n * character after an opening character if needed\n *\n * @param quotationCharacter\n * @return\n */\nbool QMarkdownTextEdit::quotationMarkCheck(const QChar quotationCharacter) {\n // check if bracket closing or read-only are enabled\n if (!(_autoTextOptions & AutoTextOption::BracketClosing) || isReadOnly()) {\n return false;\n }\n\n QTextCursor cursor = textCursor();\n const int positionInBlock = cursor.positionInBlock();\n\n // get the current text from the block\n const QString text = cursor.block().text();\n const int textLength = text.length();\n\n // if last char is not space, we are at word end, no autocompletion\n const bool isBacktick = quotationCharacter == '`';\n if (!isBacktick && positionInBlock != 0 &&\n !text.at(positionInBlock - 1).isSpace()) {\n return false;\n }\n\n // if we are at the end of the line we just want to enter the character\n if (positionInBlock >= textLength) {\n return handleBracketClosing(quotationCharacter);\n }\n\n const QChar currentChar = text.at(positionInBlock);\n\n // if the current character is not the quotation character we just want to\n // enter the character\n if (currentChar != quotationCharacter) {\n return handleBracketClosing(quotationCharacter);\n }\n\n // move the cursor to the right and don't enter the character\n cursor.movePosition(QTextCursor::Right);\n setTextCursor(cursor);\n return true;\n}\n\n/***********************************\n * helper methods for char removal\n * Rules for (') and (\"):\n * if [sp]\" -> opener (sp = space)\n * if \"[sp] -> closer\n ***********************************/\nbool isQuotOpener(int position, const QString &text) {\n if (position == 0) return true;\n const int prevCharPos = position - 1;\n return text.at(prevCharPos).isSpace();\n}\nbool isQuotCloser(int position, const QString &text) {\n const int nextCharPos = position + 1;\n if (nextCharPos >= text.length()) return true;\n return text.at(nextCharPos).isSpace();\n}\n\n/**\n * Handles removing of matching brackets and other Markdown characters\n * Only works with backspace to remove text\n *\n * @return\n */\nbool QMarkdownTextEdit::handleBackspaceEntered() {\n if (!(_autoTextOptions & AutoTextOption::BracketRemoval) || isReadOnly()) {\n return false;\n }\n\n QTextCursor cursor = textCursor();\n\n // return if some text was selected\n if (!cursor.selectedText().isEmpty()) {\n return false;\n }\n\n int position = cursor.position();\n const int positionInBlock = cursor.positionInBlock();\n int block = cursor.block().blockNumber();\n\n if (_highlighter)\n if (_highlighter->isPosInACodeSpan(block, positionInBlock - 1))\n return false;\n\n // return if backspace was pressed at the beginning of a block\n if (positionInBlock == 0) {\n return false;\n }\n\n // get the current text from the block\n const QString text = cursor.block().text();\n\n char charToRemove{};\n\n // current char\n const char charInFront = text.at(positionInBlock - 1).toLatin1();\n\n if (charInFront == '*')\n return handleCharRemoval(MarkdownHighlighter::RangeType::Emphasis,\n block, positionInBlock - 1);\n else if (charInFront == '`')\n return handleCharRemoval(MarkdownHighlighter::RangeType::CodeSpan,\n block, positionInBlock - 1);\n\n // handle removal of \", ', and brackets\n\n // is it opener?\n int pos = _openingCharacters.indexOf(charInFront);\n // for \" and '\n bool isOpener = false;\n bool isCloser = false;\n if (pos == 5 || pos == 6) {\n isOpener = isQuotOpener(positionInBlock - 1, text);\n } else {\n isOpener = pos != -1;\n }\n if (isOpener) {\n charToRemove = _closingCharacters.at(pos);\n } else {\n // is it closer?\n pos = _closingCharacters.indexOf(charInFront);\n if (pos == 5 || pos == 6)\n isCloser = isQuotCloser(positionInBlock - 1, text);\n else\n isCloser = pos != -1;\n if (isCloser)\n charToRemove = _openingCharacters.at(pos);\n else\n return false;\n }\n\n int charToRemoveIndex = -1;\n if (isOpener) {\n bool closer = true;\n charToRemoveIndex = text.indexOf(charToRemove, positionInBlock);\n if (charToRemoveIndex == -1) return false;\n if (pos == 5 || pos == 6)\n closer = isQuotCloser(charToRemoveIndex, text);\n if (!closer) return false;\n cursor.setPosition(position + (charToRemoveIndex - positionInBlock));\n cursor.deleteChar();\n } else if (isCloser) {\n charToRemoveIndex = text.lastIndexOf(charToRemove, positionInBlock - 2);\n if (charToRemoveIndex == -1) return false;\n bool opener = true;\n if (pos == 5 || pos == 6)\n opener = isQuotOpener(charToRemoveIndex, text);\n if (!opener) return false;\n const int pos = position - (positionInBlock - charToRemoveIndex);\n cursor.setPosition(pos);\n cursor.deleteChar();\n position -= 1;\n } else {\n charToRemoveIndex = text.lastIndexOf(charToRemove, positionInBlock - 2);\n if (charToRemoveIndex == -1) return false;\n const int pos = position - (positionInBlock - charToRemoveIndex);\n cursor.setPosition(pos);\n cursor.deleteChar();\n position -= 1;\n }\n\n // moving the cursor back to the old position so the previous character\n // can be removed\n cursor.setPosition(position);\n setTextCursor(cursor);\n return false;\n}\n\nbool QMarkdownTextEdit::handleCharRemoval(MarkdownHighlighter::RangeType type,\n int block, int position) {\n if (!_highlighter) return false;\n\n auto range = _highlighter->findPositionInRanges(type, block, position);\n if (range == QPair{-1, -1}) return false;\n\n int charToRemovePos = range.first;\n if (position == range.first) charToRemovePos = range.second;\n\n QTextCursor cursor = textCursor();\n auto gpos = cursor.position();\n\n if (charToRemovePos > position) {\n cursor.setPosition(gpos + (charToRemovePos - (position + 1)));\n } else {\n cursor.setPosition(gpos - (position - charToRemovePos + 1));\n gpos--;\n }\n\n cursor.deleteChar();\n cursor.setPosition(gpos);\n setTextCursor(cursor);\n return false;\n}\n\nvoid QMarkdownTextEdit::updateLineNumAreaGeometry() {\n const auto contentsRect = this->contentsRect();\n const QRect newGeometry = {contentsRect.left(), contentsRect.top(),\n _lineNumArea->sizeHint().width(),\n contentsRect.height()};\n auto oldGeometry = _lineNumArea->geometry();\n if (newGeometry != oldGeometry) {\n _lineNumArea->setGeometry(newGeometry);\n }\n}\n\nvoid QMarkdownTextEdit::resizeEvent(QResizeEvent *event) {\n QPlainTextEdit::resizeEvent(event);\n updateLineNumAreaGeometry();\n}\n\n/**\n * Increases (or decreases) the indention of the selected text\n * (if there is a text selected) in the noteTextEdit\n * @return\n */\nbool QMarkdownTextEdit::increaseSelectedTextIndention(\n bool reverse, const QString &indentCharacters) {\n QTextCursor cursor = this->textCursor();\n QString selectedText = cursor.selectedText();\n\n if (!selectedText.isEmpty()) {\n // Start the selection at start of the first block of the selection\n int end = cursor.selectionEnd();\n cursor.setPosition(cursor.selectionStart());\n cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor);\n cursor.setPosition(end, QTextCursor::KeepAnchor);\n this->setTextCursor(cursor);\n selectedText = cursor.selectedText();\n\n // we need this strange newline character we are getting in the\n // selected text for newlines\n const QString newLine =\n QString::fromUtf8(QByteArray::fromHex(QByteArrayLiteral(\"e280a9\")));\n QString newText;\n\n if (reverse) {\n // un-indent text\n\n const int indentSize = indentCharacters == QStringLiteral(\"\\t\")\n ? 4\n : indentCharacters.length();\n\n // remove leading \\t or spaces in following lines\n newText = selectedText.replace(\n QRegularExpression(newLine + QStringLiteral(\"(\\\\t| {1,\") +\n QString::number(indentSize) +\n QStringLiteral(\"})\")),\n QStringLiteral(\"\\n\"));\n\n // remove leading \\t or spaces in first line\n newText.remove(QRegularExpression(QStringLiteral(\"^(\\\\t| {1,\") +\n QString::number(indentSize) +\n QStringLiteral(\"})\")));\n } else {\n // replace trailing new line to prevent an indent of the line after\n // the selection\n newText = selectedText.replace(\n QRegularExpression(QRegularExpression::escape(newLine) +\n QStringLiteral(\"$\")),\n QStringLiteral(\"\\n\"));\n\n // indent text\n newText.replace(newLine, QStringLiteral(\"\\n\") + indentCharacters)\n .prepend(indentCharacters);\n\n // remove trailing \\t\n static QRegularExpression regex1(QStringLiteral(\"\\\\t$\"));\n newText.remove(regex1);\n }\n\n // insert the new text\n cursor.insertText(newText);\n\n // update the selection to the new text\n cursor.setPosition(cursor.position() - newText.size(),\n QTextCursor::KeepAnchor);\n this->setTextCursor(cursor);\n\n return true;\n } else if (reverse) {\n const int indentSize = indentCharacters.length();\n\n // do the check as often as we have characters to un-indent\n for (int i = 1; i <= indentSize; i++) {\n // if nothing was selected but we want to reverse the indention\n // check if there is a \\t in front or after the cursor and remove it\n // if so\n const int position = cursor.position();\n\n if (!cursor.atStart()) {\n // get character in front of cursor\n cursor.setPosition(position - 1, QTextCursor::KeepAnchor);\n }\n\n // check for \\t or space in front of cursor\n static QRegularExpression regex1(QStringLiteral(\"[\\\\t ]\"));\n QRegularExpressionMatch match = regex1.match(cursor.selectedText());\n\n if (!match.hasMatch()) {\n // (select to) check for \\t or space after the cursor\n cursor.setPosition(position);\n\n if (!cursor.atEnd()) {\n cursor.setPosition(position + 1, QTextCursor::KeepAnchor);\n }\n }\n\n match = regex1.match(cursor.selectedText());\n\n if (match.hasMatch()) {\n cursor.removeSelectedText();\n }\n\n cursor = this->textCursor();\n }\n\n return true;\n }\n\n // else just insert indentCharacters\n cursor.insertText(indentCharacters);\n\n return true;\n}\n\n/**\n * @brief Opens the link (if any) at the current cursor position\n */\nbool QMarkdownTextEdit::openLinkAtCursorPosition() {\n QTextCursor cursor = this->textCursor();\n const int clickedPosition = cursor.position();\n\n // select the text in the clicked block and find out on\n // which position we clicked\n cursor.movePosition(QTextCursor::StartOfBlock);\n const int positionFromStart = clickedPosition - cursor.position();\n cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);\n\n const QString selectedText = cursor.selectedText();\n\n // find out which url in the selected text was clicked\n const QString urlString =\n getMarkdownUrlAtPosition(selectedText, positionFromStart);\n const QUrl url = QUrl(urlString);\n const bool isRelativeFileUrl =\n urlString.startsWith(QLatin1String(\"file://..\"));\n const bool isLegacyAttachmentUrl =\n urlString.startsWith(QLatin1String(\"file://attachments\"));\n\n qDebug() << __func__ << \" - 'emit urlClicked( urlString )': \" << urlString;\n\n Q_EMIT urlClicked(urlString);\n\n if ((url.isValid() && isValidUrl(urlString)) || isRelativeFileUrl ||\n isLegacyAttachmentUrl) {\n // ignore some schemata\n if (!(_ignoredClickUrlSchemata.contains(url.scheme()) ||\n isRelativeFileUrl || isLegacyAttachmentUrl)) {\n // open the url\n openUrl(urlString);\n }\n\n return true;\n }\n\n return false;\n}\n\n/**\n * Checks if urlString is a valid url\n *\n * @param urlString\n * @return\n */\nbool QMarkdownTextEdit::isValidUrl(const QString &urlString) {\n static QRegularExpression regex(R\"(^\\w+:\\/\\/.+)\");\n const QRegularExpressionMatch match = regex.match(urlString);\n return match.hasMatch();\n}\n\n/**\n * Handles clicked urls\n *\n * examples:\n * - opens the webpage\n * - opens the file\n * \"/path/to/my/file/QOwnNotes.pdf\" if the operating system supports that\n * handler\n */\nvoid QMarkdownTextEdit::openUrl(const QString &urlString) {\n qDebug() << \"QMarkdownTextEdit \" << __func__\n << \" - 'urlString': \" << urlString;\n\n QDesktopServices::openUrl(QUrl(urlString));\n}\n\n/**\n * @brief Returns the highlighter instance\n * @return\n */\nMarkdownHighlighter *QMarkdownTextEdit::highlighter() { return _highlighter; }\n\n/**\n * @brief Returns the searchWidget instance\n * @return\n */\nQPlainTextEditSearchWidget *QMarkdownTextEdit::searchWidget() {\n return _searchWidget;\n}\n\n/**\n * @brief Sets url schemata that will be ignored when clicked on\n * @param urlSchemes\n */\nvoid QMarkdownTextEdit::setIgnoredClickUrlSchemata(\n QStringList ignoredUrlSchemata) {\n _ignoredClickUrlSchemata = std::move(ignoredUrlSchemata);\n}\n\n/**\n * @brief Returns a map of parsed Markdown urls with their link texts as key\n *\n * @param text\n * @return parsed urls\n */\nQMap QMarkdownTextEdit::parseMarkdownUrlsFromText(\n const QString &text) {\n QMap urlMap;\n QRegularExpressionMatchIterator iterator;\n\n // match urls like this: \n // re = QRegularExpression(\"(<(.+?:\\\\/\\\\/.+?)>)\");\n static QRegularExpression regex1(QStringLiteral(\"(<(.+?)>)\"));\n iterator = regex1.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString linkText = match.captured(1);\n QString url = match.captured(2);\n urlMap[linkText] = url;\n }\n\n // match urls like this: [this url](http://mylink)\n // QRegularExpression re(\"(\\\\[.*?\\\\]\\\\((.+?:\\\\/\\\\/.+?)\\\\))\");\n static QRegularExpression regex2(R\"((\\[.*?\\]\\((.+?)\\)))\");\n iterator = regex2.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString linkText = match.captured(1);\n QString url = match.captured(2);\n urlMap[linkText] = url;\n }\n\n // match urls like this: http://mylink\n static QRegularExpression regex3(R\"(\\b\\w+?:\\/\\/[^\\s]+[^\\s>\\)])\");\n iterator = regex3.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString url = match.captured(0);\n urlMap[url] = url;\n }\n\n // match urls like this: www.github.com\n static QRegularExpression regex4(R\"(\\bwww\\.[^\\s]+\\.[^\\s]+\\b)\");\n iterator = regex4.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString url = match.captured(0);\n urlMap[url] = QStringLiteral(\"http://\") + url;\n }\n\n // match reference urls like this: [this url][1] with this later:\n // [1]: http://domain\n static QRegularExpression regex5(R\"((\\[.*?\\]\\[(.+?)\\]))\");\n iterator = regex5.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString linkText = match.captured(1);\n QString referenceId = match.captured(2);\n\n // search for the referenced url in the whole text edit\n // QRegularExpression refRegExp(\n // \"\\\\[\" + QRegularExpression::escape(referenceId) +\n // \"\\\\]: (.+?:\\\\/\\\\/.+)\");\n QRegularExpression refRegExp(QStringLiteral(\"\\\\[\") +\n QRegularExpression::escape(referenceId) +\n QStringLiteral(\"\\\\]: (.+)\"));\n QRegularExpressionMatch urlMatch = refRegExp.match(toPlainText());\n\n if (urlMatch.hasMatch()) {\n QString url = urlMatch.captured(1);\n urlMap[linkText] = url;\n }\n }\n\n return urlMap;\n}\n\n/**\n * @brief Returns the Markdown url at position\n * @param text\n * @param position\n * @return url string\n */\nQString QMarkdownTextEdit::getMarkdownUrlAtPosition(const QString &text,\n int position) {\n QString url;\n\n // get a map of parsed Markdown urls with their link texts as key\n const QMap urlMap = parseMarkdownUrlsFromText(text);\n QMap::const_iterator i = urlMap.constBegin();\n for (; i != urlMap.constEnd(); ++i) {\n const QString &linkText = i.key();\n const QString &urlString = i.value();\n\n const int foundPositionStart = text.indexOf(linkText);\n\n if (foundPositionStart >= 0) {\n // calculate end position of found linkText\n const int foundPositionEnd = foundPositionStart + linkText.size();\n\n // check if position is in found string range\n if ((position >= foundPositionStart) &&\n (position <= foundPositionEnd)) {\n url = urlString;\n break;\n }\n }\n }\n\n return url;\n}\n\n/**\n * @brief Duplicates the text in the text edit\n */\nvoid QMarkdownTextEdit::duplicateText() {\n if (isReadOnly()) {\n return;\n }\n\n QTextCursor cursor = this->textCursor();\n QString selectedText = cursor.selectedText();\n\n // duplicate line if no text was selected\n if (selectedText.isEmpty()) {\n const int position = cursor.position();\n\n // select the whole line\n cursor.movePosition(QTextCursor::StartOfBlock);\n cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);\n\n const int positionDiff = cursor.position() - position;\n selectedText = \"\\n\" + cursor.selectedText();\n\n // insert text with new line at end of the selected line\n cursor.setPosition(cursor.selectionEnd());\n cursor.insertText(selectedText);\n\n // set the position to same position it was in the duplicated line\n cursor.setPosition(cursor.position() - positionDiff);\n } else {\n // duplicate selected text\n cursor.setPosition(cursor.selectionEnd());\n const int selectionStart = cursor.position();\n\n // insert selected text\n cursor.insertText(selectedText);\n const int selectionEnd = cursor.position();\n\n // select the inserted text\n cursor.setPosition(selectionStart);\n cursor.setPosition(selectionEnd, QTextCursor::KeepAnchor);\n }\n\n this->setTextCursor(cursor);\n}\n\nvoid QMarkdownTextEdit::setText(const QString &text) { setPlainText(text); }\n\nvoid QMarkdownTextEdit::setPlainText(const QString &text) {\n // clear the dirty blocks vector to increase performance and prevent\n // a possible crash in QSyntaxHighlighter::rehighlightBlock\n if (_highlighter) _highlighter->clearDirtyBlocks();\n\n QPlainTextEdit::setPlainText(text);\n adjustRightMargin();\n}\n\n/**\n * Uses another widget as parent for the search widget\n */\nvoid QMarkdownTextEdit::initSearchFrame(QWidget *searchFrame, bool darkMode) {\n _searchFrame = searchFrame;\n\n // remove the search widget from our layout\n layout()->removeWidget(_searchWidget);\n\n QLayout *layout = _searchFrame->layout();\n\n // create a grid layout for the frame and add the search widget to it\n if (layout == nullptr) {\n layout = new QVBoxLayout(_searchFrame);\n layout->setSpacing(0);\n layout->setContentsMargins(0, 0, 0, 0);\n }\n\n _searchWidget->setDarkMode(darkMode);\n layout->addWidget(_searchWidget);\n _searchFrame->setLayout(layout);\n}\n\n/**\n * Hides the text edit and the search widget\n */\nvoid QMarkdownTextEdit::hide() {\n _searchWidget->hide();\n QWidget::hide();\n}\n\n/**\n * Handles an entered return key\n */\nbool QMarkdownTextEdit::handleReturnEntered() {\n if (isReadOnly()) {\n return true;\n }\n\n // This will be the main cursor to add or remove text\n QTextCursor cursor = this->textCursor();\n\n // We need a 2nd cursor to get the text of the current block without moving\n // the main cursor that is used to remove the selected text\n QTextCursor cursor2 = this->textCursor();\n cursor2.select(QTextCursor::BlockUnderCursor);\n const QString currentLineText = cursor2.selectedText().trimmed();\n\n const int position = cursor.position();\n const bool cursorAtBlockStart = cursor.atBlockStart();\n cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);\n const QString currentLinePartialText = cursor.selectedText();\n\n // if return is pressed and there is just an unordered list symbol then we\n // want to remove the list symbol Valid listCharacters: '+ ', '-' , '* ', '+\n // [ ] ', '+ [x] ', '- [ ] ', '- [-] ', '- [x] ', '* [ ] ', '* [x] '.\n static QRegularExpression regex1(\n R\"(^(\\s*)([+|\\-|\\*] \\[(x|-| |)\\]|[+\\-\\*])(\\s+)$)\");\n QRegularExpressionMatchIterator iterator =\n regex1.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n cursor.removeSelectedText();\n return true;\n }\n\n // if return is pressed and there is just an ordered list symbol then we\n // want to remove the list symbol\n static QRegularExpression regex2(R\"(^(\\s*)(\\d+[\\.|\\)])(\\s+)$)\");\n iterator = regex2.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n qDebug() << cursor.selectedText();\n cursor.removeSelectedText();\n return true;\n }\n\n // Check if we are in an unordered list.\n // We are in a list when we have '* ', '- ' or '+ ', possibly with preceding\n // whitespace. If e.g. user has entered '**text**' and pressed enter - we\n // don't want to do more list-stuff.\n QString currentLine = currentLinePartialText.trimmed();\n QChar char0;\n QChar char1;\n if (currentLine.length() >= 1) char0 = currentLine.at(0);\n if (currentLine.length() >= 2) char1 = currentLine.at(1);\n const bool inList =\n ((char0 == QLatin1Char('*') || char0 == QLatin1Char('-') ||\n char0 == QLatin1Char('+')) &&\n char1 == QLatin1Char(' '));\n\n if (inList) {\n // if the current line starts with a list character (possibly after\n // whitespaces) add the whitespaces at the next line too\n // Valid listCharacters: '+ ', '-' , '* ', '+ [ ] ', '+ [x] ', '- [ ] ',\n // '- [x] ', '- [-] ', '* [ ] ', '* [x] '.\n static QRegularExpression regex3(\n R\"(^(\\s*)([+|\\-|\\*] \\[(x|-| |)\\]|[+\\-\\*])(\\s+))\");\n iterator = regex3.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n const QString whitespaces = match.captured(1);\n QString listCharacter = match.captured(2);\n const QString whitespaceCharacter = match.captured(4);\n\n static QRegularExpression regex4(R\"(^([+|\\-|\\*]) \\[(x| |\\-|)\\])\");\n // start new checkbox list item with an unchecked checkbox\n iterator = regex4.globalMatch(listCharacter);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match1 = iterator.next();\n const QString realListCharacter = match1.captured(1);\n listCharacter = realListCharacter + QStringLiteral(\" [ ]\");\n }\n\n cursor.setPosition(position);\n cursor.insertText(\"\\n\" + whitespaces + listCharacter +\n whitespaceCharacter);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n }\n\n // check for ordered lists and increment the list number in the next line\n static QRegularExpression regex5(R\"(^(\\s*)(\\d+)([\\.|\\)])(\\s+))\");\n iterator = regex5.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n const QString whitespaces = match.captured(1);\n const uint listNumber = match.captured(2).toUInt();\n const QString listMarker = match.captured(3);\n const QString whitespaceCharacter = match.captured(4);\n\n cursor.setPosition(position);\n cursor.insertText(\"\\n\" + whitespaces + QString::number(listNumber + 1) +\n listMarker + whitespaceCharacter);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n\n // intent next line with same whitespaces as in current line\n static QRegularExpression regex6(R\"(^(\\s+))\");\n iterator = regex6.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n const QString whitespaces = match.captured(1);\n\n cursor.setPosition(position);\n cursor.insertText(\"\\n\" + whitespaces);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n\n // Add new list item above current line if we are at the start the line of a\n // list item\n if (cursorAtBlockStart) {\n static QRegularExpression regex7(\n R\"(^([+|\\-|\\*] \\[(x|-| |)\\]|[+\\-\\*])(\\s+))\");\n iterator = regex7.globalMatch(currentLineText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n QString listCharacter = match.captured(1);\n const QString whitespaceCharacter = match.captured(3);\n\n static QRegularExpression regex8(R\"(^([+|\\-|\\*]) \\[(x| |\\-|)\\])\");\n // start new checkbox list item with an unchecked checkbox\n iterator = regex8.globalMatch(listCharacter);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match1 = iterator.next();\n const QString realListCharacter = match1.captured(1);\n listCharacter = realListCharacter + QStringLiteral(\" [ ]\");\n }\n\n cursor.setPosition(position);\n // Enter new list item above current line\n cursor.insertText(listCharacter + whitespaceCharacter + \"\\n\");\n // Move the cursor at the end of the new list item\n cursor.movePosition(QTextCursor::Left);\n setTextCursor(cursor);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Handles entered tab or reverse tab keys\n */\nbool QMarkdownTextEdit::handleTabEntered(bool reverse,\n const QString &indentCharacters) {\n if (isReadOnly()) {\n return true;\n }\n\n QTextCursor cursor = this->textCursor();\n\n // only check for lists if we haven't a text selected\n if (cursor.selectedText().isEmpty()) {\n cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);\n const QString currentLineText = cursor.selectedText();\n\n // check if we want to indent or un-indent an ordered list\n // Valid listCharacters: '+ ', '-' , '* ', '+ [ ] ', '+ [x] ', '- [ ] ',\n // '- [x] ', '- [-] ', '* [ ] ', '* [x] '.\n static QRegularExpression regex1(\n R\"(^(\\s*)([+|\\-|\\*] \\[(x|-| )\\]|[+\\-\\*])(\\s+)$)\");\n QRegularExpressionMatchIterator i = regex1.globalMatch(currentLineText);\n\n if (i.hasNext()) {\n QRegularExpressionMatch match = i.next();\n QString whitespaces = match.captured(1);\n const QString listCharacter = match.captured(2);\n const QString whitespaceCharacter = match.captured(4);\n\n // add or remove one tabulator key\n if (reverse) {\n // remove one set of indentCharacters or a tabulator\n whitespaces.remove(QRegularExpression(\n QStringLiteral(\"^(\\\\t|\") +\n QRegularExpression::escape(indentCharacters) +\n QStringLiteral(\")\")));\n\n } else {\n whitespaces += indentCharacters;\n }\n\n cursor.insertText(whitespaces + listCharacter +\n whitespaceCharacter);\n return true;\n }\n\n // check if we want to indent or un-indent an ordered list\n static QRegularExpression regex2(R\"(^(\\s*)(\\d+)([\\.|\\)])(\\s+)$)\");\n i = regex2.globalMatch(currentLineText);\n\n if (i.hasNext()) {\n const QRegularExpressionMatch match = i.next();\n QString whitespaces = match.captured(1);\n const QString listCharacter = match.captured(2);\n const QString listMarker = match.captured(3);\n const QString whitespaceCharacter = match.captured(4);\n\n // add or remove one tabulator key\n if (reverse) {\n whitespaces.chop(1);\n } else {\n whitespaces += indentCharacters;\n }\n\n cursor.insertText(whitespaces + listCharacter + listMarker +\n whitespaceCharacter);\n return true;\n }\n }\n\n // check if we want to indent the whole text\n return increaseSelectedTextIndention(reverse, indentCharacters);\n}\n\n/**\n * Sets the auto text options\n */\nvoid QMarkdownTextEdit::setAutoTextOptions(AutoTextOptions options) {\n _autoTextOptions = options;\n}\n\nvoid QMarkdownTextEdit::updateLineNumberArea(const QRect rect, int dy) {\n if (dy)\n _lineNumArea->scroll(0, dy);\n else\n _lineNumArea->update(0, rect.y(), _lineNumArea->sizeHint().width(),\n rect.height());\n\n updateLineNumAreaGeometry();\n\n if (rect.contains(viewport()->rect())) {\n updateLineNumberAreaWidth(0);\n }\n}\n\nvoid QMarkdownTextEdit::updateLineNumberAreaWidth(int) {\n QSignalBlocker blocker(this);\n const auto oldMargins = viewportMargins();\n const int width =\n _lineNumArea->isLineNumAreaEnabled()\n ? _lineNumArea->sizeHint().width() + _lineNumberLeftMarginOffset\n : oldMargins.left();\n const auto newMargins = QMargins{width, oldMargins.top(),\n oldMargins.right(), oldMargins.bottom()};\n\n if (newMargins != oldMargins) {\n setViewportMargins(newMargins);\n }\n\n // Grow lineNumArea font-size with the font size of the editor\n const int pointSize = this->font().pointSize();\n if (pointSize > 0) {\n QFont font = _lineNumArea->font();\n font.setPointSize(pointSize);\n _lineNumArea->setFont(font);\n }\n}\n\n/**\n * @param e\n * @details This does two things\n * 1. Overrides QPlainTextEdit::paintEvent to fix the RTL bug of QPlainTextEdit\n * 2. Paints a rectangle around code block fences [Code taken from\n * ghostwriter(which in turn is based on QPlaintextEdit::paintEvent() with\n * modifications and minor improvements for our use\n */\nvoid QMarkdownTextEdit::paintEvent(QPaintEvent *e) {\n QTextBlock block = firstVisibleBlock();\n\n QPainter painter(viewport());\n const QRect viewportRect = viewport()->rect();\n // painter.fillRect(viewportRect, Qt::transparent);\n bool firstVisible = true;\n QPointF offset(contentOffset());\n QRectF blockAreaRect; // Code or block quote rect.\n bool inBlockArea = false;\n\n bool clipTop = false;\n bool drawBlock = false;\n qreal dy = 0.0;\n bool done = false;\n\n const QColor &color = MarkdownHighlighter::codeBlockBackgroundColor();\n const int cornerRadius = 5;\n\n while (block.isValid() && !done) {\n const QRectF r = blockBoundingRect(block).translated(offset);\n const int state = block.userState();\n\n if (!inBlockArea && MarkdownHighlighter::isCodeBlock(state)) {\n // skip the backticks\n if (!block.text().startsWith(QLatin1String(\"```\")) &&\n !block.text().startsWith(QLatin1String(\"~~~\"))) {\n blockAreaRect = r;\n dy = 0.0;\n inBlockArea = true;\n }\n\n // If this is the first visible block within the viewport\n // and if the previous block is part of the text block area,\n // then the rectangle to draw for the block area will have\n // its top clipped by the viewport and will need to be\n // drawn specially.\n const int prevBlockState = block.previous().userState();\n if (firstVisible &&\n MarkdownHighlighter::isCodeBlock(prevBlockState)) {\n clipTop = true;\n }\n }\n // Else if the block ends a text block area...\n else if (inBlockArea && MarkdownHighlighter::isCodeBlockEnd(state)) {\n drawBlock = true;\n inBlockArea = false;\n blockAreaRect.setHeight(dy);\n }\n // If the block is at the end of the document and ends a text\n // block area...\n //\n if (inBlockArea && block == this->document()->lastBlock()) {\n drawBlock = true;\n inBlockArea = false;\n dy += r.height();\n blockAreaRect.setHeight(dy);\n }\n offset.ry() += r.height();\n dy += r.height();\n\n // If this is the last text block visible within the viewport...\n if (offset.y() > viewportRect.height()) {\n if (inBlockArea) {\n blockAreaRect.setHeight(dy);\n drawBlock = true;\n }\n\n // Finished drawing.\n done = true;\n }\n // If this is the last text block visible within the viewport...\n if (offset.y() > viewportRect.height()) {\n if (inBlockArea) {\n blockAreaRect.setHeight(dy);\n drawBlock = true;\n }\n // Finished drawing.\n done = true;\n }\n\n if (drawBlock) {\n painter.setCompositionMode(QPainter::CompositionMode_SourceOver);\n painter.setPen(Qt::NoPen);\n painter.setBrush(QBrush(color));\n\n // If the first visible block is \"clipped\" such that the previous\n // block is part of the text block area, then only draw a rectangle\n // with the bottom corners rounded, and with the top corners square\n // to reflect that the first visible block is part of a larger block\n // of text.\n //\n if (clipTop) {\n QPainterPath path;\n path.setFillRule(Qt::WindingFill);\n path.addRoundedRect(blockAreaRect, cornerRadius, cornerRadius);\n qreal adjustedHeight = blockAreaRect.height() / 2;\n path.addRect(blockAreaRect.adjusted(0, 0, 0, -adjustedHeight));\n painter.drawPath(path.simplified());\n clipTop = false;\n }\n // Else draw the entire rectangle with all corners rounded.\n else {\n painter.drawRoundedRect(blockAreaRect, cornerRadius,\n cornerRadius);\n }\n\n drawBlock = false;\n }\n\n // this fixes the RTL bug of QPlainTextEdit\n // https://bugreports.qt.io/browse/QTBUG-7516\n if (block.text().isRightToLeft()) {\n QTextLayout *layout = block.layout();\n // opt = document()->defaultTextOption();\n QTextOption opt = QTextOption(Qt::AlignRight);\n opt.setTextDirection(Qt::RightToLeft);\n layout->setTextOption(opt);\n }\n\n // Current line highlight\n QTextCursor cursor = textCursor();\n if (highlightCurrentLine() && cursor.block() == block) {\n QTextLine line =\n block.layout()->lineForTextPosition(cursor.positionInBlock());\n QRectF lineRect = line.rect();\n lineRect.moveTop(lineRect.top() + r.top());\n lineRect.setLeft(0.);\n lineRect.setRight(viewportRect.width());\n painter.fillRect(lineRect.toAlignedRect(),\n currentLineHighlightColor());\n }\n\n block = block.next();\n firstVisible = false;\n }\n\n painter.end();\n QPlainTextEdit::paintEvent(e);\n}\n\n/**\n * Overrides QPlainTextEdit::setReadOnly to fix a problem with Chinese and\n * Japanese input methods\n *\n * @param ro\n */\nvoid QMarkdownTextEdit::setReadOnly(bool ro) {\n QPlainTextEdit::setReadOnly(ro);\n\n // attempted to fix a problem with Chinese and Japanese input methods\n // @see https://github.com/pbek/QOwnNotes/issues/976\n setAttribute(Qt::WA_InputMethodEnabled, !isReadOnly());\n}\n\nvoid QMarkdownTextEdit::doSearch(\n QString &searchText, QPlainTextEditSearchWidget::SearchMode searchMode) {\n _searchWidget->setSearchText(searchText);\n _searchWidget->setSearchMode(searchMode);\n _searchWidget->doSearchCount();\n _searchWidget->activate(false);\n}\n\nvoid QMarkdownTextEdit::hideSearchWidget(bool reset) {\n _searchWidget->deactivate();\n\n if (reset) {\n _searchWidget->reset();\n }\n}\n\nvoid QMarkdownTextEdit::updateSettings() {\n // if true: centers the screen if cursor reaches bottom (but not top)\n searchWidget()->setDebounceDelay(_debounceDelay);\n setCenterOnScroll(_centerCursor);\n}\n\nvoid QMarkdownTextEdit::setLineNumberLeftMarginOffset(int offset) {\n _lineNumberLeftMarginOffset = offset;\n}\n\nQMargins QMarkdownTextEdit::viewportMargins() {\n return QPlainTextEdit::viewportMargins();\n}\n bool bracketClosingCheck(const QChar openingCharacter,\n QChar closingCharacter) {\n // check if bracket closing or read-only are enabled\n if (!(_autoTextOptions & AutoTextOption::BracketClosing) || isReadOnly()) {\n return false;\n }\n\n if (closingCharacter.isNull()) {\n closingCharacter = openingCharacter;\n }\n\n QTextCursor cursor = textCursor();\n const int positionInBlock = cursor.positionInBlock();\n\n // get the current text from the block\n const QString text = cursor.block().text();\n const int textLength = text.length();\n\n // if we are at the end of the line we just want to enter the character\n if (positionInBlock >= textLength) {\n return false;\n }\n\n const QChar currentChar = text.at(positionInBlock);\n\n // if (closingCharacter == openingCharacter) {\n\n // }\n\n qDebug() << __func__ << \" - 'currentChar': \" << currentChar;\n\n // if the current character is not the closing character we just want to\n // enter the character\n if (currentChar != closingCharacter) {\n return false;\n }\n\n const QString leftText = text.left(positionInBlock);\n const int openingCharacterCount = leftText.count(openingCharacter);\n const int closingCharacterCount = leftText.count(closingCharacter);\n\n // if there were enough opening characters just enter the character\n if (openingCharacterCount < (closingCharacterCount + 1)) {\n return false;\n }\n\n // move the cursor to the right and don't enter the character\n cursor.movePosition(QTextCursor::Right);\n setTextCursor(cursor);\n return true;\n}\n bool quotationMarkCheck(const QChar quotationCharacter) {\n // check if bracket closing or read-only are enabled\n if (!(_autoTextOptions & AutoTextOption::BracketClosing) || isReadOnly()) {\n return false;\n }\n\n QTextCursor cursor = textCursor();\n const int positionInBlock = cursor.positionInBlock();\n\n // get the current text from the block\n const QString text = cursor.block().text();\n const int textLength = text.length();\n\n // if last char is not space, we are at word end, no autocompletion\n const bool isBacktick = quotationCharacter == '`';\n if (!isBacktick && positionInBlock != 0 &&\n !text.at(positionInBlock - 1).isSpace()) {\n return false;\n }\n\n // if we are at the end of the line we just want to enter the character\n if (positionInBlock >= textLength) {\n return handleBracketClosing(quotationCharacter);\n }\n\n const QChar currentChar = text.at(positionInBlock);\n\n // if the current character is not the quotation character we just want to\n // enter the character\n if (currentChar != quotationCharacter) {\n return handleBracketClosing(quotationCharacter);\n }\n\n // move the cursor to the right and don't enter the character\n cursor.movePosition(QTextCursor::Right);\n setTextCursor(cursor);\n return true;\n}\n void focusOutEvent(QFocusEvent *event) override {\n resetMouseCursor();\n QPlainTextEdit::focusOutEvent(event);\n}\n void paintEvent(QPaintEvent *e) override {\n QTextBlock block = firstVisibleBlock();\n\n QPainter painter(viewport());\n const QRect viewportRect = viewport()->rect();\n // painter.fillRect(viewportRect, Qt::transparent);\n bool firstVisible = true;\n QPointF offset(contentOffset());\n QRectF blockAreaRect; // Code or block quote rect.\n bool inBlockArea = false;\n\n bool clipTop = false;\n bool drawBlock = false;\n qreal dy = 0.0;\n bool done = false;\n\n const QColor &color = MarkdownHighlighter::codeBlockBackgroundColor();\n const int cornerRadius = 5;\n\n while (block.isValid() && !done) {\n const QRectF r = blockBoundingRect(block).translated(offset);\n const int state = block.userState();\n\n if (!inBlockArea && MarkdownHighlighter::isCodeBlock(state)) {\n // skip the backticks\n if (!block.text().startsWith(QLatin1String(\"```\")) &&\n !block.text().startsWith(QLatin1String(\"~~~\"))) {\n blockAreaRect = r;\n dy = 0.0;\n inBlockArea = true;\n }\n\n // If this is the first visible block within the viewport\n // and if the previous block is part of the text block area,\n // then the rectangle to draw for the block area will have\n // its top clipped by the viewport and will need to be\n // drawn specially.\n const int prevBlockState = block.previous().userState();\n if (firstVisible &&\n MarkdownHighlighter::isCodeBlock(prevBlockState)) {\n clipTop = true;\n }\n }\n // Else if the block ends a text block area...\n else if (inBlockArea && MarkdownHighlighter::isCodeBlockEnd(state)) {\n drawBlock = true;\n inBlockArea = false;\n blockAreaRect.setHeight(dy);\n }\n // If the block is at the end of the document and ends a text\n // block area...\n //\n if (inBlockArea && block == this->document()->lastBlock()) {\n drawBlock = true;\n inBlockArea = false;\n dy += r.height();\n blockAreaRect.setHeight(dy);\n }\n offset.ry() += r.height();\n dy += r.height();\n\n // If this is the last text block visible within the viewport...\n if (offset.y() > viewportRect.height()) {\n if (inBlockArea) {\n blockAreaRect.setHeight(dy);\n drawBlock = true;\n }\n\n // Finished drawing.\n done = true;\n }\n // If this is the last text block visible within the viewport...\n if (offset.y() > viewportRect.height()) {\n if (inBlockArea) {\n blockAreaRect.setHeight(dy);\n drawBlock = true;\n }\n // Finished drawing.\n done = true;\n }\n\n if (drawBlock) {\n painter.setCompositionMode(QPainter::CompositionMode_SourceOver);\n painter.setPen(Qt::NoPen);\n painter.setBrush(QBrush(color));\n\n // If the first visible block is \"clipped\" such that the previous\n // block is part of the text block area, then only draw a rectangle\n // with the bottom corners rounded, and with the top corners square\n // to reflect that the first visible block is part of a larger block\n // of text.\n //\n if (clipTop) {\n QPainterPath path;\n path.setFillRule(Qt::WindingFill);\n path.addRoundedRect(blockAreaRect, cornerRadius, cornerRadius);\n qreal adjustedHeight = blockAreaRect.height() / 2;\n path.addRect(blockAreaRect.adjusted(0, 0, 0, -adjustedHeight));\n painter.drawPath(path.simplified());\n clipTop = false;\n }\n // Else draw the entire rectangle with all corners rounded.\n else {\n painter.drawRoundedRect(blockAreaRect, cornerRadius,\n cornerRadius);\n }\n\n drawBlock = false;\n }\n\n // this fixes the RTL bug of QPlainTextEdit\n // https://bugreports.qt.io/browse/QTBUG-7516\n if (block.text().isRightToLeft()) {\n QTextLayout *layout = block.layout();\n // opt = document()->defaultTextOption();\n QTextOption opt = QTextOption(Qt::AlignRight);\n opt.setTextDirection(Qt::RightToLeft);\n layout->setTextOption(opt);\n }\n\n // Current line highlight\n QTextCursor cursor = textCursor();\n if (highlightCurrentLine() && cursor.block() == block) {\n QTextLine line =\n block.layout()->lineForTextPosition(cursor.positionInBlock());\n QRectF lineRect = line.rect();\n lineRect.moveTop(lineRect.top() + r.top());\n lineRect.setLeft(0.);\n lineRect.setRight(viewportRect.width());\n painter.fillRect(lineRect.toAlignedRect(),\n currentLineHighlightColor());\n }\n\n block = block.next();\n firstVisible = false;\n }\n\n painter.end();\n QPlainTextEdit::paintEvent(e);\n}\n bool handleCharRemoval(MarkdownHighlighter::RangeType type, int block,\n int position) {\n if (!_highlighter) return false;\n\n auto range = _highlighter->findPositionInRanges(type, block, position);\n if (range == QPair{-1, -1}) return false;\n\n int charToRemovePos = range.first;\n if (position == range.first) charToRemovePos = range.second;\n\n QTextCursor cursor = textCursor();\n auto gpos = cursor.position();\n\n if (charToRemovePos > position) {\n cursor.setPosition(gpos + (charToRemovePos - (position + 1)));\n } else {\n cursor.setPosition(gpos - (position - charToRemovePos + 1));\n gpos--;\n }\n\n cursor.deleteChar();\n cursor.setPosition(gpos);\n setTextCursor(cursor);\n return false;\n}\n void resizeEvent(QResizeEvent *event) override {\n QPlainTextEdit::resizeEvent(event);\n updateLineNumAreaGeometry();\n}\n void setLineNumberLeftMarginOffset(int offset) {\n _lineNumberLeftMarginOffset = offset;\n}\n int _lineNumberLeftMarginOffset = 0;\n void updateLineNumAreaGeometry() {\n const auto contentsRect = this->contentsRect();\n const QRect newGeometry = {contentsRect.left(), contentsRect.top(),\n _lineNumArea->sizeHint().width(),\n contentsRect.height()};\n auto oldGeometry = _lineNumArea->geometry();\n if (newGeometry != oldGeometry) {\n _lineNumArea->setGeometry(newGeometry);\n }\n}\n void updateLineNumberArea(const QRect rect, int dy) {\n if (dy)\n _lineNumArea->scroll(0, dy);\n else\n _lineNumArea->update(0, rect.y(), _lineNumArea->sizeHint().width(),\n rect.height());\n\n updateLineNumAreaGeometry();\n\n if (rect.contains(viewport()->rect())) {\n updateLineNumberAreaWidth(0);\n }\n}\n Q_SLOT void updateLineNumberAreaWidth(int) {\n QSignalBlocker blocker(this);\n const auto oldMargins = viewportMargins();\n const int width =\n _lineNumArea->isLineNumAreaEnabled()\n ? _lineNumArea->sizeHint().width() + _lineNumberLeftMarginOffset\n : oldMargins.left();\n const auto newMargins = QMargins{width, oldMargins.top(),\n oldMargins.right(), oldMargins.bottom()};\n\n if (newMargins != oldMargins) {\n setViewportMargins(newMargins);\n }\n\n // Grow lineNumArea font-size with the font size of the editor\n const int pointSize = this->font().pointSize();\n if (pointSize > 0) {\n QFont font = _lineNumArea->font();\n font.setPointSize(pointSize);\n _lineNumArea->setFont(font);\n }\n}\n bool _handleBracketClosingUsed;\n LineNumArea *_lineNumArea;\n void urlClicked(QString url);\n void zoomIn();\n void zoomOut();\n};"], ["/SpeedyNote/markdown/qplaintexteditsearchwidget.h", "class QPlainTextEditSearchWidget {\n Q_OBJECT\n\n public:\n enum SearchMode { PlainTextMode, WholeWordsMode, RegularExpressionMode };\n explicit QPlainTextEditSearchWidget(QPlainTextEdit *parent = nullptr) {\n ui->setupUi(this);\n _textEdit = parent;\n _darkMode = false;\n hide();\n ui->searchCountLabel->setStyleSheet(QStringLiteral(\"* {color: grey}\"));\n // hiding will leave a open space in the horizontal layout\n ui->searchCountLabel->setEnabled(false);\n _currentSearchResult = 0;\n _searchResultCount = 0;\n\n connect(ui->closeButton, &QPushButton::clicked, this,\n &QPlainTextEditSearchWidget::deactivate);\n connect(ui->searchLineEdit, &QLineEdit::textChanged, this,\n &QPlainTextEditSearchWidget::searchLineEditTextChanged);\n connect(ui->searchDownButton, &QPushButton::clicked, this,\n &QPlainTextEditSearchWidget::doSearchDown);\n connect(ui->searchUpButton, &QPushButton::clicked, this,\n &QPlainTextEditSearchWidget::doSearchUp);\n connect(ui->replaceToggleButton, &QPushButton::toggled, this,\n &QPlainTextEditSearchWidget::setReplaceMode);\n connect(ui->replaceButton, &QPushButton::clicked, this,\n &QPlainTextEditSearchWidget::doReplace);\n connect(ui->replaceAllButton, &QPushButton::clicked, this,\n &QPlainTextEditSearchWidget::doReplaceAll);\n\n connect(&_debounceTimer, &QTimer::timeout, this,\n &QPlainTextEditSearchWidget::performSearch);\n\n installEventFilter(this);\n ui->searchLineEdit->installEventFilter(this);\n ui->replaceLineEdit->installEventFilter(this);\n\n#ifdef Q_OS_MAC\n // set the spacing to 8 for OS X\n layout()->setSpacing(8);\n ui->buttonFrame->layout()->setSpacing(9);\n\n // set the margin to 0 for the top buttons for OS X\n QString buttonStyle = QStringLiteral(\"QPushButton {margin: 0}\");\n ui->closeButton->setStyleSheet(buttonStyle);\n ui->searchDownButton->setStyleSheet(buttonStyle);\n ui->searchUpButton->setStyleSheet(buttonStyle);\n ui->replaceToggleButton->setStyleSheet(buttonStyle);\n ui->matchCaseSensitiveButton->setStyleSheet(buttonStyle);\n#endif\n}\n bool doSearch(bool searchDown = true, bool allowRestartAtTop = true,\n bool updateUI = true) {\n if (_debounceTimer.isActive()) {\n stopDebounce();\n }\n\n const QString text = ui->searchLineEdit->text();\n\n if (text.isEmpty()) {\n if (updateUI) {\n ui->searchLineEdit->setStyleSheet(QLatin1String(\"\"));\n }\n\n return false;\n }\n\n const int searchMode = ui->modeComboBox->currentIndex();\n const bool caseSensitive = ui->matchCaseSensitiveButton->isChecked();\n\n QFlags options =\n searchDown ? QTextDocument::FindFlag(0) : QTextDocument::FindBackward;\n if (searchMode == WholeWordsMode) {\n options |= QTextDocument::FindWholeWords;\n }\n\n if (caseSensitive) {\n options |= QTextDocument::FindCaseSensitively;\n }\n\n // block signal to reduce too many signals being fired and too many updates\n _textEdit->blockSignals(true);\n\n bool found =\n searchMode == RegularExpressionMode\n ?\n#if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0))\n _textEdit->find(\n QRegularExpression(\n text, caseSensitive\n ? QRegularExpression::NoPatternOption\n : QRegularExpression::CaseInsensitiveOption),\n options)\n :\n#else\n _textEdit->find(QRegExp(text, caseSensitive ? Qt::CaseSensitive\n : Qt::CaseInsensitive),\n options)\n :\n#endif\n _textEdit->find(text, options);\n\n _textEdit->blockSignals(false);\n\n if (found) {\n const int result =\n searchDown ? ++_currentSearchResult : --_currentSearchResult;\n _currentSearchResult = std::min(result, _searchResultCount);\n\n updateSearchCountLabelText();\n }\n\n // start at the top (or bottom) if not found\n if (!found && allowRestartAtTop) {\n _textEdit->moveCursor(searchDown ? QTextCursor::Start\n : QTextCursor::End);\n found =\n searchMode == RegularExpressionMode\n ?\n#if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0))\n _textEdit->find(\n QRegularExpression(\n text, caseSensitive\n ? QRegularExpression::NoPatternOption\n : QRegularExpression::CaseInsensitiveOption),\n options)\n :\n#else\n _textEdit->find(\n QRegExp(text, caseSensitive ? Qt::CaseSensitive\n : Qt::CaseInsensitive),\n options)\n :\n#endif\n _textEdit->find(text, options);\n\n if (found && updateUI) {\n _currentSearchResult = searchDown ? 1 : _searchResultCount;\n updateSearchCountLabelText();\n }\n }\n\n if (updateUI) {\n const QRect rect = _textEdit->cursorRect();\n QMargins margins = _textEdit->layout()->contentsMargins();\n const int searchWidgetHotArea = _textEdit->height() - this->height();\n const int marginBottom =\n (rect.y() > searchWidgetHotArea) ? (this->height() + 10) : 0;\n\n // move the search box a bit up if we would block the search result\n if (margins.bottom() != marginBottom) {\n margins.setBottom(marginBottom);\n _textEdit->layout()->setContentsMargins(margins);\n }\n\n // add a background color according if we found the text or not\n const QString bgColorCode = _darkMode\n ? (found ? QStringLiteral(\"#135a13\")\n : QStringLiteral(\"#8d2b36\"))\n : found ? QStringLiteral(\"#D5FAE2\")\n : QStringLiteral(\"#FAE9EB\");\n const QString fgColorCode =\n _darkMode ? QStringLiteral(\"#cccccc\") : QStringLiteral(\"#404040\");\n\n ui->searchLineEdit->setStyleSheet(\n QStringLiteral(\"* { background: \") + bgColorCode +\n QStringLiteral(\"; color: \") + fgColorCode + QStringLiteral(\"; }\"));\n\n // restore the search extra selections after the find command\n this->setSearchExtraSelections();\n }\n\n return found;\n}\n void setDarkMode(bool enabled) {\n _darkMode = enabled;\n}\n ~QPlainTextEditSearchWidget() { delete ui; }\n void setSearchText(const QString &searchText) {\n ui->searchLineEdit->setText(searchText);\n}\n void setSearchMode(SearchMode searchMode) {\n ui->modeComboBox->setCurrentIndex(searchMode);\n}\n void setDebounceDelay(uint debounceDelay) {\n _debounceTimer.setInterval(static_cast(debounceDelay));\n}\n void activate(bool focus) {\n setReplaceMode(ui->modeComboBox->currentIndex() !=\n SearchMode::PlainTextMode);\n show();\n\n // preset the selected text as search text if there is any and there is no\n // other search text\n const QString selectedText = _textEdit->textCursor().selectedText();\n if (!selectedText.isEmpty() && ui->searchLineEdit->text().isEmpty()) {\n ui->searchLineEdit->setText(selectedText);\n }\n\n if (focus) {\n ui->searchLineEdit->setFocus();\n }\n\n ui->searchLineEdit->selectAll();\n updateSearchExtraSelections();\n doSearchDown();\n}\n void clearSearchExtraSelections() {\n _searchExtraSelections.clear();\n setSearchExtraSelections();\n}\n void updateSearchExtraSelections() {\n _searchExtraSelections.clear();\n const auto textCursor = _textEdit->textCursor();\n _textEdit->moveCursor(QTextCursor::Start);\n const QColor color = selectionColor;\n QTextCharFormat extraFmt;\n extraFmt.setBackground(color);\n int findCounter = 0;\n const int searchMode = ui->modeComboBox->currentIndex();\n\n while (doSearch(true, false, false)) {\n findCounter++;\n\n // prevent infinite loops from regular expression searches like \"$\", \"^\"\n // or \"\\b\"\n if (searchMode == RegularExpressionMode && findCounter >= 10000) {\n break;\n }\n\n QTextEdit::ExtraSelection extra = QTextEdit::ExtraSelection();\n extra.format = extraFmt;\n\n extra.cursor = _textEdit->textCursor();\n _searchExtraSelections.append(extra);\n }\n\n _textEdit->setTextCursor(textCursor);\n this->setSearchExtraSelections();\n}\n private:\n Ui::QPlainTextEditSearchWidget *ui;\n int _searchResultCount;\n int _currentSearchResult;\n QList _searchExtraSelections;\n QColor selectionColor;\n QTimer _debounceTimer;\n QString _searchTerm;\n void setSearchExtraSelections() const {\n this->_textEdit->setExtraSelections(this->_searchExtraSelections);\n}\n void stopDebounce() {\n _debounceTimer.stop();\n ui->searchDownButton->setEnabled(true);\n ui->searchUpButton->setEnabled(true);\n}\n protected:\n QPlainTextEdit *_textEdit;\n bool _darkMode;\n bool eventFilter(QObject *obj, QEvent *event) override {\n if (event->type() == QEvent::KeyPress) {\n auto *keyEvent = static_cast(event);\n\n if (keyEvent->key() == Qt::Key_Escape) {\n deactivate();\n return true;\n } else if ((!_debounceTimer.isActive() &&\n keyEvent->modifiers().testFlag(Qt::ShiftModifier) &&\n (keyEvent->key() == Qt::Key_Return)) ||\n (keyEvent->key() == Qt::Key_Up)) {\n doSearchUp();\n return true;\n } else if (!_debounceTimer.isActive() &&\n ((keyEvent->key() == Qt::Key_Return) ||\n (keyEvent->key() == Qt::Key_Down))) {\n doSearchDown();\n return true;\n } else if (!_debounceTimer.isActive() &&\n keyEvent->key() == Qt::Key_F3) {\n doSearch(!keyEvent->modifiers().testFlag(Qt::ShiftModifier));\n return true;\n }\n\n // if ((obj == ui->replaceLineEdit) && (keyEvent->key() ==\n // Qt::Key_Tab)\n // && ui->replaceToggleButton->isChecked()) {\n // ui->replaceLineEdit->setFocus();\n // }\n\n return false;\n }\n\n return QWidget::eventFilter(obj, event);\n}\n public:\n void activate() {\n setReplaceMode(ui->modeComboBox->currentIndex() !=\n SearchMode::PlainTextMode);\n show();\n\n // preset the selected text as search text if there is any and there is no\n // other search text\n const QString selectedText = _textEdit->textCursor().selectedText();\n if (!selectedText.isEmpty() && ui->searchLineEdit->text().isEmpty()) {\n ui->searchLineEdit->setText(selectedText);\n }\n\n if (focus) {\n ui->searchLineEdit->setFocus();\n }\n\n ui->searchLineEdit->selectAll();\n updateSearchExtraSelections();\n doSearchDown();\n}\n void deactivate() {\n stopDebounce();\n\n hide();\n\n // Clear the search extra selections when closing the search bar\n clearSearchExtraSelections();\n\n _textEdit->setFocus();\n}\n void doSearchDown() { doSearch(true); }\n void doSearchUp() { doSearch(false); }\n void setReplaceMode(bool enabled) {\n ui->replaceToggleButton->setChecked(enabled);\n ui->replaceLabel->setVisible(enabled);\n ui->replaceLineEdit->setVisible(enabled);\n ui->modeLabel->setVisible(enabled);\n ui->buttonFrame->setVisible(enabled);\n ui->matchCaseSensitiveButton->setVisible(enabled);\n}\n void activateReplace() {\n // replacing is prohibited if the text edit is readonly\n if (_textEdit->isReadOnly()) {\n return;\n }\n\n ui->searchLineEdit->setText(_textEdit->textCursor().selectedText());\n ui->searchLineEdit->selectAll();\n activate();\n setReplaceMode(true);\n}\n bool doReplace(bool forAll = false) {\n if (_textEdit->isReadOnly()) {\n return false;\n }\n\n QTextCursor cursor = _textEdit->textCursor();\n\n if (!forAll && cursor.selectedText().isEmpty()) {\n return false;\n }\n\n const int searchMode = ui->modeComboBox->currentIndex();\n if (searchMode == RegularExpressionMode) {\n QString text = cursor.selectedText();\n text.replace(QRegularExpression(ui->searchLineEdit->text()),\n ui->replaceLineEdit->text());\n cursor.insertText(text);\n } else {\n cursor.insertText(ui->replaceLineEdit->text());\n }\n\n if (!forAll) {\n const int position = cursor.position();\n\n if (!doSearch(true)) {\n // restore the last cursor position if text wasn't found any more\n cursor.setPosition(position);\n _textEdit->setTextCursor(cursor);\n }\n }\n\n return true;\n}\n void doReplaceAll() {\n if (_textEdit->isReadOnly()) {\n return;\n }\n\n // start at the top\n _textEdit->moveCursor(QTextCursor::Start);\n\n // replace until everything to the bottom is replaced\n while (doSearch(true, false) && doReplace(true)) {\n }\n}\n void reset() {\n ui->searchLineEdit->clear();\n setSearchMode(SearchMode::PlainTextMode);\n setReplaceMode(false);\n ui->searchCountLabel->setEnabled(false);\n}\n void doSearchCount() {\n // Note that we are moving the anchor, so the search will start from the top\n // again! Alternative: Restore cursor position afterward, but then we will\n // not know\n // at what _currentSearchResult we currently are\n _textEdit->moveCursor(QTextCursor::Start, QTextCursor::MoveAnchor);\n\n bool found;\n _searchResultCount = 0;\n _currentSearchResult = 0;\n const int searchMode = ui->modeComboBox->currentIndex();\n\n do {\n found = doSearch(true, false, false);\n if (found) {\n _searchResultCount++;\n }\n\n // prevent infinite loops from regular expression searches like \"$\", \"^\"\n // or \"\\b\"\n if (searchMode == RegularExpressionMode &&\n _searchResultCount >= 10000) {\n break;\n }\n } while (found);\n\n updateSearchCountLabelText();\n}\n protected:\n void searchLineEditTextChanged(const QString &arg1) {\n _searchTerm = arg1;\n\n if (_debounceTimer.interval() != 0 && !_searchTerm.isEmpty()) {\n _debounceTimer.start();\n ui->searchDownButton->setEnabled(false);\n ui->searchUpButton->setEnabled(false);\n } else {\n performSearch();\n }\n}\n void performSearch() {\n doSearchCount();\n updateSearchExtraSelections();\n doSearchDown();\n}\n void updateSearchCountLabelText() {\n ui->searchCountLabel->setEnabled(true);\n ui->searchCountLabel->setText(QStringLiteral(\"%1/%2\").arg(\n _currentSearchResult == 0 ? QChar('-')\n : QString::number(_currentSearchResult),\n _searchResultCount == 0 ? QChar('-')\n : QString::number(_searchResultCount)));\n}\n void setSearchSelectionColor(const QColor &color) {\n selectionColor = color;\n}\n private:\n void on_modeComboBox_currentIndexChanged(int index) {\n Q_UNUSED(index)\n doSearchCount();\n doSearchDown();\n}\n void on_matchCaseSensitiveButton_toggled(bool checked) {\n Q_UNUSED(checked)\n doSearchCount();\n doSearchDown();\n}\n};"], ["/SpeedyNote/source/SDLControllerManager.h", "class SDLControllerManager {\n Q_OBJECT\npublic:\n explicit SDLControllerManager(QObject *parent = nullptr);\n ~SDLControllerManager() {\n if (joystick) SDL_JoystickClose(joystick);\n if (sdlInitialized) SDL_QuitSubSystem(SDL_INIT_JOYSTICK);\n}\n void setPhysicalButtonMapping(const QString &logicalButton, int physicalSDLButton) {\n physicalButtonMappings[logicalButton] = physicalSDLButton;\n saveControllerMappings();\n}\n int getPhysicalButtonMapping(const QString &logicalButton) const {\n return physicalButtonMappings.value(logicalButton, -1);\n}\n QMap getAllPhysicalMappings() const {\n return physicalButtonMappings;\n}\n void saveControllerMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.beginGroup(\"ControllerPhysicalMappings\");\n for (auto it = physicalButtonMappings.begin(); it != physicalButtonMappings.end(); ++it) {\n settings.setValue(it.key(), it.value());\n }\n settings.endGroup();\n}\n void loadControllerMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.beginGroup(\"ControllerPhysicalMappings\");\n QStringList keys = settings.allKeys();\n \n if (keys.isEmpty()) {\n // No saved mappings, use defaults\n physicalButtonMappings = getDefaultMappings();\n saveControllerMappings(); // Save defaults for next time\n } else {\n // Load saved mappings\n for (const QString &key : keys) {\n physicalButtonMappings[key] = settings.value(key).toInt();\n }\n }\n settings.endGroup();\n}\n QStringList getAvailablePhysicalButtons() const {\n QStringList buttons;\n if (joystick) {\n int buttonCount = SDL_JoystickNumButtons(joystick);\n for (int i = 0; i < buttonCount; ++i) {\n buttons << getPhysicalButtonName(i);\n }\n } else {\n // If no joystick connected, show a reasonable range\n for (int i = 0; i < 20; ++i) {\n buttons << getPhysicalButtonName(i);\n }\n }\n return buttons;\n}\n QString getPhysicalButtonName(int sdlButton) const {\n // Return human-readable names for physical SDL joystick buttons\n // Since we're using raw joystick buttons, we'll use generic names\n return QString(\"Button %1\").arg(sdlButton);\n}\n int getJoystickButtonCount() const {\n if (joystick) {\n return SDL_JoystickNumButtons(joystick);\n }\n return 0;\n}\n QMap getDefaultMappings() const {\n // Default mappings for Joy-Con L using raw button indices\n // These will need to be adjusted based on actual Joy-Con button indices\n QMap defaults;\n defaults[\"LEFTSHOULDER\"] = 4; // L button\n defaults[\"RIGHTSHOULDER\"] = 6; // ZL button \n defaults[\"PADDLE2\"] = 14; // SL button\n defaults[\"PADDLE4\"] = 15; // SR button\n defaults[\"Y\"] = 0; // Up arrow\n defaults[\"A\"] = 1; // Down arrow\n defaults[\"B\"] = 2; // Left arrow\n defaults[\"X\"] = 3; // Right arrow\n defaults[\"LEFTSTICK\"] = 10; // Stick press\n defaults[\"START\"] = 8; // Minus button\n defaults[\"GUIDE\"] = 13; // Screenshot button\n return defaults;\n}\n void buttonHeld(QString buttonName);\n void buttonReleased(QString buttonName);\n void buttonSinglePress(QString buttonName);\n void leftStickAngleChanged(int angle);\n void leftStickReleased();\n void rawButtonPressed(int sdlButton, QString buttonName);\n public:\n void start() {\n if (!sdlInitialized) {\n if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) != 0) {\n qWarning() << \"Failed to initialize SDL joystick subsystem:\" << SDL_GetError();\n return;\n }\n sdlInitialized = true;\n }\n\n SDL_JoystickEventState(SDL_ENABLE); // ✅ Enable joystick events\n\n // Look for any available joystick\n int numJoysticks = SDL_NumJoysticks();\n // qDebug() << \"Found\" << numJoysticks << \"joystick(s)\";\n \n for (int i = 0; i < numJoysticks; ++i) {\n const char* joystickName = SDL_JoystickNameForIndex(i);\n // qDebug() << \"Joystick\" << i << \":\" << (joystickName ? joystickName : \"Unknown\");\n \n joystick = SDL_JoystickOpen(i);\n if (joystick) {\n // qDebug() << \"Joystick connected!\";\n // qDebug() << \"Number of buttons:\" << SDL_JoystickNumButtons(joystick);\n // qDebug() << \"Number of axes:\" << SDL_JoystickNumAxes(joystick);\n // qDebug() << \"Number of hats:\" << SDL_JoystickNumHats(joystick);\n break;\n }\n }\n\n if (!joystick) {\n qWarning() << \"No joystick could be opened\";\n }\n\n pollTimer->start(16); // 60 FPS polling\n}\n void stop() {\n pollTimer->stop();\n}\n void reconnect() {\n // Stop current polling\n pollTimer->stop();\n \n // Close existing joystick if open\n if (joystick) {\n SDL_JoystickClose(joystick);\n joystick = nullptr;\n }\n \n // Clear any cached state\n buttonPressTime.clear();\n buttonHeldEmitted.clear();\n lastAngle = -1;\n leftStickActive = false;\n buttonDetectionMode = false;\n \n // Re-initialize SDL joystick subsystem\n SDL_QuitSubSystem(SDL_INIT_JOYSTICK);\n if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) != 0) {\n qWarning() << \"Failed to re-initialize SDL joystick subsystem:\" << SDL_GetError();\n sdlInitialized = false;\n return;\n }\n sdlInitialized = true;\n \n SDL_JoystickEventState(SDL_ENABLE);\n \n // Look for any available joystick\n int numJoysticks = SDL_NumJoysticks();\n qDebug() << \"Reconnect: Found\" << numJoysticks << \"joystick(s)\";\n \n for (int i = 0; i < numJoysticks; ++i) {\n const char* joystickName = SDL_JoystickNameForIndex(i);\n qDebug() << \"Reconnect: Trying joystick\" << i << \":\" << (joystickName ? joystickName : \"Unknown\");\n \n joystick = SDL_JoystickOpen(i);\n if (joystick) {\n qDebug() << \"Reconnect: Joystick connected successfully!\";\n qDebug() << \"Number of buttons:\" << SDL_JoystickNumButtons(joystick);\n qDebug() << \"Number of axes:\" << SDL_JoystickNumAxes(joystick);\n qDebug() << \"Number of hats:\" << SDL_JoystickNumHats(joystick);\n break;\n }\n }\n \n if (!joystick) {\n qWarning() << \"Reconnect: No joystick could be opened\";\n }\n \n // Restart polling\n pollTimer->start(16); // 60 FPS polling\n}\n void startButtonDetection() {\n buttonDetectionMode = true;\n}\n void stopButtonDetection() {\n buttonDetectionMode = false;\n}\n private:\n QTimer *pollTimer;\n SDL_Joystick *joystick = nullptr;\n bool sdlInitialized = false;\n bool leftStickActive = false;\n bool buttonDetectionMode = false;\n int lastAngle = -1;\n QString getButtonName(Uint8 sdlButton) {\n // This method is now deprecated in favor of getLogicalButtonName\n return getLogicalButtonName(sdlButton);\n}\n QString getLogicalButtonName(Uint8 sdlButton) {\n // Find which logical button this physical button is mapped to\n for (auto it = physicalButtonMappings.begin(); it != physicalButtonMappings.end(); ++it) {\n if (it.value() == sdlButton) {\n return it.key(); // Return the logical button name\n }\n }\n return QString(); // Return empty string if not mapped\n}\n QMap physicalButtonMappings;\n QMap buttonPressTime;\n QMap buttonHeldEmitted;\n const quint32 HOLD_THRESHOLD = 300;\n const quint32 POLL_INTERVAL = 16;\n};"], ["/SpeedyNote/markdown/linenumberarea.h", "#ifndef LINENUMBERAREA_H\n#define LINENUMBERAREA_H\n\n#include \n#include \n#include \n#include \n\n#include \"qmarkdowntextedit.h\"\n\nclass LineNumArea final : public QWidget {\n Q_OBJECT\n\n public:\n explicit LineNumArea(QMarkdownTextEdit *parent)\n : QWidget(parent), textEdit(parent) {\n Q_ASSERT(parent);\n\n _currentLineColor = QColor(QStringLiteral(\"#eef067\"));\n _otherLinesColor = QColor(QStringLiteral(\"#a6a6a6\"));\n setHidden(true);\n\n // We always use fixed font to avoid \"width\" issues\n setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont));\n }\n\n void setCurrentLineColor(QColor color) { _currentLineColor = color; }\n\n void setOtherLineColor(QColor color) {\n _otherLinesColor = std::move(color);\n }\n\n int lineNumAreaWidth() const {\n if (!enabled) {\n return 0;\n }\n\n int digits = 2;\n int max = std::max(1, textEdit->blockCount());\n while (max >= 10) {\n max /= 10;\n ++digits;\n }\n\n#if QT_VERSION >= 0x050B00\n int space =\n 13 + textEdit->fontMetrics().horizontalAdvance(u'9') * digits;\n#else\n int space =\n 13 + textEdit->fontMetrics().width(QLatin1Char('9')) * digits;\n#endif\n\n return space;\n }\n\n bool isLineNumAreaEnabled() const { return enabled; }\n\n void setLineNumAreaEnabled(bool e) {\n enabled = e;\n setHidden(!e);\n }\n\n QSize sizeHint() const override { return {lineNumAreaWidth(), 0}; }\n\n protected:\n void paintEvent(QPaintEvent *event) override {\n QPainter painter(this);\n\n painter.fillRect(event->rect(),\n palette().color(QPalette::Active, QPalette::Window));\n\n auto block = textEdit->firstVisibleBlock();\n int blockNumber = block.blockNumber();\n qreal top = textEdit->blockBoundingGeometry(block)\n .translated(textEdit->contentOffset())\n .top();\n // Maybe the top is not 0?\n top += textEdit->viewportMargins().top();\n qreal bottom = top;\n\n const QPen currentLine = _currentLineColor;\n const QPen otherLines = _otherLinesColor;\n painter.setFont(font());\n\n while (block.isValid() && top <= event->rect().bottom()) {\n top = bottom;\n bottom = top + textEdit->blockBoundingRect(block).height();\n if (block.isVisible() && bottom >= event->rect().top()) {\n QString number = QString::number(blockNumber + 1);\n\n auto isCurrentLine =\n textEdit->textCursor().blockNumber() == blockNumber;\n painter.setPen(isCurrentLine ? currentLine : otherLines);\n\n painter.drawText(-5, top, sizeHint().width(),\n textEdit->fontMetrics().height(),\n Qt::AlignRight, number);\n }\n\n block = block.next();\n ++blockNumber;\n }\n }\n\n private:\n bool enabled = false;\n QMarkdownTextEdit *textEdit;\n QColor _currentLineColor;\n QColor _otherLinesColor;\n};\n\n#endif // LINENUMBERAREA_H\n"], ["/SpeedyNote/source/Main.cpp", "#ifdef _WIN32\n#include \n#endif\n\n#include \n#include \n#include \n#include \"MainWindow.h\"\n\nint main(int argc, char *argv[]) {\n#ifdef _WIN32\n FreeConsole(); // Hide console safely on Windows\n\n /*\n AllocConsole();\n freopen(\"CONOUT$\", \"w\", stdout);\n freopen(\"CONOUT$\", \"w\", stderr);\n */\n \n \n // to show console for debugging\n \n \n#endif\n SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI, \"1\");\n SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_SWITCH, \"1\");\n SDL_Init(SDL_INIT_GAMECONTROLLER | SDL_INIT_JOYSTICK);\n\n /*\n qDebug() << \"SDL2 version:\" << SDL_GetRevision();\n qDebug() << \"Num Joysticks:\" << SDL_NumJoysticks();\n\n for (int i = 0; i < SDL_NumJoysticks(); ++i) {\n if (SDL_IsGameController(i)) {\n qDebug() << \"Controller\" << i << \"is\" << SDL_GameControllerNameForIndex(i);\n } else {\n qDebug() << \"Joystick\" << i << \"is not a recognized controller\";\n }\n }\n */ // For sdl2 debugging\n \n\n\n // Enable Windows IME support for multi-language input\n QApplication app(argc, argv);\n \n // Ensure IME is properly enabled for Windows\n #ifdef _WIN32\n app.setAttribute(Qt::AA_EnableHighDpiScaling, true);\n app.setAttribute(Qt::AA_UseHighDpiPixmaps, true);\n #endif\n\n \n QTranslator translator;\n QString locale = QLocale::system().name(); // e.g., \"zh_CN\", \"es_ES\"\n QString langCode = locale.section('_', 0, 0); // e.g., \"zh\"\n\n // printf(\"Locale: %s\\n\", locale.toStdString().c_str());\n // printf(\"Language Code: %s\\n\", langCode.toStdString().c_str());\n\n // QString locale = \"es-ES\"; // e.g., \"zh_CN\", \"es_ES\"\n // QString langCode = \"es\"; // e.g., \"zh\"\n QString translationsPath = QCoreApplication::applicationDirPath();\n\n if (translator.load(translationsPath + \"/app_\" + langCode + \".qm\")) {\n app.installTranslator(&translator);\n }\n\n QString inputFile;\n if (argc >= 2) {\n inputFile = QString::fromLocal8Bit(argv[1]);\n // qDebug() << \"Input file received:\" << inputFile;\n }\n\n MainWindow w;\n if (!inputFile.isEmpty()) {\n // Check file extension to determine how to handle it\n if (inputFile.toLower().endsWith(\".pdf\")) {\n // Handle PDF file association\n w.show(); // Show window first for dialog parent\n w.openPdfFile(inputFile);\n } else if (inputFile.toLower().endsWith(\".snpkg\")) {\n // Handle notebook package import\n w.importNotebookFromFile(inputFile);\n w.show();\n } else {\n // Unknown file type, just show the application\n w.show();\n }\n } else {\n w.show();\n }\n return app.exec();\n}\n"], ["/SpeedyNote/source/KeyCaptureDialog.h", "class KeyCaptureDialog {\n Q_OBJECT\n\npublic:\n explicit KeyCaptureDialog(QWidget *parent = nullptr);\n protected:\n void keyPressEvent(QKeyEvent *event) override {\n // Build key sequence string\n QStringList modifiers;\n \n if (event->modifiers() & Qt::ControlModifier) modifiers << \"Ctrl\";\n if (event->modifiers() & Qt::ShiftModifier) modifiers << \"Shift\";\n if (event->modifiers() & Qt::AltModifier) modifiers << \"Alt\";\n if (event->modifiers() & Qt::MetaModifier) modifiers << \"Meta\";\n \n // Don't capture modifier keys alone\n if (event->key() == Qt::Key_Control || event->key() == Qt::Key_Shift ||\n event->key() == Qt::Key_Alt || event->key() == Qt::Key_Meta) {\n return;\n }\n \n // Don't capture Escape (let it close the dialog)\n if (event->key() == Qt::Key_Escape) {\n QDialog::keyPressEvent(event);\n return;\n }\n \n QString keyString = QKeySequence(event->key()).toString();\n \n if (!modifiers.isEmpty()) {\n capturedSequence = modifiers.join(\"+\") + \"+\" + keyString;\n } else {\n capturedSequence = keyString;\n }\n \n updateDisplay();\n event->accept();\n}\n private:\n void clearSequence() {\n capturedSequence.clear();\n updateDisplay();\n setFocus(); // Return focus to dialog for key capture\n}\n private:\n QLabel *instructionLabel;\n QLabel *capturedLabel;\n QPushButton *clearButton;\n QPushButton *okButton;\n QPushButton *cancelButton;\n QString capturedSequence;\n void updateDisplay() {\n if (capturedSequence.isEmpty()) {\n capturedLabel->setText(tr(\"(No key captured yet)\"));\n okButton->setEnabled(false);\n } else {\n capturedLabel->setText(capturedSequence);\n okButton->setEnabled(true);\n }\n}\n};"], ["/SpeedyNote/source/ButtonMappingTypes.h", "class InternalDialMode {\n Q_DECLARE_TR_FUNCTIONS(ButtonMappingHelper)\n public:\n static QString dialModeToInternalKey(InternalDialMode mode) {\n switch (mode) {\n case InternalDialMode::None: return \"none\";\n case InternalDialMode::PageSwitching: return \"page_switching\";\n case InternalDialMode::ZoomControl: return \"zoom_control\";\n case InternalDialMode::ThicknessControl: return \"thickness_control\";\n\n case InternalDialMode::ToolSwitching: return \"tool_switching\";\n case InternalDialMode::PresetSelection: return \"preset_selection\";\n case InternalDialMode::PanAndPageScroll: return \"pan_and_page_scroll\";\n }\n return \"none\";\n}\n static QString actionToInternalKey(InternalControllerAction action) {\n switch (action) {\n case InternalControllerAction::None: return \"none\";\n case InternalControllerAction::ToggleFullscreen: return \"toggle_fullscreen\";\n case InternalControllerAction::ToggleDial: return \"toggle_dial\";\n case InternalControllerAction::Zoom50: return \"zoom_50\";\n case InternalControllerAction::ZoomOut: return \"zoom_out\";\n case InternalControllerAction::Zoom200: return \"zoom_200\";\n case InternalControllerAction::AddPreset: return \"add_preset\";\n case InternalControllerAction::DeletePage: return \"delete_page\";\n case InternalControllerAction::FastForward: return \"fast_forward\";\n case InternalControllerAction::OpenControlPanel: return \"open_control_panel\";\n case InternalControllerAction::RedColor: return \"red_color\";\n case InternalControllerAction::BlueColor: return \"blue_color\";\n case InternalControllerAction::YellowColor: return \"yellow_color\";\n case InternalControllerAction::GreenColor: return \"green_color\";\n case InternalControllerAction::BlackColor: return \"black_color\";\n case InternalControllerAction::WhiteColor: return \"white_color\";\n case InternalControllerAction::CustomColor: return \"custom_color\";\n case InternalControllerAction::ToggleSidebar: return \"toggle_sidebar\";\n case InternalControllerAction::Save: return \"save\";\n case InternalControllerAction::StraightLineTool: return \"straight_line_tool\";\n case InternalControllerAction::RopeTool: return \"rope_tool\";\n case InternalControllerAction::SetPenTool: return \"set_pen_tool\";\n case InternalControllerAction::SetMarkerTool: return \"set_marker_tool\";\n case InternalControllerAction::SetEraserTool: return \"set_eraser_tool\";\n case InternalControllerAction::TogglePdfTextSelection: return \"toggle_pdf_text_selection\";\n case InternalControllerAction::ToggleOutline: return \"toggle_outline\";\n case InternalControllerAction::ToggleBookmarks: return \"toggle_bookmarks\";\n case InternalControllerAction::AddBookmark: return \"add_bookmark\";\n case InternalControllerAction::ToggleTouchGestures: return \"toggle_touch_gestures\";\n }\n return \"none\";\n}\n static InternalDialMode internalKeyToDialMode(const QString &key) {\n if (key == \"none\") return InternalDialMode::None;\n if (key == \"page_switching\") return InternalDialMode::PageSwitching;\n if (key == \"zoom_control\") return InternalDialMode::ZoomControl;\n if (key == \"thickness_control\") return InternalDialMode::ThicknessControl;\n\n if (key == \"tool_switching\") return InternalDialMode::ToolSwitching;\n if (key == \"preset_selection\") return InternalDialMode::PresetSelection;\n if (key == \"pan_and_page_scroll\") return InternalDialMode::PanAndPageScroll;\n return InternalDialMode::None;\n}\n static InternalControllerAction internalKeyToAction(const QString &key) {\n if (key == \"none\") return InternalControllerAction::None;\n if (key == \"toggle_fullscreen\") return InternalControllerAction::ToggleFullscreen;\n if (key == \"toggle_dial\") return InternalControllerAction::ToggleDial;\n if (key == \"zoom_50\") return InternalControllerAction::Zoom50;\n if (key == \"zoom_out\") return InternalControllerAction::ZoomOut;\n if (key == \"zoom_200\") return InternalControllerAction::Zoom200;\n if (key == \"add_preset\") return InternalControllerAction::AddPreset;\n if (key == \"delete_page\") return InternalControllerAction::DeletePage;\n if (key == \"fast_forward\") return InternalControllerAction::FastForward;\n if (key == \"open_control_panel\") return InternalControllerAction::OpenControlPanel;\n if (key == \"red_color\") return InternalControllerAction::RedColor;\n if (key == \"blue_color\") return InternalControllerAction::BlueColor;\n if (key == \"yellow_color\") return InternalControllerAction::YellowColor;\n if (key == \"green_color\") return InternalControllerAction::GreenColor;\n if (key == \"black_color\") return InternalControllerAction::BlackColor;\n if (key == \"white_color\") return InternalControllerAction::WhiteColor;\n if (key == \"custom_color\") return InternalControllerAction::CustomColor;\n if (key == \"toggle_sidebar\") return InternalControllerAction::ToggleSidebar;\n if (key == \"save\") return InternalControllerAction::Save;\n if (key == \"straight_line_tool\") return InternalControllerAction::StraightLineTool;\n if (key == \"rope_tool\") return InternalControllerAction::RopeTool;\n if (key == \"set_pen_tool\") return InternalControllerAction::SetPenTool;\n if (key == \"set_marker_tool\") return InternalControllerAction::SetMarkerTool;\n if (key == \"set_eraser_tool\") return InternalControllerAction::SetEraserTool;\n if (key == \"toggle_pdf_text_selection\") return InternalControllerAction::TogglePdfTextSelection;\n if (key == \"toggle_outline\") return InternalControllerAction::ToggleOutline;\n if (key == \"toggle_bookmarks\") return InternalControllerAction::ToggleBookmarks;\n if (key == \"add_bookmark\") return InternalControllerAction::AddBookmark;\n if (key == \"toggle_touch_gestures\") return InternalControllerAction::ToggleTouchGestures;\n return InternalControllerAction::None;\n}\n static QStringList getTranslatedDialModes() {\n return {\n tr(\"None\"),\n tr(\"Page Switching\"),\n tr(\"Zoom Control\"),\n tr(\"Thickness Control\"),\n\n tr(\"Tool Switching\"),\n tr(\"Preset Selection\"),\n tr(\"Pan and Page Scroll\")\n };\n}\n static QStringList getTranslatedActions() {\n return {\n tr(\"None\"),\n tr(\"Toggle Fullscreen\"),\n tr(\"Toggle Dial\"),\n tr(\"Zoom 50%\"),\n tr(\"Zoom Out\"),\n tr(\"Zoom 200%\"),\n tr(\"Add Preset\"),\n tr(\"Delete Page\"),\n tr(\"Fast Forward\"),\n tr(\"Open Control Panel\"),\n tr(\"Red\"),\n tr(\"Blue\"),\n tr(\"Yellow\"),\n tr(\"Green\"),\n tr(\"Black\"),\n tr(\"White\"),\n tr(\"Custom Color\"),\n tr(\"Toggle Sidebar\"),\n tr(\"Save\"),\n tr(\"Straight Line Tool\"),\n tr(\"Rope Tool\"),\n tr(\"Set Pen Tool\"),\n tr(\"Set Marker Tool\"),\n tr(\"Set Eraser Tool\"),\n tr(\"Toggle PDF Text Selection\"),\n tr(\"Toggle PDF Outline\"),\n tr(\"Toggle Bookmarks\"),\n tr(\"Add/Remove Bookmark\"),\n tr(\"Toggle Touch Gestures\")\n };\n}\n static QStringList getTranslatedButtons() {\n return {\n tr(\"Left Shoulder\"),\n tr(\"Right Shoulder\"),\n tr(\"Paddle 2\"),\n tr(\"Paddle 4\"),\n tr(\"Y Button\"),\n tr(\"A Button\"),\n tr(\"B Button\"),\n tr(\"X Button\"),\n tr(\"Left Stick\"),\n tr(\"Start Button\"),\n tr(\"Guide Button\")\n };\n}\n static QStringList getInternalDialModeKeys() {\n return {\n \"none\",\n \"page_switching\",\n \"zoom_control\",\n \"thickness_control\",\n\n \"tool_switching\",\n \"preset_selection\",\n \"pan_and_page_scroll\"\n };\n}\n static QStringList getInternalActionKeys() {\n return {\n \"none\",\n \"toggle_fullscreen\",\n \"toggle_dial\",\n \"zoom_50\",\n \"zoom_out\",\n \"zoom_200\",\n \"add_preset\",\n \"delete_page\",\n \"fast_forward\",\n \"open_control_panel\",\n \"red_color\",\n \"blue_color\",\n \"yellow_color\",\n \"green_color\",\n \"black_color\",\n \"white_color\",\n \"custom_color\",\n \"toggle_sidebar\",\n \"save\",\n \"straight_line_tool\",\n \"rope_tool\",\n \"set_pen_tool\",\n \"set_marker_tool\",\n \"set_eraser_tool\",\n \"toggle_pdf_text_selection\",\n \"toggle_outline\",\n \"toggle_bookmarks\",\n \"add_bookmark\",\n \"toggle_touch_gestures\"\n };\n}\n static QStringList getInternalButtonKeys() {\n return {\n \"LEFTSHOULDER\",\n \"RIGHTSHOULDER\", \n \"PADDLE2\",\n \"PADDLE4\",\n \"Y\",\n \"A\",\n \"B\",\n \"X\",\n \"LEFTSTICK\",\n \"START\",\n \"GUIDE\"\n };\n}\n static QString displayToInternalKey(const QString &displayString, bool isDialMode) {\n if (isDialMode) {\n QStringList translated = getTranslatedDialModes();\n QStringList internal = getInternalDialModeKeys();\n int index = translated.indexOf(displayString);\n return (index >= 0) ? internal[index] : \"none\";\n } else {\n QStringList translated = getTranslatedActions();\n QStringList internal = getInternalActionKeys();\n int index = translated.indexOf(displayString);\n return (index >= 0) ? internal[index] : \"none\";\n }\n}\n static QString internalKeyToDisplay(const QString &internalKey, bool isDialMode) {\n if (isDialMode) {\n QStringList translated = getTranslatedDialModes();\n QStringList internal = getInternalDialModeKeys();\n int index = internal.indexOf(internalKey);\n return (index >= 0) ? translated[index] : tr(\"None\");\n } else {\n QStringList translated = getTranslatedActions();\n QStringList internal = getInternalActionKeys();\n int index = internal.indexOf(internalKey);\n return (index >= 0) ? translated[index] : tr(\"None\");\n }\n}\n};"], ["/SpeedyNote/markdown/main.cpp", "/*\n * MIT License\n *\n * Copyright (c) 2014-2025 Patrizio Bekerle -- \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#include \n\n#include \"mainwindow.h\"\n\nint main(int argc, char *argv[]) {\n QApplication a(argc, argv);\n MainWindow w;\n w.show();\n\n return a.exec();\n}\n"], ["/SpeedyNote/markdown/mainwindow.h", "class MainWindow {\n Q_OBJECT\n\n public:\n explicit MainWindow(QWidget *parent = nullptr);\n ~MainWindow() { delete ui; }\n private:\n Ui::MainWindow *ui;\n};"], ["/SpeedyNote/source/ToolType.h", "#ifndef TOOLTYPE_H\n#define TOOLTYPE_H\n\n// ✅ Now it can be used anywhere\nenum class ToolType {\n Pen,\n Marker,\n Eraser\n};\n\n#endif // TOOLTYPE_H"], ["/SpeedyNote/markdown/qownlanguagedata.h", "class qownlanguagedata {\n};"], ["/SpeedyNote/markdown/markdownhighlighter.h", "class QTextDocument {\n};"]], "task_instance_info": {"created_time": "2025-08-20 19:30:37", "created_task_model": "DeepSeek-R1", "class_skeleton": "class\nQPushButton\n{\nQ_OBJECT\n\npublic:\n explicit RecentNotebooksDialog(MainWindow *mainWindow, RecentNotebooksManager *manager, QWidget *parent = nullptr);\nprivate:\nvoid onNotebookClicked() {}\nprivate:\nvoid setupUi() {}\nvoid populateGrid() {}\nRecentNotebooksManager *notebookManager;\nQGridLayout *gridLayout;\nMainWindow *mainWindowRef;\n};", "code_description": "This code segment functions to: Manage user interaction with a grid of recent notebook entries by creating visual elements for selection, handling click events to initiate notebook loading processes, and coordinating data persistence operations with associated UI updates."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```cpp\n[TASK_BEGIN]\nclass RecentNotebooksDialog\n{\n Q_OBJECT\n\npublic:\n explicit RecentNotebooksDialog(MainWindow *mainWindow, RecentNotebooksManager *manager, QWidget *parent = nullptr) \n : mainWindowRef(mainWindow), notebookManager(manager), gridLayout(new QGridLayout(this)) {\n setupUi();\n }\n\nprivate:\n void onNotebookClicked() {\n QPushButton *button = qobject_cast(sender());\n if (button) {\n mainWindowRef->openNotebook(button->property(\"notebookPath\").toString());\n }\n }\n\n void setupUi() {\n setLayout(gridLayout);\n populateGrid();\n }\n\n void populateGrid() {\n int row = 0;\n for (const QString &path : notebookManager->getRecentNotebookPaths()) {\n QPushButton *btn = new QPushButton(QFileInfo(path).baseName(), this);\n btn->setProperty(\"notebookPath\", path);\n btn->setToolTip(path);\n gridLayout->addWidget(btn, row++, 0);\n connect(btn, &QPushButton::clicked, this, &RecentNotebooksDialog::onNotebookClicked);\n }\n }\n\n RecentNotebooksManager *notebookManager;\n QGridLayout *gridLayout;\n MainWindow *mainWindowRef;\n};\n[TASK_END]\n```", "inference_time": "2025-08-20 19-31-14"}, "editdistance_info": {"edit_distance": 18.3311, "calculate_time": "2025-08-20 19:31:14", "true_code_clean": "class QPushButton {\n Q_OBJECT\npublic:\n explicit RecentNotebooksDialog(MainWindow *mainWindow, RecentNotebooksManager *manager, QWidget *parent = nullptr);\n private:\n void onNotebookClicked() {\n QPushButton *button = qobject_cast(sender());\n if (button) {\n QString notebookPath = button->property(\"notebookPath\").toString();\n if (!notebookPath.isEmpty() && mainWindowRef) {\n InkCanvas *canvas = mainWindowRef->currentCanvas(); \n if (canvas) {\n if (canvas->isEdited()){\n mainWindowRef->saveCurrentPage(); \n }\n canvas->setSaveFolder(notebookPath);\n mainWindowRef->switchPageWithDirection(1, 1); \n mainWindowRef->pageInput->setValue(1); \n mainWindowRef->updateTabLabel(); \n if (notebookManager) {\n notebookManager->generateAndSaveCoverPreview(notebookPath, canvas);\n notebookManager->addRecentNotebook(notebookPath, canvas);\n }\n }\n accept(); \n }\n }\n}\n private:\n void setupUi() {\n QVBoxLayout *mainLayout = new QVBoxLayout(this);\n QScrollArea *scrollArea = new QScrollArea(this);\n scrollArea->setWidgetResizable(true);\n QWidget *gridContainer = new QWidget();\n gridLayout = new QGridLayout(gridContainer);\n gridLayout->setSpacing(15);\n scrollArea->setWidget(gridContainer);\n mainLayout->addWidget(scrollArea);\n setLayout(mainLayout);\n}\n void populateGrid() {\n QStringList recentPaths = notebookManager->getRecentNotebooks();\n int row = 0;\n int col = 0;\n const int numCols = 4;\n for (const QString &path : recentPaths) {\n if (path.isEmpty()) continue;\n QPushButton *button = new QPushButton(this);\n button->setFixedSize(180, 180); \n button->setProperty(\"notebookPath\", path); \n connect(button, &QPushButton::clicked, this, &RecentNotebooksDialog::onNotebookClicked);\n QVBoxLayout *buttonLayout = new QVBoxLayout(button);\n buttonLayout->setContentsMargins(5,5,5,5);\n QLabel *coverLabel = new QLabel(this);\n coverLabel->setFixedSize(170, 127); \n coverLabel->setAlignment(Qt::AlignCenter);\n QString coverPath = notebookManager->getCoverImagePathForNotebook(path);\n if (!coverPath.isEmpty()) {\n QPixmap coverPixmap(coverPath);\n coverLabel->setPixmap(coverPixmap.scaled(coverLabel->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));\n } else {\n coverLabel->setText(tr(\"No Preview\"));\n }\n coverLabel->setStyleSheet(\"border: 1px solid gray;\");\n QLabel *nameLabel = new QLabel(notebookManager->getNotebookDisplayName(path), this);\n nameLabel->setAlignment(Qt::AlignCenter);\n nameLabel->setWordWrap(true);\n nameLabel->setFixedHeight(40); \n buttonLayout->addWidget(coverLabel);\n buttonLayout->addWidget(nameLabel);\n button->setLayout(buttonLayout);\n gridLayout->addWidget(button, row, col);\n col++;\n if (col >= numCols) {\n col = 0;\n row++;\n }\n }\n}\n RecentNotebooksManager *notebookManager;\n QGridLayout *gridLayout;\n MainWindow *mainWindowRef;\n}", "predict_code_clean": "class RecentNotebooksDialog\n{\n Q_OBJECT\npublic:\n explicit RecentNotebooksDialog(MainWindow *mainWindow, RecentNotebooksManager *manager, QWidget *parent = nullptr) \n : mainWindowRef(mainWindow), notebookManager(manager), gridLayout(new QGridLayout(this)) {\n setupUi();\n }\nprivate:\n void onNotebookClicked() {\n QPushButton *button = qobject_cast(sender());\n if (button) {\n mainWindowRef->openNotebook(button->property(\"notebookPath\").toString());\n }\n }\n void setupUi() {\n setLayout(gridLayout);\n populateGrid();\n }\n void populateGrid() {\n int row = 0;\n for (const QString &path : notebookManager->getRecentNotebookPaths()) {\n QPushButton *btn = new QPushButton(QFileInfo(path).baseName(), this);\n btn->setProperty(\"notebookPath\", path);\n btn->setToolTip(path);\n gridLayout->addWidget(btn, row++, 0);\n connect(btn, &QPushButton::clicked, this, &RecentNotebooksDialog::onNotebookClicked);\n }\n }\n RecentNotebooksManager *notebookManager;\n QGridLayout *gridLayout;\n MainWindow *mainWindowRef;\n};"}} {"repo_name": "SpeedyNote", "file_name": "/SpeedyNote/source/RecentNotebooksManager.h", "inference_info": {"prefix_code": "", "suffix_code": ";", "middle_code": "class InkCanvas {\n Q_OBJECT\npublic:\n explicit RecentNotebooksManager(QObject *parent = nullptr);\n void addRecentNotebook(const QString& folderPath, InkCanvas* canvasForPreview = nullptr) {\n if (folderPath.isEmpty()) return;\n recentNotebookPaths.removeAll(folderPath);\n recentNotebookPaths.prepend(folderPath);\n while (recentNotebookPaths.size() > MAX_RECENT_NOTEBOOKS) {\n recentNotebookPaths.removeLast();\n }\n generateAndSaveCoverPreview(folderPath, canvasForPreview);\n saveRecentNotebooks();\n}\n QStringList getRecentNotebooks() const {\n return recentNotebookPaths;\n}\n QString getCoverImagePathForNotebook(const QString& folderPath) const {\n QString coverDir = getCoverImageDir();\n QString coverFileName = sanitizeFolderName(folderPath) + \"_cover.png\";\n QString coverFilePath = coverDir + coverFileName;\n if (QFile::exists(coverFilePath)) {\n return coverFilePath;\n }\n return \"\"; \n}\n QString getNotebookDisplayName(const QString& folderPath) const {\n QString metadataFile = folderPath + \"/.pdf_path.txt\";\n if (QFile::exists(metadataFile)) {\n QFile file(metadataFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString pdfPath = in.readLine().trimmed();\n file.close();\n if (!pdfPath.isEmpty()) {\n return QFileInfo(pdfPath).fileName();\n }\n }\n }\n return QFileInfo(folderPath).fileName();\n}\n void generateAndSaveCoverPreview(const QString& folderPath, InkCanvas* optionalCanvas = nullptr) {\n QString coverDir = getCoverImageDir();\n QString coverFileName = sanitizeFolderName(folderPath) + \"_cover.png\";\n QString coverFilePath = coverDir + coverFileName;\n QImage coverImage(400, 300, QImage::Format_ARGB32_Premultiplied);\n coverImage.fill(Qt::white); \n QPainter painter(&coverImage);\n painter.setRenderHint(QPainter::SmoothPixmapTransform);\n if (optionalCanvas && optionalCanvas->width() > 0 && optionalCanvas->height() > 0) {\n int logicalCanvasWidth = optionalCanvas->width();\n int logicalCanvasHeight = optionalCanvas->height();\n double targetAspectRatio = 4.0 / 3.0;\n double canvasAspectRatio = (double)logicalCanvasWidth / logicalCanvasHeight;\n int grabWidth, grabHeight;\n int xOffset = 0, yOffset = 0;\n if (canvasAspectRatio > targetAspectRatio) { \n grabHeight = logicalCanvasHeight;\n grabWidth = qRound(logicalCanvasHeight * targetAspectRatio);\n xOffset = (logicalCanvasWidth - grabWidth) / 2;\n } else { \n grabWidth = logicalCanvasWidth;\n grabHeight = qRound(logicalCanvasWidth / targetAspectRatio);\n yOffset = (logicalCanvasHeight - grabHeight) / 2;\n }\n if (grabWidth > 0 && grabHeight > 0) {\n QRect grabRect(xOffset, yOffset, grabWidth, grabHeight);\n QPixmap capturedView = optionalCanvas->grab(grabRect);\n painter.drawPixmap(coverImage.rect(), capturedView, capturedView.rect());\n } else {\n painter.fillRect(coverImage.rect(), Qt::lightGray);\n painter.setPen(Qt::black);\n painter.drawText(coverImage.rect(), Qt::AlignCenter, tr(\"Preview Error\"));\n }\n } else {\n QString notebookIdStr;\n InkCanvas tempCanvas(nullptr); \n QFile idFile(folderPath + \"/.notebook_id.txt\");\n if (idFile.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&idFile);\n notebookIdStr = in.readLine().trimmed();\n idFile.close();\n }\n QString firstPagePath, firstAnnotatedPagePath;\n if (!notebookIdStr.isEmpty()) {\n firstPagePath = folderPath + QString(\"/%1_00000.png\").arg(notebookIdStr);\n firstAnnotatedPagePath = folderPath + QString(\"/annotated_%1_00000.png\").arg(notebookIdStr);\n } else {\n }\n QImage pageImage;\n if (!firstAnnotatedPagePath.isEmpty() && QFile::exists(firstAnnotatedPagePath)) {\n pageImage.load(firstAnnotatedPagePath);\n } else if (!firstPagePath.isEmpty() && QFile::exists(firstPagePath)) {\n pageImage.load(firstPagePath);\n }\n if (!pageImage.isNull()) {\n painter.drawImage(coverImage.rect(), pageImage, pageImage.rect());\n } else {\n painter.fillRect(coverImage.rect(), Qt::darkGray);\n painter.setPen(Qt::white);\n painter.drawText(coverImage.rect(), Qt::AlignCenter, tr(\"No Page 0 Preview\"));\n }\n }\n coverImage.save(coverFilePath, \"PNG\");\n}\n private:\n void loadRecentNotebooks() {\n recentNotebookPaths = settings.value(\"recentNotebooks\").toStringList();\n}\n void saveRecentNotebooks() {\n settings.setValue(\"recentNotebooks\", recentNotebookPaths);\n}\n QString getCoverImageDir() const {\n return QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/RecentCovers/\";\n}\n QString sanitizeFolderName(const QString& folderPath) const {\n return QFileInfo(folderPath).baseName().replace(QRegularExpression(\"[^a-zA-Z0-9_]\"), \"_\");\n}\n QStringList recentNotebookPaths;\n const int MAX_RECENT_NOTEBOOKS = 16;\n QSettings settings;\n}", "code_description": null, "fill_type": "CLASS_TYPE", "language_type": "cpp", "sub_task_type": null}, "context_code": [["/SpeedyNote/source/InkCanvas.h", "class MarkdownWindowManager {\n Q_OBJECT\n\nsignals:\n void zoomChanged(int newZoom);\n void panChanged(int panX, int panY);\n void touchGestureEnded();\n void ropeSelectionCompleted(const QPoint &position);\n void pdfLinkClicked(int targetPage);\n void pdfTextSelected(const QString &text);\n void pdfLoaded();\n void markdownSelectionModeChanged(bool enabled);\n public:\n explicit InkCanvas(QWidget *parent = nullptr) { \n \n // Set theme-aware default pen color\n MainWindow *mainWindow = qobject_cast(parent);\n if (mainWindow) {\n penColor = mainWindow->getDefaultPenColor();\n } \n setAttribute(Qt::WA_StaticContents);\n setTabletTracking(true);\n setAttribute(Qt::WA_AcceptTouchEvents); // Enable touch events\n\n // Enable immediate updates for smoother animation\n setAttribute(Qt::WA_OpaquePaintEvent);\n setAttribute(Qt::WA_NoSystemBackground);\n \n // Detect screen resolution and set canvas size\n QScreen *screen = QGuiApplication::primaryScreen();\n if (screen) {\n QSize logicalSize = screen->availableGeometry().size() * 0.89;\n setMaximumSize(logicalSize); // Optional\n setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);\n } else {\n setFixedSize(1920, 1080); // Fallback size\n }\n \n initializeBuffer();\n QCache pdfCache(10);\n pdfCache.setMaxCost(10); // ✅ Ensures the cache holds at most 5 pages\n // No need to set auto-delete, QCache will handle deletion automatically\n \n // Initialize PDF text selection throttling timer (60 FPS = ~16.67ms)\n pdfTextSelectionTimer = new QTimer(this);\n pdfTextSelectionTimer->setSingleShot(true);\n pdfTextSelectionTimer->setInterval(16); // ~60 FPS\n connect(pdfTextSelectionTimer, &QTimer::timeout, this, &InkCanvas::processPendingTextSelection);\n \n // Initialize PDF cache timer (will be created on-demand)\n pdfCacheTimer = nullptr;\n currentCachedPage = -1;\n \n // Initialize note page cache system\n noteCache.setMaxCost(15); // Cache up to 15 note pages (more than PDF since they're smaller)\n noteCacheTimer = nullptr;\n currentCachedNotePage = -1;\n \n // Initialize markdown manager\n markdownManager = new MarkdownWindowManager(this, this);\n \n // Connect pan/zoom signals to update markdown window positions\n connect(this, &InkCanvas::panChanged, markdownManager, &MarkdownWindowManager::updateAllWindowPositions);\n connect(this, &InkCanvas::zoomChanged, markdownManager, &MarkdownWindowManager::updateAllWindowPositions);\n}\n virtual ~InkCanvas() {\n // Cleanup if needed\n}\n void startBenchmark() {\n benchmarking = true;\n processedTimestamps.clear();\n benchmarkTimer.start();\n}\n void stopBenchmark() {\n benchmarking = false;\n}\n int getProcessedRate() {\n qint64 now = benchmarkTimer.elapsed();\n while (!processedTimestamps.empty() && now - processedTimestamps.front() > 1000) {\n processedTimestamps.pop_front();\n }\n return static_cast(processedTimestamps.size());\n}\n void setPenColor(const QColor &color) {\n penColor = color;\n}\n void setPenThickness(qreal thickness) {\n // Set thickness for the current tool\n switch (currentTool) {\n case ToolType::Pen:\n penToolThickness = thickness;\n break;\n case ToolType::Marker:\n markerToolThickness = thickness;\n break;\n case ToolType::Eraser:\n eraserToolThickness = thickness;\n break;\n }\n \n // Update the current thickness for efficient drawing\n penThickness = thickness;\n}\n void adjustAllToolThicknesses(qreal zoomRatio) {\n // Adjust thickness for all tools to maintain visual consistency\n penToolThickness *= zoomRatio;\n markerToolThickness *= zoomRatio;\n eraserToolThickness *= zoomRatio;\n \n // Update the current thickness based on the current tool\n switch (currentTool) {\n case ToolType::Pen:\n penThickness = penToolThickness;\n break;\n case ToolType::Marker:\n penThickness = markerToolThickness;\n break;\n case ToolType::Eraser:\n penThickness = eraserToolThickness;\n break;\n }\n}\n void setTool(ToolType tool) {\n currentTool = tool;\n \n // Switch to the thickness for the new tool\n switch (currentTool) {\n case ToolType::Pen:\n penThickness = penToolThickness;\n break;\n case ToolType::Marker:\n penThickness = markerToolThickness;\n break;\n case ToolType::Eraser:\n penThickness = eraserToolThickness;\n break;\n }\n}\n void setSaveFolder(const QString &folderPath) {\n saveFolder = folderPath;\n clearPdfNoDelete(); \n\n if (!saveFolder.isEmpty()) {\n QDir().mkpath(saveFolder);\n loadNotebookId(); // ✅ Load notebook ID when save folder is set\n }\n\n QString bgMetaFile = saveFolder + \"/.background_config.txt\"; // This metadata is for background styles, not to be confused with pdf directories. \n if (QFile::exists(bgMetaFile)) {\n QFile file(bgMetaFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n while (!in.atEnd()) {\n QString line = in.readLine().trimmed();\n if (line.startsWith(\"style=\")) {\n QString val = line.mid(6);\n if (val == \"Grid\") backgroundStyle = BackgroundStyle::Grid;\n else if (val == \"Lines\") backgroundStyle = BackgroundStyle::Lines;\n else backgroundStyle = BackgroundStyle::None;\n } else if (line.startsWith(\"color=\")) {\n backgroundColor = QColor(line.mid(6));\n } else if (line.startsWith(\"density=\")) {\n backgroundDensity = line.mid(8).toInt();\n }\n }\n file.close();\n }\n }\n\n // ✅ Check if the folder has a saved PDF path\n QString metadataFile = saveFolder + \"/.pdf_path.txt\";\n if (!QFile::exists(metadataFile)) {\n return;\n }\n\n\n QFile file(metadataFile);\n if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n return;\n }\n\n QTextStream in(&file);\n QString storedPdfPath = in.readLine().trimmed();\n file.close();\n\n if (storedPdfPath.isEmpty()) {\n return;\n }\n\n\n // ✅ Ensure the stored PDF file still exists before loading\n if (!QFile::exists(storedPdfPath)) {\n return;\n }\n loadPdf(storedPdfPath);\n}\n void saveToFile(int pageNumber) {\n if (saveFolder.isEmpty()) {\n return;\n }\n QString filePath = saveFolder + QString(\"/%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n\n // ✅ If no file exists and the buffer is empty, do nothing\n \n if (!edited) {\n return;\n }\n\n QImage image(buffer.size(), QImage::Format_ARGB32);\n image.fill(Qt::transparent);\n QPainter painter(&image);\n painter.drawPixmap(0, 0, buffer);\n image.save(filePath, \"PNG\");\n edited = false;\n \n // Save markdown windows for this page\n if (markdownManager) {\n markdownManager->saveWindowsForPage(pageNumber);\n }\n \n // Update note cache with the saved buffer\n noteCache.insert(pageNumber, new QPixmap(buffer));\n}\n void saveCurrentPage() {\n MainWindow *mainWin = qobject_cast(parentWidget()); // ✅ Get main window\n if (!mainWin) return;\n \n int currentPage = mainWin->getCurrentPageForCanvas(this); // ✅ Get correct page\n saveToFile(currentPage);\n}\n void loadPage(int pageNumber) {\n if (saveFolder.isEmpty()) return;\n\n // Hide any markdown windows from the previous page BEFORE loading the new page content.\n // This ensures the correct repaint area and stops the transparency timer.\n if (markdownManager) {\n markdownManager->hideAllWindows();\n }\n\n // Update current note page tracker\n currentCachedNotePage = pageNumber;\n\n // Check if note page is already cached\n bool loadedFromCache = false;\n if (noteCache.contains(pageNumber)) {\n // Use cached note page immediately\n buffer = *noteCache.object(pageNumber);\n loadedFromCache = true;\n } else {\n // Load note page from disk and cache it\n loadNotePageToCache(pageNumber);\n \n // Use the newly cached page or initialize buffer if loading failed\n if (noteCache.contains(pageNumber)) {\n buffer = *noteCache.object(pageNumber);\n loadedFromCache = true;\n } else {\n initializeBuffer(); // Clear the canvas if no file exists\n loadedFromCache = false;\n }\n }\n \n // Reset edited state when loading a new page\n edited = false;\n \n // Handle background image loading (PDF or custom background)\n if (isPdfLoaded && pdfDocument && pageNumber >= 0 && pageNumber < pdfDocument->numPages()) {\n // Use PDF as background (should already be cached by loadPdfPage)\n if (pdfCache.contains(pageNumber)) {\n backgroundImage = *pdfCache.object(pageNumber);\n \n // Resize canvas buffer to match PDF page size if needed\n if (backgroundImage.size() != buffer.size()) {\n QPixmap newBuffer(backgroundImage.size());\n newBuffer.fill(Qt::transparent);\n\n // Copy existing drawings\n QPainter painter(&newBuffer);\n painter.drawPixmap(0, 0, buffer);\n\n buffer = newBuffer;\n // Don't constrain widget size - let it expand to fill available space\n // The paintEvent will center the PDF content within the widget\n \n // Update cache with resized buffer\n noteCache.insert(pageNumber, new QPixmap(buffer));\n }\n }\n } else {\n // Handle custom background images\n QString bgFileName = saveFolder + QString(\"/bg_%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n QString metadataFile = saveFolder + QString(\"/.%1_bgsize_%2.txt\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n\n int bgWidth = 0, bgHeight = 0;\n if (QFile::exists(metadataFile)) {\n QFile file(metadataFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n in >> bgWidth >> bgHeight;\n file.close();\n }\n }\n\n if (QFile::exists(bgFileName)) {\n QImage bgImage(bgFileName);\n backgroundImage = QPixmap::fromImage(bgImage);\n\n // Resize canvas **only if background resolution is different**\n if (bgWidth > 0 && bgHeight > 0 && (bgWidth != width() || bgHeight != height())) {\n // Create a new buffer\n QPixmap newBuffer(bgWidth, bgHeight);\n newBuffer.fill(Qt::transparent);\n\n // Copy existing drawings to the new buffer\n QPainter painter(&newBuffer);\n painter.drawPixmap(0, 0, buffer);\n\n // Assign the new buffer\n buffer = newBuffer;\n setMaximumSize(bgWidth, bgHeight);\n \n // Update cache with resized buffer\n noteCache.insert(pageNumber, new QPixmap(buffer));\n }\n } else {\n backgroundImage = QPixmap(); // No background for this page\n // Only apply device pixel ratio fix if buffer was NOT loaded from cache\n // This prevents resizing cached buffers that might already be correctly sized\n if (!loadedFromCache) {\n QScreen *screen = QGuiApplication::primaryScreen();\n qreal dpr = screen ? screen->devicePixelRatio() : 1.0;\n QSize logicalSize = screen ? screen->size() : QSize(1440, 900);\n QSize expectedPixelSize = logicalSize * dpr;\n \n if (buffer.size() != expectedPixelSize) {\n // Buffer is wrong size, need to resize it properly\n QPixmap newBuffer(expectedPixelSize);\n newBuffer.fill(Qt::transparent);\n \n // Copy existing drawings if buffer was smaller\n if (!buffer.isNull()) {\n QPainter painter(&newBuffer);\n painter.drawPixmap(0, 0, buffer);\n }\n \n buffer = newBuffer;\n setMaximumSize(expectedPixelSize);\n }\n }\n }\n }\n\n // Cache adjacent note pages after delay for faster navigation\n checkAndCacheAdjacentNotePages(pageNumber);\n\n update();\n adjustSize(); // Force the widget to update its size\n parentWidget()->update();\n \n // Load markdown windows AFTER canvas is fully rendered and sized\n // Use a single-shot timer to ensure the canvas is fully updated\n QTimer::singleShot(0, this, [this, pageNumber]() {\n if (markdownManager) {\n markdownManager->loadWindowsForPage(pageNumber);\n }\n });\n}\n void deletePage(int pageNumber) {\n if (saveFolder.isEmpty()) {\n return;\n }\n QString fileName = saveFolder + QString(\"/%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n QString bgFileName = saveFolder + QString(\"/bg_%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n QString metadataFileName = saveFolder + QString(\"/.%1_bgsize_%2.txt\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n \n #ifdef Q_OS_WIN\n // Remove hidden attribute before deleting in Windows\n SetFileAttributesW(reinterpret_cast(metadataFileName.utf16()), FILE_ATTRIBUTE_NORMAL);\n #endif\n \n QFile::remove(fileName);\n QFile::remove(bgFileName);\n QFile::remove(metadataFileName);\n\n // Remove deleted page from note cache\n noteCache.remove(pageNumber);\n\n // Delete markdown windows for this page\n if (markdownManager) {\n markdownManager->deleteWindowsForPage(pageNumber);\n }\n\n if (pdfDocument){\n loadPdfPage(pageNumber);\n }\n else{\n loadPage(pageNumber);\n }\n\n}\n void setBackground(const QString &filePath, int pageNumber) {\n if (saveFolder.isEmpty()) {\n return; // No save folder set\n }\n\n // Construct full path inside save folder\n QString bgFileName = saveFolder + QString(\"/bg_%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n\n // Copy the file to the save folder\n QFile::copy(filePath, bgFileName);\n\n // Load the background image\n QImage bgImage(bgFileName);\n\n if (!bgImage.isNull()) {\n // Save background resolution in metadata file\n QString metadataFile = saveFolder + QString(\"/.%1_bgsize_%2.txt\")\n .arg(notebookId)\n .arg(pageNumber, 5, 10, QChar('0'));\n QFile file(metadataFile);\n if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {\n QTextStream out(&file);\n out << bgImage.width() << \" \" << bgImage.height();\n file.close();\n }\n\n #ifdef Q_OS_WIN\n // Set hidden attribute for metadata on Windows\n SetFileAttributesW(reinterpret_cast(metadataFile.utf16()), FILE_ATTRIBUTE_HIDDEN);\n #endif \n\n // Only resize if the background size is different\n if (bgImage.width() != width() || bgImage.height() != height()) {\n // Create a new buffer with the new size\n QPixmap newBuffer(bgImage.width(), bgImage.height());\n newBuffer.fill(Qt::transparent);\n\n // Copy existing drawings\n QPainter painter(&newBuffer);\n painter.drawPixmap(0, 0, buffer);\n\n // Assign new buffer and update canvas size\n buffer = newBuffer;\n setMaximumSize(bgImage.width(), bgImage.height());\n }\n\n backgroundImage = QPixmap::fromImage(bgImage);\n \n update();\n adjustSize();\n parentWidget()->update();\n }\n\n update(); // Refresh canvas\n}\n void saveAnnotated(int pageNumber) {\n if (saveFolder.isEmpty()) return;\n\n QString filePath = saveFolder + QString(\"/annotated_%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n\n // Use the buffer size to ensure correct resolution\n QImage image(buffer.size(), QImage::Format_ARGB32);\n image.fill(Qt::transparent);\n QPainter painter(&image);\n \n if (!backgroundImage.isNull()) {\n painter.drawPixmap(0, 0, backgroundImage.scaled(buffer.size(), Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation));\n }\n \n painter.drawPixmap(0, 0, buffer);\n image.save(filePath, \"PNG\");\n}\n void setZoom(int zoomLevel) {\n int newZoom = qMax(10, qMin(zoomLevel, 400)); // Limit zoom to 10%-400%\n if (zoomFactor != newZoom) {\n zoomFactor = newZoom;\n internalZoomFactor = zoomFactor; // Sync internal zoom\n update();\n emit zoomChanged(zoomFactor);\n }\n}\n int getZoom() const {\n return zoomFactor;\n}\n void updatePanOffsets(int xOffset, int yOffset) {\n panOffsetX = xOffset;\n panOffsetY = yOffset;\n update();\n}\n int getPanOffsetX() const {\n return panOffsetX;\n}\n int getPanOffsetY() const {\n return panOffsetY;\n}\n void setPanX(int xOffset) {\n if (panOffsetX != value) {\n panOffsetX = value;\n update();\n emit panChanged(panOffsetX, panOffsetY);\n }\n}\n void setPanY(int yOffset) {\n if (panOffsetY != value) {\n panOffsetY = value;\n update();\n emit panChanged(panOffsetX, panOffsetY);\n }\n}\n void loadPdf(const QString &pdfPath) {\n pdfDocument = Poppler::Document::load(pdfPath);\n if (pdfDocument && !pdfDocument->isLocked()) {\n // Enable anti-aliasing rendering hints for better text quality\n pdfDocument->setRenderHint(Poppler::Document::Antialiasing, true);\n pdfDocument->setRenderHint(Poppler::Document::TextAntialiasing, true);\n pdfDocument->setRenderHint(Poppler::Document::TextHinting, true);\n pdfDocument->setRenderHint(Poppler::Document::TextSlightHinting, true);\n \n totalPdfPages = pdfDocument->numPages();\n isPdfLoaded = true;\n totalPdfPages = pdfDocument->numPages();\n loadPdfPage(0); // Load first page\n // ✅ Save the PDF path in the metadata file\n if (!saveFolder.isEmpty()) {\n QString metadataFile = saveFolder + \"/.pdf_path.txt\";\n QFile file(metadataFile);\n if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {\n QTextStream out(&file);\n out << pdfPath; // Store the absolute path of the PDF\n file.close();\n }\n }\n // Emit signal that PDF was loaded\n emit pdfLoaded();\n }\n}\n void loadPdfPage(int pageNumber) {\n if (!pdfDocument) return;\n\n // Update current page tracker\n currentCachedPage = pageNumber;\n\n // Check if target page is already cached\n if (pdfCache.contains(pageNumber)) {\n // Display the cached page immediately\n backgroundImage = *pdfCache.object(pageNumber);\n loadPage(pageNumber); // Load annotations\n loadPdfTextBoxes(pageNumber); // Load text boxes for PDF text selection\n update();\n \n // Check and cache adjacent pages after delay\n checkAndCacheAdjacentPages(pageNumber);\n return;\n }\n\n // Target page not in cache - render it immediately\n renderPdfPageToCache(pageNumber);\n \n // Display the newly rendered page\n if (pdfCache.contains(pageNumber)) {\n backgroundImage = *pdfCache.object(pageNumber);\n } else {\n backgroundImage = QPixmap(); // Clear background if rendering failed\n }\n \n loadPage(pageNumber); // Load existing canvas annotations\n loadPdfTextBoxes(pageNumber); // Load text boxes for PDF text selection\n update();\n \n // Cache adjacent pages after delay\n checkAndCacheAdjacentPages(pageNumber);\n}\n bool isPdfLoadedFunc() const {\n return isPdfLoaded;\n}\n int getTotalPdfPages() const {\n return totalPdfPages;\n}\n Poppler::Document* getPdfDocument() const;\n void clearPdf() {\n pdfDocument.reset();\n pdfDocument = nullptr;\n isPdfLoaded = false;\n totalPdfPages = 0;\n pdfCache.clear();\n \n // Reset cache system state\n currentCachedPage = -1;\n if (pdfCacheTimer && pdfCacheTimer->isActive()) {\n pdfCacheTimer->stop();\n }\n \n // Cancel and clean up any active PDF watchers\n for (QFutureWatcher* watcher : activePdfWatchers) {\n if (watcher && !watcher->isFinished()) {\n watcher->cancel();\n }\n watcher->deleteLater();\n }\n activePdfWatchers.clear();\n\n // ✅ Remove the PDF path file when clearing the PDF\n if (!saveFolder.isEmpty()) {\n QString metadataFile = saveFolder + \"/.pdf_path.txt\";\n QFile::remove(metadataFile);\n }\n}\n void clearPdfNoDelete() {\n pdfDocument.reset();\n pdfDocument = nullptr;\n isPdfLoaded = false;\n totalPdfPages = 0;\n pdfCache.clear();\n \n // Reset cache system state\n currentCachedPage = -1;\n if (pdfCacheTimer && pdfCacheTimer->isActive()) {\n pdfCacheTimer->stop();\n }\n \n // Cancel and clean up any active PDF watchers\n for (QFutureWatcher* watcher : activePdfWatchers) {\n if (watcher && !watcher->isFinished()) {\n watcher->cancel();\n }\n watcher->deleteLater();\n }\n activePdfWatchers.clear();\n}\n QString getSaveFolder() const {\n return saveFolder;\n}\n QColor getPenColor() {\n return penColor;\n}\n qreal getPenThickness() {\n return penThickness;\n}\n ToolType getCurrentTool() {\n return currentTool;\n}\n void loadPdfPreviewAsync(int pageNumber) {\n if (!pdfDocument || pageNumber < 0 || pageNumber >= pdfDocument->numPages()) return;\n\n QFutureWatcher *watcher = new QFutureWatcher(this);\n\n connect(watcher, &QFutureWatcher::finished, this, [this, watcher]() {\n QPixmap result = watcher->result();\n if (!result.isNull()) {\n backgroundImage = result;\n update(); // trigger repaint\n }\n watcher->deleteLater(); // Clean up\n });\n\n QFuture future = QtConcurrent::run([=]() -> QPixmap {\n std::unique_ptr page(pdfDocument->page(pageNumber));\n if (!page) return QPixmap();\n\n // Render with document-level anti-aliasing settings\n QImage pdfImage = page->renderToImage(96, 96);\n if (pdfImage.isNull()) return QPixmap();\n\n QImage upscaled = pdfImage.scaled(pdfImage.width() * (pdfRenderDPI / 96),\n pdfImage.height() * (pdfRenderDPI / 96),\n Qt::KeepAspectRatio,\n Qt::SmoothTransformation);\n\n return QPixmap::fromImage(upscaled);\n });\n\n watcher->setFuture(future);\n}\n void setBackgroundStyle(BackgroundStyle style) {\n backgroundStyle = style;\n update(); // Trigger repaint\n}\n void setBackgroundColor(const QColor &color) {\n backgroundColor = color;\n update();\n}\n void setBackgroundDensity(int density) {\n backgroundDensity = density;\n update();\n}\n void saveBackgroundMetadata() {\n if (saveFolder.isEmpty()) return;\n\n QString bgMetaFile = saveFolder + \"/.background_config.txt\";\n QFile file(bgMetaFile);\n if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {\n QTextStream out(&file);\n QString styleStr = \"None\";\n if (backgroundStyle == BackgroundStyle::Grid) styleStr = \"Grid\";\n else if (backgroundStyle == BackgroundStyle::Lines) styleStr = \"Lines\";\n\n out << \"style=\" << styleStr << \"\\n\";\n out << \"color=\" << backgroundColor.name().toUpper() << \"\\n\";\n out << \"density=\" << backgroundDensity << \"\\n\";\n file.close();\n }\n}\n void exportNotebook(const QString &destinationFile) {\n if (destinationFile.isEmpty()) {\n QMessageBox::warning(nullptr, tr(\"Export Error\"), tr(\"No export file specified.\"));\n return;\n }\n\n if (saveFolder.isEmpty()) {\n QMessageBox::warning(nullptr, tr(\"Export Error\"), tr(\"No notebook loaded (saveFolder is empty)\"));\n return;\n }\n\n QStringList files;\n\n // Collect all files from saveFolder\n QDir dir(saveFolder);\n QDirIterator it(saveFolder, QDir::Files, QDirIterator::Subdirectories);\n while (it.hasNext()) {\n QString filePath = it.next();\n QString relativePath = dir.relativeFilePath(filePath);\n files << relativePath;\n }\n\n if (files.isEmpty()) {\n QMessageBox::warning(nullptr, tr(\"Export Error\"), tr(\"No files found to export.\"));\n return;\n }\n\n // Generate temporary file list\n QString tempFileList = saveFolder + \"/filelist.txt\";\n QFile listFile(tempFileList);\n if (listFile.open(QIODevice::WriteOnly | QIODevice::Text)) {\n QTextStream out(&listFile);\n for (const QString &file : files) {\n out << file << \"\\n\";\n }\n listFile.close();\n } else {\n QMessageBox::warning(nullptr, tr(\"Export Error\"), tr(\"Failed to create temporary file list.\"));\n return;\n }\n\n#ifdef _WIN32\n QString tarExe = QCoreApplication::applicationDirPath() + \"/bsdtar.exe\";\n#else\n QString tarExe = \"tar\";\n#endif\n\n QStringList args;\n args << \"-cf\" << QDir::toNativeSeparators(destinationFile);\n\n for (const QString &file : files) {\n args << QDir::toNativeSeparators(file);\n }\n\n QProcess process;\n process.setWorkingDirectory(saveFolder);\n\n process.start(tarExe, args);\n if (!process.waitForFinished()) {\n QMessageBox::warning(nullptr, tr(\"Export Error\"), tr(\"Tar process failed to finish.\"));\n QFile::remove(tempFileList);\n return;\n }\n\n QFile::remove(tempFileList);\n\n if (process.exitStatus() != QProcess::NormalExit || process.exitCode() != 0) {\n QMessageBox::warning(nullptr, tr(\"Export Error\"), tr(\"Tar process failed.\"));\n return;\n }\n\n QMessageBox::information(nullptr, tr(\"Export\"), tr(\"Notebook exported successfully.\"));\n}\n void importNotebook(const QString &packageFile) {\n\n // Ask user for destination working folder\n QString destFolder = QFileDialog::getExistingDirectory(nullptr, tr(\"Select Destination Folder for Imported Notebook\"));\n\n if (destFolder.isEmpty()) {\n QMessageBox::warning(nullptr, tr(\"Import Canceled\"), tr(\"No destination folder selected.\"));\n return;\n }\n\n // Check if destination folder is empty (optional, good practice)\n QDir destDir(destFolder);\n if (!destDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot).isEmpty()) {\n QMessageBox::StandardButton reply = QMessageBox::question(nullptr, tr(\"Destination Not Empty\"),\n tr(\"The selected folder is not empty. Files may be overwritten. Continue?\"),\n QMessageBox::Yes | QMessageBox::No);\n if (reply != QMessageBox::Yes) {\n return;\n }\n }\n\n#ifdef _WIN32\n QString tarExe = QCoreApplication::applicationDirPath() + \"/bsdtar.exe\";\n#else\n QString tarExe = \"tar\";\n#endif\n\n // Extract package\n QStringList args;\n args << \"-xf\" << packageFile;\n\n QProcess process;\n process.setWorkingDirectory(destFolder);\n process.start(tarExe, args);\n process.waitForFinished();\n\n // Switch notebook folder\n setSaveFolder(destFolder);\n loadPage(0);\n\n QMessageBox::information(nullptr, tr(\"Import Complete\"), tr(\"Notebook imported successfully.\"));\n}\n void importNotebookTo(const QString &packageFile, const QString &destFolder) {\n\n #ifdef _WIN32\n QString tarExe = QCoreApplication::applicationDirPath() + \"/bsdtar.exe\";\n #else\n QString tarExe = \"tar\";\n #endif\n \n QStringList args;\n args << \"-xf\" << packageFile;\n \n QProcess process;\n process.setWorkingDirectory(destFolder);\n process.start(tarExe, args);\n process.waitForFinished();\n \n setSaveFolder(destFolder);\n loadNotebookId();\n loadPage(0);\n\n QMessageBox::information(nullptr, tr(\"Import\"), tr(\"Notebook imported successfully.\"));\n }\n void deleteRopeSelection() {\n if (!selectionBuffer.isNull() && !selectionRect.isEmpty()) {\n // If the selection area hasn't been cleared from the buffer yet, clear it now for deletion\n if (!selectionAreaCleared && !selectionMaskPath.isEmpty()) {\n QPainter painter(&buffer);\n painter.setCompositionMode(QPainter::CompositionMode_Clear);\n painter.fillPath(selectionMaskPath, Qt::transparent);\n painter.end();\n }\n \n // Clear the selection state\n selectionBuffer = QPixmap();\n selectionRect = QRect();\n exactSelectionRectF = QRectF();\n movingSelection = false;\n selectingWithRope = false;\n selectionJustCopied = false;\n selectionAreaCleared = false;\n selectionMaskPath = QPainterPath();\n selectionBufferRect = QRectF();\n \n // Mark as edited since we deleted content\n if (!edited) {\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n \n // Update the entire canvas to remove selection visuals\n update();\n }\n}\n void cancelRopeSelection() {\n if (!selectionBuffer.isNull() && !selectionRect.isEmpty()) {\n // Paste the selection back to its current location (where user moved it)\n QPainter painter(&buffer);\n // Explicitly set composition mode to draw on top of existing content\n painter.setCompositionMode(QPainter::CompositionMode_SourceOver);\n // Use the current selection position\n QPointF currentTopLeft = exactSelectionRectF.isEmpty() ? selectionRect.topLeft() : exactSelectionRectF.topLeft();\n QPointF bufferDest = mapLogicalWidgetToPhysicalBuffer(currentTopLeft);\n painter.drawPixmap(bufferDest.toPoint(), selectionBuffer);\n painter.end();\n \n // Store selection buffer size for update calculation before clearing it\n QSize selectionSize = selectionBuffer.size();\n QRect updateRect = QRect(currentTopLeft.toPoint(), selectionSize);\n \n // Clear the selection state\n selectionBuffer = QPixmap();\n selectionRect = QRect();\n exactSelectionRectF = QRectF();\n movingSelection = false;\n selectingWithRope = false;\n selectionJustCopied = false;\n selectionAreaCleared = false;\n selectionMaskPath = QPainterPath();\n selectionBufferRect = QRectF();\n \n // Update the restored area\n update(updateRect.adjusted(-5, -5, 5, 5));\n }\n}\n void copyRopeSelection() {\n if (!selectionBuffer.isNull() && !selectionRect.isEmpty()) {\n // Get current selection position\n QPointF currentTopLeft = exactSelectionRectF.isEmpty() ? selectionRect.topLeft() : exactSelectionRectF.topLeft();\n \n // Calculate new position (right next to the original), but ensure it stays within canvas bounds\n QPointF newTopLeft = currentTopLeft + QPointF(selectionRect.width() + 5, 0); // 5 pixels gap\n \n // Check if the new position would extend beyond buffer boundaries and adjust if needed\n QPointF currentBufferDest = mapLogicalWidgetToPhysicalBuffer(currentTopLeft);\n QPointF newBufferDest = mapLogicalWidgetToPhysicalBuffer(newTopLeft);\n \n // Ensure the copy stays within buffer bounds\n if (newBufferDest.x() + selectionBuffer.width() > buffer.width()) {\n // If it would extend beyond right edge, place it to the left of the original\n newTopLeft = currentTopLeft - QPointF(selectionRect.width() + 5, 0);\n newBufferDest = mapLogicalWidgetToPhysicalBuffer(newTopLeft);\n \n // If it still doesn't fit on the left, place it below the original\n if (newBufferDest.x() < 0) {\n newTopLeft = currentTopLeft + QPointF(0, selectionRect.height() + 5);\n newBufferDest = mapLogicalWidgetToPhysicalBuffer(newTopLeft);\n \n // If it doesn't fit below either, place it above\n if (newBufferDest.y() + selectionBuffer.height() > buffer.height()) {\n newTopLeft = currentTopLeft - QPointF(0, selectionRect.height() + 5);\n newBufferDest = mapLogicalWidgetToPhysicalBuffer(newTopLeft);\n \n // If none of the positions work, just offset slightly and let it extend\n if (newBufferDest.y() < 0) {\n newTopLeft = currentTopLeft + QPointF(10, 10);\n newBufferDest = mapLogicalWidgetToPhysicalBuffer(newTopLeft);\n }\n }\n }\n }\n if (newBufferDest.y() + selectionBuffer.height() > buffer.height()) {\n // If it would extend beyond bottom edge, place it above the original\n newTopLeft = currentTopLeft - QPointF(0, selectionRect.height() + 5);\n newBufferDest = mapLogicalWidgetToPhysicalBuffer(newTopLeft);\n }\n \n // First, paste the selection back to its current location to restore the original\n QPainter painter(&buffer);\n // Explicitly set composition mode to draw on top of existing content\n painter.setCompositionMode(QPainter::CompositionMode_SourceOver);\n painter.drawPixmap(currentBufferDest.toPoint(), selectionBuffer);\n \n // Then, paste the copy to the new location\n // We need to handle the case where the copy extends beyond buffer boundaries\n QRect targetRect(newBufferDest.toPoint(), selectionBuffer.size());\n QRect bufferBounds(0, 0, buffer.width(), buffer.height());\n QRect clippedRect = targetRect.intersected(bufferBounds);\n \n if (!clippedRect.isEmpty()) {\n // Calculate which part of the selectionBuffer to draw\n QRect sourceRect = QRect(\n clippedRect.x() - targetRect.x(),\n clippedRect.y() - targetRect.y(),\n clippedRect.width(),\n clippedRect.height()\n );\n \n painter.drawPixmap(clippedRect, selectionBuffer, sourceRect);\n }\n \n // For the selection buffer, we keep the FULL content, even if parts extend beyond canvas\n // This way when the user drags it back, the full content is preserved\n QPixmap newSelectionBuffer = selectionBuffer; // Keep the full original content\n \n // DON'T clear the copied area immediately - leave both original and copy on the canvas\n // The copy will only be cleared when the user actually starts moving the selection\n // This way, if the user cancels without moving, both original and copy remain permanently\n painter.end();\n \n // Update the selection buffer and position\n selectionBuffer = newSelectionBuffer;\n selectionRect = QRect(newTopLeft.toPoint(), selectionRect.size());\n exactSelectionRectF = QRectF(newTopLeft, selectionRect.size());\n selectionJustCopied = true; // Mark that this selection was just copied\n \n // Mark as edited since we added content\n if (!edited) {\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n \n // Update the entire affected area (original + copy + gap)\n QRect updateArea = QRect(currentTopLeft.toPoint(), selectionRect.size())\n .united(selectionRect)\n .adjusted(-10, -10, 10, 10);\n update(updateArea);\n }\n}\n void setMarkdownSelectionMode(bool enabled) {\n markdownSelectionMode = enabled;\n \n if (markdownManager) {\n markdownManager->setSelectionMode(enabled);\n }\n \n if (!enabled) {\n markdownSelecting = false;\n }\n \n // Update cursor\n setCursor(enabled ? Qt::CrossCursor : Qt::ArrowCursor);\n \n // Notify signal\n emit markdownSelectionModeChanged(enabled);\n}\n bool isMarkdownSelectionMode() const {\n return markdownSelectionMode;\n}\n void clearPdfTextSelection() {\n // Clear selection state\n selectedTextBoxes.clear();\n pdfTextSelecting = false;\n \n // Cancel any pending throttled updates\n if (pdfTextSelectionTimer && pdfTextSelectionTimer->isActive()) {\n pdfTextSelectionTimer->stop();\n }\n hasPendingSelection = false;\n \n // Refresh display\n update();\n}\n QString getSelectedPdfText() const {\n if (selectedTextBoxes.isEmpty()) {\n return QString();\n }\n \n // Pre-allocate string with estimated size for efficiency\n QString selectedText;\n selectedText.reserve(selectedTextBoxes.size() * 20); // Estimate ~20 chars per text box\n \n // Build text with space separators\n for (const Poppler::TextBox* textBox : selectedTextBoxes) {\n if (textBox && !textBox->text().isEmpty()) {\n if (!selectedText.isEmpty()) {\n selectedText += \" \";\n }\n selectedText += textBox->text();\n }\n }\n \n return selectedText;\n}\n QPointF mapWidgetToCanvas(const QPointF &widgetPoint) const {\n QPointF topLeft = mapWidgetToCanvas(widgetRect.topLeft());\n QPointF bottomRight = mapWidgetToCanvas(widgetRect.bottomRight());\n \n return QRect(topLeft.toPoint(), bottomRight.toPoint());\n}\n QPointF mapCanvasToWidget(const QPointF &canvasPoint) const {\n QPointF topLeft = mapCanvasToWidget(canvasRect.topLeft());\n QPointF bottomRight = mapCanvasToWidget(canvasRect.bottomRight());\n \n return QRect(topLeft.toPoint(), bottomRight.toPoint());\n}\n QRect mapWidgetToCanvas(const QRect &widgetRect) const {\n QPointF topLeft = mapWidgetToCanvas(widgetRect.topLeft());\n QPointF bottomRight = mapWidgetToCanvas(widgetRect.bottomRight());\n \n return QRect(topLeft.toPoint(), bottomRight.toPoint());\n}\n QRect mapCanvasToWidget(const QRect &canvasRect) const {\n QPointF topLeft = mapCanvasToWidget(canvasRect.topLeft());\n QPointF bottomRight = mapCanvasToWidget(canvasRect.bottomRight());\n \n return QRect(topLeft.toPoint(), bottomRight.toPoint());\n}\n protected:\n void paintEvent(QPaintEvent *event) override {\n QPainter painter(this);\n \n // Save the painter state before transformations\n painter.save();\n \n // Calculate the scaled canvas size\n qreal scaledCanvasWidth = buffer.width() * (internalZoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (internalZoomFactor / 100.0);\n \n // Calculate centering offsets\n qreal centerOffsetX = 0;\n qreal centerOffsetY = 0;\n \n // Center horizontally if canvas is smaller than widget\n if (scaledCanvasWidth < width()) {\n centerOffsetX = (width() - scaledCanvasWidth) / 2.0;\n }\n \n // Center vertically if canvas is smaller than widget\n if (scaledCanvasHeight < height()) {\n centerOffsetY = (height() - scaledCanvasHeight) / 2.0;\n }\n \n // Apply centering offset first\n painter.translate(centerOffsetX, centerOffsetY);\n \n // Use internal zoom factor for smoother animation\n painter.scale(internalZoomFactor / 100.0, internalZoomFactor / 100.0);\n\n // Pan offset needs to be reversed because painter works in transformed coordinates\n painter.translate(-panOffsetX, -panOffsetY);\n\n // Set clipping rectangle to canvas bounds to prevent painting outside\n painter.setClipRect(0, 0, buffer.width(), buffer.height());\n\n // 🟨 Notebook-style background rendering\n if (backgroundImage.isNull()) {\n painter.save();\n \n // Always apply background color regardless of style\n painter.fillRect(QRectF(0, 0, buffer.width(), buffer.height()), backgroundColor);\n\n // Only draw grid/lines if not \"None\" style\n if (backgroundStyle != BackgroundStyle::None) {\n QPen linePen(QColor(100, 100, 100, 100)); // Subtle gray lines\n linePen.setWidthF(1.0);\n painter.setPen(linePen);\n\n qreal scaledDensity = backgroundDensity;\n\n if (devicePixelRatioF() > 1.0)\n scaledDensity *= devicePixelRatioF(); // Optional DPI handling\n\n if (backgroundStyle == BackgroundStyle::Lines || backgroundStyle == BackgroundStyle::Grid) {\n for (int y = 0; y < buffer.height(); y += scaledDensity)\n painter.drawLine(0, y, buffer.width(), y);\n }\n if (backgroundStyle == BackgroundStyle::Grid) {\n for (int x = 0; x < buffer.width(); x += scaledDensity)\n painter.drawLine(x, 0, x, buffer.height());\n }\n }\n\n painter.restore();\n }\n\n // ✅ Draw loaded image or PDF background if available\n if (!backgroundImage.isNull()) {\n painter.drawPixmap(0, 0, backgroundImage);\n }\n\n // ✅ Draw user's strokes from the buffer (transparent overlay)\n painter.drawPixmap(0, 0, buffer);\n \n // Draw straight line preview if in straight line mode and drawing\n // Skip preview for eraser tool\n if (straightLineMode && drawing && currentTool != ToolType::Eraser) {\n // Save the current state before applying the eraser mode\n painter.save();\n \n // Store current pressure - ensure minimum is 0.5 for consistent preview\n qreal pressure = qMax(0.5, painter.device()->devicePixelRatioF() > 1.0 ? 0.8 : 1.0);\n \n // Set up the pen based on tool type\n if (currentTool == ToolType::Marker) {\n qreal thickness = penThickness * 8.0;\n QColor markerColor = penColor;\n // Increase alpha for better visibility in straight line mode\n // Using a higher value (80) instead of the regular 4 to compensate for single-pass drawing\n markerColor.setAlpha(80);\n QPen pen(markerColor, thickness, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);\n painter.setPen(pen);\n } else { // Default Pen\n // Match the exact same thickness calculation as in drawStroke\n qreal scaledThickness = penThickness * pressure;\n QPen pen(penColor, scaledThickness, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);\n painter.setPen(pen);\n }\n \n // Use the same coordinate transformation logic as in drawStroke\n // to ensure the preview line appears at the exact same position\n QPointF bufferStart, bufferEnd;\n \n // Convert screen coordinates to buffer coordinates using the same calculations as drawStroke\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n QPointF adjustedStart = straightLineStartPoint - QPointF(centerOffsetX, centerOffsetY);\n QPointF adjustedEnd = lastPoint - QPointF(centerOffsetX, centerOffsetY);\n \n bufferStart = (adjustedStart / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n bufferEnd = (adjustedEnd / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n \n // Draw the preview line using the same coordinates that will be used for the final line\n painter.drawLine(bufferStart, bufferEnd);\n \n // Restore the original painter state\n painter.restore();\n }\n\n // Draw selection rectangle if in rope tool mode and selecting, moving, or has a selection\n if (ropeToolMode && (selectingWithRope || movingSelection || (!selectionBuffer.isNull() && !selectionRect.isEmpty()))) {\n painter.save(); // Save painter state for overlays\n painter.resetTransform(); // Reset transform to draw directly in logical widget coordinates\n \n if (selectingWithRope && !lassoPathPoints.isEmpty()) {\n QPen selectionPen(Qt::DashLine);\n selectionPen.setColor(Qt::blue);\n selectionPen.setWidthF(1.5); // Width in logical pixels\n painter.setPen(selectionPen);\n painter.drawPolygon(lassoPathPoints); // lassoPathPoints are logical widget coordinates\n } else if (!selectionBuffer.isNull() && !selectionRect.isEmpty()) {\n // selectionRect is in logical widget coordinates.\n // selectionBuffer is in buffer coordinates, we need to handle scaling correctly\n QPixmap scaledBuffer = selectionBuffer;\n \n // Calculate the current zoom factor\n qreal currentZoom = internalZoomFactor / 100.0;\n \n // Scale the selection buffer to match the current zoom level\n if (currentZoom != 1.0) {\n QSize scaledSize = QSize(\n qRound(scaledBuffer.width() * currentZoom),\n qRound(scaledBuffer.height() * currentZoom)\n );\n scaledBuffer = scaledBuffer.scaled(scaledSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);\n }\n \n // Draw it at the logical position\n // Use exactSelectionRectF for smoother movement if available\n QPointF topLeft = exactSelectionRectF.isEmpty() ? selectionRect.topLeft() : exactSelectionRectF.topLeft();\n painter.drawPixmap(topLeft, scaledBuffer);\n\n QPen selectionBorderPen(Qt::DashLine);\n selectionBorderPen.setColor(Qt::darkCyan);\n selectionBorderPen.setWidthF(1.5); // Width in logical pixels\n painter.setPen(selectionBorderPen);\n \n // Use exactSelectionRectF for drawing the selection border if available\n if (!exactSelectionRectF.isEmpty()) {\n painter.drawRect(exactSelectionRectF);\n } else {\n painter.drawRect(selectionRect);\n }\n }\n painter.restore(); // Restore painter state to what it was for drawing the main buffer\n }\n \n\n \n\n \n // Restore the painter state\n painter.restore();\n \n // Fill the area outside the canvas with the widget's background color\n QRect widgetRect = rect();\n QRectF canvasRect(\n centerOffsetX - panOffsetX * (internalZoomFactor / 100.0),\n centerOffsetY - panOffsetY * (internalZoomFactor / 100.0),\n buffer.width() * (internalZoomFactor / 100.0),\n buffer.height() * (internalZoomFactor / 100.0)\n );\n \n // Create regions for areas outside the canvas\n QRegion outsideRegion(widgetRect);\n outsideRegion -= QRegion(canvasRect.toRect());\n \n // Fill the outside region with the background color\n painter.setClipRegion(outsideRegion);\n painter.fillRect(widgetRect, palette().window().color());\n \n // Reset clipping for overlay elements that should appear on top\n painter.setClipping(false);\n \n // Draw markdown selection overlay\n if (markdownSelectionMode && markdownSelecting) {\n painter.save();\n QPen selectionPen(Qt::DashLine);\n selectionPen.setColor(Qt::green);\n selectionPen.setWidthF(2.0);\n painter.setPen(selectionPen);\n \n QBrush selectionBrush(QColor(0, 255, 0, 30)); // Semi-transparent green\n painter.setBrush(selectionBrush);\n \n QRect selectionRect = QRect(markdownSelectionStart, markdownSelectionEnd).normalized();\n painter.drawRect(selectionRect);\n painter.restore();\n }\n \n // Draw PDF text selection overlay on top of everything\n if (pdfTextSelectionEnabled && isPdfLoaded) {\n painter.save(); // Save painter state for PDF text overlay\n painter.resetTransform(); // Reset transform to draw directly in logical widget coordinates\n \n // Draw selection rectangle if actively selecting\n if (pdfTextSelecting) {\n QPen selectionPen(Qt::DashLine);\n selectionPen.setColor(QColor(0, 120, 215)); // Blue selection rectangle\n selectionPen.setWidthF(2.0); // Make it more visible\n painter.setPen(selectionPen);\n \n QBrush selectionBrush(QColor(0, 120, 215, 30)); // Semi-transparent blue fill\n painter.setBrush(selectionBrush);\n \n QRectF selectionRect(pdfSelectionStart, pdfSelectionEnd);\n selectionRect = selectionRect.normalized();\n painter.drawRect(selectionRect);\n }\n \n // Draw highlights for selected text boxes\n if (!selectedTextBoxes.isEmpty()) {\n QColor highlightColor = QColor(255, 255, 0, 100); // Semi-transparent yellow\n painter.setBrush(highlightColor);\n painter.setPen(Qt::NoPen);\n \n // Draw highlight rectangles for selected text boxes\n for (const Poppler::TextBox* textBox : selectedTextBoxes) {\n if (textBox) {\n // Convert PDF coordinates to widget coordinates\n QRectF pdfRect = textBox->boundingBox();\n QPointF topLeft = mapPdfToWidgetCoordinates(pdfRect.topLeft());\n QPointF bottomRight = mapPdfToWidgetCoordinates(pdfRect.bottomRight());\n QRectF widgetRect(topLeft, bottomRight);\n widgetRect = widgetRect.normalized();\n \n painter.drawRect(widgetRect);\n }\n }\n }\n \n painter.restore(); // Restore painter state\n }\n}\n void tabletEvent(QTabletEvent *event) override {\n // ✅ PRIORITY: Handle PDF text selection with stylus when enabled\n // This redirects stylus input to text selection instead of drawing\n if (pdfTextSelectionEnabled && isPdfLoaded) {\n if (event->type() == QEvent::TabletPress) {\n pdfTextSelecting = true;\n pdfSelectionStart = event->position();\n pdfSelectionEnd = pdfSelectionStart;\n \n // Clear any existing selected text boxes without resetting pdfTextSelecting\n selectedTextBoxes.clear();\n \n setCursor(Qt::IBeamCursor); // Ensure cursor is correct\n update(); // Refresh display\n event->accept();\n return;\n } else if (event->type() == QEvent::TabletMove && pdfTextSelecting) {\n pdfSelectionEnd = event->position();\n \n // Store pending selection for throttled processing (60 FPS throttling)\n pendingSelectionStart = pdfSelectionStart;\n pendingSelectionEnd = pdfSelectionEnd;\n hasPendingSelection = true;\n \n // Start timer if not already running (throttled to 60 FPS)\n if (!pdfTextSelectionTimer->isActive()) {\n pdfTextSelectionTimer->start();\n }\n \n // NOTE: No direct update() call here - let the timer handle updates at 60 FPS\n event->accept();\n return;\n } else if (event->type() == QEvent::TabletRelease && pdfTextSelecting) {\n pdfSelectionEnd = event->position();\n \n // Process any pending selection immediately on release\n if (pdfTextSelectionTimer && pdfTextSelectionTimer->isActive()) {\n pdfTextSelectionTimer->stop();\n if (hasPendingSelection) {\n updatePdfTextSelection(pendingSelectionStart, pendingSelectionEnd);\n hasPendingSelection = false;\n }\n } else {\n // Update selection with final position\n updatePdfTextSelection(pdfSelectionStart, pdfSelectionEnd);\n }\n \n pdfTextSelecting = false;\n \n // Check for link clicks if no text was selected\n QString selectedText = getSelectedPdfText();\n if (selectedText.isEmpty()) {\n handlePdfLinkClick(event->position());\n } else {\n // Show context menu for text selection\n QPoint globalPos = mapToGlobal(event->position().toPoint());\n showPdfTextSelectionMenu(globalPos);\n }\n \n event->accept();\n return;\n }\n }\n \n // ✅ NORMAL STYLUS BEHAVIOR: Only reached when PDF text selection is OFF\n // Hardware eraser detection\n static bool hardwareEraserActive = false;\n bool wasUsingHardwareEraser = false;\n \n // Track hardware eraser state\n if (event->pointerType() == QPointingDevice::PointerType::Eraser) {\n // Hardware eraser is being used\n wasUsingHardwareEraser = true;\n \n if (event->type() == QEvent::TabletPress) {\n // Start of eraser stroke - save current tool and switch to eraser\n hardwareEraserActive = true;\n previousTool = currentTool;\n currentTool = ToolType::Eraser;\n }\n }\n \n // Maintain hardware eraser state across move events\n if (hardwareEraserActive && event->type() != QEvent::TabletRelease) {\n wasUsingHardwareEraser = true;\n }\n\n // Determine if we're in eraser mode (either hardware eraser or tool set to eraser)\n bool isErasing = (currentTool == ToolType::Eraser);\n\n if (event->type() == QEvent::TabletPress) {\n drawing = true;\n lastPoint = event->posF(); // Logical widget coordinates\n if (straightLineMode) {\n straightLineStartPoint = lastPoint;\n }\n if (ropeToolMode) {\n if (!selectionBuffer.isNull() && selectionRect.contains(lastPoint.toPoint())) {\n // Start moving an existing selection (or continue if already moving)\n movingSelection = true;\n selectingWithRope = false;\n lastMovePoint = lastPoint;\n // Initialize the exact floating-point rect if it's empty\n if (exactSelectionRectF.isEmpty()) {\n exactSelectionRectF = QRectF(selectionRect);\n }\n \n // If this selection was just copied, clear the area now that user is moving it\n if (selectionJustCopied) {\n QPainter painter(&buffer);\n painter.setCompositionMode(QPainter::CompositionMode_Clear);\n QPointF bufferDest = mapLogicalWidgetToPhysicalBuffer(selectionRect.topLeft());\n QRect clearRect(bufferDest.toPoint(), selectionBuffer.size());\n // Only clear the part that's within buffer bounds\n QRect bufferBounds(0, 0, buffer.width(), buffer.height());\n QRect clippedClearRect = clearRect.intersected(bufferBounds);\n if (!clippedClearRect.isEmpty()) {\n painter.fillRect(clippedClearRect, Qt::transparent);\n }\n painter.end();\n selectionJustCopied = false; // Clear the flag\n }\n \n // If the selection area hasn't been cleared from the buffer yet, clear it now\n if (!selectionAreaCleared && !selectionMaskPath.isEmpty()) {\n QPainter painter(&buffer);\n painter.setCompositionMode(QPainter::CompositionMode_Clear);\n painter.fillPath(selectionMaskPath, Qt::transparent);\n painter.end();\n selectionAreaCleared = true;\n }\n // selectionBuffer already has the content.\n // The original area in 'buffer' was already cleared when selection was made.\n } else {\n // Start a new selection or cancel existing one\n if (!selectionBuffer.isNull()) { // If there's an active selection, a tap outside cancels it\n selectionBuffer = QPixmap();\n selectionRect = QRect();\n lassoPathPoints.clear();\n movingSelection = false;\n selectingWithRope = false;\n selectionJustCopied = false;\n selectionAreaCleared = false;\n selectionMaskPath = QPainterPath();\n selectionBufferRect = QRectF();\n update(); // Full update to remove old selection visuals\n drawing = false; // Consumed this press for cancel\n return;\n }\n selectingWithRope = true;\n movingSelection = false;\n selectionJustCopied = false;\n selectionAreaCleared = false;\n selectionMaskPath = QPainterPath();\n selectionBufferRect = QRectF();\n lassoPathPoints.clear();\n lassoPathPoints << lastPoint; // Start the lasso path\n selectionRect = QRect();\n selectionBuffer = QPixmap();\n }\n }\n } else if (event->type() == QEvent::TabletMove && drawing) {\n if (ropeToolMode) {\n if (selectingWithRope) {\n QRectF oldPreviewBoundingRect = lassoPathPoints.boundingRect();\n lassoPathPoints << event->posF();\n lastPoint = event->posF();\n QRectF newPreviewBoundingRect = lassoPathPoints.boundingRect();\n // Update the area of the selection rectangle preview (logical widget coordinates)\n update(oldPreviewBoundingRect.united(newPreviewBoundingRect).toRect().adjusted(-5,-5,5,5));\n } else if (movingSelection) {\n QPointF delta = event->posF() - lastMovePoint; // Delta in logical widget coordinates\n QRect oldWidgetSelectionRect = selectionRect;\n \n // Update the exact floating-point rectangle first\n exactSelectionRectF.translate(delta);\n \n // Convert back to integer rect, but only when the position actually changes\n QRect newRect = exactSelectionRectF.toRect();\n if (newRect != selectionRect) {\n selectionRect = newRect;\n // Update the combined area of the old and new selection positions (logical widget coordinates)\n update(oldWidgetSelectionRect.united(selectionRect).adjusted(-2,-2,2,2));\n } else {\n // Even if the integer position didn't change, we still need to update\n // to make movement feel smoother, especially with slow movements\n update(selectionRect.adjusted(-2,-2,2,2));\n }\n \n lastMovePoint = event->posF();\n if (!edited){\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n }\n } else if (straightLineMode && !isErasing) {\n // For straight line mode with non-eraser tools, just update the last position\n // and trigger a repaint of only the affected area for preview\n static QElapsedTimer updateTimer;\n static bool timerInitialized = false;\n \n if (!timerInitialized) {\n updateTimer.start();\n timerInitialized = true;\n }\n \n // Throttle updates based on time for high CPU usage tools\n bool shouldUpdate = true;\n \n // Apply throttling for marker which can be CPU intensive\n if (currentTool == ToolType::Marker) {\n shouldUpdate = updateTimer.elapsed() > 16; // Only update every 16ms (approx 60fps)\n }\n \n if (shouldUpdate) {\n QPointF oldLastPoint = lastPoint;\n lastPoint = event->posF();\n \n // Calculate affected rectangle that needs updating\n QRectF updateRect = calculatePreviewRect(straightLineStartPoint, oldLastPoint, lastPoint);\n update(updateRect.toRect());\n \n // Reset timer\n updateTimer.restart();\n } else {\n // Just update the last point without redrawing\n lastPoint = event->posF();\n }\n } else if (straightLineMode && isErasing) {\n // For eraser in straight line mode, continuously erase from start to current point\n // This gives immediate visual feedback and smoother erasing experience\n \n // Store current point\n QPointF currentPoint = event->posF();\n \n // Clear previous stroke by redrawing with transparency\n QRectF updateRect = QRectF(straightLineStartPoint, lastPoint).normalized().adjusted(-20, -20, 20, 20);\n update(updateRect.toRect());\n \n // Erase from start point to current position\n eraseStroke(straightLineStartPoint, currentPoint, event->pressure());\n \n // Update last point\n lastPoint = currentPoint;\n \n // Only track benchmarking when enabled\n if (benchmarking) {\n processedTimestamps.push_back(benchmarkTimer.elapsed());\n }\n } else {\n // Normal drawing mode OR eraser regardless of straight line mode\n if (isErasing) {\n eraseStroke(lastPoint, event->posF(), event->pressure());\n } else {\n drawStroke(lastPoint, event->posF(), event->pressure());\n }\n lastPoint = event->posF();\n \n // Only track benchmarking when enabled\n if (benchmarking) {\n processedTimestamps.push_back(benchmarkTimer.elapsed());\n }\n }\n } else if (event->type() == QEvent::TabletRelease) {\n if (straightLineMode && !isErasing) {\n // Draw the final line on release with the current pressure\n qreal pressure = event->pressure();\n \n // Always use at least a minimum pressure\n pressure = qMax(pressure, 0.5);\n \n drawStroke(straightLineStartPoint, event->posF(), pressure);\n \n // Only track benchmarking when enabled\n if (benchmarking) {\n processedTimestamps.push_back(benchmarkTimer.elapsed());\n }\n \n // Force repaint to clear the preview line\n update();\n if (!edited){\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n } else if (straightLineMode && isErasing) {\n // For erasing in straight line mode, most of the work is done during movement\n // Just ensure one final erasing pass from start to end point\n qreal pressure = qMax(event->pressure(), 0.5);\n \n // Final pass to ensure the entire line is erased\n eraseStroke(straightLineStartPoint, event->posF(), pressure);\n \n // Force update to clear any remaining artifacts\n update();\n if (!edited){\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n }\n \n drawing = false;\n \n // Reset tool state if we were using the hardware eraser\n if (wasUsingHardwareEraser) {\n currentTool = previousTool;\n hardwareEraserActive = false; // Reset hardware eraser tracking\n }\n\n if (ropeToolMode) {\n if (selectingWithRope) {\n if (lassoPathPoints.size() > 2) { // Need at least 3 points for a polygon\n lassoPathPoints << lassoPathPoints.first(); // Close the polygon\n \n if (!lassoPathPoints.boundingRect().isEmpty()) {\n // 1. Create a QPolygonF in buffer coordinates using proper transformation\n QPolygonF bufferLassoPath;\n for (const QPointF& p_widget_logical : qAsConst(lassoPathPoints)) {\n bufferLassoPath << mapLogicalWidgetToPhysicalBuffer(p_widget_logical);\n }\n\n // 2. Get the bounding box of this path on the buffer\n QRectF bufferPathBoundingRect = bufferLassoPath.boundingRect();\n\n // 3. Copy that part of the main buffer\n QPixmap originalPiece = buffer.copy(bufferPathBoundingRect.toRect());\n\n // 4. Create the selectionBuffer (same size as originalPiece) and fill transparent\n selectionBuffer = QPixmap(originalPiece.size());\n selectionBuffer.fill(Qt::transparent);\n \n // 5. Create a mask from the lasso path\n QPainterPath maskPath;\n // The lasso path for the mask needs to be relative to originalPiece.topLeft()\n maskPath.addPolygon(bufferLassoPath.translated(-bufferPathBoundingRect.topLeft()));\n \n // 6. Paint the originalPiece onto selectionBuffer, using the mask\n QPainter selectionPainter(&selectionBuffer);\n selectionPainter.setClipPath(maskPath);\n selectionPainter.drawPixmap(0,0, originalPiece);\n selectionPainter.end();\n\n // 7. DON'T clear the selected area from the main buffer yet\n // The area will only be cleared when the user actually starts moving the selection\n // This way, if the user cancels without moving, the original content remains\n selectionAreaCleared = false;\n \n // Store the mask path and buffer rect for later clearing when movement starts\n selectionMaskPath = maskPath.translated(bufferPathBoundingRect.topLeft());\n selectionBufferRect = bufferPathBoundingRect;\n \n // 8. Calculate the correct selectionRect in logical widget coordinates\n QRectF logicalSelectionRect = mapRectBufferToWidgetLogical(bufferPathBoundingRect);\n selectionRect = logicalSelectionRect.toRect();\n exactSelectionRectF = logicalSelectionRect;\n \n // Update the area of the selection on screen\n update(logicalSelectionRect.adjusted(-2,-2,2,2).toRect());\n \n // Emit signal for context menu at the center of the selection with a delay\n // This allows the user to immediately start moving the selection if desired\n QPoint menuPosition = selectionRect.center();\n QTimer::singleShot(500, this, [this, menuPosition]() {\n // Only show menu if selection still exists and hasn't been moved\n if (!selectionBuffer.isNull() && !selectionRect.isEmpty() && !movingSelection) {\n emit ropeSelectionCompleted(menuPosition);\n }\n });\n }\n }\n lassoPathPoints.clear(); // Ready for next selection, or move\n selectingWithRope = false;\n // Now, if the user presses inside selectionRect, movingSelection will become true.\n } else if (movingSelection) {\n if (!selectionBuffer.isNull() && !selectionRect.isEmpty()) {\n QPainter painter(&buffer);\n // Explicitly set composition mode to draw on top of existing content\n painter.setCompositionMode(QPainter::CompositionMode_SourceOver);\n // Use exact floating-point position if available for more precise placement\n QPointF topLeft = exactSelectionRectF.isEmpty() ? selectionRect.topLeft() : exactSelectionRectF.topLeft();\n // Use proper coordinate transformation to get buffer coordinates\n QPointF bufferDest = mapLogicalWidgetToPhysicalBuffer(topLeft);\n painter.drawPixmap(bufferDest.toPoint(), selectionBuffer);\n painter.end();\n \n // Update the pasted area\n QRectF bufferPasteRect(bufferDest, selectionBuffer.size());\n update(mapRectBufferToWidgetLogical(bufferPasteRect).adjusted(-2,-2,2,2));\n \n // Clear selection after pasting, making it permanent\n selectionBuffer = QPixmap();\n selectionRect = QRect();\n exactSelectionRectF = QRectF();\n movingSelection = false;\n selectionJustCopied = false;\n selectionAreaCleared = false;\n selectionMaskPath = QPainterPath();\n selectionBufferRect = QRectF();\n }\n }\n }\n \n\n }\n event->accept();\n}\n void mousePressEvent(QMouseEvent *event) override {\n // Handle markdown selection when enabled\n if (markdownSelectionMode && event->button() == Qt::LeftButton) {\n markdownSelecting = true;\n markdownSelectionStart = event->pos();\n markdownSelectionEnd = markdownSelectionStart;\n event->accept();\n return;\n }\n \n // Handle PDF text selection when enabled (mouse/touch fallback - stylus handled in tabletEvent)\n if (pdfTextSelectionEnabled && isPdfLoaded) {\n if (event->button() == Qt::LeftButton) {\n pdfTextSelecting = true;\n pdfSelectionStart = event->position();\n pdfSelectionEnd = pdfSelectionStart;\n \n // Clear any existing selected text boxes without resetting pdfTextSelecting\n selectedTextBoxes.clear();\n \n setCursor(Qt::IBeamCursor); // Ensure cursor is correct\n update(); // Refresh display\n event->accept();\n return;\n }\n }\n \n // Ignore mouse/touch input on canvas for drawing (drawing only works with tablet/stylus)\n event->ignore();\n}\n void mouseMoveEvent(QMouseEvent *event) override {\n // Handle markdown selection when enabled\n if (markdownSelectionMode && markdownSelecting) {\n markdownSelectionEnd = event->pos();\n update(); // Refresh to show selection rectangle\n event->accept();\n return;\n }\n \n // Handle PDF text selection when enabled (mouse/touch fallback - stylus handled in tabletEvent)\n if (pdfTextSelectionEnabled && isPdfLoaded && pdfTextSelecting) {\n pdfSelectionEnd = event->position();\n \n // Store pending selection for throttled processing\n pendingSelectionStart = pdfSelectionStart;\n pendingSelectionEnd = pdfSelectionEnd;\n hasPendingSelection = true;\n \n // Start timer if not already running (throttled to 60 FPS)\n if (!pdfTextSelectionTimer->isActive()) {\n pdfTextSelectionTimer->start();\n }\n \n event->accept();\n return;\n }\n \n // Update cursor based on mode when not actively selecting\n if (pdfTextSelectionEnabled && isPdfLoaded && !pdfTextSelecting) {\n setCursor(Qt::IBeamCursor);\n }\n \n event->ignore();\n}\n void mouseReleaseEvent(QMouseEvent *event) override {\n // Handle markdown selection when enabled\n if (markdownSelectionMode && markdownSelecting && event->button() == Qt::LeftButton) {\n markdownSelecting = false;\n \n // Create markdown window if selection is valid\n QRect selectionRect = QRect(markdownSelectionStart, markdownSelectionEnd).normalized();\n if (selectionRect.width() > 50 && selectionRect.height() > 50 && markdownManager) {\n markdownManager->createMarkdownWindow(selectionRect);\n }\n \n // Exit selection mode\n setMarkdownSelectionMode(false);\n \n // Force screen update to clear the green selection overlay\n update();\n \n event->accept();\n return;\n }\n \n // Handle PDF text selection when enabled (mouse/touch fallback - stylus handled in tabletEvent)\n if (pdfTextSelectionEnabled && isPdfLoaded && pdfTextSelecting) {\n if (event->button() == Qt::LeftButton) {\n pdfSelectionEnd = event->position();\n \n // Process any pending selection immediately on release\n if (pdfTextSelectionTimer && pdfTextSelectionTimer->isActive()) {\n pdfTextSelectionTimer->stop();\n if (hasPendingSelection) {\n updatePdfTextSelection(pendingSelectionStart, pendingSelectionEnd);\n hasPendingSelection = false;\n }\n } else {\n // Update selection with final position\n updatePdfTextSelection(pdfSelectionStart, pdfSelectionEnd);\n }\n \n pdfTextSelecting = false;\n \n // Check for link clicks if no text was selected\n QString selectedText = getSelectedPdfText();\n if (selectedText.isEmpty()) {\n handlePdfLinkClick(event->position());\n } else {\n // Show context menu for text selection\n QPoint globalPos = mapToGlobal(event->position().toPoint());\n showPdfTextSelectionMenu(globalPos);\n }\n \n event->accept();\n return;\n }\n }\n \n\n \n event->ignore();\n}\n void resizeEvent(QResizeEvent *event) override {\n // Don't resize the buffer when the widget resizes\n // The buffer size should be determined by the PDF/document content, not the widget size\n // The paintEvent will handle centering the buffer content within the widget\n \n QWidget::resizeEvent(event);\n}\n bool event(QEvent *event) override {\n if (!touchGesturesEnabled) {\n return QWidget::event(event);\n }\n\n if (event->type() == QEvent::TouchBegin || \n event->type() == QEvent::TouchUpdate || \n event->type() == QEvent::TouchEnd) {\n \n QTouchEvent *touchEvent = static_cast(event);\n const QList touchPoints = touchEvent->points();\n \n activeTouchPoints = touchPoints.count();\n\n if (activeTouchPoints == 1) {\n // Single finger pan\n const QTouchEvent::TouchPoint &touchPoint = touchPoints.first();\n \n if (event->type() == QEvent::TouchBegin) {\n isPanning = true;\n lastTouchPos = touchPoint.position();\n } else if (event->type() == QEvent::TouchUpdate && isPanning) {\n QPointF delta = touchPoint.position() - lastTouchPos;\n \n // Make panning more responsive by using floating-point calculations\n qreal scaledDeltaX = delta.x() / (internalZoomFactor / 100.0);\n qreal scaledDeltaY = delta.y() / (internalZoomFactor / 100.0);\n \n // Calculate new pan positions with sub-pixel precision\n qreal newPanX = panOffsetX - scaledDeltaX;\n qreal newPanY = panOffsetY - scaledDeltaY;\n \n // Clamp pan values when canvas is smaller than viewport\n qreal scaledCanvasWidth = buffer.width() * (internalZoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (internalZoomFactor / 100.0);\n \n // If canvas is smaller than widget, lock pan to 0 (centered)\n if (scaledCanvasWidth < width()) {\n newPanX = 0;\n }\n if (scaledCanvasHeight < height()) {\n newPanY = 0;\n }\n \n // Emit signal with integer values for compatibility\n emit panChanged(qRound(newPanX), qRound(newPanY));\n \n lastTouchPos = touchPoint.position();\n }\n } else if (activeTouchPoints == 2) {\n // Two finger pinch zoom\n isPanning = false;\n \n const QTouchEvent::TouchPoint &touch1 = touchPoints[0];\n const QTouchEvent::TouchPoint &touch2 = touchPoints[1];\n \n // Calculate distance between touch points with higher precision\n qreal currentDist = QLineF(touch1.position(), touch2.position()).length();\n qreal startDist = QLineF(touch1.pressPosition(), touch2.pressPosition()).length();\n \n if (event->type() == QEvent::TouchBegin) {\n lastPinchScale = 1.0;\n // Store the starting internal zoom\n internalZoomFactor = zoomFactor;\n } else if (event->type() == QEvent::TouchUpdate && startDist > 0) {\n qreal scale = currentDist / startDist;\n \n // Use exponential scaling for more natural feel\n qreal scaleChange = scale / lastPinchScale;\n \n // Apply scale with higher sensitivity\n internalZoomFactor *= scaleChange;\n internalZoomFactor = qBound(10.0, internalZoomFactor, 400.0);\n \n // Calculate zoom center (midpoint between two fingers)\n QPointF center = (touch1.position() + touch2.position()) / 2.0;\n \n // Account for centering offset\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n // Adjust center point for centering offset\n QPointF adjustedCenter = center - QPointF(centerOffsetX, centerOffsetY);\n \n // Always update zoom for smooth animation\n int newZoom = qRound(internalZoomFactor);\n \n // Calculate pan adjustment to keep the zoom centered at pinch point\n QPointF bufferCenter = adjustedCenter / (zoomFactor / 100.0) + QPointF(panOffsetX, panOffsetY);\n \n // Update zoom factor before emitting\n qreal oldZoomFactor = zoomFactor;\n zoomFactor = newZoom;\n \n // Emit zoom change even for small changes\n emit zoomChanged(newZoom);\n \n // Adjust pan to keep center point fixed with sub-pixel precision\n qreal newPanX = bufferCenter.x() - adjustedCenter.x() / (internalZoomFactor / 100.0);\n qreal newPanY = bufferCenter.y() - adjustedCenter.y() / (internalZoomFactor / 100.0);\n \n // After zoom, check if we need to center\n qreal newScaledCanvasWidth = buffer.width() * (internalZoomFactor / 100.0);\n qreal newScaledCanvasHeight = buffer.height() * (internalZoomFactor / 100.0);\n \n if (newScaledCanvasWidth < width()) {\n newPanX = 0;\n }\n if (newScaledCanvasHeight < height()) {\n newPanY = 0;\n }\n \n emit panChanged(qRound(newPanX), qRound(newPanY));\n \n lastPinchScale = scale;\n \n // Request update only for visible area\n update();\n }\n } else {\n // More than 2 fingers - ignore\n isPanning = false;\n }\n \n if (event->type() == QEvent::TouchEnd) {\n isPanning = false;\n lastPinchScale = 1.0;\n activeTouchPoints = 0;\n // Sync internal zoom with actual zoom\n internalZoomFactor = zoomFactor;\n \n // Emit signal that touch gesture has ended\n emit touchGestureEnded();\n }\n \n event->accept();\n return true;\n }\n \n return QWidget::event(event);\n}\n private:\n QPointF mapLogicalWidgetToPhysicalBuffer(const QPointF& logicalWidgetPoint) {\n // Use the same coordinate transformation logic as drawStroke for consistency\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n // Convert widget position to buffer position, accounting for centering\n QPointF adjustedPoint = logicalWidgetPoint - QPointF(centerOffsetX, centerOffsetY);\n QPointF bufferPoint = (adjustedPoint / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n \n return bufferPoint;\n}\n QRect mapRectBufferToWidgetLogical(const QRectF& physicalBufferRect) {\n // Use the same coordinate transformation logic as drawStroke for consistency\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n // Convert buffer coordinates back to widget coordinates\n QRectF widgetRect = QRectF(\n (physicalBufferRect.topLeft() - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY),\n physicalBufferRect.size() * (zoomFactor / 100.0)\n );\n \n return widgetRect.toRect();\n}\n QPixmap buffer;\n QImage background;\n QPointF lastPoint;\n QPointF straightLineStartPoint;\n bool drawing;\n QColor penColor;\n qreal penThickness;\n ToolType currentTool;\n ToolType previousTool;\n qreal penToolThickness = 5.0;\n qreal markerToolThickness = 5.0;\n qreal eraserToolThickness = 5.0;\n QString saveFolder;\n QPixmap backgroundImage;\n bool straightLineMode = false;\n bool ropeToolMode = false;\n QPixmap selectionBuffer;\n QRect selectionRect;\n QRectF exactSelectionRectF;\n QPolygonF lassoPathPoints;\n bool selectingWithRope = false;\n bool movingSelection = false;\n bool selectionJustCopied = false;\n bool selectionAreaCleared = false;\n QPainterPath selectionMaskPath;\n QRectF selectionBufferRect;\n QPointF lastMovePoint;\n int zoomFactor;\n int panOffsetX;\n int panOffsetY;\n qreal internalZoomFactor = 100.0;\n void initializeBuffer() {\n QScreen *screen = QGuiApplication::primaryScreen();\n qreal dpr = screen ? screen->devicePixelRatio() : 1.0;\n\n // Get logical screen size\n QSize logicalSize = screen ? screen->size() : QSize(1440, 900);\n QSize pixelSize = logicalSize * dpr;\n\n buffer = QPixmap(pixelSize);\n buffer.fill(Qt::transparent);\n\n setMaximumSize(pixelSize); // 🔥 KEY LINE to make full canvas drawable\n}\n void drawStroke(const QPointF &start, const QPointF &end, qreal pressure) {\n if (buffer.isNull()) {\n initializeBuffer();\n }\n\n if (!edited){\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n\n QPainter painter(&buffer);\n painter.setRenderHint(QPainter::Antialiasing);\n\n qreal thickness = penThickness;\n\n qreal updatePadding = (currentTool == ToolType::Marker) ? thickness * 4.0 : 10;\n\n if (currentTool == ToolType::Marker) {\n thickness *= 8.0;\n QColor markerColor = penColor;\n // Adjust alpha based on whether we're in straight line mode\n if (straightLineMode) {\n // For straight line mode, use higher alpha to make it more visible\n markerColor.setAlpha(40);\n } else {\n // For regular drawing, use lower alpha for the usual marker effect\n markerColor.setAlpha(4);\n }\n QPen pen(markerColor, thickness, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);\n painter.setPen(pen);\n } else { // Default Pen\n qreal scaledThickness = thickness * pressure; // **Linear pressure scaling**\n QPen pen(penColor, scaledThickness, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);\n painter.setPen(pen);\n }\n\n // Calculate centering offsets\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n // Convert screen position to buffer position, accounting for centering\n QPointF adjustedStart = start - QPointF(centerOffsetX, centerOffsetY);\n QPointF adjustedEnd = end - QPointF(centerOffsetX, centerOffsetY);\n \n QPointF bufferStart = (adjustedStart / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n QPointF bufferEnd = (adjustedEnd / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n\n painter.drawLine(bufferStart, bufferEnd);\n\n QRectF updateRect = QRectF(bufferStart, bufferEnd)\n .normalized()\n .adjusted(-updatePadding, -updatePadding, updatePadding, updatePadding);\n\n QRect scaledUpdateRect = QRect(\n ((updateRect.topLeft() - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY)).toPoint(),\n ((updateRect.bottomRight() - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY)).toPoint()\n );\n update(scaledUpdateRect);\n}\n void eraseStroke(const QPointF &start, const QPointF &end, qreal pressure) {\n if (buffer.isNull()) {\n initializeBuffer();\n }\n\n if (!edited){\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n\n QPainter painter(&buffer);\n painter.setCompositionMode(QPainter::CompositionMode_Clear);\n\n qreal eraserThickness = penThickness * 6.0;\n QPen eraserPen(Qt::transparent, eraserThickness, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);\n painter.setPen(eraserPen);\n\n // Calculate centering offsets\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n // Convert screen position to buffer position, accounting for centering\n QPointF adjustedStart = start - QPointF(centerOffsetX, centerOffsetY);\n QPointF adjustedEnd = end - QPointF(centerOffsetX, centerOffsetY);\n \n QPointF bufferStart = (adjustedStart / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n QPointF bufferEnd = (adjustedEnd / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n\n painter.drawLine(bufferStart, bufferEnd);\n\n qreal updatePadding = eraserThickness / 2.0 + 5.0; // Half the eraser thickness plus some extra padding\n QRectF updateRect = QRectF(bufferStart, bufferEnd)\n .normalized()\n .adjusted(-updatePadding, -updatePadding, updatePadding, updatePadding);\n\n QRect scaledUpdateRect = QRect(\n ((updateRect.topLeft() - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY)).toPoint(),\n ((updateRect.bottomRight() - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY)).toPoint()\n );\n update(scaledUpdateRect);\n}\n QRectF calculatePreviewRect(const QPointF &start, const QPointF &oldEnd, const QPointF &newEnd) {\n // Calculate centering offsets - use the same calculation as in paintEvent\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n // Calculate the buffer coordinates for our points (same as in drawStroke)\n QPointF adjustedStart = start - QPointF(centerOffsetX, centerOffsetY);\n QPointF adjustedOldEnd = oldEnd - QPointF(centerOffsetX, centerOffsetY);\n QPointF adjustedNewEnd = newEnd - QPointF(centerOffsetX, centerOffsetY);\n \n QPointF bufferStart = (adjustedStart / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n QPointF bufferOldEnd = (adjustedOldEnd / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n QPointF bufferNewEnd = (adjustedNewEnd / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n \n // Now convert from buffer coordinates to screen coordinates\n QPointF screenStart = (bufferStart - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY);\n QPointF screenOldEnd = (bufferOldEnd - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY);\n QPointF screenNewEnd = (bufferNewEnd - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY);\n \n // Create rectangles for both the old and new lines\n QRectF oldLineRect = QRectF(screenStart, screenOldEnd).normalized();\n QRectF newLineRect = QRectF(screenStart, screenNewEnd).normalized();\n \n // Calculate padding based on pen thickness and device pixel ratio\n qreal dpr = devicePixelRatioF();\n qreal padding;\n \n if (currentTool == ToolType::Eraser) {\n padding = penThickness * 6.0 * dpr;\n } else if (currentTool == ToolType::Marker) {\n padding = penThickness * 8.0 * dpr;\n } else {\n padding = penThickness * dpr;\n }\n \n // Ensure minimum padding\n padding = qMax(padding, 15.0);\n \n // Combine rectangles with appropriate padding\n QRectF combinedRect = oldLineRect.united(newLineRect);\n return combinedRect.adjusted(-padding, -padding, padding, padding);\n}\n QCache pdfCache;\n std::unique_ptr pdfDocument;\n int currentPdfPage;\n bool isPdfLoaded = false;\n int totalPdfPages = 0;\n int lastActivePage = 0;\n int lastZoomLevel = 100;\n int lastPanX = 0;\n int lastPanY = 0;\n bool edited = false;\n bool benchmarking;\n std::deque processedTimestamps;\n QElapsedTimer benchmarkTimer;\n QString notebookId;\n void loadNotebookId() {\n QString idFile = saveFolder + \"/.notebook_id.txt\";\n if (QFile::exists(idFile)) {\n QFile file(idFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n notebookId = in.readLine().trimmed();\n }\n } else {\n // No ID file → create new random ID\n notebookId = QUuid::createUuid().toString(QUuid::WithoutBraces).replace(\"-\", \"\");\n saveNotebookId();\n }\n}\n void saveNotebookId() {\n QString idFile = saveFolder + \"/.notebook_id.txt\";\n QFile file(idFile);\n if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {\n QTextStream out(&file);\n out << notebookId;\n }\n}\n int pdfRenderDPI = 192;\n bool touchGesturesEnabled = false;\n QPointF lastTouchPos;\n qreal lastPinchScale = 1.0;\n bool isPanning = false;\n int activeTouchPoints = 0;\n BackgroundStyle backgroundStyle = BackgroundStyle::None;\n QColor backgroundColor = Qt::white;\n int backgroundDensity = 40;\n bool pdfTextSelectionEnabled = false;\n bool pdfTextSelecting = false;\n QPointF pdfSelectionStart;\n QPointF pdfSelectionEnd;\n QList currentPdfTextBoxes;\n QList selectedTextBoxes;\n std::unique_ptr currentPdfPageForText;\n QTimer* pdfTextSelectionTimer = nullptr;\n QPointF pendingSelectionStart;\n QPointF pendingSelectionEnd;\n bool hasPendingSelection = false;\n QTimer* pdfCacheTimer = nullptr;\n int currentCachedPage = -1;\n int pendingCacheTargetPage = -1;\n QList*> activePdfWatchers;\n QCache noteCache;\n QTimer* noteCacheTimer = nullptr;\n int currentCachedNotePage = -1;\n int pendingNoteCacheTargetPage = -1;\n QList*> activeNoteWatchers;\n MarkdownWindowManager* markdownManager = nullptr;\n bool markdownSelectionMode = false;\n QPoint markdownSelectionStart;\n QPoint markdownSelectionEnd;\n bool markdownSelecting = false;\n void loadPdfTextBoxes(int pageNumber) {\n // Clear existing text boxes\n qDeleteAll(currentPdfTextBoxes);\n currentPdfTextBoxes.clear();\n \n if (!pdfDocument || pageNumber < 0 || pageNumber >= pdfDocument->numPages()) {\n return;\n }\n \n // Get the page for text operations\n currentPdfPageForText = std::unique_ptr(pdfDocument->page(pageNumber));\n if (!currentPdfPageForText) {\n return;\n }\n \n // Load text boxes for the page\n auto textBoxVector = currentPdfPageForText->textList();\n currentPdfTextBoxes.clear();\n for (auto& textBox : textBoxVector) {\n currentPdfTextBoxes.append(textBox.release()); // Transfer ownership to QList\n }\n}\n QPointF mapWidgetToPdfCoordinates(const QPointF &widgetPoint) {\n if (!currentPdfPageForText || backgroundImage.isNull()) {\n return QPointF();\n }\n \n // Use the same zoom factor as in paintEvent (internalZoomFactor for smooth animations)\n qreal zoom = internalZoomFactor / 100.0;\n \n // Calculate the scaled canvas size (same as in paintEvent)\n qreal scaledCanvasWidth = buffer.width() * zoom;\n qreal scaledCanvasHeight = buffer.height() * zoom;\n \n // Calculate centering offsets (same as in paintEvent)\n qreal centerOffsetX = 0;\n qreal centerOffsetY = 0;\n \n // Center horizontally if canvas is smaller than widget\n if (scaledCanvasWidth < width()) {\n centerOffsetX = (width() - scaledCanvasWidth) / 2.0;\n }\n \n // Center vertically if canvas is smaller than widget\n if (scaledCanvasHeight < height()) {\n centerOffsetY = (height() - scaledCanvasHeight) / 2.0;\n }\n \n // Reverse the transformations applied in paintEvent\n QPointF adjustedPoint = widgetPoint;\n adjustedPoint -= QPointF(centerOffsetX, centerOffsetY);\n adjustedPoint /= zoom;\n adjustedPoint += QPointF(panOffsetX, panOffsetY);\n \n // Convert to PDF coordinates\n // Since Poppler renders the PDF in Qt coordinate system (top-left origin),\n // we don't need to flip the Y coordinate\n QSizeF pdfPageSize = currentPdfPageForText->pageSizeF();\n QSizeF imageSize = backgroundImage.size();\n \n // Scale from image coordinates to PDF coordinates\n qreal scaleX = pdfPageSize.width() / imageSize.width();\n qreal scaleY = pdfPageSize.height() / imageSize.height();\n \n QPointF pdfPoint;\n pdfPoint.setX(adjustedPoint.x() * scaleX);\n pdfPoint.setY(adjustedPoint.y() * scaleY); // No Y-axis flipping needed\n \n return pdfPoint;\n}\n QPointF mapPdfToWidgetCoordinates(const QPointF &pdfPoint) {\n if (!currentPdfPageForText || backgroundImage.isNull()) {\n return QPointF();\n }\n \n // Convert from PDF coordinates to image coordinates\n QSizeF pdfPageSize = currentPdfPageForText->pageSizeF();\n QSizeF imageSize = backgroundImage.size();\n \n // Scale from PDF coordinates to image coordinates\n qreal scaleX = imageSize.width() / pdfPageSize.width();\n qreal scaleY = imageSize.height() / pdfPageSize.height();\n \n QPointF imagePoint;\n imagePoint.setX(pdfPoint.x() * scaleX);\n imagePoint.setY(pdfPoint.y() * scaleY); // No Y-axis flipping needed\n \n // Use the same zoom factor as in paintEvent (internalZoomFactor for smooth animations)\n qreal zoom = internalZoomFactor / 100.0;\n \n // Apply the same transformations as in paintEvent\n QPointF widgetPoint = imagePoint;\n widgetPoint -= QPointF(panOffsetX, panOffsetY);\n widgetPoint *= zoom;\n \n // Calculate the scaled canvas size (same as in paintEvent)\n qreal scaledCanvasWidth = buffer.width() * zoom;\n qreal scaledCanvasHeight = buffer.height() * zoom;\n \n // Calculate centering offsets (same as in paintEvent)\n qreal centerOffsetX = 0;\n qreal centerOffsetY = 0;\n \n // Center horizontally if canvas is smaller than widget\n if (scaledCanvasWidth < width()) {\n centerOffsetX = (width() - scaledCanvasWidth) / 2.0;\n }\n \n // Center vertically if canvas is smaller than widget\n if (scaledCanvasHeight < height()) {\n centerOffsetY = (height() - scaledCanvasHeight) / 2.0;\n }\n \n widgetPoint += QPointF(centerOffsetX, centerOffsetY);\n \n return widgetPoint;\n}\n void updatePdfTextSelection(const QPointF &start, const QPointF &end) {\n // Early return if PDF is not loaded or no text boxes available\n if (!isPdfLoaded || currentPdfTextBoxes.isEmpty()) {\n return;\n }\n \n // Clear previous selection efficiently\n selectedTextBoxes.clear();\n \n // Create normalized selection rectangle in widget coordinates\n QRectF widgetSelectionRect(start, end);\n widgetSelectionRect = widgetSelectionRect.normalized();\n \n // Convert to PDF coordinate space\n QPointF pdfTopLeft = mapWidgetToPdfCoordinates(widgetSelectionRect.topLeft());\n QPointF pdfBottomRight = mapWidgetToPdfCoordinates(widgetSelectionRect.bottomRight());\n QRectF pdfSelectionRect(pdfTopLeft, pdfBottomRight);\n pdfSelectionRect = pdfSelectionRect.normalized();\n \n // Reserve space for efficiency if we expect many selections\n selectedTextBoxes.reserve(qMin(currentPdfTextBoxes.size(), 50));\n \n // Find intersecting text boxes with optimized loop\n for (const Poppler::TextBox* textBox : currentPdfTextBoxes) {\n if (textBox && textBox->boundingBox().intersects(pdfSelectionRect)) {\n selectedTextBoxes.append(const_cast(textBox));\n }\n }\n \n // Only emit signal and update if we have selected text\n if (!selectedTextBoxes.isEmpty()) {\n QString selectedText = getSelectedPdfText();\n if (!selectedText.isEmpty()) {\n emit pdfTextSelected(selectedText);\n }\n }\n \n // Trigger repaint to show selection\n update();\n}\n void handlePdfLinkClick(const QPointF &clickPoint) {\n if (!isPdfLoaded || !currentPdfPageForText) {\n return;\n }\n \n // Convert widget coordinates to PDF coordinates\n QPointF pdfPoint = mapWidgetToPdfCoordinates(position);\n \n // Get PDF page size for reference\n QSizeF pdfPageSize = currentPdfPageForText->pageSizeF();\n \n // Convert to normalized coordinates (0.0 to 1.0) to match Poppler's link coordinate system\n QPointF normalizedPoint(pdfPoint.x() / pdfPageSize.width(), pdfPoint.y() / pdfPageSize.height());\n \n // Get links for the current page\n auto links = currentPdfPageForText->links();\n \n for (const auto& link : links) {\n QRectF linkArea = link->linkArea();\n \n // Normalize the rectangle to handle negative width/height\n QRectF normalizedLinkArea = linkArea.normalized();\n \n // Check if the normalized rectangle contains the normalized point\n if (normalizedLinkArea.contains(normalizedPoint)) {\n // Handle different types of links\n if (link->linkType() == Poppler::Link::Goto) {\n Poppler::LinkGoto* gotoLink = static_cast(link.get());\n if (gotoLink && gotoLink->destination().pageNumber() >= 0) {\n int targetPage = gotoLink->destination().pageNumber() - 1; // Convert to 0-based\n emit pdfLinkClicked(targetPage);\n return;\n }\n }\n // Add other link types as needed (URI, etc.)\n }\n }\n}\n void showPdfTextSelectionMenu(const QPoint &position) {\n QString selectedText = getSelectedPdfText();\n if (selectedText.isEmpty()) {\n return; // No text selected, don't show menu\n }\n \n // Create context menu\n QMenu *contextMenu = new QMenu(this);\n contextMenu->setAttribute(Qt::WA_DeleteOnClose);\n \n // Add Copy action\n QAction *copyAction = contextMenu->addAction(tr(\"Copy\"));\n copyAction->setIcon(QIcon(\":/resources/icons/copy.png\")); // You may need to add this icon\n connect(copyAction, &QAction::triggered, this, [selectedText]() {\n QClipboard *clipboard = QGuiApplication::clipboard();\n clipboard->setText(selectedText);\n });\n \n // Add separator\n contextMenu->addSeparator();\n \n // Add Cancel action\n QAction *cancelAction = contextMenu->addAction(tr(\"Cancel\"));\n cancelAction->setIcon(QIcon(\":/resources/icons/cross.png\"));\n connect(cancelAction, &QAction::triggered, this, [this]() {\n clearPdfTextSelection();\n });\n \n // Show the menu at the specified position\n contextMenu->popup(position);\n}\n QList getTextBoxesInSelection(const QPointF &start, const QPointF &end) {\n QList selectedBoxes;\n \n if (!currentPdfPageForText) {\n // qDebug() << \"PDF text selection: No current page for text\";\n return selectedBoxes;\n }\n \n // Convert widget coordinates to PDF coordinates\n QPointF pdfStart = mapWidgetToPdfCoordinates(start);\n QPointF pdfEnd = mapWidgetToPdfCoordinates(end);\n \n // qDebug() << \"PDF text selection: Widget coords\" << start << \"to\" << end;\n // qDebug() << \"PDF text selection: PDF coords\" << pdfStart << \"to\" << pdfEnd;\n \n // Create selection rectangle in PDF coordinates\n QRectF selectionRect(pdfStart, pdfEnd);\n selectionRect = selectionRect.normalized();\n \n // qDebug() << \"PDF text selection: Selection rect in PDF coords:\" << selectionRect;\n \n // Find text boxes that intersect with the selection\n int intersectionCount = 0;\n for (Poppler::TextBox* textBox : currentPdfTextBoxes) {\n if (textBox) {\n QRectF textBoxRect = textBox->boundingBox();\n bool intersects = textBoxRect.intersects(selectionRect);\n \n if (intersects) {\n selectedBoxes.append(textBox);\n intersectionCount++;\n // qDebug() << \"PDF text selection: Text box intersects:\" << textBox->text() \n // << \"at\" << textBoxRect;\n }\n }\n }\n \n // qDebug() << \"PDF text selection: Found\" << intersectionCount << \"intersecting text boxes\";\n \n return selectedBoxes;\n}\n void renderPdfPageToCache(int pageNumber) {\n if (!pdfDocument || !isValidPageNumber(pageNumber)) {\n return;\n }\n \n // Check if already cached\n if (pdfCache.contains(pageNumber)) {\n return;\n }\n \n // Ensure the cache holds only 10 pages max\n if (pdfCache.count() >= 10) {\n auto oldestKey = pdfCache.keys().first();\n pdfCache.remove(oldestKey);\n }\n \n // Render the page and store it in the cache\n std::unique_ptr page(pdfDocument->page(pageNumber));\n if (page) {\n // Render with document-level anti-aliasing settings\n QImage pdfImage = page->renderToImage(pdfRenderDPI, pdfRenderDPI);\n if (!pdfImage.isNull()) {\n QPixmap cachedPixmap = QPixmap::fromImage(pdfImage);\n pdfCache.insert(pageNumber, new QPixmap(cachedPixmap));\n }\n }\n}\n void checkAndCacheAdjacentPages(int targetPage) {\n if (!pdfDocument || !isValidPageNumber(targetPage)) {\n return;\n }\n \n // Calculate adjacent pages\n int prevPage = targetPage - 1;\n int nextPage = targetPage + 1;\n \n // Check what needs to be cached\n bool needPrevPage = isValidPageNumber(prevPage) && !pdfCache.contains(prevPage);\n bool needCurrentPage = !pdfCache.contains(targetPage);\n bool needNextPage = isValidPageNumber(nextPage) && !pdfCache.contains(nextPage);\n \n // If all pages are cached, nothing to do\n if (!needPrevPage && !needCurrentPage && !needNextPage) {\n return;\n }\n \n // Stop any existing timer\n if (pdfCacheTimer && pdfCacheTimer->isActive()) {\n pdfCacheTimer->stop();\n }\n \n // Create timer if it doesn't exist\n if (!pdfCacheTimer) {\n pdfCacheTimer = new QTimer(this);\n pdfCacheTimer->setSingleShot(true);\n connect(pdfCacheTimer, &QTimer::timeout, this, &InkCanvas::cacheAdjacentPages);\n }\n \n // Store the target page for validation when timer fires\n pendingCacheTargetPage = targetPage;\n \n // Start 1-second delay timer\n pdfCacheTimer->start(1000);\n}\n bool isValidPageNumber(int pageNumber) const {\n return (pageNumber >= 0 && pageNumber < totalPdfPages);\n}\n void loadNotePageToCache(int pageNumber) {\n // Check if already cached\n if (noteCache.contains(pageNumber)) {\n return;\n }\n \n QString filePath = getNotePageFilePath(pageNumber);\n if (filePath.isEmpty()) {\n return;\n }\n \n // Ensure the cache doesn't exceed its limit\n if (noteCache.count() >= 15) {\n // QCache will automatically remove least recently used items\n // but we can be explicit about it\n auto keys = noteCache.keys();\n if (!keys.isEmpty()) {\n noteCache.remove(keys.first());\n }\n }\n \n // Load note page from disk if it exists\n if (QFile::exists(filePath)) {\n QPixmap notePixmap;\n if (notePixmap.load(filePath)) {\n noteCache.insert(pageNumber, new QPixmap(notePixmap));\n }\n }\n // If file doesn't exist, we don't cache anything - loadPage will handle initialization\n}\n void checkAndCacheAdjacentNotePages(int targetPage) {\n if (saveFolder.isEmpty()) {\n return;\n }\n \n // Calculate adjacent pages\n int prevPage = targetPage - 1;\n int nextPage = targetPage + 1;\n \n // Check what needs to be cached (we don't have a max page limit for notes)\n bool needPrevPage = (prevPage >= 0) && !noteCache.contains(prevPage);\n bool needCurrentPage = !noteCache.contains(targetPage);\n bool needNextPage = !noteCache.contains(nextPage); // No upper limit check for notes\n \n // If all nearby pages are cached, nothing to do\n if (!needPrevPage && !needCurrentPage && !needNextPage) {\n return;\n }\n \n // Stop any existing timer\n if (noteCacheTimer && noteCacheTimer->isActive()) {\n noteCacheTimer->stop();\n }\n \n // Create timer if it doesn't exist\n if (!noteCacheTimer) {\n noteCacheTimer = new QTimer(this);\n noteCacheTimer->setSingleShot(true);\n connect(noteCacheTimer, &QTimer::timeout, this, &InkCanvas::cacheAdjacentNotePages);\n }\n \n // Store the target page for validation when timer fires\n pendingNoteCacheTargetPage = targetPage;\n \n // Start 1-second delay timer\n noteCacheTimer->start(1000);\n}\n QString getNotePageFilePath(int pageNumber) const {\n if (saveFolder.isEmpty() || notebookId.isEmpty()) {\n return QString();\n }\n return saveFolder + QString(\"/%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n}\n void invalidateCurrentPageCache() {\n if (currentCachedNotePage >= 0) {\n noteCache.remove(currentCachedNotePage);\n }\n}\n private:\n void processPendingTextSelection() {\n if (!hasPendingSelection) {\n return;\n }\n \n // Process the pending selection update\n updatePdfTextSelection(pendingSelectionStart, pendingSelectionEnd);\n hasPendingSelection = false;\n}\n void cacheAdjacentPages() {\n if (!pdfDocument || currentCachedPage < 0) {\n return;\n }\n \n // Check if the user has moved to a different page since the timer was started\n // If so, skip caching adjacent pages as they're no longer relevant\n if (pendingCacheTargetPage != currentCachedPage) {\n return; // User switched pages, don't cache adjacent pages for old page\n }\n \n int targetPage = currentCachedPage;\n int prevPage = targetPage - 1;\n int nextPage = targetPage + 1;\n \n // Create list of pages to cache asynchronously\n QList pagesToCache;\n \n // Add previous page if needed\n if (isValidPageNumber(prevPage) && !pdfCache.contains(prevPage)) {\n pagesToCache.append(prevPage);\n }\n \n // Add next page if needed\n if (isValidPageNumber(nextPage) && !pdfCache.contains(nextPage)) {\n pagesToCache.append(nextPage);\n }\n \n // Cache pages asynchronously\n for (int pageNum : pagesToCache) {\n QFutureWatcher *watcher = new QFutureWatcher(this);\n \n // Track the watcher for cleanup\n activePdfWatchers.append(watcher);\n \n connect(watcher, &QFutureWatcher::finished, this, [this, watcher]() {\n // Remove from active list and delete\n activePdfWatchers.removeOne(watcher);\n watcher->deleteLater();\n });\n \n // Capture pageNum by value to avoid issues with lambda capture\n QFuture future = QtConcurrent::run([this, pageNum]() {\n renderPdfPageToCache(pageNum);\n });\n \n watcher->setFuture(future);\n }\n}\n void cacheAdjacentNotePages() {\n if (saveFolder.isEmpty() || currentCachedNotePage < 0) {\n return;\n }\n \n // Check if the user has moved to a different page since the timer was started\n // If so, skip caching adjacent pages as they're no longer relevant\n if (pendingNoteCacheTargetPage != currentCachedNotePage) {\n return; // User switched pages, don't cache adjacent pages for old page\n }\n \n int targetPage = currentCachedNotePage;\n int prevPage = targetPage - 1;\n int nextPage = targetPage + 1;\n \n // Create list of note pages to cache asynchronously\n QList notePagesToCache;\n \n // Add previous page if needed (check for >= 0 since notes can start from page 0)\n if (prevPage >= 0 && !noteCache.contains(prevPage)) {\n notePagesToCache.append(prevPage);\n }\n \n // Add next page if needed (no upper limit check for notes)\n if (!noteCache.contains(nextPage)) {\n notePagesToCache.append(nextPage);\n }\n \n // Cache note pages asynchronously\n for (int pageNum : notePagesToCache) {\n QFutureWatcher *watcher = new QFutureWatcher(this);\n \n // Track the watcher for cleanup\n activeNoteWatchers.append(watcher);\n \n connect(watcher, &QFutureWatcher::finished, this, [this, watcher]() {\n // Remove from active list and delete\n activeNoteWatchers.removeOne(watcher);\n watcher->deleteLater();\n });\n \n // Capture pageNum by value to avoid issues with lambda capture\n QFuture future = QtConcurrent::run([this, pageNum]() {\n loadNotePageToCache(pageNum);\n });\n \n watcher->setFuture(future);\n }\n}\n};"], ["/SpeedyNote/source/MainWindow.h", "class QTreeWidgetItem {\n Q_OBJECT\n\npublic:\n explicit MainWindow(QWidget *parent = nullptr);\n virtual ~MainWindow() {\n\n saveButtonMappings(); // ✅ Save on exit, as backup\n delete canvas;\n}\n int getCurrentPageForCanvas(InkCanvas *canvas) {\n return pageMap.contains(canvas) ? pageMap[canvas] : 0;\n}\n bool lowResPreviewEnabled = true;\n void setLowResPreviewEnabled(bool enabled) {\n lowResPreviewEnabled = enabled;\n\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"lowResPreviewEnabled\", enabled);\n}\n bool isLowResPreviewEnabled() const {\n return lowResPreviewEnabled;\n}\n bool areBenchmarkControlsVisible() const {\n return benchmarkButton->isVisible() && benchmarkLabel->isVisible();\n}\n void setBenchmarkControlsVisible(bool visible) {\n benchmarkButton->setVisible(visible);\n benchmarkLabel->setVisible(visible);\n}\n bool zoomButtonsVisible = true;\n bool areZoomButtonsVisible() const {\n return zoomButtonsVisible;\n}\n void setZoomButtonsVisible(bool visible) {\n zoom50Button->setVisible(visible);\n dezoomButton->setVisible(visible);\n zoom200Button->setVisible(visible);\n\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"zoomButtonsVisible\", visible);\n \n // Update zoomButtonsVisible flag and trigger layout update\n zoomButtonsVisible = visible;\n \n // Trigger layout update to adjust responsive thresholds\n if (layoutUpdateTimer) {\n layoutUpdateTimer->stop();\n layoutUpdateTimer->start(50); // Quick update for settings change\n } else {\n updateToolbarLayout(); // Direct update if no timer exists yet\n }\n}\n bool scrollOnTopEnabled = false;\n bool isScrollOnTopEnabled() const {\n return scrollOnTopEnabled;\n}\n void setScrollOnTopEnabled(bool enabled) {\n scrollOnTopEnabled = enabled;\n\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"scrollOnTopEnabled\", enabled);\n}\n bool touchGesturesEnabled = true;\n bool areTouchGesturesEnabled() const {\n return touchGesturesEnabled;\n}\n void setTouchGesturesEnabled(bool enabled) {\n touchGesturesEnabled = enabled;\n \n // Apply to all canvases\n for (int i = 0; i < canvasStack->count(); ++i) {\n InkCanvas *canvas = qobject_cast(canvasStack->widget(i));\n if (canvas) {\n canvas->setTouchGesturesEnabled(enabled);\n }\n }\n \n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"touchGesturesEnabled\", enabled);\n}\n QColor customAccentColor;\n bool useCustomAccentColor = false;\n QColor getAccentColor() const {\n if (useCustomAccentColor && customAccentColor.isValid()) {\n return customAccentColor;\n }\n \n // Return system accent color\n QPalette palette = QGuiApplication::palette();\n return palette.highlight().color();\n}\n void setCustomAccentColor(const QColor &color) {\n if (customAccentColor != color) {\n customAccentColor = color;\n saveThemeSettings();\n // Always update theme if custom accent color is enabled\n if (useCustomAccentColor) {\n updateTheme();\n }\n }\n}\n void setUseCustomAccentColor(bool use) {\n if (useCustomAccentColor != use) {\n useCustomAccentColor = use;\n updateTheme();\n saveThemeSettings();\n }\n}\n void setUseBrighterPalette(bool use) {\n if (useBrighterPalette != use) {\n useBrighterPalette = use;\n \n // Update all colors - call updateColorPalette which handles null checks\n updateColorPalette();\n \n // Save preference\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"useBrighterPalette\", useBrighterPalette);\n }\n}\n QColor getDefaultPenColor() {\n return isDarkMode() ? Qt::white : Qt::black;\n}\n SDLControllerManager *controllerManager = nullptr;\n QThread *controllerThread = nullptr;\n QString getHoldMapping(const QString &buttonName) {\n return buttonHoldMapping.value(buttonName, \"None\");\n}\n QString getPressMapping(const QString &buttonName) {\n return buttonPressMapping.value(buttonName, \"None\");\n}\n void saveButtonMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n\n settings.beginGroup(\"ButtonHoldMappings\");\n for (auto it = buttonHoldMapping.begin(); it != buttonHoldMapping.end(); ++it) {\n settings.setValue(it.key(), it.value());\n }\n settings.endGroup();\n\n settings.beginGroup(\"ButtonPressMappings\");\n for (auto it = buttonPressMapping.begin(); it != buttonPressMapping.end(); ++it) {\n settings.setValue(it.key(), it.value());\n }\n settings.endGroup();\n}\n void loadButtonMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n\n // First, check if we need to migrate old settings\n migrateOldButtonMappings();\n\n settings.beginGroup(\"ButtonHoldMappings\");\n QStringList holdKeys = settings.allKeys();\n for (const QString &key : holdKeys) {\n buttonHoldMapping[key] = settings.value(key, \"none\").toString();\n }\n settings.endGroup();\n\n settings.beginGroup(\"ButtonPressMappings\");\n QStringList pressKeys = settings.allKeys();\n for (const QString &key : pressKeys) {\n QString value = settings.value(key, \"none\").toString();\n buttonPressMapping[key] = value;\n\n // ✅ Convert internal key to action enum\n buttonPressActionMapping[key] = stringToAction(value);\n }\n settings.endGroup();\n}\n void setHoldMapping(const QString &buttonName, const QString &dialMode) {\n buttonHoldMapping[buttonName] = dialMode;\n}\n void setPressMapping(const QString &buttonName, const QString &action) {\n buttonPressMapping[buttonName] = action;\n buttonPressActionMapping[buttonName] = stringToAction(action); // ✅ THIS LINE WAS MISSING\n}\n DialMode dialModeFromString(const QString &mode) {\n // Convert internal key to our existing DialMode enum\n InternalDialMode internalMode = ButtonMappingHelper::internalKeyToDialMode(mode);\n \n switch (internalMode) {\n case InternalDialMode::None: return PageSwitching; // Default fallback\n case InternalDialMode::PageSwitching: return PageSwitching;\n case InternalDialMode::ZoomControl: return ZoomControl;\n case InternalDialMode::ThicknessControl: return ThicknessControl;\n\n case InternalDialMode::ToolSwitching: return ToolSwitching;\n case InternalDialMode::PresetSelection: return PresetSelection;\n case InternalDialMode::PanAndPageScroll: return PanAndPageScroll;\n }\n return PanAndPageScroll; // Default fallback\n}\n void importNotebookFromFile(const QString &packageFile) {\n\n QString destDir = QFileDialog::getExistingDirectory(this, tr(\"Select Working Directory for Notebook\"));\n\n if (destDir.isEmpty()) {\n QMessageBox::warning(this, tr(\"Import Cancelled\"), tr(\"No directory selected. Notebook will not be opened.\"));\n return;\n }\n\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n\n canvas->importNotebookTo(packageFile, destDir);\n\n // Change saveFolder in InkCanvas\n canvas->setSaveFolder(destDir);\n canvas->loadPage(0);\n updateZoom(); // ✅ Update zoom and pan range after importing notebook\n}\n void openPdfFile(const QString &pdfPath) {\n // Check if the PDF file exists\n if (!QFile::exists(pdfPath)) {\n QMessageBox::warning(this, tr(\"File Not Found\"), tr(\"The PDF file could not be found:\\n%1\").arg(pdfPath));\n return;\n }\n \n // First, check if there's already a valid notebook folder for this PDF\n QString existingFolderPath;\n if (PdfOpenDialog::hasValidNotebookFolder(pdfPath, existingFolderPath)) {\n // Found a valid notebook folder, open it directly without showing dialog\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n \n // Save current work if edited\n if (canvas->isEdited()) {\n saveCurrentPage();\n }\n \n // Set the existing folder as save folder\n canvas->setSaveFolder(existingFolderPath);\n \n // Load the PDF\n canvas->loadPdf(pdfPath);\n \n // Update tab label and recent notebooks\n updateTabLabel();\n if (recentNotebooksManager) {\n recentNotebooksManager->addRecentNotebook(existingFolderPath, canvas);\n }\n \n // Switch to page 1 and update UI\n switchPageWithDirection(1, 1);\n pageInput->setValue(1);\n updateZoom();\n updatePanRange();\n \n return; // Exit early, no need to show dialog\n }\n \n // No valid notebook folder found, show the dialog with options\n PdfOpenDialog dialog(pdfPath, this);\n dialog.exec();\n \n PdfOpenDialog::Result result = dialog.getResult();\n QString selectedFolder = dialog.getSelectedFolder();\n \n if (result == PdfOpenDialog::Cancel) {\n return; // User cancelled, do nothing\n }\n \n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n \n // Save current work if edited\n if (canvas->isEdited()) {\n saveCurrentPage();\n }\n \n if (result == PdfOpenDialog::CreateNewFolder) {\n // Set the new folder as save folder\n canvas->setSaveFolder(selectedFolder);\n \n // Load the PDF\n canvas->loadPdf(pdfPath);\n \n // Update tab label and recent notebooks\n updateTabLabel();\n if (recentNotebooksManager) {\n recentNotebooksManager->addRecentNotebook(selectedFolder, canvas);\n }\n \n // Switch to page 1 and update UI\n switchPageWithDirection(1, 1);\n pageInput->setValue(1);\n updateZoom();\n updatePanRange();\n \n } else if (result == PdfOpenDialog::UseExistingFolder) {\n // Check if the existing folder is linked to the same PDF\n QString metadataFile = selectedFolder + \"/.pdf_path.txt\";\n bool isLinkedToSamePdf = false;\n \n if (QFile::exists(metadataFile)) {\n QFile file(metadataFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString existingPdfPath = in.readLine().trimmed();\n file.close();\n \n // Compare absolute paths\n QFileInfo existingInfo(existingPdfPath);\n QFileInfo newInfo(pdfPath);\n isLinkedToSamePdf = (existingInfo.absoluteFilePath() == newInfo.absoluteFilePath());\n }\n }\n \n if (!isLinkedToSamePdf && QFile::exists(metadataFile)) {\n // Folder is linked to a different PDF, ask user what to do\n QMessageBox::StandardButton reply = QMessageBox::question(\n this,\n tr(\"Different PDF Linked\"),\n tr(\"This notebook folder is already linked to a different PDF file.\\n\\nDo you want to replace the link with the new PDF?\"),\n QMessageBox::Yes | QMessageBox::No\n );\n \n if (reply == QMessageBox::No) {\n return; // User chose not to replace\n }\n }\n \n // Set the existing folder as save folder\n canvas->setSaveFolder(selectedFolder);\n \n // Load the PDF\n canvas->loadPdf(pdfPath);\n \n // Update tab label and recent notebooks\n updateTabLabel();\n if (recentNotebooksManager) {\n recentNotebooksManager->addRecentNotebook(selectedFolder, canvas);\n }\n \n // Switch to page 1 and update UI\n switchPageWithDirection(1, 1);\n pageInput->setValue(1);\n updateZoom();\n updatePanRange();\n }\n}\n void setPdfDPI(int dpi) {\n if (dpi != pdfRenderDPI) {\n pdfRenderDPI = dpi;\n savePdfDPI(dpi);\n\n // Apply immediately to current canvas if needed\n if (currentCanvas()) {\n currentCanvas()->setPDFRenderDPI(dpi);\n currentCanvas()->clearPdfCache();\n currentCanvas()->loadPdfPage(getCurrentPageForCanvas(currentCanvas())); // Optional: add this if needed\n updateZoom();\n updatePanRange();\n }\n }\n}\n void savePdfDPI(int dpi) {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"pdfRenderDPI\", dpi);\n}\n void saveDefaultBackgroundSettings(BackgroundStyle style, QColor color, int density) {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"defaultBackgroundStyle\", static_cast(style));\n settings.setValue(\"defaultBackgroundColor\", color.name());\n settings.setValue(\"defaultBackgroundDensity\", density);\n}\n void loadDefaultBackgroundSettings(BackgroundStyle &style, QColor &color, int &density) {\n QSettings settings(\"SpeedyNote\", \"App\");\n style = static_cast(settings.value(\"defaultBackgroundStyle\", static_cast(BackgroundStyle::Grid)).toInt());\n color = QColor(settings.value(\"defaultBackgroundColor\", \"#FFFFFF\").toString());\n density = settings.value(\"defaultBackgroundDensity\", 30).toInt();\n \n // Ensure valid values\n if (!color.isValid()) color = Qt::white;\n if (density < 10) density = 10;\n if (density > 200) density = 200;\n}\n void saveThemeSettings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"useCustomAccentColor\", useCustomAccentColor);\n if (customAccentColor.isValid()) {\n settings.setValue(\"customAccentColor\", customAccentColor.name());\n }\n settings.setValue(\"useBrighterPalette\", useBrighterPalette);\n}\n void loadThemeSettings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n useCustomAccentColor = settings.value(\"useCustomAccentColor\", false).toBool();\n QString colorName = settings.value(\"customAccentColor\", \"#0078D4\").toString();\n customAccentColor = QColor(colorName);\n useBrighterPalette = settings.value(\"useBrighterPalette\", false).toBool();\n \n // Ensure valid values\n if (!customAccentColor.isValid()) {\n customAccentColor = QColor(\"#0078D4\"); // Default blue\n }\n \n // Apply theme immediately after loading\n updateTheme();\n}\n void updateTheme() {\n // Update control bar background color\n QColor accentColor = getAccentColor();\n if (controlBar) {\n controlBar->setStyleSheet(QString(R\"(\n QWidget#controlBar {\n background-color: %1;\n }\n )\").arg(accentColor.name()));\n }\n \n // Update dial background color\n if (pageDial) {\n pageDial->setStyleSheet(QString(R\"(\n QDial {\n background-color: %1;\n }\n )\").arg(accentColor.name()));\n }\n \n // Update add tab button styling\n if (addTabButton) {\n bool darkMode = isDarkMode();\n QString buttonBgColor = darkMode ? \"rgba(80, 80, 80, 255)\" : \"rgba(220, 220, 220, 255)\";\n QString buttonHoverColor = darkMode ? \"rgba(90, 90, 90, 255)\" : \"rgba(200, 200, 200, 255)\";\n QString buttonPressColor = darkMode ? \"rgba(70, 70, 70, 255)\" : \"rgba(180, 180, 180, 255)\";\n QString borderColor = darkMode ? \"rgba(100, 100, 100, 255)\" : \"rgba(180, 180, 180, 255)\";\n \n addTabButton->setStyleSheet(QString(R\"(\n QPushButton {\n background-color: %1;\n border: 1px solid %2;\n border-radius: 12px;\n margin: 2px;\n }\n QPushButton:hover {\n background-color: %3;\n }\n QPushButton:pressed {\n background-color: %4;\n }\n )\").arg(buttonBgColor).arg(borderColor).arg(buttonHoverColor).arg(buttonPressColor));\n }\n \n // Update PDF outline sidebar styling\n if (outlineSidebar && outlineTree) {\n bool darkMode = isDarkMode();\n QString bgColor = darkMode ? \"rgba(45, 45, 45, 255)\" : \"rgba(250, 250, 250, 255)\";\n QString borderColor = darkMode ? \"rgba(80, 80, 80, 255)\" : \"rgba(200, 200, 200, 255)\";\n QString textColor = darkMode ? \"#E0E0E0\" : \"#333\";\n QString hoverColor = darkMode ? \"rgba(60, 60, 60, 255)\" : \"rgba(240, 240, 240, 255)\";\n QString selectedColor = QString(\"rgba(%1, %2, %3, 100)\").arg(accentColor.red()).arg(accentColor.green()).arg(accentColor.blue());\n \n outlineSidebar->setStyleSheet(QString(R\"(\n QWidget {\n background-color: %1;\n border-right: 1px solid %2;\n }\n QLabel {\n color: %3;\n background: transparent;\n }\n )\").arg(bgColor).arg(borderColor).arg(textColor));\n \n outlineTree->setStyleSheet(QString(R\"(\n QTreeWidget {\n background-color: %1;\n border: none;\n color: %2;\n outline: none;\n }\n QTreeWidget::item {\n padding: 4px;\n border: none;\n }\n QTreeWidget::item:hover {\n background-color: %3;\n }\n QTreeWidget::item:selected {\n background-color: %4;\n color: %2;\n }\n QTreeWidget::branch {\n background: transparent;\n }\n QTreeWidget::branch:has-children:!has-siblings:closed,\n QTreeWidget::branch:closed:has-children:has-siblings {\n border-image: none;\n image: url(:/resources/icons/down_arrow.png);\n }\n QTreeWidget::branch:open:has-children:!has-siblings,\n QTreeWidget::branch:open:has-children:has-siblings {\n border-image: none;\n image: url(:/resources/icons/up_arrow.png);\n }\n QScrollBar:vertical {\n background: rgba(200, 200, 200, 80);\n border: none;\n margin: 0px;\n width: 16px !important;\n max-width: 16px !important;\n }\n QScrollBar:vertical:hover {\n background: rgba(200, 200, 200, 120);\n }\n QScrollBar::handle:vertical {\n background: rgba(100, 100, 100, 150);\n border-radius: 2px;\n min-height: 120px;\n }\n QScrollBar::handle:vertical:hover {\n background: rgba(80, 80, 80, 210);\n }\n QScrollBar::add-line:vertical, \n QScrollBar::sub-line:vertical {\n width: 0px;\n height: 0px;\n background: none;\n border: none;\n }\n QScrollBar::add-page:vertical, \n QScrollBar::sub-page:vertical {\n background: transparent;\n }\n )\").arg(bgColor).arg(textColor).arg(hoverColor).arg(selectedColor));\n \n // Apply same styling to bookmarks tree\n bookmarksTree->setStyleSheet(QString(R\"(\n QTreeWidget {\n background-color: %1;\n border: none;\n color: %2;\n outline: none;\n }\n QTreeWidget::item {\n padding: 2px;\n border: none;\n min-height: 26px;\n }\n QTreeWidget::item:hover {\n background-color: %3;\n }\n QTreeWidget::item:selected {\n background-color: %4;\n color: %2;\n }\n QScrollBar:vertical {\n background: rgba(200, 200, 200, 80);\n border: none;\n margin: 0px;\n width: 16px !important;\n max-width: 16px !important;\n }\n QScrollBar:vertical:hover {\n background: rgba(200, 200, 200, 120);\n }\n QScrollBar::handle:vertical {\n background: rgba(100, 100, 100, 150);\n border-radius: 2px;\n min-height: 120px;\n }\n QScrollBar::handle:vertical:hover {\n background: rgba(80, 80, 80, 210);\n }\n QScrollBar::add-line:vertical, \n QScrollBar::sub-line:vertical {\n width: 0px;\n height: 0px;\n background: none;\n border: none;\n }\n QScrollBar::add-page:vertical, \n QScrollBar::sub-page:vertical {\n background: transparent;\n }\n )\").arg(bgColor).arg(textColor).arg(hoverColor).arg(selectedColor));\n }\n \n // Update horizontal tab bar styling with accent color\n if (tabList) {\n bool darkMode = isDarkMode();\n QString bgColor = darkMode ? \"rgba(60, 60, 60, 255)\" : \"rgba(240, 240, 240, 255)\";\n QString itemBgColor = darkMode ? \"rgba(80, 80, 80, 255)\" : \"rgba(220, 220, 220, 255)\";\n QString selectedBgColor = darkMode ? \"rgba(45, 45, 45, 255)\" : \"white\";\n QString borderColor = darkMode ? \"rgba(100, 100, 100, 255)\" : \"rgba(180, 180, 180, 255)\";\n QString hoverBgColor = darkMode ? \"rgba(90, 90, 90, 255)\" : \"rgba(230, 230, 230, 255)\";\n \n tabList->setStyleSheet(QString(R\"(\n QListWidget {\n background-color: %1;\n border: none;\n border-bottom: 2px solid %2;\n outline: none;\n }\n QListWidget::item {\n background-color: %3;\n border: 1px solid %4;\n border-bottom: none;\n margin-right: 1px;\n margin-top: 2px;\n padding: 0px;\n min-width: 80px;\n max-width: 120px;\n }\n QListWidget::item:selected {\n background-color: %5;\n border: 1px solid %4;\n border-bottom: 2px solid %2;\n margin-top: 1px;\n }\n QListWidget::item:hover:!selected {\n background-color: %6;\n }\n QScrollBar:horizontal {\n background: %1;\n height: 8px;\n border: none;\n margin: 0px;\n border-top: 1px solid %4;\n }\n QScrollBar::handle:horizontal {\n background: rgba(150, 150, 150, 120);\n border-radius: 4px;\n min-width: 20px;\n margin: 1px;\n }\n QScrollBar::handle:horizontal:hover {\n background: rgba(120, 120, 120, 200);\n }\n QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal {\n width: 0px;\n height: 0px;\n background: none;\n border: none;\n }\n QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {\n background: transparent;\n }\n )\").arg(bgColor)\n .arg(accentColor.name())\n .arg(itemBgColor)\n .arg(borderColor)\n .arg(selectedBgColor)\n .arg(hoverBgColor));\n }\n \n\n \n // Force icon reload for all buttons that use themed icons\n if (loadPdfButton) loadPdfButton->setIcon(loadThemedIcon(\"pdf\"));\n if (clearPdfButton) clearPdfButton->setIcon(loadThemedIcon(\"pdfdelete\"));\n if (pdfTextSelectButton) pdfTextSelectButton->setIcon(loadThemedIcon(\"ibeam\"));\n if (exportNotebookButton) exportNotebookButton->setIcon(loadThemedIcon(\"export\"));\n if (importNotebookButton) importNotebookButton->setIcon(loadThemedIcon(\"import\"));\n if (benchmarkButton) benchmarkButton->setIcon(loadThemedIcon(\"benchmark\"));\n if (toggleTabBarButton) toggleTabBarButton->setIcon(loadThemedIcon(\"tabs\"));\n if (toggleOutlineButton) toggleOutlineButton->setIcon(loadThemedIcon(\"outline\"));\n if (toggleBookmarksButton) toggleBookmarksButton->setIcon(loadThemedIcon(\"bookmark\"));\n if (toggleBookmarkButton) toggleBookmarkButton->setIcon(loadThemedIcon(\"star\"));\n if (selectFolderButton) selectFolderButton->setIcon(loadThemedIcon(\"folder\"));\n if (saveButton) saveButton->setIcon(loadThemedIcon(\"save\"));\n if (saveAnnotatedButton) saveAnnotatedButton->setIcon(loadThemedIcon(\"saveannotated\"));\n if (fullscreenButton) fullscreenButton->setIcon(loadThemedIcon(\"fullscreen\"));\n if (backgroundButton) backgroundButton->setIcon(loadThemedIcon(\"background\"));\n if (straightLineToggleButton) straightLineToggleButton->setIcon(loadThemedIcon(\"straightLine\"));\n if (ropeToolButton) ropeToolButton->setIcon(loadThemedIcon(\"rope\"));\n if (markdownButton) markdownButton->setIcon(loadThemedIcon(\"markdown\"));\n if (deletePageButton) deletePageButton->setIcon(loadThemedIcon(\"trash\"));\n if (zoomButton) zoomButton->setIcon(loadThemedIcon(\"zoom\"));\n if (dialToggleButton) dialToggleButton->setIcon(loadThemedIcon(\"dial\"));\n if (fastForwardButton) fastForwardButton->setIcon(loadThemedIcon(\"fastforward\"));\n if (jumpToPageButton) jumpToPageButton->setIcon(loadThemedIcon(\"bookpage\"));\n if (thicknessButton) thicknessButton->setIcon(loadThemedIcon(\"thickness\"));\n if (btnPageSwitch) btnPageSwitch->setIcon(loadThemedIcon(\"bookpage\"));\n if (btnZoom) btnZoom->setIcon(loadThemedIcon(\"zoom\"));\n if (btnThickness) btnThickness->setIcon(loadThemedIcon(\"thickness\"));\n if (btnTool) btnTool->setIcon(loadThemedIcon(\"pen\"));\n if (btnPresets) btnPresets->setIcon(loadThemedIcon(\"preset\"));\n if (btnPannScroll) btnPannScroll->setIcon(loadThemedIcon(\"scroll\"));\n if (addPresetButton) addPresetButton->setIcon(loadThemedIcon(\"savepreset\"));\n if (openControlPanelButton) openControlPanelButton->setIcon(loadThemedIcon(\"settings\"));\n if (openRecentNotebooksButton) openRecentNotebooksButton->setIcon(loadThemedIcon(\"recent\"));\n if (penToolButton) penToolButton->setIcon(loadThemedIcon(\"pen\"));\n if (markerToolButton) markerToolButton->setIcon(loadThemedIcon(\"marker\"));\n if (eraserToolButton) eraserToolButton->setIcon(loadThemedIcon(\"eraser\"));\n \n // Update button styles with new theme\n bool darkMode = isDarkMode();\n QString newButtonStyle = createButtonStyle(darkMode);\n \n // Update all buttons that use the buttonStyle\n if (loadPdfButton) loadPdfButton->setStyleSheet(newButtonStyle);\n if (clearPdfButton) clearPdfButton->setStyleSheet(newButtonStyle);\n if (pdfTextSelectButton) pdfTextSelectButton->setStyleSheet(newButtonStyle);\n if (exportNotebookButton) exportNotebookButton->setStyleSheet(newButtonStyle);\n if (importNotebookButton) importNotebookButton->setStyleSheet(newButtonStyle);\n if (benchmarkButton) benchmarkButton->setStyleSheet(newButtonStyle);\n if (toggleTabBarButton) toggleTabBarButton->setStyleSheet(newButtonStyle);\n if (toggleOutlineButton) toggleOutlineButton->setStyleSheet(newButtonStyle);\n if (toggleBookmarksButton) toggleBookmarksButton->setStyleSheet(newButtonStyle);\n if (toggleBookmarkButton) toggleBookmarkButton->setStyleSheet(newButtonStyle);\n if (selectFolderButton) selectFolderButton->setStyleSheet(newButtonStyle);\n if (saveButton) saveButton->setStyleSheet(newButtonStyle);\n if (saveAnnotatedButton) saveAnnotatedButton->setStyleSheet(newButtonStyle);\n if (fullscreenButton) fullscreenButton->setStyleSheet(newButtonStyle);\n if (redButton) redButton->setStyleSheet(newButtonStyle);\n if (blueButton) blueButton->setStyleSheet(newButtonStyle);\n if (yellowButton) yellowButton->setStyleSheet(newButtonStyle);\n if (greenButton) greenButton->setStyleSheet(newButtonStyle);\n if (blackButton) blackButton->setStyleSheet(newButtonStyle);\n if (whiteButton) whiteButton->setStyleSheet(newButtonStyle);\n if (thicknessButton) thicknessButton->setStyleSheet(newButtonStyle);\n if (penToolButton) penToolButton->setStyleSheet(newButtonStyle);\n if (markerToolButton) markerToolButton->setStyleSheet(newButtonStyle);\n if (eraserToolButton) eraserToolButton->setStyleSheet(newButtonStyle);\n if (backgroundButton) backgroundButton->setStyleSheet(newButtonStyle);\n if (straightLineToggleButton) straightLineToggleButton->setStyleSheet(newButtonStyle);\n if (ropeToolButton) ropeToolButton->setStyleSheet(newButtonStyle);\n if (markdownButton) markdownButton->setStyleSheet(newButtonStyle);\n if (deletePageButton) deletePageButton->setStyleSheet(newButtonStyle);\n if (zoomButton) zoomButton->setStyleSheet(newButtonStyle);\n if (dialToggleButton) dialToggleButton->setStyleSheet(newButtonStyle);\n if (fastForwardButton) fastForwardButton->setStyleSheet(newButtonStyle);\n if (jumpToPageButton) jumpToPageButton->setStyleSheet(newButtonStyle);\n if (btnPageSwitch) btnPageSwitch->setStyleSheet(newButtonStyle);\n if (btnZoom) btnZoom->setStyleSheet(newButtonStyle);\n if (btnThickness) btnThickness->setStyleSheet(newButtonStyle);\n if (btnTool) btnTool->setStyleSheet(newButtonStyle);\n if (btnPresets) btnPresets->setStyleSheet(newButtonStyle);\n if (btnPannScroll) btnPannScroll->setStyleSheet(newButtonStyle);\n if (addPresetButton) addPresetButton->setStyleSheet(newButtonStyle);\n if (openControlPanelButton) openControlPanelButton->setStyleSheet(newButtonStyle);\n if (openRecentNotebooksButton) openRecentNotebooksButton->setStyleSheet(newButtonStyle);\n if (zoom50Button) zoom50Button->setStyleSheet(newButtonStyle);\n if (dezoomButton) dezoomButton->setStyleSheet(newButtonStyle);\n if (zoom200Button) zoom200Button->setStyleSheet(newButtonStyle);\n if (prevPageButton) prevPageButton->setStyleSheet(newButtonStyle);\n if (nextPageButton) nextPageButton->setStyleSheet(newButtonStyle);\n \n // Update color buttons with palette-based icons\n if (redButton) {\n QString redIconPath = useBrighterPalette ? \":/resources/icons/pen_light_red.png\" : \":/resources/icons/pen_dark_red.png\";\n redButton->setIcon(QIcon(redIconPath));\n }\n if (blueButton) {\n QString blueIconPath = useBrighterPalette ? \":/resources/icons/pen_light_blue.png\" : \":/resources/icons/pen_dark_blue.png\";\n blueButton->setIcon(QIcon(blueIconPath));\n }\n if (yellowButton) {\n QString yellowIconPath = useBrighterPalette ? \":/resources/icons/pen_light_yellow.png\" : \":/resources/icons/pen_dark_yellow.png\";\n yellowButton->setIcon(QIcon(yellowIconPath));\n }\n if (greenButton) {\n QString greenIconPath = useBrighterPalette ? \":/resources/icons/pen_light_green.png\" : \":/resources/icons/pen_dark_green.png\";\n greenButton->setIcon(QIcon(greenIconPath));\n }\n if (blackButton) {\n QString blackIconPath = darkMode ? \":/resources/icons/pen_light_black.png\" : \":/resources/icons/pen_dark_black.png\";\n blackButton->setIcon(QIcon(blackIconPath));\n }\n if (whiteButton) {\n QString whiteIconPath = darkMode ? \":/resources/icons/pen_light_white.png\" : \":/resources/icons/pen_dark_white.png\";\n whiteButton->setIcon(QIcon(whiteIconPath));\n }\n \n // Update tab close button icons and label styling\n if (tabList) {\n bool darkMode = isDarkMode();\n QString labelColor = darkMode ? \"#E0E0E0\" : \"#333\";\n \n for (int i = 0; i < tabList->count(); ++i) {\n QListWidgetItem *item = tabList->item(i);\n if (item) {\n QWidget *tabWidget = tabList->itemWidget(item);\n if (tabWidget) {\n QPushButton *closeButton = tabWidget->findChild();\n if (closeButton) {\n closeButton->setIcon(loadThemedIcon(\"cross\"));\n }\n \n QLabel *tabLabel = tabWidget->findChild(\"tabLabel\");\n if (tabLabel) {\n tabLabel->setStyleSheet(QString(\"color: %1; font-weight: 500; padding: 2px; text-align: left;\").arg(labelColor));\n }\n }\n }\n }\n }\n \n // Update dial display\n updateDialDisplay();\n}\n void migrateOldButtonMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n \n // Check if migration is needed by looking for old format strings\n settings.beginGroup(\"ButtonHoldMappings\");\n QStringList holdKeys = settings.allKeys();\n bool needsMigration = false;\n \n for (const QString &key : holdKeys) {\n QString value = settings.value(key).toString();\n // If we find old English strings, we need to migrate\n if (value == \"PageSwitching\" || value == \"ZoomControl\" || value == \"ThicknessControl\" ||\n value == \"ToolSwitching\" || value == \"PresetSelection\" ||\n value == \"PanAndPageScroll\") {\n needsMigration = true;\n break;\n }\n }\n settings.endGroup();\n \n if (!needsMigration) {\n settings.beginGroup(\"ButtonPressMappings\");\n QStringList pressKeys = settings.allKeys();\n for (const QString &key : pressKeys) {\n QString value = settings.value(key).toString();\n // Check for old English action strings\n if (value == \"Toggle Fullscreen\" || value == \"Toggle Dial\" || value == \"Zoom 50%\" ||\n value == \"Add Preset\" || value == \"Delete Page\" || value == \"Fast Forward\" ||\n value == \"Open Control Panel\" || value == \"Custom Color\") {\n needsMigration = true;\n break;\n }\n }\n settings.endGroup();\n }\n \n if (!needsMigration) return;\n \n // Perform migration\n // qDebug() << \"Migrating old button mappings to new format...\";\n \n // Migrate hold mappings\n settings.beginGroup(\"ButtonHoldMappings\");\n holdKeys = settings.allKeys();\n for (const QString &key : holdKeys) {\n QString oldValue = settings.value(key).toString();\n QString newValue = migrateOldDialModeString(oldValue);\n if (newValue != oldValue) {\n settings.setValue(key, newValue);\n }\n }\n settings.endGroup();\n \n // Migrate press mappings\n settings.beginGroup(\"ButtonPressMappings\");\n QStringList pressKeys = settings.allKeys();\n for (const QString &key : pressKeys) {\n QString oldValue = settings.value(key).toString();\n QString newValue = migrateOldActionString(oldValue);\n if (newValue != oldValue) {\n settings.setValue(key, newValue);\n }\n }\n settings.endGroup();\n \n // qDebug() << \"Button mapping migration completed.\";\n}\n QString migrateOldDialModeString(const QString &oldString) {\n // Convert old English strings to new internal keys\n if (oldString == \"None\") return \"none\";\n if (oldString == \"PageSwitching\") return \"page_switching\";\n if (oldString == \"ZoomControl\") return \"zoom_control\";\n if (oldString == \"ThicknessControl\") return \"thickness_control\";\n\n if (oldString == \"ToolSwitching\") return \"tool_switching\";\n if (oldString == \"PresetSelection\") return \"preset_selection\";\n if (oldString == \"PanAndPageScroll\") return \"pan_and_page_scroll\";\n return oldString; // Return as-is if not found (might already be new format)\n}\n QString migrateOldActionString(const QString &oldString) {\n // Convert old English strings to new internal keys\n if (oldString == \"None\") return \"none\";\n if (oldString == \"Toggle Fullscreen\") return \"toggle_fullscreen\";\n if (oldString == \"Toggle Dial\") return \"toggle_dial\";\n if (oldString == \"Zoom 50%\") return \"zoom_50\";\n if (oldString == \"Zoom Out\") return \"zoom_out\";\n if (oldString == \"Zoom 200%\") return \"zoom_200\";\n if (oldString == \"Add Preset\") return \"add_preset\";\n if (oldString == \"Delete Page\") return \"delete_page\";\n if (oldString == \"Fast Forward\") return \"fast_forward\";\n if (oldString == \"Open Control Panel\") return \"open_control_panel\";\n if (oldString == \"Red\") return \"red_color\";\n if (oldString == \"Blue\") return \"blue_color\";\n if (oldString == \"Yellow\") return \"yellow_color\";\n if (oldString == \"Green\") return \"green_color\";\n if (oldString == \"Black\") return \"black_color\";\n if (oldString == \"White\") return \"white_color\";\n if (oldString == \"Custom Color\") return \"custom_color\";\n if (oldString == \"Toggle Sidebar\") return \"toggle_sidebar\";\n if (oldString == \"Save\") return \"save\";\n if (oldString == \"Straight Line Tool\") return \"straight_line_tool\";\n if (oldString == \"Rope Tool\") return \"rope_tool\";\n if (oldString == \"Set Pen Tool\") return \"set_pen_tool\";\n if (oldString == \"Set Marker Tool\") return \"set_marker_tool\";\n if (oldString == \"Set Eraser Tool\") return \"set_eraser_tool\";\n if (oldString == \"Toggle PDF Text Selection\") return \"toggle_pdf_text_selection\";\n return oldString; // Return as-is if not found (might already be new format)\n}\n InkCanvas* currentCanvas();\n void saveCurrentPage() {\n currentCanvas()->saveToFile(getCurrentPageForCanvas(currentCanvas()));\n}\n void saveCurrentPageConcurrent() {\n InkCanvas *canvas = currentCanvas();\n if (!canvas || !canvas->isEdited()) return;\n \n int pageNumber = getCurrentPageForCanvas(canvas);\n QString saveFolder = canvas->getSaveFolder();\n \n if (saveFolder.isEmpty()) return;\n \n // Create a copy of the buffer for concurrent saving\n QPixmap bufferCopy = canvas->getBuffer();\n \n // Save markdown windows for this page (this must be done on the main thread)\n if (canvas->getMarkdownManager()) {\n canvas->getMarkdownManager()->saveWindowsForPage(pageNumber);\n }\n \n // Run the save operation concurrently\n QFuture future = QtConcurrent::run([saveFolder, pageNumber, bufferCopy]() {\n // Get notebook ID from the save folder (similar to how InkCanvas does it)\n QString notebookId = \"notebook\"; // Default fallback\n QString idFile = saveFolder + \"/.notebook_id.txt\";\n if (QFile::exists(idFile)) {\n QFile file(idFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n notebookId = in.readLine().trimmed();\n file.close();\n }\n }\n \n QString filePath = saveFolder + QString(\"/%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n \n QImage image(bufferCopy.size(), QImage::Format_ARGB32);\n image.fill(Qt::transparent);\n QPainter painter(&image);\n painter.drawPixmap(0, 0, bufferCopy);\n image.save(filePath, \"PNG\");\n });\n \n // Mark as not edited since we're saving\n canvas->setEdited(false);\n}\n void switchPage(int pageNumber) {\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n\n if (currentCanvas()->isEdited()){\n saveCurrentPageConcurrent(); // Use concurrent saving for smoother page flipping\n }\n\n int oldPage = getCurrentPageForCanvas(currentCanvas()) + 1; // Convert to 1-based for comparison\n int newPage = pageNumber - 1;\n pageMap[canvas] = newPage; // ✅ Save the page for this tab\n\n if (canvas->isPdfLoadedFunc() && pageNumber - 1 < canvas->getTotalPdfPages()) {\n canvas->loadPdfPage(newPage);\n } else {\n canvas->loadPage(newPage);\n }\n\n canvas->setLastActivePage(newPage);\n updateZoom();\n // It seems panXSlider and panYSlider can be null here during startup.\n if(panXSlider && panYSlider){\n canvas->setLastPanX(panXSlider->maximum());\n canvas->setLastPanY(panYSlider->maximum());\n \n // ✅ Enhanced scroll-on-top functionality\n if (scrollOnTopEnabled && panYSlider->maximum() > 0) {\n if (pageNumber > oldPage) {\n // Forward page switching → scroll to top\n panYSlider->setValue(0);\n } else if (pageNumber < oldPage) {\n // Backward page switching → scroll to bottom\n panYSlider->setValue(panYSlider->maximum());\n }\n }\n }\n updateDialDisplay();\n updateBookmarkButtonState(); // Update bookmark button state when switching pages\n}\n void switchPageWithDirection(int pageNumber, int direction) {\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n\n if (currentCanvas()->isEdited()){\n saveCurrentPageConcurrent(); // Use concurrent saving for smoother page flipping\n }\n\n int newPage = pageNumber - 1;\n pageMap[canvas] = newPage; // ✅ Save the page for this tab\n\n if (canvas->isPdfLoadedFunc() && pageNumber - 1 < canvas->getTotalPdfPages()) {\n canvas->loadPdfPage(newPage);\n } else {\n canvas->loadPage(newPage);\n }\n\n canvas->setLastActivePage(newPage);\n updateZoom();\n // It seems panXSlider and panYSlider can be null here during startup.\n if(panXSlider && panYSlider){\n canvas->setLastPanX(panXSlider->maximum());\n canvas->setLastPanY(panYSlider->maximum());\n \n // ✅ Enhanced scroll-on-top functionality with explicit direction\n if (scrollOnTopEnabled && panYSlider->maximum() > 0) {\n if (direction > 0) {\n // Forward page switching → scroll to top\n panYSlider->setValue(0);\n } else if (direction < 0) {\n // Backward page switching → scroll to bottom\n panYSlider->setValue(panYSlider->maximum());\n }\n }\n }\n updateDialDisplay();\n updateBookmarkButtonState(); // Update bookmark button state when switching pages\n}\n void updateTabLabel() {\n int index = tabList->currentRow();\n if (index < 0) return;\n\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n\n QString folderPath = canvas->getSaveFolder(); // ✅ Get save folder\n if (folderPath.isEmpty()) return;\n\n QString tabName;\n\n // ✅ Check if there is an assigned PDF\n QString metadataFile = folderPath + \"/.pdf_path.txt\";\n if (QFile::exists(metadataFile)) {\n QFile file(metadataFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString pdfPath = in.readLine().trimmed();\n file.close();\n\n // ✅ Extract just the PDF filename (not full path)\n QFileInfo pdfInfo(pdfPath);\n if (pdfInfo.exists()) {\n tabName = elideTabText(pdfInfo.fileName(), 90); // e.g., \"mydocument.pdf\" (elided)\n }\n }\n }\n\n // ✅ If no PDF, use the folder name\n if (tabName.isEmpty()) {\n QFileInfo folderInfo(folderPath);\n tabName = elideTabText(folderInfo.fileName(), 90); // e.g., \"MyNotebook\" (elided)\n }\n\n QListWidgetItem *tabItem = tabList->item(index);\n if (tabItem) {\n QWidget *tabWidget = tabList->itemWidget(tabItem); // Get the tab's custom widget\n if (tabWidget) {\n QLabel *tabLabel = tabWidget->findChild(); // Get the QLabel inside\n if (tabLabel) {\n tabLabel->setText(tabName); // ✅ Update tab label\n tabLabel->setWordWrap(false); // No wrapping for horizontal tabs\n }\n }\n }\n}\n QSpinBox *pageInput;\n QPushButton *prevPageButton;\n QPushButton *nextPageButton;\n void addKeyboardMapping(const QString &keySequence, const QString &action) {\n // List of IME-related shortcuts that should not be intercepted\n QStringList imeShortcuts = {\n \"Ctrl+Space\", // Primary IME toggle\n \"Ctrl+Shift\", // Language switching\n \"Ctrl+Alt\", // IME functions\n \"Shift+Alt\", // Alternative language switching\n \"Alt+Shift\" // Alternative language switching (reversed)\n };\n \n // Don't allow mapping of IME-related shortcuts\n if (imeShortcuts.contains(keySequence)) {\n qWarning() << \"Cannot map IME-related shortcut:\" << keySequence;\n return;\n }\n \n keyboardMappings[keySequence] = action;\n keyboardActionMapping[keySequence] = stringToAction(action);\n saveKeyboardMappings();\n}\n void removeKeyboardMapping(const QString &keySequence) {\n keyboardMappings.remove(keySequence);\n keyboardActionMapping.remove(keySequence);\n saveKeyboardMappings();\n}\n QMap getKeyboardMappings() const {\n return keyboardMappings;\n}\n void reconnectControllerSignals() {\n if (!controllerManager || !pageDial) {\n return;\n }\n \n // Reset internal dial state\n tracking = false;\n accumulatedRotation = 0;\n grossTotalClicks = 0;\n tempClicks = 0;\n lastAngle = 0;\n startAngle = 0;\n pendingPageFlip = 0;\n accumulatedRotationAfterLimit = 0;\n \n // Disconnect all existing connections to avoid duplicates\n disconnect(controllerManager, nullptr, this, nullptr);\n disconnect(controllerManager, nullptr, pageDial, nullptr);\n \n // Reconnect all controller signals\n connect(controllerManager, &SDLControllerManager::buttonHeld, this, &MainWindow::handleButtonHeld);\n connect(controllerManager, &SDLControllerManager::buttonReleased, this, &MainWindow::handleButtonReleased);\n connect(controllerManager, &SDLControllerManager::leftStickAngleChanged, pageDial, &QDial::setValue);\n connect(controllerManager, &SDLControllerManager::leftStickReleased, pageDial, &QDial::sliderReleased);\n connect(controllerManager, &SDLControllerManager::buttonSinglePress, this, &MainWindow::handleControllerButton);\n \n // Re-establish dial mode connections by changing to current mode\n DialMode currentMode = currentDialMode;\n changeDialMode(currentMode);\n \n // Update dial display to reflect current state\n updateDialDisplay();\n \n // qDebug() << \"Controller signals reconnected successfully\";\n}\n void updateDialButtonState() {\n // Check if dial is visible\n bool isDialVisible = dialContainer && dialContainer->isVisible();\n \n if (dialToggleButton) {\n dialToggleButton->setProperty(\"selected\", isDialVisible);\n \n // Force style update\n dialToggleButton->style()->unpolish(dialToggleButton);\n dialToggleButton->style()->polish(dialToggleButton);\n }\n}\n void updateFastForwardButtonState() {\n if (fastForwardButton) {\n fastForwardButton->setProperty(\"selected\", fastForwardMode);\n \n // Force style update\n fastForwardButton->style()->unpolish(fastForwardButton);\n fastForwardButton->style()->polish(fastForwardButton);\n }\n}\n void updateToolButtonStates() {\n if (!currentCanvas()) return;\n \n // Reset all tool buttons\n penToolButton->setProperty(\"selected\", false);\n markerToolButton->setProperty(\"selected\", false);\n eraserToolButton->setProperty(\"selected\", false);\n \n // Set the selected property for the current tool\n ToolType currentTool = currentCanvas()->getCurrentTool();\n switch (currentTool) {\n case ToolType::Pen:\n penToolButton->setProperty(\"selected\", true);\n break;\n case ToolType::Marker:\n markerToolButton->setProperty(\"selected\", true);\n break;\n case ToolType::Eraser:\n eraserToolButton->setProperty(\"selected\", true);\n break;\n }\n \n // Force style update\n penToolButton->style()->unpolish(penToolButton);\n penToolButton->style()->polish(penToolButton);\n markerToolButton->style()->unpolish(markerToolButton);\n markerToolButton->style()->polish(markerToolButton);\n eraserToolButton->style()->unpolish(eraserToolButton);\n eraserToolButton->style()->polish(eraserToolButton);\n}\n void handleColorButtonClick() {\n if (!currentCanvas()) return;\n \n ToolType currentTool = currentCanvas()->getCurrentTool();\n \n // If in eraser mode, switch back to pen mode\n if (currentTool == ToolType::Eraser) {\n currentCanvas()->setTool(ToolType::Pen);\n updateToolButtonStates();\n updateThicknessSliderForCurrentTool();\n }\n \n // If rope tool is enabled, turn it off\n if (currentCanvas()->isRopeToolMode()) {\n currentCanvas()->setRopeToolMode(false);\n updateRopeToolButtonState();\n }\n \n // For marker and straight line mode, leave them as they are\n // No special handling needed - they can work with color changes\n}\n void updateThicknessSliderForCurrentTool() {\n if (!currentCanvas() || !thicknessSlider) return;\n \n // Block signals to prevent recursive calls\n thicknessSlider->blockSignals(true);\n \n // Update slider to reflect current tool's thickness\n qreal currentThickness = currentCanvas()->getPenThickness();\n \n // Convert thickness back to slider value (reverse of updateThickness calculation)\n qreal visualThickness = currentThickness * (currentCanvas()->getZoom() / 100.0);\n int sliderValue = qBound(1, static_cast(qRound(visualThickness)), 50);\n \n thicknessSlider->setValue(sliderValue);\n thicknessSlider->blockSignals(false);\n}\n void updatePdfTextSelectButtonState() {\n // Check if PDF text selection is enabled\n bool isEnabled = currentCanvas() && currentCanvas()->isPdfTextSelectionEnabled();\n \n if (pdfTextSelectButton) {\n pdfTextSelectButton->setProperty(\"selected\", isEnabled);\n \n // Force style update (uses the same buttonStyle as other toggle buttons)\n pdfTextSelectButton->style()->unpolish(pdfTextSelectButton);\n pdfTextSelectButton->style()->polish(pdfTextSelectButton);\n }\n}\n private:\n void toggleBenchmark() {\n benchmarking = !benchmarking;\n if (benchmarking) {\n currentCanvas()->startBenchmark();\n benchmarkTimer->start(1000); // Update every second\n } else {\n currentCanvas()->stopBenchmark();\n benchmarkTimer->stop();\n benchmarkLabel->setText(tr(\"PR:N/A\"));\n }\n}\n void updateBenchmarkDisplay() {\n int sampleRate = currentCanvas()->getProcessedRate();\n benchmarkLabel->setText(QString(tr(\"PR:%1 Hz\")).arg(sampleRate));\n}\n void applyCustomColor() {\n QString colorCode = customColorInput->text();\n if (!colorCode.startsWith(\"#\")) {\n colorCode.prepend(\"#\");\n }\n currentCanvas()->setPenColor(QColor(colorCode));\n updateDialDisplay(); \n}\n void updateThickness(int value) {\n // Calculate thickness based on the slider value at 100% zoom\n // The slider value represents the desired visual thickness\n qreal visualThickness = value; // Scale slider value to reasonable thickness\n \n // Apply zoom scaling to maintain visual consistency\n qreal actualThickness = visualThickness * (100.0 / currentCanvas()->getZoom()); \n \n currentCanvas()->setPenThickness(actualThickness);\n}\n void adjustThicknessForZoom(int oldZoom, int newZoom) {\n // Adjust all tool thicknesses to maintain visual consistency when zoom changes\n if (oldZoom == newZoom || oldZoom <= 0 || newZoom <= 0) return;\n \n InkCanvas* canvas = currentCanvas();\n if (!canvas) return;\n \n qreal zoomRatio = qreal(oldZoom) / qreal(newZoom);\n ToolType currentTool = canvas->getCurrentTool();\n \n // Adjust thickness for all tools, not just the current one\n canvas->adjustAllToolThicknesses(zoomRatio);\n \n // Update the thickness slider to reflect the current tool's new thickness\n updateThicknessSliderForCurrentTool();\n \n // ✅ FIXED: Update dial display to show new thickness immediately during zoom changes\n updateDialDisplay();\n}\n void changeTool(int index) {\n if (index == 0) {\n currentCanvas()->setTool(ToolType::Pen);\n } else if (index == 1) {\n currentCanvas()->setTool(ToolType::Marker);\n } else if (index == 2) {\n currentCanvas()->setTool(ToolType::Eraser);\n }\n updateToolButtonStates();\n updateThicknessSliderForCurrentTool();\n updateDialDisplay();\n}\n void selectFolder() {\n QString folder = QFileDialog::getExistingDirectory(this, tr(\"Select Save Folder\"));\n if (!folder.isEmpty()) {\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n if (canvas->isEdited()){\n saveCurrentPage();\n }\n canvas->setSaveFolder(folder);\n switchPageWithDirection(1, 1); // Going to page 1 is forward direction\n pageInput->setValue(1);\n updateTabLabel();\n recentNotebooksManager->addRecentNotebook(folder, canvas); // Track when folder is selected\n }\n }\n}\n void saveCanvas() {\n currentCanvas()->saveToFile(getCurrentPageForCanvas(currentCanvas()));\n}\n void saveAnnotated() {\n currentCanvas()->saveAnnotated(getCurrentPageForCanvas(currentCanvas()));\n}\n void deleteCurrentPage() {\n currentCanvas()->deletePage(getCurrentPageForCanvas(currentCanvas()));\n}\n void loadPdf() {\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n\n QString saveFolder = canvas->getSaveFolder();\n QString tempDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\";\n \n // Check if no save folder is set or if it's the temporary directory\n if (saveFolder.isEmpty() || saveFolder == tempDir) {\n QMessageBox::warning(this, tr(\"Cannot Load PDF\"), \n tr(\"Please select a permanent save folder before loading a PDF.\\n\\nClick the folder icon to choose a location for your notebook.\"));\n return;\n }\n\n QString filePath = QFileDialog::getOpenFileName(this, tr(\"Select PDF\"), \"\", \"PDF Files (*.pdf)\");\n if (!filePath.isEmpty()) {\n currentCanvas()->loadPdf(filePath);\n updateTabLabel(); // ✅ Update the tab name after assigning a PDF\n updateZoom(); // ✅ Update zoom and pan range after PDF is loaded\n \n // Refresh PDF outline if sidebar is visible\n if (outlineSidebarVisible) {\n loadPdfOutline();\n }\n }\n}\n void clearPdf() {\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n \n canvas->clearPdf();\n updateZoom(); // ✅ Update zoom and pan range after PDF is cleared\n}\n void updateZoom() {\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n canvas->setZoom(zoomSlider->value());\n canvas->setLastZoomLevel(zoomSlider->value()); // ✅ Store zoom level per tab\n updatePanRange();\n // updateThickness(thicknessSlider->value()); // ✅ REMOVED: This was resetting thickness on page switch\n // updateDialDisplay();\n }\n}\n void onZoomSliderChanged(int value) {\n // This handles manual zoom slider changes and preserves thickness\n int oldZoom = currentCanvas() ? currentCanvas()->getZoom() : 100;\n int newZoom = value;\n \n updateZoom();\n adjustThicknessForZoom(oldZoom, newZoom); // Maintain visual thickness consistency\n}\n void applyZoom() {\n bool ok;\n int zoomValue = zoomInput->text().toInt(&ok);\n if (ok && zoomValue > 0) {\n currentCanvas()->setZoom(zoomValue);\n updatePanRange(); // Update slider range after zoom change\n }\n}\n void updatePanRange() {\n int zoom = currentCanvas()->getZoom();\n\n QSize canvasSize = currentCanvas()->getCanvasSize();\n QSize viewportSize = QGuiApplication::primaryScreen()->size() * QGuiApplication::primaryScreen()->devicePixelRatio();\n qreal dpr = initialDpr;\n \n // Get the actual widget size instead of screen size for more accurate calculation\n QSize actualViewportSize = size();\n \n // Adjust viewport size for toolbar and tab bar layout\n QSize effectiveViewportSize = actualViewportSize;\n int toolbarHeight = isToolbarTwoRows ? 80 : 50; // Toolbar height\n int tabBarHeight = (tabBarContainer && tabBarContainer->isVisible()) ? 38 : 0; // Tab bar height\n effectiveViewportSize.setHeight(actualViewportSize.height() - toolbarHeight - tabBarHeight);\n \n // Calculate scaled canvas size using proper DPR scaling\n int scaledCanvasWidth = canvasSize.width() * zoom / 100;\n int scaledCanvasHeight = canvasSize.height() * zoom / 100;\n \n // Calculate max pan values - if canvas is smaller than viewport, pan should be 0\n int maxPanX = qMax(0, scaledCanvasWidth - effectiveViewportSize.width());\n int maxPanY = qMax(0, scaledCanvasHeight - effectiveViewportSize.height());\n\n // Scale the pan range properly\n int maxPanX_scaled = maxPanX * 100 / zoom;\n int maxPanY_scaled = maxPanY * 100 / zoom;\n\n // Set range to 0 when canvas is smaller than viewport (centered)\n if (scaledCanvasWidth <= effectiveViewportSize.width()) {\n panXSlider->setRange(0, 0);\n panXSlider->setValue(0);\n // No need for horizontal scrollbar\n panXSlider->setVisible(false);\n } else {\n panXSlider->setRange(0, maxPanX_scaled);\n // Show scrollbar only if mouse is near and timeout hasn't occurred\n if (scrollbarsVisible && !scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->start();\n }\n }\n \n if (scaledCanvasHeight <= effectiveViewportSize.height()) {\n panYSlider->setRange(0, 0);\n panYSlider->setValue(0);\n // No need for vertical scrollbar\n panYSlider->setVisible(false);\n } else {\n panYSlider->setRange(0, maxPanY_scaled);\n // Show scrollbar only if mouse is near and timeout hasn't occurred\n if (scrollbarsVisible && !scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->start();\n }\n }\n}\n void updatePanX(int value) {\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n canvas->setPanX(value);\n canvas->setLastPanX(value); // ✅ Store panX per tab\n \n // Show horizontal scrollbar temporarily\n if (panXSlider->maximum() > 0) {\n panXSlider->setVisible(true);\n scrollbarsVisible = true;\n \n // Make sure scrollbar position matches the canvas position\n if (panXSlider->value() != value) {\n panXSlider->blockSignals(true);\n panXSlider->setValue(value);\n panXSlider->blockSignals(false);\n }\n \n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n scrollbarHideTimer->start();\n }\n }\n}\n void updatePanY(int value) {\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n canvas->setPanY(value);\n canvas->setLastPanY(value); // ✅ Store panY per tab\n \n // Show vertical scrollbar temporarily\n if (panYSlider->maximum() > 0) {\n panYSlider->setVisible(true);\n scrollbarsVisible = true;\n \n // Make sure scrollbar position matches the canvas position\n if (panYSlider->value() != value) {\n panYSlider->blockSignals(true);\n panYSlider->setValue(value);\n panYSlider->blockSignals(false);\n }\n \n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n scrollbarHideTimer->start();\n }\n }\n}\n void selectBackground() {\n QString filePath = QFileDialog::getOpenFileName(this, tr(\"Select Background Image\"), \"\", \"Images (*.png *.jpg *.jpeg)\");\n if (!filePath.isEmpty()) {\n currentCanvas()->setBackground(filePath, getCurrentPageForCanvas(currentCanvas()));\n updateZoom(); // ✅ Update zoom and pan range after background is set\n }\n}\n void forceUIRefresh() {\n setWindowState(Qt::WindowNoState); // Restore first\n setWindowState(Qt::WindowMaximized); // Maximize again\n}\n void switchTab(int index) {\n if (!canvasStack || !tabList || !pageInput || !zoomSlider || !panXSlider || !panYSlider) {\n // qDebug() << \"Error: switchTab() called before UI was fully initialized!\";\n return;\n }\n\n if (index >= 0 && index < canvasStack->count()) {\n canvasStack->setCurrentIndex(index);\n \n // Ensure the tab list selection is properly set and styled\n if (tabList->currentRow() != index) {\n tabList->setCurrentRow(index);\n }\n \n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n int savedPage = canvas->getLastActivePage();\n \n // ✅ Only call blockSignals if pageInput is valid\n if (pageInput) { \n pageInput->blockSignals(true);\n pageInput->setValue(savedPage + 1);\n pageInput->blockSignals(false);\n }\n\n // ✅ Ensure zoomSlider exists before calling methods\n if (zoomSlider) {\n zoomSlider->blockSignals(true);\n zoomSlider->setValue(canvas->getLastZoomLevel());\n zoomSlider->blockSignals(false);\n canvas->setZoom(canvas->getLastZoomLevel());\n }\n\n // ✅ Ensure pan sliders exist before modifying values\n if (panXSlider && panYSlider) {\n panXSlider->blockSignals(true);\n panYSlider->blockSignals(true);\n panXSlider->setValue(canvas->getLastPanX());\n panYSlider->setValue(canvas->getLastPanY());\n panXSlider->blockSignals(false);\n panYSlider->blockSignals(false);\n updatePanRange();\n }\n updateDialDisplay();\n updateColorButtonStates(); // Update button states when switching tabs\n updateStraightLineButtonState(); // Update straight line button state when switching tabs\n updateRopeToolButtonState(); // Update rope tool button state when switching tabs\n updateMarkdownButtonState(); // Update markdown button state when switching tabs\n updatePdfTextSelectButtonState(); // Update PDF text selection button state when switching tabs\n updateBookmarkButtonState(); // Update bookmark button state when switching tabs\n updateDialButtonState(); // Update dial button state when switching tabs\n updateFastForwardButtonState(); // Update fast forward button state when switching tabs\n updateToolButtonStates(); // Update tool button states when switching tabs\n updateThicknessSliderForCurrentTool(); // Update thickness slider for current tool when switching tabs\n \n // Refresh PDF outline if sidebar is visible\n if (outlineSidebarVisible) {\n loadPdfOutline();\n }\n }\n }\n}\n void addNewTab() {\n if (!tabList || !canvasStack) return; // Ensure tabList and canvasStack exist\n\n int newTabIndex = tabList->count(); // New tab index\n QWidget *tabWidget = new QWidget(); // Custom tab container\n tabWidget->setObjectName(\"tabWidget\"); // Name the widget for easy retrieval later\n QHBoxLayout *tabLayout = new QHBoxLayout(tabWidget);\n tabLayout->setContentsMargins(5, 2, 5, 2);\n\n // ✅ Create the label (Tab Name) - optimized for horizontal layout\n QLabel *tabLabel = new QLabel(QString(\"Tab %1\").arg(newTabIndex + 1), tabWidget); \n tabLabel->setObjectName(\"tabLabel\"); // ✅ Name the label for easy retrieval later\n tabLabel->setWordWrap(false); // ✅ No wrapping for horizontal tabs\n tabLabel->setFixedWidth(115); // ✅ Narrower width for compact layout\n tabLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);\n tabLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter); // Left-align to show filename start\n tabLabel->setTextFormat(Qt::PlainText); // Ensure plain text for proper eliding\n // Tab label styling will be updated by theme\n\n // ✅ Create the close button (❌) - styled for browser-like tabs\n QPushButton *closeButton = new QPushButton(tabWidget);\n closeButton->setFixedSize(14, 14); // Smaller to fit narrower tabs\n closeButton->setIcon(loadThemedIcon(\"cross\")); // Set themed icon\n closeButton->setStyleSheet(R\"(\n QPushButton { \n border: none; \n background: transparent; \n border-radius: 6px;\n padding: 1px;\n }\n QPushButton:hover { \n background: rgba(255, 100, 100, 150); \n border-radius: 6px;\n }\n QPushButton:pressed { \n background: rgba(255, 50, 50, 200); \n border-radius: 6px;\n }\n )\"); // Themed styling with hover and press effects\n \n // ✅ Create new InkCanvas instance EARLIER so it can be captured by the lambda\n InkCanvas *newCanvas = new InkCanvas(this);\n \n // ✅ Handle tab closing when the button is clicked\n connect(closeButton, &QPushButton::clicked, this, [=]() { // newCanvas is now captured\n\n // Prevent closing if it's the last remaining tab\n if (tabList->count() <= 1) {\n // Optional: show a message or do nothing silently\n QMessageBox::information(this, tr(\"Notice\"), tr(\"At least one tab must remain open.\"));\n\n return;\n }\n\n // Find the index of the tab associated with this button's parent (tabWidget)\n int indexToRemove = -1;\n // newCanvas is captured by the lambda, representing the canvas of the tab being closed.\n // tabWidget is also captured.\n for (int i = 0; i < tabList->count(); ++i) {\n if (tabList->itemWidget(tabList->item(i)) == tabWidget) {\n indexToRemove = i;\n break;\n }\n }\n\n if (indexToRemove == -1) {\n qWarning() << \"Could not find tab to remove based on tabWidget.\";\n // Fallback or error handling if needed, though this shouldn't happen if tabWidget is valid.\n // As a fallback, try to find the index based on newCanvas if lists are in sync.\n for (int i = 0; i < canvasStack->count(); ++i) {\n if (canvasStack->widget(i) == newCanvas) {\n indexToRemove = i;\n break;\n }\n }\n if (indexToRemove == -1) {\n qWarning() << \"Could not find tab to remove based on newCanvas either.\";\n return; // Critical error, cannot proceed.\n }\n }\n \n // At this point, newCanvas is the InkCanvas instance for the tab being closed.\n // And indexToRemove is its index in tabList and canvasStack.\n\n // 1. Ensure the notebook has a unique save folder if it's temporary/edited\n ensureTabHasUniqueSaveFolder(newCanvas); // Pass the specific canvas\n\n // 2. Get the final save folder path\n QString folderPath = newCanvas->getSaveFolder();\n QString tempDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\";\n\n // 3. Update cover preview and recent list if it's a permanent notebook\n if (!folderPath.isEmpty() && folderPath != tempDir && recentNotebooksManager) {\n recentNotebooksManager->generateAndSaveCoverPreview(folderPath, newCanvas);\n // Add/update in recent list. This also moves it to the top.\n recentNotebooksManager->addRecentNotebook(folderPath, newCanvas);\n }\n \n // 4. Update the tab's label directly as folderPath might have changed\n QLabel *label = tabWidget->findChild(\"tabLabel\");\n if (label) {\n QString tabNameText;\n if (!folderPath.isEmpty() && folderPath != tempDir) { // Only for permanent notebooks\n QString metadataFile = folderPath + \"/.pdf_path.txt\";\n if (QFile::exists(metadataFile)) {\n QFile file(metadataFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString pdfPath = in.readLine().trimmed();\n file.close();\n if (QFile::exists(pdfPath)) { // Check if PDF file actually exists\n tabNameText = elideTabText(QFileInfo(pdfPath).fileName(), 90); // Elide to fit tab width\n }\n }\n }\n // Fallback to folder name if no PDF or PDF path invalid\n if (tabNameText.isEmpty()) {\n tabNameText = elideTabText(QFileInfo(folderPath).fileName(), 90); // Elide to fit tab width\n }\n }\n // Only update the label if a new valid name was determined.\n // If it's still a temp folder, the original \"Tab X\" label remains appropriate.\n if (!tabNameText.isEmpty()) {\n label->setText(tabNameText);\n }\n }\n\n // 5. Remove the tab\n removeTabAt(indexToRemove);\n });\n\n\n // ✅ Add widgets to the tab layout\n tabLayout->addWidget(tabLabel);\n tabLayout->addWidget(closeButton);\n tabLayout->setStretch(0, 1);\n tabLayout->setStretch(1, 0);\n \n // ✅ Create the tab item and set widget (horizontal layout)\n QListWidgetItem *tabItem = new QListWidgetItem();\n tabItem->setSizeHint(QSize(135, 22)); // ✅ Narrower and thinner for compact layout\n tabList->addItem(tabItem);\n tabList->setItemWidget(tabItem, tabWidget); // Attach tab layout\n\n canvasStack->addWidget(newCanvas);\n\n // ✅ Connect touch gesture signals\n connect(newCanvas, &InkCanvas::zoomChanged, this, &MainWindow::handleTouchZoomChange);\n connect(newCanvas, &InkCanvas::panChanged, this, &MainWindow::handleTouchPanChange);\n connect(newCanvas, &InkCanvas::touchGestureEnded, this, &MainWindow::handleTouchGestureEnd);\n connect(newCanvas, &InkCanvas::ropeSelectionCompleted, this, &MainWindow::showRopeSelectionMenu);\n connect(newCanvas, &InkCanvas::pdfLinkClicked, this, [this](int targetPage) {\n // Navigate to the target page when a PDF link is clicked\n if (targetPage >= 0 && targetPage < 9999) {\n switchPageWithDirection(targetPage + 1, (targetPage + 1 > getCurrentPageForCanvas(currentCanvas()) + 1) ? 1 : -1);\n pageInput->setValue(targetPage + 1);\n }\n });\n connect(newCanvas, &InkCanvas::pdfLoaded, this, [this]() {\n // Refresh PDF outline if sidebar is visible\n if (outlineSidebarVisible) {\n loadPdfOutline();\n }\n });\n connect(newCanvas, &InkCanvas::markdownSelectionModeChanged, this, &MainWindow::updateMarkdownButtonState);\n \n // Install event filter to detect mouse movement for scrollbar visibility\n newCanvas->setMouseTracking(true);\n newCanvas->installEventFilter(this);\n \n // Disable tablet tracking for canvases for now to prevent crashes\n // TODO: Find a safer way to implement hover tooltips without tablet tracking\n // QTimer::singleShot(50, this, [newCanvas]() {\n // try {\n // if (newCanvas && newCanvas->window() && newCanvas->window()->windowHandle()) {\n // newCanvas->setAttribute(Qt::WA_TabletTracking, true);\n // }\n // } catch (...) {\n // // Silently ignore tablet tracking errors\n // }\n // });\n \n // ✅ Apply touch gesture setting\n newCanvas->setTouchGesturesEnabled(touchGesturesEnabled);\n\n pageMap[newCanvas] = 0;\n\n // ✅ Select the new tab\n tabList->setCurrentItem(tabItem);\n canvasStack->setCurrentWidget(newCanvas);\n\n zoomSlider->setValue(100 / initialDpr); // Set initial zoom level based on DPR\n updateDialDisplay();\n updateStraightLineButtonState(); // Initialize straight line button state for the new tab\n updateRopeToolButtonState(); // Initialize rope tool button state for the new tab\n updatePdfTextSelectButtonState(); // Initialize PDF text selection button state for the new tab\n updateBookmarkButtonState(); // Initialize bookmark button state for the new tab\n updateMarkdownButtonState(); // Initialize markdown button state for the new tab\n updateDialButtonState(); // Initialize dial button state for the new tab\n updateFastForwardButtonState(); // Initialize fast forward button state for the new tab\n updateToolButtonStates(); // Initialize tool button states for the new tab\n\n QString tempDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\";\n newCanvas->setSaveFolder(tempDir);\n \n // Load persistent background settings\n BackgroundStyle defaultStyle;\n QColor defaultColor;\n int defaultDensity;\n loadDefaultBackgroundSettings(defaultStyle, defaultColor, defaultDensity);\n \n newCanvas->setBackgroundStyle(defaultStyle);\n newCanvas->setBackgroundColor(defaultColor);\n newCanvas->setBackgroundDensity(defaultDensity);\n newCanvas->setPDFRenderDPI(getPdfDPI());\n \n // Update color button states for the new tab\n updateColorButtonStates();\n}\n void removeTabAt(int index) {\n if (!tabList || !canvasStack) return; // Ensure UI elements exist\n if (index < 0 || index >= canvasStack->count()) return;\n\n // ✅ Remove tab entry\n QListWidgetItem *item = tabList->takeItem(index);\n delete item;\n\n // ✅ Remove and delete the canvas safely\n QWidget *canvasWidget = canvasStack->widget(index); // Get widget before removal\n // ensureTabHasUniqueSaveFolder(currentCanvas()); // Moved to the close button lambda\n\n if (canvasWidget) {\n canvasStack->removeWidget(canvasWidget); // Remove from stack\n // InkCanvas *canvasInstance = qobject_cast(canvasWidget);\n // if (canvasInstance) {\n // QString folderPath = canvasInstance->getSaveFolder();\n // QString tempDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\";\n // if (!folderPath.isEmpty() && folderPath != tempDir && recentNotebooksManager) {\n // recentNotebooksManager->addRecentNotebook(folderPath, canvasInstance); // Moved to close button lambda\n // }\n // }\n delete canvasWidget; // Now delete the widget (and its InkCanvas)\n }\n\n // ✅ Select the previous tab (or first tab if none left)\n if (tabList->count() > 0) {\n int newIndex = qMax(0, index - 1);\n tabList->setCurrentRow(newIndex);\n canvasStack->setCurrentWidget(canvasStack->widget(newIndex));\n }\n\n // QWidget *canvasWidget = canvasStack->widget(index); // Redeclaration - remove this block\n // InkCanvas *canvasInstance = qobject_cast(canvasWidget);\n //\n // if (canvasInstance) {\n // QString folderPath = canvasInstance->getSaveFolder();\n // if (!folderPath.isEmpty() && folderPath != QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\") {\n // // recentNotebooksManager->addRecentNotebook(folderPath, canvasInstance); // Moved to close button lambda\n // }\n // }\n}\n void toggleZoomSlider() {\n if (zoomFrame->isVisible()) {\n zoomFrame->hide();\n return;\n }\n\n // ✅ Set as a standalone pop-up window so it can receive events\n zoomFrame->setWindowFlags(Qt::Popup);\n\n // ✅ Position it right below the button\n QPoint buttonPos = zoomButton->mapToGlobal(QPoint(0, zoomButton->height()));\n zoomFrame->move(buttonPos.x(), buttonPos.y() + 5);\n zoomFrame->show();\n}\n void toggleThicknessSlider() {\n if (thicknessFrame->isVisible()) {\n thicknessFrame->hide();\n return;\n }\n\n // ✅ Set as a standalone pop-up window so it can receive events\n thicknessFrame->setWindowFlags(Qt::Popup);\n\n // ✅ Position it right below the button\n QPoint buttonPos = thicknessButton->mapToGlobal(QPoint(0, thicknessButton->height()));\n thicknessFrame->move(buttonPos.x(), buttonPos.y() + 5);\n\n thicknessFrame->show();\n}\n void toggleFullscreen() {\n if (isFullScreen()) {\n showNormal(); // Exit fullscreen mode\n } else {\n showFullScreen(); // Enter fullscreen mode\n }\n}\n void showJumpToPageDialog() {\n bool ok;\n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1; // ✅ Convert zero-based to one-based\n int newPage = QInputDialog::getInt(this, \"Jump to Page\", \"Enter Page Number:\", \n currentPage, 1, 9999, 1, &ok);\n if (ok) {\n // ✅ Use direction-aware page switching for jump-to-page\n int direction = (newPage > currentPage) ? 1 : (newPage < currentPage) ? -1 : 0;\n if (direction != 0) {\n switchPageWithDirection(newPage, direction);\n } else {\n switchPage(newPage); // Same page, no direction needed\n }\n pageInput->setValue(newPage);\n }\n}\n void goToPreviousPage() {\n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1; // Convert to 1-based\n if (currentPage > 1) {\n int newPage = currentPage - 1;\n switchPageWithDirection(newPage, -1); // -1 indicates backward\n pageInput->setValue(newPage);\n }\n}\n void goToNextPage() {\n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1; // Convert to 1-based\n int newPage = currentPage + 1;\n switchPageWithDirection(newPage, 1); // 1 indicates forward\n pageInput->setValue(newPage);\n}\n void onPageInputChanged(int newPage) {\n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1; // Convert to 1-based\n \n // ✅ Use direction-aware page switching for spinbox\n int direction = (newPage > currentPage) ? 1 : (newPage < currentPage) ? -1 : 0;\n if (direction != 0) {\n switchPageWithDirection(newPage, direction);\n } else {\n switchPage(newPage); // Same page, no direction needed\n }\n}\n void toggleDial() {\n if (!dialContainer) { \n // ✅ Create floating container for the dial\n dialContainer = new QWidget(this);\n dialContainer->setObjectName(\"dialContainer\");\n dialContainer->setFixedSize(140, 140);\n dialContainer->setAttribute(Qt::WA_TranslucentBackground);\n dialContainer->setAttribute(Qt::WA_NoSystemBackground);\n dialContainer->setAttribute(Qt::WA_OpaquePaintEvent);\n dialContainer->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);\n dialContainer->setStyleSheet(\"background: transparent; border-radius: 100px;\"); // ✅ More transparent\n\n // ✅ Create dial\n pageDial = new QDial(dialContainer);\n pageDial->setFixedSize(140, 140);\n pageDial->setMinimum(0);\n pageDial->setMaximum(360);\n pageDial->setWrapping(true); // ✅ Allow full-circle rotation\n \n // Apply theme color immediately when dial is created\n QColor accentColor = getAccentColor();\n pageDial->setStyleSheet(QString(R\"(\n QDial {\n background-color: %1;\n }\n )\").arg(accentColor.name()));\n\n /*\n\n modeDial = new QDial(dialContainer);\n modeDial->setFixedSize(150, 150);\n modeDial->setMinimum(0);\n modeDial->setMaximum(300); // 6 modes, 60° each\n modeDial->setSingleStep(60);\n modeDial->setWrapping(true);\n modeDial->setStyleSheet(\"background:rgb(0, 76, 147);\");\n modeDial->move(25, 25);\n \n */\n \n\n dialColorPreview = new QFrame(dialContainer);\n dialColorPreview->setFixedSize(30, 30);\n dialColorPreview->setStyleSheet(\"border-radius: 15px; border: 1px solid black;\");\n dialColorPreview->move(55, 35); // Center of dial\n\n dialIconView = new QLabel(dialContainer);\n dialIconView->setFixedSize(30, 30);\n dialIconView->setStyleSheet(\"border-radius: 1px; border: 1px solid black;\");\n dialIconView->move(55, 35); // Center of dial\n\n // ✅ Position dial near top-right corner initially\n positionDialContainer();\n\n dialDisplay = new QLabel(dialContainer);\n dialDisplay->setAlignment(Qt::AlignCenter);\n dialDisplay->setFixedSize(80, 80);\n dialDisplay->move(30, 30); // Center position inside the dial\n \n\n int fontId = QFontDatabase::addApplicationFont(\":/resources/fonts/Jersey20-Regular.ttf\");\n // int chnFontId = QFontDatabase::addApplicationFont(\":/resources/fonts/NotoSansSC-Medium.ttf\");\n QStringList fontFamilies = QFontDatabase::applicationFontFamilies(fontId);\n\n if (!fontFamilies.isEmpty()) {\n QFont pixelFont(fontFamilies.at(0), 11);\n dialDisplay->setFont(pixelFont);\n }\n\n dialDisplay->setStyleSheet(\"background-color: black; color: white; font-size: 14px; border-radius: 4px;\");\n\n dialHiddenButton = new QPushButton(dialContainer);\n dialHiddenButton->setFixedSize(80, 80);\n dialHiddenButton->move(30, 30); // Same position as dialDisplay\n dialHiddenButton->setStyleSheet(\"background: transparent; border: none;\"); // ✅ Fully invisible\n dialHiddenButton->setFocusPolicy(Qt::NoFocus); // ✅ Prevents accidental focus issues\n dialHiddenButton->setEnabled(false); // ✅ Disabled by default\n\n // ✅ Connection will be set in changeDialMode() based on current mode\n\n dialColorPreview->raise(); // ✅ Ensure it's on top\n dialIconView->raise();\n // ✅ Connect dial input and release\n // connect(pageDial, &QDial::valueChanged, this, &MainWindow::handleDialInput);\n // connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onDialReleased);\n\n // connect(modeDial, &QDial::valueChanged, this, &MainWindow::handleModeSelection);\n changeDialMode(currentDialMode); // ✅ Set initial mode\n\n // ✅ Enable drag detection\n dialContainer->installEventFilter(this);\n }\n\n // ✅ Ensure that `dialContainer` is always initialized before setting visibility\n if (dialContainer) {\n dialContainer->setVisible(!dialContainer->isVisible());\n }\n\n initializeDialSound(); // ✅ Ensure sound is loaded\n\n // Inside toggleDial():\n \n if (!dialDisplay) {\n dialDisplay = new QLabel(dialContainer);\n }\n updateDialDisplay(); // ✅ Ensure it's updated before showing\n\n if (controllerManager) {\n connect(controllerManager, &SDLControllerManager::buttonHeld, this, &MainWindow::handleButtonHeld);\n connect(controllerManager, &SDLControllerManager::buttonReleased, this, &MainWindow::handleButtonReleased);\n connect(controllerManager, &SDLControllerManager::leftStickAngleChanged, pageDial, &QDial::setValue);\n connect(controllerManager, &SDLControllerManager::leftStickReleased, pageDial, &QDial::sliderReleased);\n connect(controllerManager, &SDLControllerManager::buttonSinglePress, this, &MainWindow::handleControllerButton);\n }\n\n loadButtonMappings(); // ✅ Load button mappings for the controller\n\n // Update button state to reflect dial visibility\n updateDialButtonState();\n}\n void positionDialContainer() {\n if (!dialContainer) return;\n \n // Get window dimensions\n int windowWidth = width();\n int windowHeight = height();\n \n // Get dial dimensions\n int dialWidth = dialContainer->width(); // 140px\n int dialHeight = dialContainer->height(); // 140px\n \n // Calculate toolbar height based on current layout\n int toolbarHeight = isToolbarTwoRows ? 80 : 50; // Approximate heights\n \n // Add tab bar height if visible\n int tabBarHeight = (tabBarContainer && tabBarContainer->isVisible()) ? 38 : 0;\n \n // Define margins from edges\n int rightMargin = 20; // Distance from right edge\n int topMargin = 20; // Distance from top edge (below toolbar and tabs)\n \n // Calculate ideal position (top-right corner with margins)\n int idealX = windowWidth - dialWidth - rightMargin;\n int idealY = toolbarHeight + tabBarHeight + topMargin;\n \n // Ensure dial stays within window bounds with minimum margins\n int minMargin = 10;\n int maxX = windowWidth - dialWidth - minMargin;\n int maxY = windowHeight - dialHeight - minMargin;\n \n // Clamp position to stay within bounds\n int finalX = qBound(minMargin, idealX, maxX);\n int finalY = qBound(toolbarHeight + tabBarHeight + minMargin, idealY, maxY);\n \n // Move the dial to the calculated position\n dialContainer->move(finalX, finalY);\n}\n void handleDialInput(int angle) {\n if (!tracking) {\n startAngle = angle; // ✅ Set initial position\n accumulatedRotation = 0; // ✅ Reset tracking\n tracking = true;\n lastAngle = angle;\n return;\n }\n\n int delta = angle - lastAngle;\n\n // ✅ Handle 360-degree wrapping\n if (delta > 180) delta -= 360; // Example: 350° → 10° should be -20° instead of +340°\n if (delta < -180) delta += 360; // Example: 10° → 350° should be +20° instead of -340°\n\n accumulatedRotation += delta; // ✅ Accumulate movement\n\n // ✅ Detect crossing a 45-degree boundary\n int currentClicks = accumulatedRotation / 45; // Total number of \"clicks\" crossed\n int previousClicks = (accumulatedRotation - delta) / 45; // Previous click count\n\n if (currentClicks != previousClicks) { // ✅ Play sound if a new boundary is crossed\n \n if (dialClickSound) {\n dialClickSound->play();\n \n // ✅ Vibrate controller\n SDL_Joystick *joystick = controllerManager->getJoystick();\n if (joystick) {\n // Note: SDL_JoystickRumble requires SDL 2.0.9+\n // For older versions, this will be a no-op\n #if SDL_VERSION_ATLEAST(2, 0, 9)\n SDL_JoystickRumble(joystick, 0xA000, 0xF000, 10); // Vibrate shortly\n #endif\n }\n \n grossTotalClicks += 1;\n tempClicks = currentClicks;\n updateDialDisplay();\n \n if (isLowResPreviewEnabled()) {\n int previewPage = qBound(1, getCurrentPageForCanvas(currentCanvas()) + currentClicks, 99999);\n currentCanvas()->loadPdfPreviewAsync(previewPage);\n }\n }\n }\n\n lastAngle = angle; // ✅ Store last position\n}\n void onDialReleased() {\n if (!tracking) return; // ✅ Ignore if no tracking\n\n int pagesToAdvance = fastForwardMode ? 8 : 1;\n int totalClicks = accumulatedRotation / 45; // ✅ Convert degrees to pages\n\n /*\n int leftOver = accumulatedRotation % 45; // ✅ Track remaining rotation\n if (leftOver > 22 && totalClicks >= 0) {\n totalClicks += 1; // ✅ Round up if more than halfway\n } \n else if (leftOver <= -22 && totalClicks >= 0) {\n totalClicks -= 1; // ✅ Round down if more than halfway\n }\n */\n \n\n if (totalClicks != 0 || grossTotalClicks != 0) { // ✅ Only switch pages if movement happened\n // Use concurrent autosave for smoother dial operation\n if (currentCanvas()->isEdited()) {\n saveCurrentPageConcurrent();\n }\n\n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1;\n int newPage = qBound(1, currentPage + totalClicks * pagesToAdvance, 99999);\n \n // ✅ Use direction-aware page switching for dial\n int direction = (totalClicks * pagesToAdvance > 0) ? 1 : -1;\n switchPageWithDirection(newPage, direction);\n pageInput->setValue(newPage);\n tempClicks = 0;\n updateDialDisplay(); \n /*\n if (dialClickSound) {\n dialClickSound->play();\n }\n */\n }\n\n accumulatedRotation = 0; // ✅ Reset tracking\n grossTotalClicks = 0;\n tracking = false;\n}\n void initializeDialSound() {\n if (!dialClickSound) {\n dialClickSound = new QSoundEffect(this);\n dialClickSound->setSource(QUrl::fromLocalFile(\":/resources/sounds/dial_click.wav\")); // ✅ Path to the sound file\n dialClickSound->setVolume(0.8); // ✅ Set volume (0.0 - 1.0)\n }\n}\n void changeDialMode(DialMode mode) {\n\n if (!dialContainer) return; // ✅ Ensure dial container exists\n currentDialMode = mode; // ✅ Set new mode\n updateDialDisplay();\n\n // ✅ Enable dialHiddenButton for PanAndPageScroll and ZoomControl modes\n dialHiddenButton->setEnabled(currentDialMode == PanAndPageScroll || currentDialMode == ZoomControl);\n\n // ✅ Disconnect previous slots\n disconnect(pageDial, &QDial::valueChanged, nullptr, nullptr);\n disconnect(pageDial, &QDial::sliderReleased, nullptr, nullptr);\n \n // ✅ Disconnect dialHiddenButton to reconnect with appropriate function\n disconnect(dialHiddenButton, &QPushButton::clicked, nullptr, nullptr);\n \n // ✅ Connect dialHiddenButton to appropriate function based on mode\n if (currentDialMode == PanAndPageScroll) {\n connect(dialHiddenButton, &QPushButton::clicked, this, &MainWindow::toggleControlBar);\n } else if (currentDialMode == ZoomControl) {\n connect(dialHiddenButton, &QPushButton::clicked, this, &MainWindow::cycleZoomLevels);\n }\n\n dialColorPreview->hide();\n dialDisplay->setStyleSheet(\"background-color: black; color: white; font-size: 14px; border-radius: 40px;\");\n\n // ✅ Connect the correct function set for the current mode\n switch (currentDialMode) {\n case PageSwitching:\n connect(pageDial, &QDial::valueChanged, this, &MainWindow::handleDialInput);\n connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onDialReleased);\n break;\n case ZoomControl:\n connect(pageDial, &QDial::valueChanged, this, &MainWindow::handleDialZoom);\n connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onZoomReleased);\n break;\n case ThicknessControl:\n connect(pageDial, &QDial::valueChanged, this, &MainWindow::handleDialThickness);\n connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onThicknessReleased);\n break;\n\n case ToolSwitching:\n connect(pageDial, &QDial::valueChanged, this, &MainWindow::handleToolSelection);\n connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onToolReleased);\n break;\n case PresetSelection:\n connect(pageDial, &QDial::valueChanged, this, &MainWindow::handlePresetSelection);\n connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onPresetReleased);\n break;\n case PanAndPageScroll:\n connect(pageDial, &QDial::valueChanged, this, &MainWindow::handleDialPanScroll);\n connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onPanScrollReleased);\n break;\n \n }\n}\n void handleDialZoom(int angle) {\n if (!tracking) {\n startAngle = angle; \n accumulatedRotation = 0; \n tracking = true;\n lastAngle = angle;\n return;\n }\n\n int delta = angle - lastAngle;\n\n // ✅ Handle 360-degree wrapping\n if (delta > 180) delta -= 360;\n if (delta < -180) delta += 360;\n\n accumulatedRotation += delta;\n\n if (abs(delta) < 4) { \n return; \n }\n\n // ✅ Apply zoom dynamically (instead of waiting for release)\n int oldZoom = zoomSlider->value();\n int newZoom = qBound(10, oldZoom + (delta / 4), 400); \n zoomSlider->setValue(newZoom);\n updateZoom(); // ✅ Ensure zoom updates immediately\n updateDialDisplay(); \n\n lastAngle = angle;\n}\n void handleDialThickness(int angle) {\n if (!tracking) {\n startAngle = angle;\n tracking = true;\n lastAngle = angle;\n return;\n }\n\n int delta = angle - lastAngle;\n if (delta > 180) delta -= 360;\n if (delta < -180) delta += 360;\n\n int thicknessStep = fastForwardMode ? 5 : 1;\n currentCanvas()->setPenThickness(qBound(1.0, currentCanvas()->getPenThickness() + (delta / 10.0) * thicknessStep, 50.0));\n\n updateDialDisplay();\n lastAngle = angle;\n}\n void onZoomReleased() {\n accumulatedRotation = 0;\n tracking = false;\n}\n void onThicknessReleased() {\n accumulatedRotation = 0;\n tracking = false;\n}\n void updateDialDisplay() {\n if (!dialDisplay) return;\n if (!dialColorPreview) return;\n if (!dialIconView) return;\n dialIconView->show();\n qreal dpr = initialDpr;\n QColor currentColor = currentCanvas()->getPenColor();\n switch (currentDialMode) {\n case DialMode::PageSwitching:\n if (fastForwardMode){\n dialDisplay->setText(QString(tr(\"\\n\\nPage\\n%1\").arg(getCurrentPageForCanvas(currentCanvas()) + 1 + tempClicks * 8)));\n }\n else {\n dialDisplay->setText(QString(tr(\"\\n\\nPage\\n%1\").arg(getCurrentPageForCanvas(currentCanvas()) + 1 + tempClicks)));\n }\n dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/bookpage_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n break;\n case DialMode::ThicknessControl:\n {\n QString toolName;\n switch (currentCanvas()->getCurrentTool()) {\n case ToolType::Pen:\n toolName = tr(\"Pen\");\n break;\n case ToolType::Marker:\n toolName = tr(\"Marker\");\n break;\n case ToolType::Eraser:\n toolName = tr(\"Eraser\");\n break;\n }\n dialDisplay->setText(QString(tr(\"\\n\\n%1\\n%2\").arg(toolName).arg(QString::number(currentCanvas()->getPenThickness(), 'f', 1))));\n dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/thickness_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n }\n break;\n case DialMode::ZoomControl:\n dialDisplay->setText(QString(tr(\"\\n\\nZoom\\n%1%\").arg(currentCanvas() ? currentCanvas()->getZoom() * initialDpr : zoomSlider->value() * initialDpr)));\n dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/zoom_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n break;\n \n case DialMode::ToolSwitching:\n // ✅ Convert ToolType to QString for display\n switch (currentCanvas()->getCurrentTool()) {\n case ToolType::Pen:\n dialDisplay->setText(tr(\"\\n\\n\\nPen\"));\n dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/pen_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n break;\n case ToolType::Marker:\n dialDisplay->setText(tr(\"\\n\\n\\nMarker\"));\n dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/marker_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n break;\n case ToolType::Eraser:\n dialDisplay->setText(tr(\"\\n\\n\\nEraser\"));\n dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/eraser_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n break;\n }\n break;\n case PresetSelection:\n dialColorPreview->show();\n dialIconView->hide();\n dialColorPreview->setStyleSheet(QString(\"background-color: %1; border-radius: 15px; border: 1px solid black;\")\n .arg(colorPresets[currentPresetIndex].name()));\n dialDisplay->setText(QString(tr(\"\\n\\nPreset %1\\n#%2\"))\n .arg(currentPresetIndex + 1) // ✅ Display preset index (1-based)\n .arg(colorPresets[currentPresetIndex].name().remove(\"#\"))); // ✅ Display hex color\n // dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/preset_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n break;\n case DialMode::PanAndPageScroll:\n dialIconView->setPixmap(QPixmap(\":/resources/icons/scroll_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n QString fullscreenStatus = controlBarVisible ? tr(\"Etr\") : tr(\"Exit\");\n dialDisplay->setText(QString(tr(\"\\n\\nPage %1\\n%2 FulScr\")).arg(getCurrentPageForCanvas(currentCanvas()) + 1).arg(fullscreenStatus));\n break;\n }\n}\n void handleToolSelection(int angle) {\n static int lastToolIndex = -1; // ✅ Track last tool index\n\n // ✅ Snap to closest fixed 120° step\n int snappedAngle = (angle + 60) / 120 * 120; // Round to nearest 120°\n int toolIndex = snappedAngle / 120; // Convert to tool index (0, 1, 2)\n\n if (toolIndex >= 3) toolIndex = 0; // ✅ Wrap around at 360° → Back to Pen (0)\n\n if (toolIndex != lastToolIndex) { // ✅ Only switch if tool actually changes\n toolSelector->setCurrentIndex(toolIndex); // ✅ Change tool\n lastToolIndex = toolIndex; // ✅ Update last selected tool\n\n // ✅ Play click sound when tool changes\n if (dialClickSound) {\n dialClickSound->play();\n }\n\n SDL_Joystick *joystick = controllerManager->getJoystick();\n\n if (joystick) {\n #if SDL_VERSION_ATLEAST(2, 0, 9)\n SDL_JoystickRumble(joystick, 0xA000, 0xF000, 20); // ✅ Vibrate controller\n #endif\n }\n\n updateToolButtonStates(); // ✅ Update tool button states\n updateDialDisplay(); // ✅ Update dial display]\n }\n}\n void onToolReleased() {\n \n}\n void handlePresetSelection(int angle) {\n static int lastAngle = angle;\n int delta = angle - lastAngle;\n\n // ✅ Handle 360-degree wrapping\n if (delta > 180) delta -= 360;\n if (delta < -180) delta += 360;\n\n if (abs(delta) >= 60) { // ✅ Change preset every 60° (6 presets)\n lastAngle = angle;\n currentPresetIndex = (currentPresetIndex + (delta > 0 ? 1 : -1) + colorPresets.size()) % colorPresets.size();\n \n QColor selectedColor = colorPresets[currentPresetIndex];\n currentCanvas()->setPenColor(selectedColor);\n updateCustomColorButtonStyle(selectedColor);\n updateDialDisplay();\n updateColorButtonStates(); // Update button states when preset is selected\n \n if (dialClickSound) dialClickSound->play(); // ✅ Provide feedback\n SDL_Joystick *joystick = controllerManager->getJoystick();\n if (joystick) {\n #if SDL_VERSION_ATLEAST(2, 0, 9)\n SDL_JoystickRumble(joystick, 0xA000, 0xF000, 25); // Vibrate shortly\n #endif\n }\n }\n}\n void onPresetReleased() {\n accumulatedRotation = 0;\n tracking = false;\n}\n void addColorPreset() {\n QColor currentColor = currentCanvas()->getPenColor();\n\n // ✅ Prevent duplicates\n if (!colorPresets.contains(currentColor)) {\n if (colorPresets.size() >= 6) {\n colorPresets.dequeue(); // ✅ Remove oldest color\n }\n colorPresets.enqueue(currentColor);\n }\n}\n void updateColorPalette() {\n // Clear existing presets\n colorPresets.clear();\n currentPresetIndex = 0;\n \n // Add default pen color (theme-aware)\n colorPresets.enqueue(getDefaultPenColor());\n \n // Add palette colors\n colorPresets.enqueue(getPaletteColor(\"red\"));\n colorPresets.enqueue(getPaletteColor(\"yellow\"));\n colorPresets.enqueue(getPaletteColor(\"blue\"));\n colorPresets.enqueue(getPaletteColor(\"green\"));\n colorPresets.enqueue(QColor(\"#000000\")); // Black (always same)\n colorPresets.enqueue(QColor(\"#FFFFFF\")); // White (always same)\n \n // Only update UI elements if they exist\n if (redButton && blueButton && yellowButton && greenButton) {\n bool darkMode = isDarkMode();\n \n // Update color button icons based on current palette (not theme)\n QString redIconPath = useBrighterPalette ? \":/resources/icons/pen_light_red.png\" : \":/resources/icons/pen_dark_red.png\";\n QString blueIconPath = useBrighterPalette ? \":/resources/icons/pen_light_blue.png\" : \":/resources/icons/pen_dark_blue.png\";\n QString yellowIconPath = useBrighterPalette ? \":/resources/icons/pen_light_yellow.png\" : \":/resources/icons/pen_dark_yellow.png\";\n QString greenIconPath = useBrighterPalette ? \":/resources/icons/pen_light_green.png\" : \":/resources/icons/pen_dark_green.png\";\n \n redButton->setIcon(QIcon(redIconPath));\n blueButton->setIcon(QIcon(blueIconPath));\n yellowButton->setIcon(QIcon(yellowIconPath));\n greenButton->setIcon(QIcon(greenIconPath));\n \n // Update color button states\n updateColorButtonStates();\n }\n}\n QColor getPaletteColor(const QString &colorName) {\n if (useBrighterPalette) {\n // Brighter colors (good for dark backgrounds)\n if (colorName == \"red\") return QColor(\"#FF7755\");\n if (colorName == \"yellow\") return QColor(\"#EECC00\");\n if (colorName == \"blue\") return QColor(\"#66CCFF\");\n if (colorName == \"green\") return QColor(\"#55FF77\");\n } else {\n // Darker colors (good for light backgrounds)\n if (colorName == \"red\") return QColor(\"#AA0000\");\n if (colorName == \"yellow\") return QColor(\"#997700\");\n if (colorName == \"blue\") return QColor(\"#0000AA\");\n if (colorName == \"green\") return QColor(\"#007700\");\n }\n \n // Fallback colors\n if (colorName == \"black\") return QColor(\"#000000\");\n if (colorName == \"white\") return QColor(\"#FFFFFF\");\n \n return QColor(\"#000000\"); // Default fallback\n}\n qreal getDevicePixelRatio() {\n QScreen *screen = QGuiApplication::primaryScreen();\n qreal devicePixelRatio = screen ? screen->devicePixelRatio() : 1.0; // Default to 1.0 if null\n return devicePixelRatio;\n}\n bool isDarkMode() {\n QColor bg = palette().color(QPalette::Window);\n return bg.lightness() < 128; // Lightness scale: 0 (black) - 255 (white)\n}\n QIcon loadThemedIcon(const QString& baseName) {\n QString path = isDarkMode()\n ? QString(\":/resources/icons/%1_reversed.png\").arg(baseName)\n : QString(\":/resources/icons/%1.png\").arg(baseName);\n return QIcon(path);\n}\n QString createButtonStyle(bool darkMode) {\n if (darkMode) {\n // Dark mode: Keep current white highlights (good contrast)\n return R\"(\n QPushButton {\n background: transparent;\n border: none;\n padding: 6px;\n }\n QPushButton:hover {\n background: rgba(255, 255, 255, 50);\n }\n QPushButton:pressed {\n background: rgba(0, 0, 0, 50);\n }\n QPushButton[selected=\"true\"] {\n background: rgba(255, 255, 255, 100);\n border: 2px solid rgba(255, 255, 255, 150);\n padding: 4px;\n border-radius: 4px;\n }\n QPushButton[selected=\"true\"]:hover {\n background: rgba(255, 255, 255, 120);\n }\n QPushButton[selected=\"true\"]:pressed {\n background: rgba(0, 0, 0, 50);\n }\n )\";\n } else {\n // Light mode: Use darker colors for better visibility\n return R\"(\n QPushButton {\n background: transparent;\n border: none;\n padding: 6px;\n }\n QPushButton:hover {\n background: rgba(0, 0, 0, 30);\n }\n QPushButton:pressed {\n background: rgba(0, 0, 0, 60);\n }\n QPushButton[selected=\"true\"] {\n background: rgba(0, 0, 0, 80);\n border: 2px solid rgba(0, 0, 0, 120);\n padding: 4px;\n border-radius: 4px;\n }\n QPushButton[selected=\"true\"]:hover {\n background: rgba(0, 0, 0, 100);\n }\n QPushButton[selected=\"true\"]:pressed {\n background: rgba(0, 0, 0, 140);\n }\n )\";\n }\n}\n void handleDialPanScroll(int angle) {\n if (!tracking) {\n startAngle = angle;\n accumulatedRotation = 0;\n accumulatedRotationAfterLimit = 0;\n tracking = true;\n lastAngle = angle;\n pendingPageFlip = 0;\n return;\n }\n\n int delta = angle - lastAngle;\n\n // Handle 360 wrap\n if (delta > 180) delta -= 360;\n if (delta < -180) delta += 360;\n\n accumulatedRotation += delta;\n\n // Pan scroll\n int panDelta = delta * 4; // Adjust scroll sensitivity here\n int currentPan = panYSlider->value();\n int newPan = currentPan + panDelta;\n\n // Clamp pan slider\n newPan = qBound(panYSlider->minimum(), newPan, panYSlider->maximum());\n panYSlider->setValue(newPan);\n\n // ✅ NEW → if slider reached top/bottom, accumulate AFTER LIMIT\n if (newPan == panYSlider->maximum()) {\n accumulatedRotationAfterLimit += delta;\n\n if (accumulatedRotationAfterLimit >= 120) {\n pendingPageFlip = +1; // Flip next when released\n }\n } \n else if (newPan == panYSlider->minimum()) {\n accumulatedRotationAfterLimit += delta;\n\n if (accumulatedRotationAfterLimit <= -120) {\n pendingPageFlip = -1; // Flip previous when released\n }\n } \n else {\n // Reset after limit accumulator when not at limit\n accumulatedRotationAfterLimit = 0;\n pendingPageFlip = 0;\n }\n\n lastAngle = angle;\n}\n void onPanScrollReleased() {\n // ✅ Perform page flip only when dial released and flip is pending\n if (pendingPageFlip != 0) {\n // Use concurrent saving for smooth dial operation\n if (currentCanvas()->isEdited()) {\n saveCurrentPageConcurrent();\n }\n\n int currentPage = getCurrentPageForCanvas(currentCanvas());\n int newPage = qBound(1, currentPage + pendingPageFlip + 1, 99999);\n \n // ✅ Use direction-aware page switching for pan-and-scroll dial\n switchPageWithDirection(newPage, pendingPageFlip);\n pageInput->setValue(newPage);\n updateDialDisplay();\n\n SDL_Joystick *joystick = controllerManager->getJoystick();\n if (joystick) {\n #if SDL_VERSION_ATLEAST(2, 0, 9)\n SDL_JoystickRumble(joystick, 0xA000, 0xF000, 25); // Vibrate shortly\n #endif\n }\n }\n\n // Reset states\n pendingPageFlip = 0;\n accumulatedRotation = 0;\n accumulatedRotationAfterLimit = 0;\n tracking = false;\n}\n void handleTouchZoomChange(int newZoom) {\n // Update zoom slider without triggering updateZoom again\n zoomSlider->blockSignals(true);\n int oldZoom = zoomSlider->value(); // Get the old zoom value before updating the slider\n zoomSlider->setValue(newZoom);\n zoomSlider->blockSignals(false);\n \n // Show both scrollbars during gesture\n if (panXSlider->maximum() > 0) {\n panXSlider->setVisible(true);\n }\n if (panYSlider->maximum() > 0) {\n panYSlider->setVisible(true);\n }\n scrollbarsVisible = true;\n \n // Update canvas zoom directly\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n // The canvas zoom has already been set by the gesture processing in InkCanvas::event()\n // So we don't need to set it again, just update the last zoom level\n canvas->setLastZoomLevel(newZoom);\n updatePanRange();\n \n // ✅ FIXED: Add thickness adjustment for pinch-to-zoom gestures to maintain visual consistency\n adjustThicknessForZoom(oldZoom, newZoom);\n \n updateDialDisplay();\n }\n}\n void handleTouchPanChange(int panX, int panY) {\n // Clamp values to valid ranges\n panX = qBound(panXSlider->minimum(), panX, panXSlider->maximum());\n panY = qBound(panYSlider->minimum(), panY, panYSlider->maximum());\n \n // Show both scrollbars during gesture\n if (panXSlider->maximum() > 0) {\n panXSlider->setVisible(true);\n }\n if (panYSlider->maximum() > 0) {\n panYSlider->setVisible(true);\n }\n scrollbarsVisible = true;\n \n // Update sliders without triggering their valueChanged signals\n panXSlider->blockSignals(true);\n panYSlider->blockSignals(true);\n panXSlider->setValue(panX);\n panYSlider->setValue(panY);\n panXSlider->blockSignals(false);\n panYSlider->blockSignals(false);\n \n // Update canvas pan directly\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n canvas->setPanX(panX);\n canvas->setPanY(panY);\n canvas->setLastPanX(panX);\n canvas->setLastPanY(panY);\n }\n}\n void handleTouchGestureEnd() {\n // Hide scrollbars immediately when touch gesture ends\n panXSlider->setVisible(false);\n panYSlider->setVisible(false);\n scrollbarsVisible = false;\n}\n void updateColorButtonStates() {\n // Check if there's a current canvas\n if (!currentCanvas()) return;\n \n // Get current pen color\n QColor currentColor = currentCanvas()->getPenColor();\n \n // Determine if we're in dark mode to match the correct colors\n bool darkMode = isDarkMode();\n \n // Reset all color buttons to original style\n redButton->setProperty(\"selected\", false);\n blueButton->setProperty(\"selected\", false);\n yellowButton->setProperty(\"selected\", false);\n greenButton->setProperty(\"selected\", false);\n blackButton->setProperty(\"selected\", false);\n whiteButton->setProperty(\"selected\", false);\n \n // Set the selected property for the matching color button based on current palette\n QColor redColor = getPaletteColor(\"red\");\n QColor blueColor = getPaletteColor(\"blue\");\n QColor yellowColor = getPaletteColor(\"yellow\");\n QColor greenColor = getPaletteColor(\"green\");\n \n if (currentColor == redColor) {\n redButton->setProperty(\"selected\", true);\n } else if (currentColor == blueColor) {\n blueButton->setProperty(\"selected\", true);\n } else if (currentColor == yellowColor) {\n yellowButton->setProperty(\"selected\", true);\n } else if (currentColor == greenColor) {\n greenButton->setProperty(\"selected\", true);\n } else if (currentColor == QColor(\"#000000\")) {\n blackButton->setProperty(\"selected\", true);\n } else if (currentColor == QColor(\"#FFFFFF\")) {\n whiteButton->setProperty(\"selected\", true);\n }\n \n // Force style update\n redButton->style()->unpolish(redButton);\n redButton->style()->polish(redButton);\n blueButton->style()->unpolish(blueButton);\n blueButton->style()->polish(blueButton);\n yellowButton->style()->unpolish(yellowButton);\n yellowButton->style()->polish(yellowButton);\n greenButton->style()->unpolish(greenButton);\n greenButton->style()->polish(greenButton);\n blackButton->style()->unpolish(blackButton);\n blackButton->style()->polish(blackButton);\n whiteButton->style()->unpolish(whiteButton);\n whiteButton->style()->polish(whiteButton);\n}\n void selectColorButton(QPushButton* selectedButton) {\n updateColorButtonStates();\n}\n void updateStraightLineButtonState() {\n // Check if there's a current canvas\n if (!currentCanvas()) return;\n \n // Update the button state to match the canvas straight line mode\n bool isEnabled = currentCanvas()->isStraightLineMode();\n \n // Set visual indicator that the button is active/inactive\n if (straightLineToggleButton) {\n straightLineToggleButton->setProperty(\"selected\", isEnabled);\n \n // Force style update\n straightLineToggleButton->style()->unpolish(straightLineToggleButton);\n straightLineToggleButton->style()->polish(straightLineToggleButton);\n }\n}\n void updateRopeToolButtonState() {\n // Check if there's a current canvas\n if (!currentCanvas()) return;\n\n // Update the button state to match the canvas rope tool mode\n bool isEnabled = currentCanvas()->isRopeToolMode();\n\n // Set visual indicator that the button is active/inactive\n if (ropeToolButton) {\n ropeToolButton->setProperty(\"selected\", isEnabled);\n\n // Force style update\n ropeToolButton->style()->unpolish(ropeToolButton);\n ropeToolButton->style()->polish(ropeToolButton);\n }\n}\n void updateMarkdownButtonState() {\n // Check if there's a current canvas\n if (!currentCanvas()) return;\n\n // Update the button state to match the canvas markdown selection mode\n bool isEnabled = currentCanvas()->isMarkdownSelectionMode();\n\n // Set visual indicator that the button is active/inactive\n if (markdownButton) {\n markdownButton->setProperty(\"selected\", isEnabled);\n\n // Force style update\n markdownButton->style()->unpolish(markdownButton);\n markdownButton->style()->polish(markdownButton);\n }\n}\n void setPenTool() {\n if (!currentCanvas()) return;\n currentCanvas()->setTool(ToolType::Pen);\n updateToolButtonStates();\n updateThicknessSliderForCurrentTool();\n updateDialDisplay();\n}\n void setMarkerTool() {\n if (!currentCanvas()) return;\n currentCanvas()->setTool(ToolType::Marker);\n updateToolButtonStates();\n updateThicknessSliderForCurrentTool();\n updateDialDisplay();\n}\n void setEraserTool() {\n if (!currentCanvas()) return;\n currentCanvas()->setTool(ToolType::Eraser);\n updateToolButtonStates();\n updateThicknessSliderForCurrentTool();\n updateDialDisplay();\n}\n QColor getContrastingTextColor(const QColor &backgroundColor) {\n // Calculate relative luminance using the formula from WCAG 2.0\n double r = backgroundColor.redF();\n double g = backgroundColor.greenF();\n double b = backgroundColor.blueF();\n \n // Gamma correction\n r = (r <= 0.03928) ? r/12.92 : pow((r + 0.055)/1.055, 2.4);\n g = (g <= 0.03928) ? g/12.92 : pow((g + 0.055)/1.055, 2.4);\n b = (b <= 0.03928) ? b/12.92 : pow((b + 0.055)/1.055, 2.4);\n \n // Calculate luminance\n double luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;\n \n // Use white text for darker backgrounds\n return (luminance < 0.5) ? Qt::white : Qt::black;\n}\n void updateCustomColorButtonStyle(const QColor &color) {\n QColor textColor = getContrastingTextColor(color);\n customColorButton->setStyleSheet(QString(\"background-color: %1; color: %2\")\n .arg(color.name())\n .arg(textColor.name()));\n customColorButton->setText(QString(\"%1\").arg(color.name()).toUpper());\n}\n void openRecentNotebooksDialog() {\n RecentNotebooksDialog dialog(this, recentNotebooksManager, this);\n dialog.exec();\n}\n void showPendingTooltip() {\n // This function is now unused since we disabled tablet tracking\n // Tooltips will work through normal mouse hover events instead\n // Keeping the function for potential future use\n}\n void showRopeSelectionMenu(const QPoint &position) {\n // Create context menu for rope tool selection\n QMenu *contextMenu = new QMenu(this);\n contextMenu->setAttribute(Qt::WA_DeleteOnClose);\n \n // Add Copy action\n QAction *copyAction = contextMenu->addAction(tr(\"Copy\"));\n copyAction->setIcon(loadThemedIcon(\"copy\"));\n connect(copyAction, &QAction::triggered, this, [this]() {\n if (currentCanvas()) {\n currentCanvas()->copyRopeSelection();\n }\n });\n \n // Add Delete action\n QAction *deleteAction = contextMenu->addAction(tr(\"Delete\"));\n deleteAction->setIcon(loadThemedIcon(\"trash\"));\n connect(deleteAction, &QAction::triggered, this, [this]() {\n if (currentCanvas()) {\n currentCanvas()->deleteRopeSelection();\n }\n });\n \n // Add Cancel action\n QAction *cancelAction = contextMenu->addAction(tr(\"Cancel\"));\n cancelAction->setIcon(loadThemedIcon(\"cross\"));\n connect(cancelAction, &QAction::triggered, this, [this]() {\n if (currentCanvas()) {\n currentCanvas()->cancelRopeSelection();\n }\n });\n \n // Convert position from canvas coordinates to global coordinates\n QPoint globalPos = currentCanvas()->mapToGlobal(position);\n \n // Show the menu at the specified position\n contextMenu->popup(globalPos);\n}\n void toggleOutlineSidebar() {\n outlineSidebarVisible = !outlineSidebarVisible;\n \n // Hide bookmarks sidebar if it's visible when opening outline\n if (outlineSidebarVisible && bookmarksSidebar && bookmarksSidebar->isVisible()) {\n bookmarksSidebar->setVisible(false);\n bookmarksSidebarVisible = false;\n // Update bookmarks button state\n if (toggleBookmarksButton) {\n toggleBookmarksButton->setProperty(\"selected\", false);\n toggleBookmarksButton->style()->unpolish(toggleBookmarksButton);\n toggleBookmarksButton->style()->polish(toggleBookmarksButton);\n }\n }\n \n outlineSidebar->setVisible(outlineSidebarVisible);\n \n // Update button toggle state\n if (toggleOutlineButton) {\n toggleOutlineButton->setProperty(\"selected\", outlineSidebarVisible);\n toggleOutlineButton->style()->unpolish(toggleOutlineButton);\n toggleOutlineButton->style()->polish(toggleOutlineButton);\n }\n \n // Load PDF outline when showing sidebar for the first time\n if (outlineSidebarVisible) {\n loadPdfOutline();\n }\n}\n void onOutlineItemClicked(QTreeWidgetItem *item, int column) {\n Q_UNUSED(column);\n \n if (!item) return;\n \n // Get the page number stored in the item data\n QVariant pageData = item->data(0, Qt::UserRole);\n if (pageData.isValid()) {\n int pageNumber = pageData.toInt();\n if (pageNumber >= 0) {\n // Switch to the selected page (convert from 0-based to 1-based)\n switchPage(pageNumber + 1);\n pageInput->setValue(pageNumber + 1);\n }\n }\n}\n void loadPdfOutline() {\n if (!outlineTree) return;\n \n outlineTree->clear();\n \n // Get current PDF document\n Poppler::Document* pdfDoc = getPdfDocument();\n if (!pdfDoc) return;\n \n // Get the outline from the PDF document\n QVector outlineItems = pdfDoc->outline();\n \n if (outlineItems.isEmpty()) {\n // If no outline exists, show page numbers as fallback\n int pageCount = pdfDoc->numPages();\n for (int i = 0; i < pageCount; ++i) {\n QTreeWidgetItem* item = new QTreeWidgetItem(outlineTree);\n item->setText(0, QString(tr(\"Page %1\")).arg(i + 1));\n item->setData(0, Qt::UserRole, i); // Store 0-based page index\n }\n } else {\n // Process the actual PDF outline\n for (const Poppler::OutlineItem& outlineItem : outlineItems) {\n addOutlineItem(outlineItem, nullptr);\n }\n }\n \n // Expand the first level by default\n outlineTree->expandToDepth(0);\n}\n void addOutlineItem(const Poppler::OutlineItem& outlineItem, QTreeWidgetItem* parentItem) {\n if (outlineItem.isNull()) return;\n \n QTreeWidgetItem* item;\n if (parentItem) {\n item = new QTreeWidgetItem(parentItem);\n } else {\n item = new QTreeWidgetItem(outlineTree);\n }\n \n // Set the title\n item->setText(0, outlineItem.name());\n \n // Try to get the page number from the destination\n int pageNumber = -1;\n auto destination = outlineItem.destination();\n if (destination) {\n pageNumber = destination->pageNumber();\n }\n \n // Store the page number (1-based) in the item data\n if (pageNumber >= 0) {\n item->setData(0, Qt::UserRole, pageNumber + 1); // Convert to 1-based\n }\n \n // Add child items recursively\n if (outlineItem.hasChildren()) {\n QVector children = outlineItem.children();\n for (const Poppler::OutlineItem& child : children) {\n addOutlineItem(child, item);\n }\n }\n}\n Poppler::Document* getPdfDocument();\n void toggleBookmarksSidebar() {\n if (!bookmarksSidebar) return;\n \n bool isVisible = bookmarksSidebar->isVisible();\n \n // Hide outline sidebar if it's visible\n if (!isVisible && outlineSidebar && outlineSidebar->isVisible()) {\n outlineSidebar->setVisible(false);\n outlineSidebarVisible = false;\n // Update outline button state\n if (toggleOutlineButton) {\n toggleOutlineButton->setProperty(\"selected\", false);\n toggleOutlineButton->style()->unpolish(toggleOutlineButton);\n toggleOutlineButton->style()->polish(toggleOutlineButton);\n }\n }\n \n bookmarksSidebar->setVisible(!isVisible);\n bookmarksSidebarVisible = !isVisible;\n \n // Update button toggle state\n if (toggleBookmarksButton) {\n toggleBookmarksButton->setProperty(\"selected\", bookmarksSidebarVisible);\n toggleBookmarksButton->style()->unpolish(toggleBookmarksButton);\n toggleBookmarksButton->style()->polish(toggleBookmarksButton);\n }\n \n if (bookmarksSidebarVisible) {\n loadBookmarks(); // Refresh bookmarks when opening\n }\n}\n void onBookmarkItemClicked(QTreeWidgetItem *item, int column) {\n Q_UNUSED(column);\n if (!item) return;\n \n // Get the page number from the item data\n bool ok;\n int pageNumber = item->data(0, Qt::UserRole).toInt(&ok);\n if (ok && pageNumber > 0) {\n // Navigate to the bookmarked page\n switchPageWithDirection(pageNumber, (pageNumber > getCurrentPageForCanvas(currentCanvas()) + 1) ? 1 : -1);\n pageInput->setValue(pageNumber);\n }\n}\n void loadBookmarks() {\n if (!bookmarksTree || !currentCanvas()) return;\n \n bookmarksTree->clear();\n \n // Get the current notebook's save folder\n QString saveFolder = currentCanvas()->getSaveFolder();\n if (saveFolder.isEmpty()) return;\n \n QString bookmarksFile = saveFolder + \"/.bookmarks.txt\";\n QFile file(bookmarksFile);\n \n bookmarks.clear();\n \n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n while (!in.atEnd()) {\n QString line = in.readLine().trimmed();\n if (line.isEmpty()) continue;\n \n QStringList parts = line.split('\\t', Qt::KeepEmptyParts);\n if (parts.size() >= 2) {\n bool ok;\n int pageNum = parts[0].toInt(&ok);\n if (ok) {\n QString title = parts[1];\n bookmarks[pageNum] = title;\n }\n }\n }\n file.close();\n }\n \n // Populate the tree widget\n for (auto it = bookmarks.begin(); it != bookmarks.end(); ++it) {\n QTreeWidgetItem *item = new QTreeWidgetItem(bookmarksTree);\n \n // Create a custom widget for each bookmark item\n QWidget *itemWidget = new QWidget();\n QHBoxLayout *itemLayout = new QHBoxLayout(itemWidget);\n itemLayout->setContentsMargins(5, 2, 5, 2);\n itemLayout->setSpacing(5);\n \n // Page number label (fixed width)\n QLabel *pageLabel = new QLabel(QString(tr(\"Page %1\")).arg(it.key()));\n pageLabel->setFixedWidth(60);\n pageLabel->setStyleSheet(\"font-weight: bold; color: #666;\");\n itemLayout->addWidget(pageLabel);\n \n // Editable title (supports Windows handwriting if available)\n QLineEdit *titleEdit = new QLineEdit(it.value());\n titleEdit->setPlaceholderText(\"Enter bookmark title...\");\n titleEdit->setProperty(\"pageNumber\", it.key()); // Store page number for saving\n \n // Enable IME support for multi-language input\n titleEdit->setAttribute(Qt::WA_InputMethodEnabled, true);\n titleEdit->setInputMethodHints(Qt::ImhNone); // Allow all input methods\n titleEdit->installEventFilter(this); // Install event filter for IME handling\n \n // Connect to save when editing is finished\n connect(titleEdit, &QLineEdit::editingFinished, this, [this, titleEdit]() {\n int pageNum = titleEdit->property(\"pageNumber\").toInt();\n QString newTitle = titleEdit->text().trimmed();\n \n if (newTitle.isEmpty()) {\n // Remove bookmark if title is empty\n bookmarks.remove(pageNum);\n } else {\n // Update bookmark title\n bookmarks[pageNum] = newTitle;\n }\n saveBookmarks();\n updateBookmarkButtonState(); // Update button state\n });\n \n itemLayout->addWidget(titleEdit, 1);\n \n // Store page number in item data for navigation\n item->setData(0, Qt::UserRole, it.key());\n \n // Set the custom widget\n bookmarksTree->setItemWidget(item, 0, itemWidget);\n \n // Set item height\n item->setSizeHint(0, QSize(0, 30));\n }\n \n updateBookmarkButtonState(); // Update button state after loading\n}\n void saveBookmarks() {\n if (!currentCanvas()) return;\n \n QString saveFolder = currentCanvas()->getSaveFolder();\n if (saveFolder.isEmpty()) return;\n \n QString bookmarksFile = saveFolder + \"/.bookmarks.txt\";\n QFile file(bookmarksFile);\n \n if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {\n QTextStream out(&file);\n \n // Sort bookmarks by page number\n QList sortedPages = bookmarks.keys();\n std::sort(sortedPages.begin(), sortedPages.end());\n \n for (int pageNum : sortedPages) {\n out << pageNum << '\\t' << bookmarks[pageNum] << '\\n';\n }\n \n file.close();\n }\n}\n void toggleCurrentPageBookmark() {\n if (!currentCanvas()) return;\n \n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1; // Convert to 1-based\n \n if (bookmarks.contains(currentPage)) {\n // Remove bookmark\n bookmarks.remove(currentPage);\n } else {\n // Add bookmark with default title\n QString defaultTitle = QString(tr(\"Bookmark %1\")).arg(currentPage);\n bookmarks[currentPage] = defaultTitle;\n }\n \n saveBookmarks();\n updateBookmarkButtonState();\n \n // Refresh bookmarks view if visible\n if (bookmarksSidebarVisible) {\n loadBookmarks();\n }\n}\n void updateBookmarkButtonState() {\n if (!toggleBookmarkButton || !currentCanvas()) return;\n \n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1; // Convert to 1-based\n bool isBookmarked = bookmarks.contains(currentPage);\n \n toggleBookmarkButton->setProperty(\"selected\", isBookmarked);\n \n // Update tooltip\n if (isBookmarked) {\n toggleBookmarkButton->setToolTip(tr(\"Remove Bookmark\"));\n } else {\n toggleBookmarkButton->setToolTip(tr(\"Add Bookmark\"));\n }\n \n // Force style update\n toggleBookmarkButton->style()->unpolish(toggleBookmarkButton);\n toggleBookmarkButton->style()->polish(toggleBookmarkButton);\n}\n private:\n InkCanvas *canvas;\n QPushButton *benchmarkButton;\n QLabel *benchmarkLabel;\n QTimer *benchmarkTimer;\n bool benchmarking;\n QPushButton *exportNotebookButton;\n QPushButton *importNotebookButton;\n QPushButton *redButton;\n QPushButton *blueButton;\n QPushButton *yellowButton;\n QPushButton *greenButton;\n QPushButton *blackButton;\n QPushButton *whiteButton;\n QLineEdit *customColorInput;\n QPushButton *customColorButton;\n QPushButton *thicknessButton;\n QSlider *thicknessSlider;\n QFrame *thicknessFrame;\n QComboBox *toolSelector;\n QPushButton *penToolButton;\n QPushButton *markerToolButton;\n QPushButton *eraserToolButton;\n QPushButton *deletePageButton;\n QPushButton *selectFolderButton;\n QPushButton *saveButton;\n QPushButton *saveAnnotatedButton;\n QPushButton *fullscreenButton;\n QPushButton *openControlPanelButton;\n QPushButton *openRecentNotebooksButton;\n QPushButton *loadPdfButton;\n QPushButton *clearPdfButton;\n QPushButton *pdfTextSelectButton;\n QPushButton *toggleTabBarButton;\n QMap pageMap;\n QPushButton *backgroundButton;\n QPushButton *straightLineToggleButton;\n QPushButton *ropeToolButton;\n QPushButton *markdownButton;\n QSlider *zoomSlider;\n QPushButton *zoomButton;\n QFrame *zoomFrame;\n QPushButton *dezoomButton;\n QPushButton *zoom50Button;\n QPushButton *zoom200Button;\n QWidget *zoomContainer;\n QLineEdit *zoomInput;\n QScrollBar *panXSlider;\n QScrollBar *panYSlider;\n QListWidget *tabList;\n QStackedWidget *canvasStack;\n QPushButton *addTabButton;\n QWidget *tabBarContainer;\n QWidget *outlineSidebar;\n QTreeWidget *outlineTree;\n QPushButton *toggleOutlineButton;\n bool outlineSidebarVisible = false;\n QWidget *bookmarksSidebar;\n QTreeWidget *bookmarksTree;\n QPushButton *toggleBookmarksButton;\n QPushButton *toggleBookmarkButton;\n QPushButton *touchGesturesButton;\n bool bookmarksSidebarVisible = false;\n QMap bookmarks;\n QPushButton *jumpToPageButton;\n QWidget *dialContainer = nullptr;\n QDial *pageDial = nullptr;\n QDial *modeDial = nullptr;\n QPushButton *dialToggleButton;\n bool fastForwardMode = false;\n QPushButton *fastForwardButton;\n int lastAngle = 0;\n int startAngle = 0;\n bool tracking = false;\n int accumulatedRotation = 0;\n QSoundEffect *dialClickSound = nullptr;\n int grossTotalClicks = 0;\n DialMode currentDialMode = PanAndPageScroll;\n DialMode temporaryDialMode = None;\n QComboBox *dialModeSelector;\n QPushButton *colorPreview;\n QLabel *dialDisplay = nullptr;\n QFrame *dialColorPreview;\n QLabel *dialIconView;\n QFont pixelFont;\n QPushButton *btnPageSwitch;\n QPushButton *btnZoom;\n QPushButton *btnThickness;\n QPushButton *btnTool;\n QPushButton *btnPresets;\n QPushButton *btnPannScroll;\n int tempClicks = 0;\n QPushButton *dialHiddenButton;\n QQueue colorPresets;\n QPushButton *addPresetButton;\n int currentPresetIndex = 0;\n bool useBrighterPalette = false;\n qreal initialDpr = 1.0;\n QWidget *sidebarContainer;\n QWidget *controlBar;\n void setTemporaryDialMode(DialMode mode) {\n if (temporaryDialMode == None) {\n temporaryDialMode = currentDialMode;\n }\n changeDialMode(mode);\n}\n void clearTemporaryDialMode() {\n if (temporaryDialMode != None) {\n changeDialMode(temporaryDialMode);\n temporaryDialMode = None;\n }\n}\n bool controlBarVisible = true;\n void toggleControlBar() {\n // Proper fullscreen toggle: handle both sidebar and control bar\n \n if (controlBarVisible) {\n // Going into fullscreen mode\n \n // First, remember current tab bar state\n sidebarWasVisibleBeforeFullscreen = tabBarContainer->isVisible();\n \n // Hide tab bar if it's visible\n if (tabBarContainer->isVisible()) {\n tabBarContainer->setVisible(false);\n }\n \n // Hide control bar\n controlBarVisible = false;\n controlBar->setVisible(false);\n \n // Hide floating popup widgets when control bar is hidden to prevent stacking\n if (zoomFrame && zoomFrame->isVisible()) zoomFrame->hide();\n if (thicknessFrame && thicknessFrame->isVisible()) thicknessFrame->hide();\n \n // Hide orphaned widgets that are not added to any layout\n if (colorPreview) colorPreview->hide();\n if (thicknessButton) thicknessButton->hide();\n if (jumpToPageButton) jumpToPageButton->hide();\n\n if (toolSelector) toolSelector->hide();\n if (zoomButton) zoomButton->hide();\n if (customColorInput) customColorInput->hide();\n \n // Find and hide local widgets that might be orphaned\n QList comboBoxes = findChildren();\n for (QComboBox* combo : comboBoxes) {\n if (combo->parent() == this && !combo->isVisible()) {\n // Already hidden, keep it hidden\n } else if (combo->parent() == this) {\n // This might be the orphaned dialModeSelector or similar\n combo->hide();\n }\n }\n } else {\n // Coming out of fullscreen mode\n \n // Restore control bar\n controlBarVisible = true;\n controlBar->setVisible(true);\n \n // Restore tab bar to its previous state\n tabBarContainer->setVisible(sidebarWasVisibleBeforeFullscreen);\n \n // Show orphaned widgets when control bar is visible\n // Note: These are kept hidden normally since they're not in the layout\n // Only show them if they were specifically intended to be visible\n }\n \n // Update dial display to reflect new status\n updateDialDisplay();\n \n // Force layout update to recalculate space\n if (auto *canvas = currentCanvas()) {\n QTimer::singleShot(0, this, [this, canvas]() {\n canvas->setMaximumSize(canvas->getCanvasSize());\n });\n }\n}\n void cycleZoomLevels() {\n if (!zoomSlider) return;\n \n int currentZoom = zoomSlider->value();\n int targetZoom;\n \n // Calculate the scaled zoom levels based on initial DPR\n int zoom50 = 50 / initialDpr;\n int zoom100 = 100 / initialDpr;\n int zoom200 = 200 / initialDpr;\n \n // Cycle through 0.5x -> 1x -> 2x -> 0.5x...\n if (currentZoom <= zoom50 + 5) { // Close to 0.5x (with small tolerance)\n targetZoom = zoom100; // Go to 1x\n } else if (currentZoom <= zoom100 + 5) { // Close to 1x\n targetZoom = zoom200; // Go to 2x\n } else { // Any other zoom level or close to 2x\n targetZoom = zoom50; // Go to 0.5x\n }\n \n zoomSlider->setValue(targetZoom);\n updateZoom();\n updateDialDisplay();\n}\n bool sidebarWasVisibleBeforeFullscreen = true;\n int accumulatedRotationAfterLimit = 0;\n int pendingPageFlip = 0;\n QMap buttonHoldMapping;\n QMap buttonPressMapping;\n QMap buttonPressActionMapping;\n QMap keyboardMappings;\n QMap keyboardActionMapping;\n QTimer *tooltipTimer;\n QWidget *lastHoveredWidget;\n QPoint pendingTooltipPos;\n void handleButtonHeld(const QString &buttonName) {\n QString mode = buttonHoldMapping.value(buttonName, \"None\");\n if (mode != \"None\") {\n setTemporaryDialMode(dialModeFromString(mode));\n return;\n }\n}\n void handleButtonReleased(const QString &buttonName) {\n QString mode = buttonHoldMapping.value(buttonName, \"None\");\n if (mode != \"None\") {\n clearTemporaryDialMode();\n }\n}\n void handleControllerButton(const QString &buttonName) { // This is for single press functions\n ControllerAction action = buttonPressActionMapping.value(buttonName, ControllerAction::None);\n\n switch (action) {\n case ControllerAction::ToggleFullscreen:\n fullscreenButton->click();\n break;\n case ControllerAction::ToggleDial:\n toggleDial();\n break;\n case ControllerAction::Zoom50:\n zoom50Button->click();\n break;\n case ControllerAction::ZoomOut:\n dezoomButton->click();\n break;\n case ControllerAction::Zoom200:\n zoom200Button->click();\n break;\n case ControllerAction::AddPreset:\n addPresetButton->click();\n break;\n case ControllerAction::DeletePage:\n deletePageButton->click(); // assuming you have this\n break;\n case ControllerAction::FastForward:\n fastForwardButton->click(); // assuming you have this\n break;\n case ControllerAction::OpenControlPanel:\n openControlPanelButton->click();\n break;\n case ControllerAction::RedColor:\n redButton->click();\n break;\n case ControllerAction::BlueColor:\n blueButton->click();\n break;\n case ControllerAction::YellowColor:\n yellowButton->click();\n break;\n case ControllerAction::GreenColor:\n greenButton->click();\n break;\n case ControllerAction::BlackColor:\n blackButton->click();\n break;\n case ControllerAction::WhiteColor:\n whiteButton->click();\n break;\n case ControllerAction::CustomColor:\n customColorButton->click();\n break;\n case ControllerAction::ToggleSidebar:\n toggleTabBarButton->click();\n break;\n case ControllerAction::Save:\n saveButton->click();\n break;\n case ControllerAction::StraightLineTool:\n straightLineToggleButton->click();\n break;\n case ControllerAction::RopeTool:\n ropeToolButton->click();\n break;\n case ControllerAction::SetPenTool:\n setPenTool();\n break;\n case ControllerAction::SetMarkerTool:\n setMarkerTool();\n break;\n case ControllerAction::SetEraserTool:\n setEraserTool();\n break;\n case ControllerAction::TogglePdfTextSelection:\n pdfTextSelectButton->click();\n break;\n case ControllerAction::ToggleOutline:\n toggleOutlineButton->click();\n break;\n case ControllerAction::ToggleBookmarks:\n toggleBookmarksButton->click();\n break;\n case ControllerAction::AddBookmark:\n toggleBookmarkButton->click();\n break;\n case ControllerAction::ToggleTouchGestures:\n touchGesturesButton->click();\n break;\n default:\n break;\n }\n}\n void handleKeyboardShortcut(const QString &keySequence) {\n ControllerAction action = keyboardActionMapping.value(keySequence, ControllerAction::None);\n \n // Use the same handler as Joy-Con buttons\n switch (action) {\n case ControllerAction::ToggleFullscreen:\n fullscreenButton->click();\n break;\n case ControllerAction::ToggleDial:\n toggleDial();\n break;\n case ControllerAction::Zoom50:\n zoom50Button->click();\n break;\n case ControllerAction::ZoomOut:\n dezoomButton->click();\n break;\n case ControllerAction::Zoom200:\n zoom200Button->click();\n break;\n case ControllerAction::AddPreset:\n addPresetButton->click();\n break;\n case ControllerAction::DeletePage:\n deletePageButton->click();\n break;\n case ControllerAction::FastForward:\n fastForwardButton->click();\n break;\n case ControllerAction::OpenControlPanel:\n openControlPanelButton->click();\n break;\n case ControllerAction::RedColor:\n redButton->click();\n break;\n case ControllerAction::BlueColor:\n blueButton->click();\n break;\n case ControllerAction::YellowColor:\n yellowButton->click();\n break;\n case ControllerAction::GreenColor:\n greenButton->click();\n break;\n case ControllerAction::BlackColor:\n blackButton->click();\n break;\n case ControllerAction::WhiteColor:\n whiteButton->click();\n break;\n case ControllerAction::CustomColor:\n customColorButton->click();\n break;\n case ControllerAction::ToggleSidebar:\n toggleTabBarButton->click();\n break;\n case ControllerAction::Save:\n saveButton->click();\n break;\n case ControllerAction::StraightLineTool:\n straightLineToggleButton->click();\n break;\n case ControllerAction::RopeTool:\n ropeToolButton->click();\n break;\n case ControllerAction::SetPenTool:\n setPenTool();\n break;\n case ControllerAction::SetMarkerTool:\n setMarkerTool();\n break;\n case ControllerAction::SetEraserTool:\n setEraserTool();\n break;\n case ControllerAction::TogglePdfTextSelection:\n pdfTextSelectButton->click();\n break;\n case ControllerAction::ToggleOutline:\n toggleOutlineButton->click();\n break;\n case ControllerAction::ToggleBookmarks:\n toggleBookmarksButton->click();\n break;\n case ControllerAction::AddBookmark:\n toggleBookmarkButton->click();\n break;\n case ControllerAction::ToggleTouchGestures:\n touchGesturesButton->click();\n break;\n default:\n break;\n }\n}\n void saveKeyboardMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.beginGroup(\"KeyboardMappings\");\n for (auto it = keyboardMappings.begin(); it != keyboardMappings.end(); ++it) {\n settings.setValue(it.key(), it.value());\n }\n settings.endGroup();\n}\n void loadKeyboardMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.beginGroup(\"KeyboardMappings\");\n QStringList keys = settings.allKeys();\n \n // List of IME-related shortcuts that should not be intercepted\n QStringList imeShortcuts = {\n \"Ctrl+Space\", // Primary IME toggle\n \"Ctrl+Shift\", // Language switching\n \"Ctrl+Alt\", // IME functions\n \"Shift+Alt\", // Alternative language switching\n \"Alt+Shift\" // Alternative language switching (reversed)\n };\n \n for (const QString &key : keys) {\n // Skip IME-related shortcuts\n if (imeShortcuts.contains(key)) {\n // Remove from settings if it exists\n settings.remove(key);\n continue;\n }\n \n QString value = settings.value(key).toString();\n keyboardMappings[key] = value;\n keyboardActionMapping[key] = stringToAction(value);\n }\n settings.endGroup();\n \n // Save settings to persist the removal of IME shortcuts\n settings.sync();\n}\n void ensureTabHasUniqueSaveFolder(InkCanvas* canvas) {\n if (!canvas) return;\n\n if (canvasStack->count() == 0) return;\n\n QString currentFolder = canvas->getSaveFolder();\n QString tempFolder = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\";\n\n if (currentFolder.isEmpty() || currentFolder == tempFolder) {\n\n QDir sourceDir(tempFolder);\n QStringList pageFiles = sourceDir.entryList(QStringList() << \"*.png\", QDir::Files);\n\n // No pages to save → skip prompting\n if (pageFiles.isEmpty()) {\n return;\n }\n\n QMessageBox::warning(this, tr(\"Unsaved Notebook\"),\n tr(\"This notebook is still using a temporary session folder.\\nPlease select a permanent folder to avoid data loss.\"));\n\n QString selectedFolder = QFileDialog::getExistingDirectory(this, tr(\"Select Save Folder\"));\n if (selectedFolder.isEmpty()) return;\n\n QDir destDir(selectedFolder);\n if (!destDir.exists()) {\n QDir().mkpath(selectedFolder);\n }\n\n // Copy contents from temp to selected folder\n for (const QString &file : sourceDir.entryList(QDir::Files)) {\n QString srcFilePath = tempFolder + \"/\" + file;\n QString dstFilePath = selectedFolder + \"/\" + file;\n\n // If file already exists at destination, remove it to avoid rename failure\n if (QFile::exists(dstFilePath)) {\n QFile::remove(dstFilePath);\n }\n\n QFile::rename(srcFilePath, dstFilePath); // This moves the file\n }\n\n canvas->setSaveFolder(selectedFolder);\n // updateTabLabel(); // No longer needed here, handled by the close button lambda\n }\n\n return;\n}\n RecentNotebooksManager *recentNotebooksManager;\n int pdfRenderDPI = 192;\n void setupUi() {\n \n // Ensure IME is properly enabled for the application\n QInputMethod *inputMethod = QGuiApplication::inputMethod();\n if (inputMethod) {\n inputMethod->show();\n inputMethod->reset();\n }\n \n // Create theme-aware button style\n bool darkMode = isDarkMode();\n QString buttonStyle = createButtonStyle(darkMode);\n\n\n loadPdfButton = new QPushButton(this);\n clearPdfButton = new QPushButton(this);\n loadPdfButton->setFixedSize(26, 30);\n clearPdfButton->setFixedSize(26, 30);\n QIcon pdfIcon(loadThemedIcon(\"pdf\")); // Path to your icon in resources\n QIcon pdfDeleteIcon(loadThemedIcon(\"pdfdelete\")); // Path to your icon in resources\n loadPdfButton->setIcon(pdfIcon);\n clearPdfButton->setIcon(pdfDeleteIcon);\n loadPdfButton->setStyleSheet(buttonStyle);\n clearPdfButton->setStyleSheet(buttonStyle);\n loadPdfButton->setToolTip(tr(\"Load PDF\"));\n clearPdfButton->setToolTip(tr(\"Clear PDF\"));\n connect(loadPdfButton, &QPushButton::clicked, this, &MainWindow::loadPdf);\n connect(clearPdfButton, &QPushButton::clicked, this, &MainWindow::clearPdf);\n\n pdfTextSelectButton = new QPushButton(this);\n pdfTextSelectButton->setFixedSize(26, 30);\n QIcon pdfTextIcon(loadThemedIcon(\"ibeam\"));\n pdfTextSelectButton->setIcon(pdfTextIcon);\n pdfTextSelectButton->setStyleSheet(buttonStyle);\n pdfTextSelectButton->setToolTip(tr(\"Toggle PDF Text Selection\"));\n connect(pdfTextSelectButton, &QPushButton::clicked, this, [this]() {\n if (!currentCanvas()) return;\n \n bool newMode = !currentCanvas()->isPdfTextSelectionEnabled();\n currentCanvas()->setPdfTextSelectionEnabled(newMode);\n updatePdfTextSelectButtonState();\n updateBookmarkButtonState();\n \n // Clear any existing selection when toggling\n if (!newMode) {\n currentCanvas()->clearPdfTextSelection();\n }\n });\n\n exportNotebookButton = new QPushButton(this);\n exportNotebookButton->setFixedSize(26, 30);\n QIcon exportIcon(loadThemedIcon(\"export\")); // Path to your icon in resources\n exportNotebookButton->setIcon(exportIcon);\n exportNotebookButton->setStyleSheet(buttonStyle);\n exportNotebookButton->setToolTip(tr(\"Export Notebook Into .SNPKG File\"));\n importNotebookButton = new QPushButton(this);\n importNotebookButton->setFixedSize(26, 30);\n QIcon importIcon(loadThemedIcon(\"import\")); // Path to your icon in resources\n importNotebookButton->setIcon(importIcon);\n importNotebookButton->setStyleSheet(buttonStyle);\n importNotebookButton->setToolTip(tr(\"Import Notebook From .SNPKG File\"));\n\n connect(exportNotebookButton, &QPushButton::clicked, this, [=]() {\n QString filename = QFileDialog::getSaveFileName(this, tr(\"Export Notebook\"), \"\", \"SpeedyNote Package (*.snpkg)\");\n if (!filename.isEmpty()) {\n if (!filename.endsWith(\".snpkg\")) filename += \".snpkg\";\n currentCanvas()->exportNotebook(filename);\n }\n });\n \n connect(importNotebookButton, &QPushButton::clicked, this, [=]() {\n QString filename = QFileDialog::getOpenFileName(this, tr(\"Import Notebook\"), \"\", \"SpeedyNote Package (*.snpkg)\");\n if (!filename.isEmpty()) {\n currentCanvas()->importNotebook(filename);\n }\n });\n\n benchmarkButton = new QPushButton(this);\n QIcon benchmarkIcon(loadThemedIcon(\"benchmark\")); // Path to your icon in resources\n benchmarkButton->setIcon(benchmarkIcon);\n benchmarkButton->setFixedSize(26, 30); // Make the benchmark button smaller\n benchmarkButton->setStyleSheet(buttonStyle);\n benchmarkButton->setToolTip(tr(\"Toggle Benchmark\"));\n benchmarkLabel = new QLabel(\"PR:N/A\", this);\n benchmarkLabel->setFixedHeight(30); // Make the benchmark bar smaller\n\n toggleTabBarButton = new QPushButton(this);\n toggleTabBarButton->setIcon(loadThemedIcon(\"tabs\")); // You can design separate icons for \"show\" and \"hide\"\n toggleTabBarButton->setToolTip(tr(\"Show/Hide Tab Bar\"));\n toggleTabBarButton->setFixedSize(26, 30);\n toggleTabBarButton->setStyleSheet(buttonStyle);\n toggleTabBarButton->setProperty(\"selected\", true); // Initially visible\n \n // PDF Outline Toggle Button\n toggleOutlineButton = new QPushButton(this);\n toggleOutlineButton->setIcon(loadThemedIcon(\"outline\")); // Icon to be added later\n toggleOutlineButton->setToolTip(tr(\"Show/Hide PDF Outline\"));\n toggleOutlineButton->setFixedSize(26, 30);\n toggleOutlineButton->setStyleSheet(buttonStyle);\n toggleOutlineButton->setProperty(\"selected\", false); // Initially hidden\n \n // Bookmarks Toggle Button\n toggleBookmarksButton = new QPushButton(this);\n toggleBookmarksButton->setIcon(loadThemedIcon(\"bookmark\")); // Using bookpage icon for bookmarks\n toggleBookmarksButton->setToolTip(tr(\"Show/Hide Bookmarks\"));\n toggleBookmarksButton->setFixedSize(26, 30);\n toggleBookmarksButton->setStyleSheet(buttonStyle);\n toggleBookmarksButton->setProperty(\"selected\", false); // Initially hidden\n \n // Add/Remove Bookmark Toggle Button\n toggleBookmarkButton = new QPushButton(this);\n toggleBookmarkButton->setIcon(loadThemedIcon(\"star\"));\n toggleBookmarkButton->setToolTip(tr(\"Add/Remove Bookmark\"));\n toggleBookmarkButton->setFixedSize(26, 30);\n toggleBookmarkButton->setStyleSheet(buttonStyle);\n toggleBookmarkButton->setProperty(\"selected\", false); // For toggle state styling\n\n // Touch Gestures Toggle Button\n touchGesturesButton = new QPushButton(this);\n touchGesturesButton->setIcon(loadThemedIcon(\"hand\")); // Using hand icon for touch/gesture\n touchGesturesButton->setToolTip(tr(\"Toggle Touch Gestures\"));\n touchGesturesButton->setFixedSize(26, 30);\n touchGesturesButton->setStyleSheet(buttonStyle);\n touchGesturesButton->setProperty(\"selected\", touchGesturesEnabled); // For toggle state styling\n\n selectFolderButton = new QPushButton(this);\n selectFolderButton->setFixedSize(26, 30);\n QIcon folderIcon(loadThemedIcon(\"folder\")); // Path to your icon in resources\n selectFolderButton->setIcon(folderIcon);\n selectFolderButton->setStyleSheet(buttonStyle);\n selectFolderButton->setToolTip(tr(\"Select Save Folder\"));\n connect(selectFolderButton, &QPushButton::clicked, this, &MainWindow::selectFolder);\n \n \n saveButton = new QPushButton(this);\n saveButton->setFixedSize(26, 30);\n QIcon saveIcon(loadThemedIcon(\"save\")); // Path to your icon in resources\n saveButton->setIcon(saveIcon);\n saveButton->setStyleSheet(buttonStyle);\n saveButton->setToolTip(tr(\"Save Current Page\"));\n connect(saveButton, &QPushButton::clicked, this, &MainWindow::saveCurrentPage);\n \n saveAnnotatedButton = new QPushButton(this);\n saveAnnotatedButton->setFixedSize(26, 30);\n QIcon saveAnnotatedIcon(loadThemedIcon(\"saveannotated\")); // Path to your icon in resources\n saveAnnotatedButton->setIcon(saveAnnotatedIcon);\n saveAnnotatedButton->setStyleSheet(buttonStyle);\n saveAnnotatedButton->setToolTip(tr(\"Save Page with Background\"));\n connect(saveAnnotatedButton, &QPushButton::clicked, this, &MainWindow::saveAnnotated);\n\n fullscreenButton = new QPushButton(this);\n fullscreenButton->setIcon(loadThemedIcon(\"fullscreen\")); // Load from resources\n fullscreenButton->setFixedSize(26, 30);\n fullscreenButton->setToolTip(tr(\"Toggle Fullscreen\"));\n fullscreenButton->setStyleSheet(buttonStyle);\n\n // ✅ Connect button click to toggleFullscreen() function\n connect(fullscreenButton, &QPushButton::clicked, this, &MainWindow::toggleFullscreen);\n\n // Use the darkMode variable already declared at the beginning of setupUi()\n\n redButton = new QPushButton(this);\n redButton->setFixedSize(18, 30); // Half width\n QString redIconPath = darkMode ? \":/resources/icons/pen_light_red.png\" : \":/resources/icons/pen_dark_red.png\";\n QIcon redIcon(redIconPath);\n redButton->setIcon(redIcon);\n redButton->setStyleSheet(buttonStyle);\n connect(redButton, &QPushButton::clicked, [this]() { \n handleColorButtonClick();\n currentCanvas()->setPenColor(getPaletteColor(\"red\")); \n updateDialDisplay(); \n updateColorButtonStates();\n });\n \n blueButton = new QPushButton(this);\n blueButton->setFixedSize(18, 30); // Half width\n QString blueIconPath = darkMode ? \":/resources/icons/pen_light_blue.png\" : \":/resources/icons/pen_dark_blue.png\";\n QIcon blueIcon(blueIconPath);\n blueButton->setIcon(blueIcon);\n blueButton->setStyleSheet(buttonStyle);\n connect(blueButton, &QPushButton::clicked, [this]() { \n handleColorButtonClick();\n currentCanvas()->setPenColor(getPaletteColor(\"blue\")); \n updateDialDisplay(); \n updateColorButtonStates();\n });\n\n yellowButton = new QPushButton(this);\n yellowButton->setFixedSize(18, 30); // Half width\n QString yellowIconPath = darkMode ? \":/resources/icons/pen_light_yellow.png\" : \":/resources/icons/pen_dark_yellow.png\";\n QIcon yellowIcon(yellowIconPath);\n yellowButton->setIcon(yellowIcon);\n yellowButton->setStyleSheet(buttonStyle);\n connect(yellowButton, &QPushButton::clicked, [this]() { \n handleColorButtonClick();\n currentCanvas()->setPenColor(getPaletteColor(\"yellow\")); \n updateDialDisplay(); \n updateColorButtonStates();\n });\n\n greenButton = new QPushButton(this);\n greenButton->setFixedSize(18, 30); // Half width\n QString greenIconPath = darkMode ? \":/resources/icons/pen_light_green.png\" : \":/resources/icons/pen_dark_green.png\";\n QIcon greenIcon(greenIconPath);\n greenButton->setIcon(greenIcon);\n greenButton->setStyleSheet(buttonStyle);\n connect(greenButton, &QPushButton::clicked, [this]() { \n handleColorButtonClick();\n currentCanvas()->setPenColor(getPaletteColor(\"green\")); \n updateDialDisplay(); \n updateColorButtonStates();\n });\n\n blackButton = new QPushButton(this);\n blackButton->setFixedSize(18, 30); // Half width\n QString blackIconPath = darkMode ? \":/resources/icons/pen_light_black.png\" : \":/resources/icons/pen_dark_black.png\";\n QIcon blackIcon(blackIconPath);\n blackButton->setIcon(blackIcon);\n blackButton->setStyleSheet(buttonStyle);\n connect(blackButton, &QPushButton::clicked, [this]() { \n handleColorButtonClick();\n currentCanvas()->setPenColor(QColor(\"#000000\")); \n updateDialDisplay(); \n updateColorButtonStates();\n });\n\n whiteButton = new QPushButton(this);\n whiteButton->setFixedSize(18, 30); // Half width\n QString whiteIconPath = darkMode ? \":/resources/icons/pen_light_white.png\" : \":/resources/icons/pen_dark_white.png\";\n QIcon whiteIcon(whiteIconPath);\n whiteButton->setIcon(whiteIcon);\n whiteButton->setStyleSheet(buttonStyle);\n connect(whiteButton, &QPushButton::clicked, [this]() { \n handleColorButtonClick();\n currentCanvas()->setPenColor(QColor(\"#FFFFFF\")); \n updateDialDisplay(); \n updateColorButtonStates();\n });\n \n customColorInput = new QLineEdit(this);\n customColorInput->setPlaceholderText(\"Custom HEX\");\n customColorInput->setFixedSize(85, 30);\n \n // Enable IME support for multi-language input\n customColorInput->setAttribute(Qt::WA_InputMethodEnabled, true);\n customColorInput->setInputMethodHints(Qt::ImhNone); // Allow all input methods\n customColorInput->installEventFilter(this); // Install event filter for IME handling\n \n connect(customColorInput, &QLineEdit::returnPressed, this, &MainWindow::applyCustomColor);\n\n \n thicknessButton = new QPushButton(this);\n thicknessButton->setIcon(loadThemedIcon(\"thickness\"));\n thicknessButton->setFixedSize(26, 30);\n thicknessButton->setStyleSheet(buttonStyle);\n connect(thicknessButton, &QPushButton::clicked, this, &MainWindow::toggleThicknessSlider);\n\n thicknessFrame = new QFrame(this);\n thicknessFrame->setFrameShape(QFrame::StyledPanel);\n thicknessFrame->setStyleSheet(R\"(\n background-color: black;\n border: 1px solid black;\n padding: 5px;\n )\");\n thicknessFrame->setVisible(false);\n thicknessFrame->setFixedSize(220, 40); // Adjust width/height as needed\n\n thicknessSlider = new QSlider(Qt::Horizontal, this);\n thicknessSlider->setRange(1, 50);\n thicknessSlider->setValue(5);\n thicknessSlider->setMaximumWidth(200);\n\n\n connect(thicknessSlider, &QSlider::valueChanged, this, &MainWindow::updateThickness);\n\n QVBoxLayout *popupLayoutThickness = new QVBoxLayout();\n popupLayoutThickness->setContentsMargins(10, 5, 10, 5);\n popupLayoutThickness->addWidget(thicknessSlider);\n thicknessFrame->setLayout(popupLayoutThickness);\n\n\n toolSelector = new QComboBox(this);\n toolSelector->addItem(loadThemedIcon(\"pen\"), \"\");\n toolSelector->addItem(loadThemedIcon(\"marker\"), \"\");\n toolSelector->addItem(loadThemedIcon(\"eraser\"), \"\");\n toolSelector->setFixedWidth(43);\n toolSelector->setFixedHeight(30);\n connect(toolSelector, QOverload::of(&QComboBox::currentIndexChanged), this, &MainWindow::changeTool);\n\n // ✅ Individual tool buttons\n penToolButton = new QPushButton(this);\n penToolButton->setFixedSize(26, 30);\n penToolButton->setIcon(loadThemedIcon(\"pen\"));\n penToolButton->setStyleSheet(buttonStyle);\n penToolButton->setToolTip(tr(\"Pen Tool\"));\n connect(penToolButton, &QPushButton::clicked, this, &MainWindow::setPenTool);\n\n markerToolButton = new QPushButton(this);\n markerToolButton->setFixedSize(26, 30);\n markerToolButton->setIcon(loadThemedIcon(\"marker\"));\n markerToolButton->setStyleSheet(buttonStyle);\n markerToolButton->setToolTip(tr(\"Marker Tool\"));\n connect(markerToolButton, &QPushButton::clicked, this, &MainWindow::setMarkerTool);\n\n eraserToolButton = new QPushButton(this);\n eraserToolButton->setFixedSize(26, 30);\n eraserToolButton->setIcon(loadThemedIcon(\"eraser\"));\n eraserToolButton->setStyleSheet(buttonStyle);\n eraserToolButton->setToolTip(tr(\"Eraser Tool\"));\n connect(eraserToolButton, &QPushButton::clicked, this, &MainWindow::setEraserTool);\n\n backgroundButton = new QPushButton(this);\n backgroundButton->setFixedSize(26, 30);\n QIcon bgIcon(loadThemedIcon(\"background\")); // Path to your icon in resources\n backgroundButton->setIcon(bgIcon);\n backgroundButton->setStyleSheet(buttonStyle);\n backgroundButton->setToolTip(tr(\"Set Background Pic\"));\n connect(backgroundButton, &QPushButton::clicked, this, &MainWindow::selectBackground);\n\n // Initialize straight line toggle button\n straightLineToggleButton = new QPushButton(this);\n straightLineToggleButton->setFixedSize(26, 30);\n QIcon straightLineIcon(loadThemedIcon(\"straightLine\")); // Make sure this icon exists or use a different one\n straightLineToggleButton->setIcon(straightLineIcon);\n straightLineToggleButton->setStyleSheet(buttonStyle);\n straightLineToggleButton->setToolTip(tr(\"Toggle Straight Line Mode\"));\n connect(straightLineToggleButton, &QPushButton::clicked, this, [this]() {\n if (!currentCanvas()) return;\n \n // If we're turning on straight line mode, first disable rope tool\n if (!currentCanvas()->isStraightLineMode()) {\n currentCanvas()->setRopeToolMode(false);\n updateRopeToolButtonState();\n }\n \n bool newMode = !currentCanvas()->isStraightLineMode();\n currentCanvas()->setStraightLineMode(newMode);\n updateStraightLineButtonState();\n });\n \n ropeToolButton = new QPushButton(this);\n ropeToolButton->setFixedSize(26, 30);\n QIcon ropeToolIcon(loadThemedIcon(\"rope\")); // Make sure this icon exists\n ropeToolButton->setIcon(ropeToolIcon);\n ropeToolButton->setStyleSheet(buttonStyle);\n ropeToolButton->setToolTip(tr(\"Toggle Rope Tool Mode\"));\n connect(ropeToolButton, &QPushButton::clicked, this, [this]() {\n if (!currentCanvas()) return;\n \n // If we're turning on rope tool mode, first disable straight line\n if (!currentCanvas()->isRopeToolMode()) {\n currentCanvas()->setStraightLineMode(false);\n updateStraightLineButtonState();\n }\n \n bool newMode = !currentCanvas()->isRopeToolMode();\n currentCanvas()->setRopeToolMode(newMode);\n updateRopeToolButtonState();\n });\n \n markdownButton = new QPushButton(this);\n markdownButton->setFixedSize(26, 30);\n QIcon markdownIcon(loadThemedIcon(\"markdown\")); // Using text icon for markdown\n markdownButton->setIcon(markdownIcon);\n markdownButton->setStyleSheet(buttonStyle);\n markdownButton->setToolTip(tr(\"Add Markdown Window\"));\n connect(markdownButton, &QPushButton::clicked, this, [this]() {\n if (!currentCanvas()) return;\n \n // Toggle markdown selection mode\n bool newMode = !currentCanvas()->isMarkdownSelectionMode();\n currentCanvas()->setMarkdownSelectionMode(newMode);\n updateMarkdownButtonState();\n });\n \n deletePageButton = new QPushButton(this);\n deletePageButton->setFixedSize(26, 30);\n QIcon trashIcon(loadThemedIcon(\"trash\")); // Path to your icon in resources\n deletePageButton->setIcon(trashIcon);\n deletePageButton->setStyleSheet(buttonStyle);\n deletePageButton->setToolTip(tr(\"Delete Current Page\"));\n connect(deletePageButton, &QPushButton::clicked, this, &MainWindow::deleteCurrentPage);\n\n zoomButton = new QPushButton(this);\n zoomButton->setIcon(loadThemedIcon(\"zoom\"));\n zoomButton->setFixedSize(26, 30);\n zoomButton->setStyleSheet(buttonStyle);\n connect(zoomButton, &QPushButton::clicked, this, &MainWindow::toggleZoomSlider);\n\n // ✅ Create the floating frame (Initially Hidden)\n zoomFrame = new QFrame(this);\n zoomFrame->setFrameShape(QFrame::StyledPanel);\n zoomFrame->setStyleSheet(R\"(\n background-color: black;\n border: 1px solid black;\n padding: 5px;\n )\");\n zoomFrame->setVisible(false);\n zoomFrame->setFixedSize(440, 40); // Adjust width/height as needed\n\n zoomSlider = new QSlider(Qt::Horizontal, this);\n zoomSlider->setRange(10, 400);\n zoomSlider->setValue(100);\n zoomSlider->setMaximumWidth(405);\n\n connect(zoomSlider, &QSlider::valueChanged, this, &MainWindow::onZoomSliderChanged);\n\n QVBoxLayout *popupLayout = new QVBoxLayout();\n popupLayout->setContentsMargins(10, 5, 10, 5);\n popupLayout->addWidget(zoomSlider);\n zoomFrame->setLayout(popupLayout);\n \n\n zoom50Button = new QPushButton(\"0.5x\", this);\n zoom50Button->setFixedSize(35, 30);\n zoom50Button->setStyleSheet(buttonStyle);\n zoom50Button->setToolTip(tr(\"Set Zoom to 50%\"));\n connect(zoom50Button, &QPushButton::clicked, [this]() { zoomSlider->setValue(50 / initialDpr); updateDialDisplay(); });\n\n dezoomButton = new QPushButton(\"1x\", this);\n dezoomButton->setFixedSize(26, 30);\n dezoomButton->setStyleSheet(buttonStyle);\n dezoomButton->setToolTip(tr(\"Set Zoom to 100%\"));\n connect(dezoomButton, &QPushButton::clicked, [this]() { zoomSlider->setValue(100 / initialDpr); updateDialDisplay(); });\n\n zoom200Button = new QPushButton(\"2x\", this);\n zoom200Button->setFixedSize(31, 30);\n zoom200Button->setStyleSheet(buttonStyle);\n zoom200Button->setToolTip(tr(\"Set Zoom to 200%\"));\n connect(zoom200Button, &QPushButton::clicked, [this]() { zoomSlider->setValue(200 / initialDpr); updateDialDisplay(); });\n\n panXSlider = new QScrollBar(Qt::Horizontal, this);\n panYSlider = new QScrollBar(Qt::Vertical, this);\n panYSlider->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);\n \n // Set scrollbar styling\n QString scrollBarStyle = R\"(\n QScrollBar {\n background: rgba(200, 200, 200, 80);\n border: none;\n margin: 0px;\n }\n QScrollBar:hover {\n background: rgba(200, 200, 200, 120);\n }\n QScrollBar:horizontal {\n height: 16px !important; /* Force narrow height */\n max-height: 16px !important;\n }\n QScrollBar:vertical {\n width: 16px !important; /* Force narrow width */\n max-width: 16px !important;\n }\n QScrollBar::handle {\n background: rgba(100, 100, 100, 150);\n border-radius: 2px;\n min-height: 120px; /* Longer handle for vertical scrollbar */\n min-width: 120px; /* Longer handle for horizontal scrollbar */\n }\n QScrollBar::handle:hover {\n background: rgba(80, 80, 80, 210);\n }\n /* Hide scroll buttons */\n QScrollBar::add-line, \n QScrollBar::sub-line {\n width: 0px;\n height: 0px;\n background: none;\n border: none;\n }\n /* Disable scroll page buttons */\n QScrollBar::add-page, \n QScrollBar::sub-page {\n background: transparent;\n }\n )\";\n \n panXSlider->setStyleSheet(scrollBarStyle);\n panYSlider->setStyleSheet(scrollBarStyle);\n \n // Force fixed dimensions programmatically\n panXSlider->setFixedHeight(16);\n panYSlider->setFixedWidth(16);\n \n // Set up auto-hiding\n panXSlider->setMouseTracking(true);\n panYSlider->setMouseTracking(true);\n panXSlider->installEventFilter(this);\n panYSlider->installEventFilter(this);\n panXSlider->setVisible(false);\n panYSlider->setVisible(false);\n \n // Create timer for auto-hiding\n scrollbarHideTimer = new QTimer(this);\n scrollbarHideTimer->setSingleShot(true);\n scrollbarHideTimer->setInterval(200); // Hide after 0.2 seconds\n connect(scrollbarHideTimer, &QTimer::timeout, this, [this]() {\n panXSlider->setVisible(false);\n panYSlider->setVisible(false);\n scrollbarsVisible = false;\n });\n \n // panXSlider->setFixedHeight(30);\n // panYSlider->setFixedWidth(30);\n\n connect(panXSlider, &QScrollBar::valueChanged, this, &MainWindow::updatePanX);\n \n connect(panYSlider, &QScrollBar::valueChanged, this, &MainWindow::updatePanY);\n\n\n\n\n // 🌟 PDF Outline Sidebar\n outlineSidebar = new QWidget(this);\n outlineSidebar->setFixedWidth(250);\n outlineSidebar->setVisible(false); // Hidden by default\n \n QVBoxLayout *outlineLayout = new QVBoxLayout(outlineSidebar);\n outlineLayout->setContentsMargins(5, 5, 5, 5);\n \n QLabel *outlineLabel = new QLabel(tr(\"PDF Outline\"), outlineSidebar);\n outlineLabel->setStyleSheet(\"font-weight: bold; padding: 5px;\");\n outlineLayout->addWidget(outlineLabel);\n \n outlineTree = new QTreeWidget(outlineSidebar);\n outlineTree->setHeaderHidden(true);\n outlineTree->setRootIsDecorated(true);\n outlineTree->setIndentation(15);\n outlineLayout->addWidget(outlineTree);\n \n // Connect outline tree item clicks\n connect(outlineTree, &QTreeWidget::itemClicked, this, &MainWindow::onOutlineItemClicked);\n \n // 🌟 Bookmarks Sidebar\n bookmarksSidebar = new QWidget(this);\n bookmarksSidebar->setFixedWidth(250);\n bookmarksSidebar->setVisible(false); // Hidden by default\n \n QVBoxLayout *bookmarksLayout = new QVBoxLayout(bookmarksSidebar);\n bookmarksLayout->setContentsMargins(5, 5, 5, 5);\n \n QLabel *bookmarksLabel = new QLabel(tr(\"Bookmarks\"), bookmarksSidebar);\n bookmarksLabel->setStyleSheet(\"font-weight: bold; padding: 5px;\");\n bookmarksLayout->addWidget(bookmarksLabel);\n \n bookmarksTree = new QTreeWidget(bookmarksSidebar);\n bookmarksTree->setHeaderHidden(true);\n bookmarksTree->setRootIsDecorated(false);\n bookmarksTree->setIndentation(0);\n bookmarksLayout->addWidget(bookmarksTree);\n \n // Connect bookmarks tree item clicks\n connect(bookmarksTree, &QTreeWidget::itemClicked, this, &MainWindow::onBookmarkItemClicked);\n\n // 🌟 Horizontal Tab Bar (like modern web browsers)\n tabList = new QListWidget(this);\n tabList->setFlow(QListView::LeftToRight); // Make it horizontal\n tabList->setFixedHeight(32); // Increased to accommodate scrollbar below tabs\n tabList->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);\n tabList->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n tabList->setSelectionMode(QAbstractItemView::SingleSelection);\n\n // Style the tab bar like a modern browser with transparent scrollbar\n tabList->setStyleSheet(R\"(\n QListWidget {\n background-color: rgba(240, 240, 240, 255);\n border: none;\n border-bottom: 1px solid rgba(200, 200, 200, 255);\n outline: none;\n }\n QListWidget::item {\n background-color: rgba(220, 220, 220, 255);\n border: 1px solid rgba(180, 180, 180, 255);\n border-bottom: none;\n margin-right: 1px;\n margin-top: 2px;\n padding: 0px;\n min-width: 80px;\n max-width: 120px;\n }\n QListWidget::item:selected {\n background-color: white;\n border: 1px solid rgba(180, 180, 180, 255);\n border-bottom: 1px solid white;\n margin-top: 1px;\n }\n QListWidget::item:hover:!selected {\n background-color: rgba(230, 230, 230, 255);\n }\n QScrollBar:horizontal {\n background: rgba(240, 240, 240, 255);\n height: 8px;\n border: none;\n margin: 0px;\n border-top: 1px solid rgba(200, 200, 200, 255);\n }\n QScrollBar::handle:horizontal {\n background: rgba(150, 150, 150, 120);\n border-radius: 4px;\n min-width: 20px;\n margin: 1px;\n }\n QScrollBar::handle:horizontal:hover {\n background: rgba(120, 120, 120, 200);\n }\n QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal {\n width: 0px;\n height: 0px;\n background: none;\n border: none;\n }\n QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {\n background: transparent;\n }\n )\");\n\n // 🌟 Add Button for New Tab (styled like browser + button)\n addTabButton = new QPushButton(this);\n QIcon addTab(loadThemedIcon(\"addtab\")); // Path to your icon in resources\n addTabButton->setIcon(addTab);\n addTabButton->setFixedSize(30, 30); // Even smaller to match thinner layout\n addTabButton->setStyleSheet(R\"(\n QPushButton {\n background-color: rgba(220, 220, 220, 255);\n border: 1px solid rgba(180, 180, 180, 255);\n border-radius: 15px;\n margin: 2px;\n }\n QPushButton:hover {\n background-color: rgba(200, 200, 200, 255);\n }\n QPushButton:pressed {\n background-color: rgba(180, 180, 180, 255);\n }\n )\");\n addTabButton->setToolTip(tr(\"Add New Tab\"));\n connect(addTabButton, &QPushButton::clicked, this, &MainWindow::addNewTab);\n\n if (!canvasStack) {\n canvasStack = new QStackedWidget(this);\n }\n\n connect(tabList, &QListWidget::currentRowChanged, this, &MainWindow::switchTab);\n\n // Create horizontal tab container\n tabBarContainer = new QWidget(this);\n tabBarContainer->setObjectName(\"tabBarContainer\");\n tabBarContainer->setFixedHeight(38); // Increased to accommodate scrollbar below tabs\n \n QHBoxLayout *tabBarLayout = new QHBoxLayout(tabBarContainer);\n tabBarLayout->setContentsMargins(5, 5, 5, 5);\n tabBarLayout->setSpacing(5);\n tabBarLayout->addWidget(tabList, 1); // Tab list takes most space\n tabBarLayout->addWidget(addTabButton, 0); // Add button stays at the end\n\n connect(toggleTabBarButton, &QPushButton::clicked, this, [=]() {\n bool isVisible = tabBarContainer->isVisible();\n tabBarContainer->setVisible(!isVisible);\n \n // Update button toggle state\n toggleTabBarButton->setProperty(\"selected\", !isVisible);\n toggleTabBarButton->style()->unpolish(toggleTabBarButton);\n toggleTabBarButton->style()->polish(toggleTabBarButton);\n\n QTimer::singleShot(0, this, [this]() {\n if (auto *canvas = currentCanvas()) {\n canvas->setMaximumSize(canvas->getCanvasSize());\n }\n });\n });\n \n connect(toggleOutlineButton, &QPushButton::clicked, this, &MainWindow::toggleOutlineSidebar);\n connect(toggleBookmarksButton, &QPushButton::clicked, this, &MainWindow::toggleBookmarksSidebar);\n connect(toggleBookmarkButton, &QPushButton::clicked, this, &MainWindow::toggleCurrentPageBookmark);\n connect(touchGesturesButton, &QPushButton::clicked, this, [this]() {\n setTouchGesturesEnabled(!touchGesturesEnabled);\n touchGesturesButton->setProperty(\"selected\", touchGesturesEnabled);\n touchGesturesButton->style()->unpolish(touchGesturesButton);\n touchGesturesButton->style()->polish(touchGesturesButton);\n });\n\n \n\n\n // Previous page button\n prevPageButton = new QPushButton(this);\n prevPageButton->setFixedSize(26, 30);\n prevPageButton->setText(\"◀\");\n prevPageButton->setStyleSheet(buttonStyle);\n prevPageButton->setToolTip(tr(\"Previous Page\"));\n connect(prevPageButton, &QPushButton::clicked, this, &MainWindow::goToPreviousPage);\n\n pageInput = new QSpinBox(this);\n pageInput->setFixedSize(42, 30);\n pageInput->setMinimum(1);\n pageInput->setMaximum(9999);\n pageInput->setValue(1);\n pageInput->setMaximumWidth(100);\n connect(pageInput, QOverload::of(&QSpinBox::valueChanged), this, &MainWindow::onPageInputChanged);\n\n // Next page button\n nextPageButton = new QPushButton(this);\n nextPageButton->setFixedSize(26, 30);\n nextPageButton->setText(\"▶\");\n nextPageButton->setStyleSheet(buttonStyle);\n nextPageButton->setToolTip(tr(\"Next Page\"));\n connect(nextPageButton, &QPushButton::clicked, this, &MainWindow::goToNextPage);\n\n jumpToPageButton = new QPushButton(this);\n // QIcon jumpIcon(\":/resources/icons/bookpage.png\"); // Path to your icon in resources\n jumpToPageButton->setFixedSize(26, 30);\n jumpToPageButton->setStyleSheet(buttonStyle);\n jumpToPageButton->setIcon(loadThemedIcon(\"bookpage\"));\n connect(jumpToPageButton, &QPushButton::clicked, this, &MainWindow::showJumpToPageDialog);\n\n // ✅ Dial Toggle Button\n dialToggleButton = new QPushButton(this);\n dialToggleButton->setIcon(loadThemedIcon(\"dial\")); // Icon for dial\n dialToggleButton->setFixedSize(26, 30);\n dialToggleButton->setToolTip(tr(\"Toggle Magic Dial\"));\n dialToggleButton->setStyleSheet(buttonStyle);\n\n // ✅ Connect to toggle function\n connect(dialToggleButton, &QPushButton::clicked, this, &MainWindow::toggleDial);\n\n // toggleDial();\n\n \n\n fastForwardButton = new QPushButton(this);\n fastForwardButton->setFixedSize(26, 30);\n // QIcon ffIcon(\":/resources/icons/fastforward.png\"); // Path to your icon in resources\n fastForwardButton->setIcon(loadThemedIcon(\"fastforward\"));\n fastForwardButton->setToolTip(tr(\"Toggle Fast Forward 8x\"));\n fastForwardButton->setStyleSheet(buttonStyle);\n\n // ✅ Toggle fast-forward mode\n connect(fastForwardButton, &QPushButton::clicked, [this]() {\n fastForwardMode = !fastForwardMode;\n updateFastForwardButtonState();\n });\n\n QComboBox *dialModeSelector = new QComboBox(this);\n dialModeSelector->addItem(\"Page Switch\", PageSwitching);\n dialModeSelector->addItem(\"Zoom\", ZoomControl);\n dialModeSelector->addItem(\"Thickness\", ThicknessControl);\n\n dialModeSelector->addItem(\"Tool Switch\", ToolSwitching);\n dialModeSelector->setFixedWidth(120);\n\n connect(dialModeSelector, QOverload::of(&QComboBox::currentIndexChanged), this,\n [this](int index) { changeDialMode(static_cast(index)); });\n\n\n\n colorPreview = new QPushButton(this);\n colorPreview->setFixedSize(26, 30);\n colorPreview->setStyleSheet(\"border-radius: 15px; border: 1px solid gray;\");\n colorPreview->setEnabled(false); // ✅ Prevents it from being clicked\n\n btnPageSwitch = new QPushButton(loadThemedIcon(\"bookpage\"), \"\", this);\n btnPageSwitch->setStyleSheet(buttonStyle);\n btnPageSwitch->setFixedSize(26, 30);\n btnPageSwitch->setToolTip(tr(\"Set Dial Mode to Page Switching\"));\n btnZoom = new QPushButton(loadThemedIcon(\"zoom\"), \"\", this);\n btnZoom->setStyleSheet(buttonStyle);\n btnZoom->setFixedSize(26, 30);\n btnZoom->setToolTip(tr(\"Set Dial Mode to Zoom Ctrl\"));\n btnThickness = new QPushButton(loadThemedIcon(\"thickness\"), \"\", this);\n btnThickness->setStyleSheet(buttonStyle);\n btnThickness->setFixedSize(26, 30);\n btnThickness->setToolTip(tr(\"Set Dial Mode to Pen Tip Thickness Ctrl\"));\n\n btnTool = new QPushButton(loadThemedIcon(\"pen\"), \"\", this);\n btnTool->setStyleSheet(buttonStyle);\n btnTool->setFixedSize(26, 30);\n btnTool->setToolTip(tr(\"Set Dial Mode to Tool Switching\"));\n btnPresets = new QPushButton(loadThemedIcon(\"preset\"), \"\", this);\n btnPresets->setStyleSheet(buttonStyle);\n btnPresets->setFixedSize(26, 30);\n btnPresets->setToolTip(tr(\"Set Dial Mode to Color Preset Selection\"));\n btnPannScroll = new QPushButton(loadThemedIcon(\"scroll\"), \"\", this);\n btnPannScroll->setStyleSheet(buttonStyle);\n btnPannScroll->setFixedSize(26, 30);\n btnPannScroll->setToolTip(tr(\"Slide and turn pages with the dial\"));\n\n connect(btnPageSwitch, &QPushButton::clicked, this, [this]() { changeDialMode(PageSwitching); });\n connect(btnZoom, &QPushButton::clicked, this, [this]() { changeDialMode(ZoomControl); });\n connect(btnThickness, &QPushButton::clicked, this, [this]() { changeDialMode(ThicknessControl); });\n\n connect(btnTool, &QPushButton::clicked, this, [this]() { changeDialMode(ToolSwitching); });\n connect(btnPresets, &QPushButton::clicked, this, [this]() { changeDialMode(PresetSelection); }); \n connect(btnPannScroll, &QPushButton::clicked, this, [this]() { changeDialMode(PanAndPageScroll); });\n\n\n // ✅ Initialize color presets based on palette mode (will be updated after UI setup)\n colorPresets.enqueue(getDefaultPenColor());\n colorPresets.enqueue(QColor(\"#AA0000\")); // Temporary - will be updated later\n colorPresets.enqueue(QColor(\"#997700\"));\n colorPresets.enqueue(QColor(\"#0000AA\"));\n colorPresets.enqueue(QColor(\"#007700\"));\n colorPresets.enqueue(QColor(\"#000000\"));\n colorPresets.enqueue(QColor(\"#FFFFFF\"));\n\n // ✅ Button to add current color to presets\n addPresetButton = new QPushButton(loadThemedIcon(\"savepreset\"), \"\", this);\n addPresetButton->setStyleSheet(buttonStyle);\n addPresetButton->setToolTip(tr(\"Add Current Color to Presets\"));\n addPresetButton->setFixedSize(26, 30);\n connect(addPresetButton, &QPushButton::clicked, this, &MainWindow::addColorPreset);\n\n\n\n\n openControlPanelButton = new QPushButton(this);\n openControlPanelButton->setIcon(loadThemedIcon(\"settings\")); // Replace with your actual settings icon\n openControlPanelButton->setStyleSheet(buttonStyle);\n openControlPanelButton->setToolTip(tr(\"Open Control Panel\"));\n openControlPanelButton->setFixedSize(26, 30); // Adjust to match your other buttons\n\n connect(openControlPanelButton, &QPushButton::clicked, this, [=]() {\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n ControlPanelDialog dialog(this, canvas, this);\n dialog.exec(); // Modal\n }\n });\n\n openRecentNotebooksButton = new QPushButton(this); // Create button\n openRecentNotebooksButton->setIcon(loadThemedIcon(\"recent\")); // Replace with actual icon if available\n openRecentNotebooksButton->setStyleSheet(buttonStyle);\n openRecentNotebooksButton->setToolTip(tr(\"Open Recent Notebooks\"));\n openRecentNotebooksButton->setFixedSize(26, 30);\n connect(openRecentNotebooksButton, &QPushButton::clicked, this, &MainWindow::openRecentNotebooksDialog);\n\n customColorButton = new QPushButton(this);\n customColorButton->setFixedSize(62, 30);\n QColor initialColor = getDefaultPenColor(); // Theme-aware default color\n customColorButton->setText(initialColor.name().toUpper());\n\n if (currentCanvas()) {\n initialColor = currentCanvas()->getPenColor();\n }\n\n updateCustomColorButtonStyle(initialColor);\n\n QTimer::singleShot(0, this, [=]() {\n connect(customColorButton, &QPushButton::clicked, this, [=]() {\n if (!currentCanvas()) return;\n \n handleColorButtonClick();\n \n // Get the current custom color from the button text\n QString buttonText = customColorButton->text();\n QColor customColor(buttonText);\n \n // Check if the custom color is already the current pen color\n if (currentCanvas()->getPenColor() == customColor) {\n // Second click - show color picker dialog\n QColor chosen = QColorDialog::getColor(currentCanvas()->getPenColor(), this, \"Select Pen Color\");\n if (chosen.isValid()) {\n currentCanvas()->setPenColor(chosen);\n updateCustomColorButtonStyle(chosen);\n updateDialDisplay();\n updateColorButtonStates();\n }\n } else {\n // First click - apply the custom color\n currentCanvas()->setPenColor(customColor);\n updateDialDisplay();\n updateColorButtonStates();\n }\n });\n });\n\n QHBoxLayout *controlLayout = new QHBoxLayout;\n \n controlLayout->addWidget(toggleOutlineButton);\n controlLayout->addWidget(toggleBookmarksButton);\n controlLayout->addWidget(toggleBookmarkButton);\n controlLayout->addWidget(touchGesturesButton);\n controlLayout->addWidget(toggleTabBarButton);\n controlLayout->addWidget(selectFolderButton);\n\n controlLayout->addWidget(exportNotebookButton);\n controlLayout->addWidget(importNotebookButton);\n controlLayout->addWidget(loadPdfButton);\n controlLayout->addWidget(clearPdfButton);\n controlLayout->addWidget(pdfTextSelectButton);\n controlLayout->addWidget(backgroundButton);\n controlLayout->addWidget(saveButton);\n controlLayout->addWidget(saveAnnotatedButton);\n controlLayout->addWidget(openControlPanelButton);\n controlLayout->addWidget(openRecentNotebooksButton); // Add button to layout\n controlLayout->addWidget(redButton);\n controlLayout->addWidget(blueButton);\n controlLayout->addWidget(yellowButton);\n controlLayout->addWidget(greenButton);\n controlLayout->addWidget(blackButton);\n controlLayout->addWidget(whiteButton);\n controlLayout->addWidget(customColorButton);\n controlLayout->addWidget(straightLineToggleButton);\n controlLayout->addWidget(ropeToolButton); // Add rope tool button to layout\n controlLayout->addWidget(markdownButton); // Add markdown button to layout\n // controlLayout->addWidget(colorPreview);\n // controlLayout->addWidget(thicknessButton);\n // controlLayout->addWidget(jumpToPageButton);\n controlLayout->addWidget(dialToggleButton);\n controlLayout->addWidget(fastForwardButton);\n // controlLayout->addWidget(channelSelector);\n controlLayout->addWidget(btnPageSwitch);\n controlLayout->addWidget(btnPannScroll);\n controlLayout->addWidget(btnZoom);\n controlLayout->addWidget(btnThickness);\n\n controlLayout->addWidget(btnTool);\n controlLayout->addWidget(btnPresets);\n controlLayout->addWidget(addPresetButton);\n // controlLayout->addWidget(dialModeSelector);\n // controlLayout->addStretch();\n \n // controlLayout->addWidget(toolSelector);\n controlLayout->addWidget(fullscreenButton);\n // controlLayout->addWidget(zoomButton);\n controlLayout->addWidget(zoom50Button);\n controlLayout->addWidget(dezoomButton);\n controlLayout->addWidget(zoom200Button);\n controlLayout->addStretch();\n \n \n controlLayout->addWidget(prevPageButton);\n controlLayout->addWidget(pageInput);\n controlLayout->addWidget(nextPageButton);\n controlLayout->addWidget(benchmarkButton);\n controlLayout->addWidget(benchmarkLabel);\n controlLayout->addWidget(deletePageButton);\n \n \n \n controlBar = new QWidget; // Use member variable instead of local\n controlBar->setObjectName(\"controlBar\");\n // controlBar->setLayout(controlLayout); // Commented out - responsive layout will handle this\n controlBar->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);\n\n // Theme will be applied later in loadUserSettings -> updateTheme()\n controlBar->setStyleSheet(\"\");\n\n \n \n\n canvasStack = new QStackedWidget();\n canvasStack->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);\n\n // Create a container for the canvas and scrollbars with relative positioning\n QWidget *canvasContainer = new QWidget;\n QVBoxLayout *canvasLayout = new QVBoxLayout(canvasContainer);\n canvasLayout->setContentsMargins(0, 0, 0, 0);\n canvasLayout->addWidget(canvasStack);\n\n // Enable context menu for the workaround\n canvasContainer->setContextMenuPolicy(Qt::CustomContextMenu);\n \n // Set up the scrollbars to overlay the canvas\n panXSlider->setParent(canvasContainer);\n panYSlider->setParent(canvasContainer);\n \n // Raise scrollbars to ensure they're visible above the canvas\n panXSlider->raise();\n panYSlider->raise();\n \n // Handle scrollbar intersection\n connect(canvasContainer, &QWidget::customContextMenuRequested, this, [this]() {\n // This connection is just to make sure the container exists\n // and can receive signals - a workaround for some Qt versions\n });\n \n // Position the scrollbars at the bottom and right edges\n canvasContainer->installEventFilter(this);\n \n // Update scrollbar positions initially\n QTimer::singleShot(0, this, [this, canvasContainer]() {\n updateScrollbarPositions();\n });\n\n // Main layout: toolbar -> tab bar -> canvas (vertical stack)\n QWidget *container = new QWidget;\n container->setObjectName(\"container\");\n QVBoxLayout *mainLayout = new QVBoxLayout(container);\n mainLayout->setContentsMargins(0, 0, 0, 0); // ✅ Remove extra margins\n mainLayout->setSpacing(0); // ✅ Remove spacing between components\n \n // Add components in vertical order\n mainLayout->addWidget(controlBar); // Toolbar at top\n mainLayout->addWidget(tabBarContainer); // Tab bar below toolbar\n \n // Content area with sidebars and canvas\n QHBoxLayout *contentLayout = new QHBoxLayout;\n contentLayout->setContentsMargins(0, 0, 0, 0);\n contentLayout->setSpacing(0);\n contentLayout->addWidget(outlineSidebar, 0); // Fixed width outline sidebar\n contentLayout->addWidget(bookmarksSidebar, 0); // Fixed width bookmarks sidebar\n contentLayout->addWidget(canvasContainer, 1); // Canvas takes remaining space\n \n QWidget *contentWidget = new QWidget;\n contentWidget->setLayout(contentLayout);\n mainLayout->addWidget(contentWidget, 1);\n\n setCentralWidget(container);\n\n benchmarkTimer = new QTimer(this);\n connect(benchmarkButton, &QPushButton::clicked, this, &MainWindow::toggleBenchmark);\n connect(benchmarkTimer, &QTimer::timeout, this, &MainWindow::updateBenchmarkDisplay);\n\n QString tempDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\";\n QDir dir(tempDir);\n\n // Remove all contents (but keep the directory itself)\n if (dir.exists()) {\n dir.removeRecursively(); // Careful: this wipes everything inside\n }\n QDir().mkpath(tempDir); // Recreate clean directory\n\n addNewTab();\n\n // Initialize responsive toolbar layout\n createSingleRowLayout(); // Start with single row layout\n \n // Now that all UI components are created, update the color palette\n updateColorPalette();\n\n}\n void loadUserSettings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n\n // Load low-res toggle\n lowResPreviewEnabled = settings.value(\"lowResPreviewEnabled\", true).toBool();\n setLowResPreviewEnabled(lowResPreviewEnabled);\n\n \n zoomButtonsVisible = settings.value(\"zoomButtonsVisible\", true).toBool();\n setZoomButtonsVisible(zoomButtonsVisible);\n\n scrollOnTopEnabled = settings.value(\"scrollOnTopEnabled\", true).toBool();\n setScrollOnTopEnabled(scrollOnTopEnabled);\n\n touchGesturesEnabled = settings.value(\"touchGesturesEnabled\", true).toBool();\n setTouchGesturesEnabled(touchGesturesEnabled);\n \n // Update button visual state to match loaded setting\n touchGesturesButton->setProperty(\"selected\", touchGesturesEnabled);\n touchGesturesButton->style()->unpolish(touchGesturesButton);\n touchGesturesButton->style()->polish(touchGesturesButton);\n \n // Initialize default background settings if they don't exist\n if (!settings.contains(\"defaultBackgroundStyle\")) {\n saveDefaultBackgroundSettings(BackgroundStyle::Grid, Qt::white, 30);\n }\n \n // Load keyboard mappings\n loadKeyboardMappings();\n \n // Load theme settings\n loadThemeSettings();\n}\n bool scrollbarsVisible = false;\n QTimer *scrollbarHideTimer = nullptr;\n bool eventFilter(QObject *obj, QEvent *event) override {\n static bool dragging = false;\n static QPoint lastMousePos;\n static QTimer *longPressTimer = nullptr;\n\n // Handle IME focus events for text input widgets\n QLineEdit *lineEdit = qobject_cast(obj);\n if (lineEdit) {\n if (event->type() == QEvent::FocusIn) {\n // Ensure IME is enabled when text field gets focus\n lineEdit->setAttribute(Qt::WA_InputMethodEnabled, true);\n QInputMethod *inputMethod = QGuiApplication::inputMethod();\n if (inputMethod) {\n inputMethod->show();\n }\n }\n else if (event->type() == QEvent::FocusOut) {\n // Keep IME available but reset state\n QInputMethod *inputMethod = QGuiApplication::inputMethod();\n if (inputMethod) {\n inputMethod->reset();\n }\n }\n }\n\n // Handle resize events for canvas container\n QWidget *container = canvasStack ? canvasStack->parentWidget() : nullptr;\n if (obj == container && event->type() == QEvent::Resize) {\n updateScrollbarPositions();\n return false; // Let the event propagate\n }\n\n // Handle scrollbar visibility\n if (obj == panXSlider || obj == panYSlider) {\n if (event->type() == QEvent::Enter) {\n // Mouse entered scrollbar area\n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n return false;\n } \n else if (event->type() == QEvent::Leave) {\n // Mouse left scrollbar area - start timer to hide\n if (!scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->start();\n }\n return false;\n }\n }\n\n // Check if this is a canvas event for scrollbar handling\n InkCanvas* canvas = qobject_cast(obj);\n if (canvas) {\n // Handle mouse movement for scrollbar visibility\n if (event->type() == QEvent::MouseMove) {\n QMouseEvent* mouseEvent = static_cast(event);\n handleEdgeProximity(canvas, mouseEvent->pos());\n }\n // Handle tablet events for stylus hover (safely)\n else if (event->type() == QEvent::TabletMove) {\n try {\n QTabletEvent* tabletEvent = static_cast(event);\n handleEdgeProximity(canvas, tabletEvent->position().toPoint());\n } catch (...) {\n // Ignore tablet event errors to prevent crashes\n }\n }\n // Handle mouse button press events for forward/backward navigation\n else if (event->type() == QEvent::MouseButtonPress) {\n QMouseEvent* mouseEvent = static_cast(event);\n \n // Mouse button 4 (Back button) - Previous page\n if (mouseEvent->button() == Qt::BackButton) {\n if (prevPageButton) {\n prevPageButton->click();\n }\n return true; // Consume the event\n }\n // Mouse button 5 (Forward button) - Next page\n else if (mouseEvent->button() == Qt::ForwardButton) {\n if (nextPageButton) {\n nextPageButton->click();\n }\n return true; // Consume the event\n }\n }\n // Handle wheel events for scrolling\n else if (event->type() == QEvent::Wheel) {\n QWheelEvent* wheelEvent = static_cast(event);\n \n // Check if we need scrolling\n bool needHorizontalScroll = panXSlider->maximum() > 0;\n bool needVerticalScroll = panYSlider->maximum() > 0;\n \n // Handle vertical scrolling (Y axis)\n if (wheelEvent->angleDelta().y() != 0 && needVerticalScroll) {\n // Calculate scroll amount (negative because wheel up should scroll up)\n int scrollDelta = -wheelEvent->angleDelta().y() / 8; // Convert from 1/8 degree units\n scrollDelta = scrollDelta / 15; // Convert to steps (typical wheel step is 15 degrees)\n \n // Much faster base scroll speed - aim for ~3-5 scrolls to reach bottom\n int baseScrollAmount = panYSlider->maximum() / 8; // 1/8 of total range per scroll\n scrollDelta = scrollDelta * qMax(baseScrollAmount, 50); // Minimum 50 units per scroll\n \n // Apply the scroll\n int currentPan = panYSlider->value();\n int newPan = qBound(panYSlider->minimum(), currentPan + scrollDelta, panYSlider->maximum());\n panYSlider->setValue(newPan);\n \n // Show scrollbar temporarily\n panYSlider->setVisible(true);\n scrollbarsVisible = true;\n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n scrollbarHideTimer->start();\n \n // Consume the event\n return true;\n }\n \n // Handle horizontal scrolling (X axis) - for completeness\n if (wheelEvent->angleDelta().x() != 0 && needHorizontalScroll) {\n // Calculate scroll amount\n int scrollDelta = wheelEvent->angleDelta().x() / 8; // Convert from 1/8 degree units\n scrollDelta = scrollDelta / 15; // Convert to steps\n \n // Much faster base scroll speed - same logic as vertical\n int baseScrollAmount = panXSlider->maximum() / 8; // 1/8 of total range per scroll\n scrollDelta = scrollDelta * qMax(baseScrollAmount, 50); // Minimum 50 units per scroll\n \n // Apply the scroll\n int currentPan = panXSlider->value();\n int newPan = qBound(panXSlider->minimum(), currentPan + scrollDelta, panXSlider->maximum());\n panXSlider->setValue(newPan);\n \n // Show scrollbar temporarily\n panXSlider->setVisible(true);\n scrollbarsVisible = true;\n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n scrollbarHideTimer->start();\n \n // Consume the event\n return true;\n }\n \n // If no scrolling was needed, let the event propagate\n return false;\n }\n }\n\n // Handle dial container drag events\n if (obj == dialContainer) {\n if (event->type() == QEvent::MouseButtonPress) {\n QMouseEvent *mouseEvent = static_cast(event);\n lastMousePos = mouseEvent->globalPos();\n dragging = false;\n\n if (!longPressTimer) {\n longPressTimer = new QTimer(this);\n longPressTimer->setSingleShot(true);\n connect(longPressTimer, &QTimer::timeout, [this]() {\n dragging = true; // ✅ Allow movement after long press\n });\n }\n longPressTimer->start(1500); // ✅ Start long press timer (500ms)\n return true;\n }\n\n if (event->type() == QEvent::MouseMove && dragging) {\n QMouseEvent *mouseEvent = static_cast(event);\n QPoint delta = mouseEvent->globalPos() - lastMousePos;\n dialContainer->move(dialContainer->pos() + delta);\n lastMousePos = mouseEvent->globalPos();\n return true;\n }\n\n if (event->type() == QEvent::MouseButtonRelease) {\n if (longPressTimer) longPressTimer->stop();\n dragging = false; // ✅ Stop dragging on release\n return true;\n }\n }\n\n return QObject::eventFilter(obj, event);\n}\n void updateScrollbarPositions() {\n QWidget *container = canvasStack->parentWidget();\n if (!container || !panXSlider || !panYSlider) return;\n \n // Add small margins for better visibility\n const int margin = 3;\n \n // Get scrollbar dimensions\n const int scrollbarWidth = panYSlider->width();\n const int scrollbarHeight = panXSlider->height();\n \n // Calculate sizes based on container\n int containerWidth = container->width();\n int containerHeight = container->height();\n \n // Leave a bit of space for the corner\n int cornerOffset = 15;\n \n // Position horizontal scrollbar at top\n panXSlider->setGeometry(\n cornerOffset + margin, // Leave space at left corner\n margin,\n containerWidth - cornerOffset - margin*2, // Full width minus corner and right margin\n scrollbarHeight\n );\n \n // Position vertical scrollbar at left\n panYSlider->setGeometry(\n margin,\n cornerOffset + margin, // Leave space at top corner\n scrollbarWidth,\n containerHeight - cornerOffset - margin*2 // Full height minus corner and bottom margin\n );\n}\n void handleEdgeProximity(InkCanvas* canvas, const QPoint& pos) {\n if (!canvas) return;\n \n // Get canvas dimensions\n int canvasWidth = canvas->width();\n int canvasHeight = canvas->height();\n \n // Edge detection zones - show scrollbars when pointer is within 50px of edges\n bool nearLeftEdge = pos.x() < 25; // For vertical scrollbar\n bool nearTopEdge = pos.y() < 25; // For horizontal scrollbar - entire top edge\n \n // Only show scrollbars if canvas is larger than viewport\n bool needHorizontalScroll = panXSlider->maximum() > 0;\n bool needVerticalScroll = panYSlider->maximum() > 0;\n \n // Show/hide scrollbars based on pointer position\n if (nearLeftEdge && needVerticalScroll) {\n panYSlider->setVisible(true);\n scrollbarsVisible = true;\n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n scrollbarHideTimer->start();\n }\n \n if (nearTopEdge && needHorizontalScroll) {\n panXSlider->setVisible(true);\n scrollbarsVisible = true;\n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n scrollbarHideTimer->start();\n }\n}\n bool isToolbarTwoRows = false;\n QVBoxLayout *controlLayoutVertical = nullptr;\n QHBoxLayout *controlLayoutSingle = nullptr;\n QHBoxLayout *controlLayoutFirstRow = nullptr;\n QHBoxLayout *controlLayoutSecondRow = nullptr;\n void updateToolbarLayout() {\n // Calculate scaled width using device pixel ratio\n QScreen *screen = QGuiApplication::primaryScreen();\n // qreal dpr = screen ? screen->devicePixelRatio() : 1.0;\n int scaledWidth = width();\n \n // Dynamic threshold based on zoom button visibility\n int threshold = areZoomButtonsVisible() ? 1548 : 1438;\n \n // Debug output to understand what's happening\n // qDebug() << \"Window width:\" << scaledWidth << \"Threshold:\" << threshold << \"Zoom buttons visible:\" << areZoomButtonsVisible();\n \n bool shouldBeTwoRows = scaledWidth <= threshold;\n \n // qDebug() << \"Should be two rows:\" << shouldBeTwoRows << \"Currently is two rows:\" << isToolbarTwoRows;\n \n if (shouldBeTwoRows != isToolbarTwoRows) {\n isToolbarTwoRows = shouldBeTwoRows;\n \n // qDebug() << \"Switching to\" << (isToolbarTwoRows ? \"two rows\" : \"single row\");\n \n if (isToolbarTwoRows) {\n createTwoRowLayout();\n } else {\n createSingleRowLayout();\n }\n }\n}\n void createSingleRowLayout() {\n // Delete separator line if it exists (from previous 2-row layout)\n if (separatorLine) {\n delete separatorLine;\n separatorLine = nullptr;\n }\n \n // Create new single row layout first\n QHBoxLayout *newLayout = new QHBoxLayout;\n \n // Add all widgets to single row (same order as before)\n newLayout->addWidget(toggleTabBarButton);\n newLayout->addWidget(toggleOutlineButton);\n newLayout->addWidget(toggleBookmarksButton);\n newLayout->addWidget(toggleBookmarkButton);\n newLayout->addWidget(touchGesturesButton);\n newLayout->addWidget(selectFolderButton);\n newLayout->addWidget(exportNotebookButton);\n newLayout->addWidget(importNotebookButton);\n newLayout->addWidget(loadPdfButton);\n newLayout->addWidget(clearPdfButton);\n newLayout->addWidget(pdfTextSelectButton);\n newLayout->addWidget(backgroundButton);\n newLayout->addWidget(saveButton);\n newLayout->addWidget(saveAnnotatedButton);\n newLayout->addWidget(openControlPanelButton);\n newLayout->addWidget(openRecentNotebooksButton);\n newLayout->addWidget(redButton);\n newLayout->addWidget(blueButton);\n newLayout->addWidget(yellowButton);\n newLayout->addWidget(greenButton);\n newLayout->addWidget(blackButton);\n newLayout->addWidget(whiteButton);\n newLayout->addWidget(customColorButton);\n newLayout->addWidget(penToolButton);\n newLayout->addWidget(markerToolButton);\n newLayout->addWidget(eraserToolButton);\n newLayout->addWidget(straightLineToggleButton);\n newLayout->addWidget(ropeToolButton);\n newLayout->addWidget(markdownButton);\n newLayout->addWidget(dialToggleButton);\n newLayout->addWidget(fastForwardButton);\n newLayout->addWidget(btnPageSwitch);\n newLayout->addWidget(btnPannScroll);\n newLayout->addWidget(btnZoom);\n newLayout->addWidget(btnThickness);\n\n newLayout->addWidget(btnTool);\n newLayout->addWidget(btnPresets);\n newLayout->addWidget(addPresetButton);\n newLayout->addWidget(fullscreenButton);\n \n // Only add zoom buttons if they're visible\n if (areZoomButtonsVisible()) {\n newLayout->addWidget(zoom50Button);\n newLayout->addWidget(dezoomButton);\n newLayout->addWidget(zoom200Button);\n }\n \n newLayout->addStretch();\n newLayout->addWidget(prevPageButton);\n newLayout->addWidget(pageInput);\n newLayout->addWidget(nextPageButton);\n newLayout->addWidget(benchmarkButton);\n newLayout->addWidget(benchmarkLabel);\n newLayout->addWidget(deletePageButton);\n \n // Safely replace the layout\n QLayout* oldLayout = controlBar->layout();\n if (oldLayout) {\n // Remove all items from old layout (but don't delete widgets)\n QLayoutItem* item;\n while ((item = oldLayout->takeAt(0)) != nullptr) {\n // Just removing, not deleting widgets\n }\n delete oldLayout;\n }\n \n // Set the new layout\n controlBar->setLayout(newLayout);\n controlLayoutSingle = newLayout;\n \n // Clean up other layout pointers\n controlLayoutVertical = nullptr;\n controlLayoutFirstRow = nullptr;\n controlLayoutSecondRow = nullptr;\n \n // Update pan range after layout change\n updatePanRange();\n}\n void createTwoRowLayout() {\n // Create new layouts first\n QVBoxLayout *newVerticalLayout = new QVBoxLayout;\n QHBoxLayout *newFirstRowLayout = new QHBoxLayout;\n QHBoxLayout *newSecondRowLayout = new QHBoxLayout;\n \n // Add comfortable spacing and margins for 2-row layout\n newFirstRowLayout->setContentsMargins(8, 8, 8, 6); // More generous margins\n newFirstRowLayout->setSpacing(3); // Add spacing between buttons for less cramped feel\n newSecondRowLayout->setContentsMargins(8, 6, 8, 8); // More generous margins\n newSecondRowLayout->setSpacing(3); // Add spacing between buttons for less cramped feel\n \n // First row: up to customColorButton\n newFirstRowLayout->addWidget(toggleTabBarButton);\n newFirstRowLayout->addWidget(toggleOutlineButton);\n newFirstRowLayout->addWidget(toggleBookmarksButton);\n newFirstRowLayout->addWidget(toggleBookmarkButton);\n newFirstRowLayout->addWidget(touchGesturesButton);\n newFirstRowLayout->addWidget(selectFolderButton);\n newFirstRowLayout->addWidget(exportNotebookButton);\n newFirstRowLayout->addWidget(importNotebookButton);\n newFirstRowLayout->addWidget(loadPdfButton);\n newFirstRowLayout->addWidget(clearPdfButton);\n newFirstRowLayout->addWidget(pdfTextSelectButton);\n newFirstRowLayout->addWidget(backgroundButton);\n newFirstRowLayout->addWidget(saveButton);\n newFirstRowLayout->addWidget(saveAnnotatedButton);\n newFirstRowLayout->addWidget(openControlPanelButton);\n newFirstRowLayout->addWidget(openRecentNotebooksButton);\n newFirstRowLayout->addWidget(redButton);\n newFirstRowLayout->addWidget(blueButton);\n newFirstRowLayout->addWidget(yellowButton);\n newFirstRowLayout->addWidget(greenButton);\n newFirstRowLayout->addWidget(blackButton);\n newFirstRowLayout->addWidget(whiteButton);\n newFirstRowLayout->addWidget(customColorButton);\n newFirstRowLayout->addWidget(penToolButton);\n newFirstRowLayout->addWidget(markerToolButton);\n newFirstRowLayout->addWidget(eraserToolButton);\n newFirstRowLayout->addStretch();\n \n // Create a separator line\n if (!separatorLine) {\n separatorLine = new QFrame();\n separatorLine->setFrameShape(QFrame::HLine);\n separatorLine->setFrameShadow(QFrame::Sunken);\n separatorLine->setLineWidth(1);\n separatorLine->setStyleSheet(\"QFrame { color: rgba(255, 255, 255, 255); }\");\n }\n \n // Second row: everything after customColorButton\n newSecondRowLayout->addWidget(straightLineToggleButton);\n newSecondRowLayout->addWidget(ropeToolButton);\n newSecondRowLayout->addWidget(markdownButton);\n newSecondRowLayout->addWidget(dialToggleButton);\n newSecondRowLayout->addWidget(fastForwardButton);\n newSecondRowLayout->addWidget(btnPageSwitch);\n newSecondRowLayout->addWidget(btnPannScroll);\n newSecondRowLayout->addWidget(btnZoom);\n newSecondRowLayout->addWidget(btnThickness);\n\n newSecondRowLayout->addWidget(btnTool);\n newSecondRowLayout->addWidget(btnPresets);\n newSecondRowLayout->addWidget(addPresetButton);\n newSecondRowLayout->addWidget(fullscreenButton);\n \n // Only add zoom buttons if they're visible\n if (areZoomButtonsVisible()) {\n newSecondRowLayout->addWidget(zoom50Button);\n newSecondRowLayout->addWidget(dezoomButton);\n newSecondRowLayout->addWidget(zoom200Button);\n }\n \n newSecondRowLayout->addStretch();\n newSecondRowLayout->addWidget(prevPageButton);\n newSecondRowLayout->addWidget(pageInput);\n newSecondRowLayout->addWidget(nextPageButton);\n newSecondRowLayout->addWidget(benchmarkButton);\n newSecondRowLayout->addWidget(benchmarkLabel);\n newSecondRowLayout->addWidget(deletePageButton);\n \n // Add layouts to vertical layout with separator\n newVerticalLayout->addLayout(newFirstRowLayout);\n newVerticalLayout->addWidget(separatorLine);\n newVerticalLayout->addLayout(newSecondRowLayout);\n newVerticalLayout->setContentsMargins(0, 0, 0, 0);\n newVerticalLayout->setSpacing(0); // No spacing since we have our own separator\n \n // Safely replace the layout\n QLayout* oldLayout = controlBar->layout();\n if (oldLayout) {\n // Remove all items from old layout (but don't delete widgets)\n QLayoutItem* item;\n while ((item = oldLayout->takeAt(0)) != nullptr) {\n // Just removing, not deleting widgets\n }\n delete oldLayout;\n }\n \n // Set the new layout\n controlBar->setLayout(newVerticalLayout);\n controlLayoutVertical = newVerticalLayout;\n controlLayoutFirstRow = newFirstRowLayout;\n controlLayoutSecondRow = newSecondRowLayout;\n \n // Clean up other layout pointer\n controlLayoutSingle = nullptr;\n \n // Update pan range after layout change\n updatePanRange();\n}\n QString elideTabText(const QString &text, int maxWidth) {\n // Create a font metrics object using the default font\n QFontMetrics fontMetrics(QApplication::font());\n \n // Elide the text from the right (showing the beginning)\n return fontMetrics.elidedText(text, Qt::ElideRight, maxWidth);\n}\n QTimer *layoutUpdateTimer = nullptr;\n QFrame *separatorLine = nullptr;\n protected:\n void resizeEvent(QResizeEvent *event) override {\n QMainWindow::resizeEvent(event);\n \n // Use a timer to delay layout updates during resize to prevent excessive switching\n if (!layoutUpdateTimer) {\n layoutUpdateTimer = new QTimer(this);\n layoutUpdateTimer->setSingleShot(true);\n connect(layoutUpdateTimer, &QTimer::timeout, this, [this]() {\n updateToolbarLayout();\n // Also reposition dial after resize finishes\n if (dialContainer && dialContainer->isVisible()) {\n positionDialContainer();\n }\n });\n }\n \n layoutUpdateTimer->stop();\n layoutUpdateTimer->start(100); // Wait 100ms after resize stops\n}\n void keyPressEvent(QKeyEvent *event) override {\n // Don't intercept keyboard events when text input widgets have focus\n // This prevents conflicts with Windows TextInputFramework\n QWidget *focusWidget = QApplication::focusWidget();\n if (focusWidget) {\n bool isTextInputWidget = qobject_cast(focusWidget) || \n qobject_cast(focusWidget) || \n qobject_cast(focusWidget) ||\n qobject_cast(focusWidget) ||\n qobject_cast(focusWidget);\n \n if (isTextInputWidget) {\n // Let text input widgets handle their own keyboard events\n QMainWindow::keyPressEvent(event);\n return;\n }\n }\n \n // Don't intercept IME-related keyboard shortcuts\n // These are reserved for Windows Input Method Editor\n if (event->modifiers() & Qt::ControlModifier) {\n if (event->key() == Qt::Key_Space || // Ctrl+Space (IME toggle)\n event->key() == Qt::Key_Shift || // Ctrl+Shift (language switch)\n event->key() == Qt::Key_Alt) { // Ctrl+Alt (IME functions)\n // Let Windows handle IME shortcuts\n QMainWindow::keyPressEvent(event);\n return;\n }\n }\n \n // Don't intercept Shift+Alt (another common IME shortcut)\n if ((event->modifiers() & Qt::ShiftModifier) && (event->modifiers() & Qt::AltModifier)) {\n QMainWindow::keyPressEvent(event);\n return;\n }\n \n // Build key sequence string\n QStringList modifiers;\n \n if (event->modifiers() & Qt::ControlModifier) modifiers << \"Ctrl\";\n if (event->modifiers() & Qt::ShiftModifier) modifiers << \"Shift\";\n if (event->modifiers() & Qt::AltModifier) modifiers << \"Alt\";\n if (event->modifiers() & Qt::MetaModifier) modifiers << \"Meta\";\n \n QString keyString = QKeySequence(event->key()).toString();\n \n QString fullSequence;\n if (!modifiers.isEmpty()) {\n fullSequence = modifiers.join(\"+\") + \"+\" + keyString;\n } else {\n fullSequence = keyString;\n }\n \n // Check if this sequence is mapped\n if (keyboardMappings.contains(fullSequence)) {\n handleKeyboardShortcut(fullSequence);\n event->accept();\n return;\n }\n \n // If not handled, pass to parent\n QMainWindow::keyPressEvent(event);\n}\n void tabletEvent(QTabletEvent *event) override {\n // Since tablet tracking is disabled to prevent crashes, we now only handle\n // basic tablet events that come through when stylus is touching the surface\n if (!event) {\n return;\n }\n \n // Just pass tablet events to parent safely without custom hover handling\n // (hover tooltips will work through normal mouse events instead)\n try {\n QMainWindow::tabletEvent(event);\n } catch (...) {\n // Catch any exceptions and just accept the event\n event->accept();\n }\n}\n void inputMethodEvent(QInputMethodEvent *event) override {\n // Forward IME events to the focused widget\n QWidget *focusWidget = QApplication::focusWidget();\n if (focusWidget && focusWidget != this) {\n QApplication::sendEvent(focusWidget, event);\n event->accept();\n return;\n }\n \n // Default handling\n QMainWindow::inputMethodEvent(event);\n}\n QVariant inputMethodQuery(Qt::InputMethodQuery query) const override {\n // Forward IME queries to the focused widget\n QWidget *focusWidget = QApplication::focusWidget();\n if (focusWidget && focusWidget != this) {\n return focusWidget->inputMethodQuery(query);\n }\n \n // Default handling\n return QMainWindow::inputMethodQuery(query);\n}\n};"], ["/SpeedyNote/source/RecentNotebooksDialog.h", "class QPushButton {\n Q_OBJECT\n\npublic:\n explicit RecentNotebooksDialog(MainWindow *mainWindow, RecentNotebooksManager *manager, QWidget *parent = nullptr);\n private:\n void onNotebookClicked() {\n QPushButton *button = qobject_cast(sender());\n if (button) {\n QString notebookPath = button->property(\"notebookPath\").toString();\n if (!notebookPath.isEmpty() && mainWindowRef) {\n // This logic is similar to MainWindow::selectFolder but directly sets the folder.\n InkCanvas *canvas = mainWindowRef->currentCanvas(); // Get current canvas from MainWindow\n if (canvas) {\n if (canvas->isEdited()){\n mainWindowRef->saveCurrentPage(); // Use MainWindow's save method\n }\n canvas->setSaveFolder(notebookPath);\n mainWindowRef->switchPageWithDirection(1, 1); // Use MainWindow's direction-aware switchPage method\n mainWindowRef->pageInput->setValue(1); // Update pageInput in MainWindow\n mainWindowRef->updateTabLabel(); // Update tab label in MainWindow\n \n // Update recent notebooks list and refresh cover page\n if (notebookManager) {\n // Generate and save fresh cover preview\n notebookManager->generateAndSaveCoverPreview(notebookPath, canvas);\n // Add/update in recent list (this moves it to the top)\n notebookManager->addRecentNotebook(notebookPath, canvas);\n }\n }\n accept(); // Close the dialog\n }\n }\n}\n private:\n void setupUi() {\n QVBoxLayout *mainLayout = new QVBoxLayout(this);\n QScrollArea *scrollArea = new QScrollArea(this);\n scrollArea->setWidgetResizable(true);\n QWidget *gridContainer = new QWidget();\n gridLayout = new QGridLayout(gridContainer);\n gridLayout->setSpacing(15);\n\n scrollArea->setWidget(gridContainer);\n mainLayout->addWidget(scrollArea);\n setLayout(mainLayout);\n}\n void populateGrid() {\n QStringList recentPaths = notebookManager->getRecentNotebooks();\n int row = 0;\n int col = 0;\n const int numCols = 4;\n\n for (const QString &path : recentPaths) {\n if (path.isEmpty()) continue;\n\n QPushButton *button = new QPushButton(this);\n button->setFixedSize(180, 180); // Larger buttons\n button->setProperty(\"notebookPath\", path); // Store path for slot\n connect(button, &QPushButton::clicked, this, &RecentNotebooksDialog::onNotebookClicked);\n\n QVBoxLayout *buttonLayout = new QVBoxLayout(button);\n buttonLayout->setContentsMargins(5,5,5,5);\n\n QLabel *coverLabel = new QLabel(this);\n coverLabel->setFixedSize(170, 127); // 4:3 aspect ratio for cover\n coverLabel->setAlignment(Qt::AlignCenter);\n QString coverPath = notebookManager->getCoverImagePathForNotebook(path);\n if (!coverPath.isEmpty()) {\n QPixmap coverPixmap(coverPath);\n coverLabel->setPixmap(coverPixmap.scaled(coverLabel->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));\n } else {\n coverLabel->setText(tr(\"No Preview\"));\n }\n coverLabel->setStyleSheet(\"border: 1px solid gray;\");\n\n QLabel *nameLabel = new QLabel(notebookManager->getNotebookDisplayName(path), this);\n nameLabel->setAlignment(Qt::AlignCenter);\n nameLabel->setWordWrap(true);\n nameLabel->setFixedHeight(40); // Fixed height for name label\n\n buttonLayout->addWidget(coverLabel);\n buttonLayout->addWidget(nameLabel);\n button->setLayout(buttonLayout);\n\n gridLayout->addWidget(button, row, col);\n\n col++;\n if (col >= numCols) {\n col = 0;\n row++;\n }\n }\n}\n RecentNotebooksManager *notebookManager;\n QGridLayout *gridLayout;\n MainWindow *mainWindowRef;\n};"], ["/SpeedyNote/source/PdfOpenDialog.h", "class PdfOpenDialog {\n Q_OBJECT\n\npublic:\n enum Result {\n Cancel,\n CreateNewFolder,\n UseExistingFolder\n };\n explicit PdfOpenDialog(const QString &pdfPath, QWidget *parent = nullptr) {\n setWindowTitle(tr(\"Open PDF with SpeedyNote\"));\n setWindowIcon(QIcon(\":/resources/icons/mainicon.png\"));\n setModal(true);\n \n // Remove setFixedSize and use proper size management instead\n // Calculate size based on DPI\n QScreen *screen = QGuiApplication::primaryScreen();\n qreal dpr = screen ? screen->devicePixelRatio() : 1.0;\n \n // Set minimum and maximum sizes instead of fixed size\n int baseWidth = 500;\n int baseHeight = 200;\n \n // Scale sizes appropriately for DPI\n int scaledWidth = static_cast(baseWidth * qMax(1.0, dpr * 0.8));\n int scaledHeight = static_cast(baseHeight * qMax(1.0, dpr * 0.8));\n \n setMinimumSize(scaledWidth, scaledHeight);\n setMaximumSize(scaledWidth + 100, scaledHeight + 50); // Allow some flexibility\n \n // Set size policy to prevent unwanted resizing\n setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);\n \n setupUI();\n \n // Ensure the dialog is properly sized after UI setup\n adjustSize();\n \n // Center the dialog on parent or screen\n if (parent) {\n move(parent->geometry().center() - rect().center());\n } else {\n move(screen->geometry().center() - rect().center());\n }\n}\n static bool hasValidNotebookFolder(const QString &pdfPath, QString &folderPath) {\n QFileInfo fileInfo(pdfPath);\n QString suggestedFolderName = fileInfo.baseName(); // Filename without extension\n QString pdfDir = fileInfo.absolutePath(); // Directory containing the PDF\n QString potentialFolderPath = pdfDir + \"/\" + suggestedFolderName;\n \n if (isValidNotebookFolder(potentialFolderPath, pdfPath)) {\n folderPath = potentialFolderPath;\n return true;\n }\n \n return false;\n}\n protected:\n void resizeEvent(QResizeEvent *event) override {\n // Handle resize events smoothly to prevent jitter during window dragging\n if (event->size() != event->oldSize()) {\n // Only process if size actually changed\n QDialog::resizeEvent(event);\n \n // Ensure the dialog stays within reasonable bounds\n QSize newSize = event->size();\n QSize minSize = minimumSize();\n QSize maxSize = maximumSize();\n \n // Clamp the size to prevent unwanted resizing\n newSize = newSize.expandedTo(minSize).boundedTo(maxSize);\n \n if (newSize != event->size()) {\n // If size needs to be adjusted, do it without triggering another resize event\n resize(newSize);\n }\n } else {\n // If size hasn't changed, just call parent implementation\n QDialog::resizeEvent(event);\n }\n}\n private:\n void onCreateNewFolder() {\n QFileInfo fileInfo(pdfPath);\n QString suggestedFolderName = fileInfo.baseName();\n \n // Get the directory where the PDF is located\n QString pdfDir = fileInfo.absolutePath();\n QString newFolderPath = pdfDir + \"/\" + suggestedFolderName;\n \n // Check if folder already exists\n if (QDir(newFolderPath).exists()) {\n QMessageBox::StandardButton reply = QMessageBox::question(\n this, \n tr(\"Folder Exists\"), \n tr(\"A folder named \\\"%1\\\" already exists in the same directory as the PDF.\\n\\nDo you want to use this existing folder?\").arg(suggestedFolderName),\n QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel\n );\n \n if (reply == QMessageBox::Yes) {\n selectedFolder = newFolderPath;\n result = UseExistingFolder;\n accept();\n return;\n } else if (reply == QMessageBox::Cancel) {\n return; // Stay in dialog\n }\n // If No, continue to create with different name\n \n // Try to create with incremented name\n int counter = 1;\n do {\n newFolderPath = pdfDir + \"/\" + suggestedFolderName + QString(\"_%1\").arg(counter);\n counter++;\n } while (QDir(newFolderPath).exists() && counter < 100);\n \n if (counter >= 100) {\n QMessageBox::warning(this, tr(\"Error\"), tr(\"Could not create a unique folder name.\"));\n return;\n }\n }\n \n // Create the new folder\n QDir dir;\n if (dir.mkpath(newFolderPath)) {\n selectedFolder = newFolderPath;\n result = CreateNewFolder;\n accept();\n } else {\n QMessageBox::warning(this, tr(\"Error\"), tr(\"Failed to create folder: %1\").arg(newFolderPath));\n }\n}\n void onUseExistingFolder() {\n QString folder = QFileDialog::getExistingDirectory(\n this, \n tr(\"Select Existing Notebook Folder\"), \n QFileInfo(pdfPath).absolutePath()\n );\n \n if (!folder.isEmpty()) {\n selectedFolder = folder;\n result = UseExistingFolder;\n accept();\n }\n}\n void onCancel() {\n result = Cancel;\n reject();\n}\n private:\n void setupUI() {\n QVBoxLayout *mainLayout = new QVBoxLayout(this);\n mainLayout->setSpacing(15);\n mainLayout->setContentsMargins(20, 20, 20, 20);\n \n // Set layout size constraint to prevent unwanted resizing\n mainLayout->setSizeConstraint(QLayout::SetMinAndMaxSize);\n \n // Icon and title\n QHBoxLayout *headerLayout = new QHBoxLayout();\n headerLayout->setSpacing(10);\n \n QLabel *iconLabel = new QLabel();\n QPixmap icon = QIcon(\":/resources/icons/mainicon.png\").pixmap(48, 48);\n iconLabel->setPixmap(icon);\n iconLabel->setFixedSize(48, 48);\n iconLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);\n \n QLabel *titleLabel = new QLabel(tr(\"Open PDF with SpeedyNote\"));\n titleLabel->setStyleSheet(\"font-size: 16px; font-weight: bold;\");\n titleLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);\n \n headerLayout->addWidget(iconLabel);\n headerLayout->addWidget(titleLabel);\n headerLayout->addStretch();\n \n mainLayout->addLayout(headerLayout);\n \n // PDF file info\n QFileInfo fileInfo(pdfPath);\n QString fileName = fileInfo.fileName();\n QString folderName = fileInfo.baseName(); // Filename without extension\n \n QLabel *messageLabel = new QLabel(tr(\"PDF File: %1\\n\\nHow would you like to open this PDF?\").arg(fileName));\n messageLabel->setWordWrap(true);\n messageLabel->setStyleSheet(\"font-size: 12px; color: #666;\");\n messageLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);\n \n mainLayout->addWidget(messageLabel);\n \n // Buttons\n QVBoxLayout *buttonLayout = new QVBoxLayout();\n buttonLayout->setSpacing(10);\n \n // Create new folder button\n QPushButton *createFolderBtn = new QPushButton(tr(\"Create New Notebook Folder (\\\"%1\\\")\").arg(folderName));\n createFolderBtn->setIcon(QApplication::style()->standardIcon(QStyle::SP_DirIcon));\n createFolderBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);\n createFolderBtn->setMinimumHeight(40);\n createFolderBtn->setStyleSheet(R\"(\n QPushButton {\n text-align: left;\n padding: 10px;\n border: 1px solid palette(mid);\n border-radius: 5px;\n background: palette(button);\n }\n QPushButton:hover {\n background: palette(light);\n border-color: palette(dark);\n }\n QPushButton:pressed {\n background: palette(midlight);\n }\n )\");\n connect(createFolderBtn, &QPushButton::clicked, this, &PdfOpenDialog::onCreateNewFolder);\n \n // Use existing folder button\n QPushButton *existingFolderBtn = new QPushButton(tr(\"Use Existing Notebook Folder...\"));\n existingFolderBtn->setIcon(QApplication::style()->standardIcon(QStyle::SP_DirOpenIcon));\n existingFolderBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);\n existingFolderBtn->setMinimumHeight(40);\n existingFolderBtn->setStyleSheet(R\"(\n QPushButton {\n text-align: left;\n padding: 10px;\n border: 1px solid palette(mid);\n border-radius: 5px;\n background: palette(button);\n }\n QPushButton:hover {\n background: palette(light);\n border-color: palette(dark);\n }\n QPushButton:pressed {\n background: palette(midlight);\n }\n )\");\n connect(existingFolderBtn, &QPushButton::clicked, this, &PdfOpenDialog::onUseExistingFolder);\n \n buttonLayout->addWidget(createFolderBtn);\n buttonLayout->addWidget(existingFolderBtn);\n \n mainLayout->addLayout(buttonLayout);\n \n // Cancel button\n QHBoxLayout *cancelLayout = new QHBoxLayout();\n cancelLayout->addStretch();\n \n QPushButton *cancelBtn = new QPushButton(tr(\"Cancel\"));\n cancelBtn->setIcon(QApplication::style()->standardIcon(QStyle::SP_DialogCancelButton));\n cancelBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);\n cancelBtn->setMinimumSize(80, 30);\n cancelBtn->setStyleSheet(R\"(\n QPushButton {\n padding: 8px 20px;\n border: 1px solid palette(mid);\n border-radius: 3px;\n background: palette(button);\n }\n QPushButton:hover {\n background: palette(light);\n }\n QPushButton:pressed {\n background: palette(midlight);\n }\n )\");\n connect(cancelBtn, &QPushButton::clicked, this, &PdfOpenDialog::onCancel);\n \n cancelLayout->addWidget(cancelBtn);\n mainLayout->addLayout(cancelLayout);\n}\n static bool isValidNotebookFolder(const QString &folderPath, const QString &pdfPath) {\n QDir folder(folderPath);\n if (!folder.exists()) {\n return false;\n }\n \n // Priority 1: Check for .pdf_path.txt file with matching PDF path\n QString pdfPathFile = folderPath + \"/.pdf_path.txt\";\n if (QFile::exists(pdfPathFile)) {\n QFile file(pdfPathFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString storedPdfPath = in.readLine().trimmed();\n file.close();\n \n if (!storedPdfPath.isEmpty()) {\n // Compare absolute paths to handle relative path differences\n QFileInfo currentPdf(pdfPath);\n QFileInfo storedPdf(storedPdfPath);\n \n // Check if the stored PDF file still exists and matches\n if (storedPdf.exists() && \n currentPdf.absoluteFilePath() == storedPdf.absoluteFilePath()) {\n return true;\n }\n }\n }\n }\n \n // Priority 2: Check for .notebook_id.txt file (SpeedyNote notebook folder)\n QString notebookIdFile = folderPath + \"/.notebook_id.txt\";\n if (QFile::exists(notebookIdFile)) {\n // Additional check: ensure this folder has some notebook content\n QStringList contentFiles = folder.entryList(\n QStringList() << \"*.png\" << \".pdf_path.txt\" << \".bookmarks.txt\" << \".background_config.txt\", \n QDir::Files\n );\n \n // If it has notebook-related files, it's likely a valid SpeedyNote folder\n // but not necessarily for this specific PDF\n if (!contentFiles.isEmpty()) {\n // This is a SpeedyNote notebook, but for a different PDF\n // Return false so the user gets the dialog to choose what to do\n return false;\n }\n }\n \n return false;\n}\n Result result;\n QString selectedFolder;\n QString pdfPath;\n};"], ["/SpeedyNote/source/MarkdownWindowManager.h", "class MarkdownWindow {\n Q_OBJECT\n\npublic:\n explicit MarkdownWindowManager(InkCanvas *canvas, QObject *parent = nullptr);\n ~MarkdownWindowManager() {\n clearAllWindows();\n}\n MarkdownWindow* createMarkdownWindow(const QRect &rect);\n void removeMarkdownWindow(MarkdownWindow *window) {\n if (!window) return;\n \n // Remove from current windows\n currentWindows.removeAll(window);\n \n // Remove from all page windows\n for (auto it = pageWindows.begin(); it != pageWindows.end(); ++it) {\n it.value().removeAll(window);\n }\n \n emit windowRemoved(window);\n \n // Delete the window\n window->deleteLater();\n}\n void clearAllWindows() {\n // Stop transparency timer\n transparencyTimer->stop();\n currentlyFocusedWindow = nullptr;\n windowsAreTransparent = false;\n \n // Clear current windows\n for (MarkdownWindow *window : currentWindows) {\n window->deleteLater();\n }\n currentWindows.clear();\n \n // Clear page windows\n for (auto it = pageWindows.begin(); it != pageWindows.end(); ++it) {\n for (MarkdownWindow *window : it.value()) {\n window->deleteLater();\n }\n }\n pageWindows.clear();\n}\n void saveWindowsForPage(int pageNumber) {\n if (!canvas || currentWindows.isEmpty()) return;\n \n // Update page windows map\n pageWindows[pageNumber] = currentWindows;\n \n // Save to file\n saveWindowData(pageNumber, currentWindows);\n}\n void loadWindowsForPage(int pageNumber) {\n if (!canvas) return;\n\n // qDebug() << \"MarkdownWindowManager::loadWindowsForPage(\" << pageNumber << \")\";\n\n // This method is now only responsible for loading and showing the\n // windows for the specified page. Hiding of old windows is handled before this.\n\n QList newPageWindows;\n\n // Check if we have windows for this page in memory\n if (pageWindows.contains(pageNumber)) {\n // qDebug() << \"Found windows in memory for page\" << pageNumber;\n newPageWindows = pageWindows[pageNumber];\n } else {\n // qDebug() << \"Loading windows from file for page\" << pageNumber;\n // Load from file\n newPageWindows = loadWindowData(pageNumber);\n\n // Update page windows map\n if (!newPageWindows.isEmpty()) {\n pageWindows[pageNumber] = newPageWindows;\n }\n }\n\n // qDebug() << \"Loaded\" << newPageWindows.size() << \"windows for page\" << pageNumber;\n\n // Update the current window list and show the windows\n currentWindows = newPageWindows;\n for (MarkdownWindow *window : currentWindows) {\n // Validate that the window is within canvas bounds\n if (!window->isValidForCanvas()) {\n // qDebug() << \"Warning: Markdown window at\" << window->getCanvasRect() \n // << \"is outside canvas bounds\" << canvas->getCanvasRect();\n // Optionally adjust the window position to fit within bounds\n QRect canvasBounds = canvas->getCanvasRect();\n QRect windowRect = window->getCanvasRect();\n \n // Clamp the window position to canvas bounds\n int newX = qMax(0, qMin(windowRect.x(), canvasBounds.width() - windowRect.width()));\n int newY = qMax(0, qMin(windowRect.y(), canvasBounds.height() - windowRect.height()));\n \n if (newX != windowRect.x() || newY != windowRect.y()) {\n QRect adjustedRect(newX, newY, windowRect.width(), windowRect.height());\n window->setCanvasRect(adjustedRect);\n // qDebug() << \"Adjusted window position to\" << adjustedRect;\n }\n }\n \n // Ensure canvas connections are set up for loaded windows\n window->ensureCanvasConnections();\n \n window->show();\n window->updateScreenPosition();\n // Make sure window is not transparent when loaded\n window->setTransparent(false);\n }\n \n // Start transparency timer if there are windows but none are focused\n if (!currentWindows.isEmpty()) {\n // qDebug() << \"Starting transparency timer for\" << currentWindows.size() << \"windows\";\n resetTransparencyTimer();\n } else {\n // qDebug() << \"No windows to show, not starting timer\";\n }\n}\n void deleteWindowsForPage(int pageNumber) {\n // Remove windows from memory\n if (pageWindows.contains(pageNumber)) {\n QList windows = pageWindows[pageNumber];\n for (MarkdownWindow *window : windows) {\n window->deleteLater();\n }\n pageWindows.remove(pageNumber);\n }\n \n // Delete file\n QString filePath = getWindowDataFilePath(pageNumber);\n if (QFile::exists(filePath)) {\n QFile::remove(filePath);\n }\n \n // Clear current windows if they belong to this page\n if (pageWindows.value(pageNumber) == currentWindows) {\n currentWindows.clear();\n }\n}\n void setSelectionMode(bool enabled) {\n selectionMode = enabled;\n \n // Change cursor for canvas\n if (canvas) {\n canvas->setCursor(enabled ? Qt::CrossCursor : Qt::ArrowCursor);\n }\n}\n QList getCurrentPageWindows() const {\n return currentWindows;\n}\n void resetTransparencyTimer() {\n // qDebug() << \"MarkdownWindowManager::resetTransparencyTimer() called\";\n transparencyTimer->stop();\n \n // DON'T make all windows opaque here - only stop the timer\n // The focused window should be made opaque by the caller if needed\n windowsAreTransparent = false; // Reset the state\n \n // Start the timer again\n transparencyTimer->start();\n // qDebug() << \"Transparency timer started for 10 seconds\";\n}\n void setWindowsTransparent(bool transparent) {\n if (windowsAreTransparent == transparent) return;\n \n // qDebug() << \"MarkdownWindowManager::setWindowsTransparent(\" << transparent << \")\";\n // qDebug() << \"Current windows count:\" << currentWindows.size();\n // qDebug() << \"Currently focused window:\" << currentlyFocusedWindow;\n \n windowsAreTransparent = transparent;\n \n // Apply transparency logic:\n // - If transparent=true: make all windows except focused one transparent\n // - If transparent=false: make all windows opaque\n for (MarkdownWindow *window : currentWindows) {\n if (transparent) {\n // When making transparent, only make non-focused windows transparent\n if (window != currentlyFocusedWindow) {\n // qDebug() << \"Setting unfocused window\" << window << \"transparent: true\";\n window->setTransparent(true);\n } else {\n // qDebug() << \"Keeping focused window\" << window << \"opaque\";\n window->setTransparent(false);\n }\n } else {\n // When making opaque, make all windows opaque\n // qDebug() << \"Setting window\" << window << \"transparent: false\";\n window->setTransparent(false);\n }\n }\n}\n void hideAllWindows() {\n // Stop transparency timer when hiding windows\n transparencyTimer->stop();\n currentlyFocusedWindow = nullptr;\n windowsAreTransparent = false;\n \n // Hide all current windows\n for (MarkdownWindow *window : currentWindows) {\n window->hide();\n window->setTransparent(false); // Reset transparency state\n }\n}\n void windowCreated(MarkdownWindow *window);\n void windowRemoved(MarkdownWindow *window);\n private:\n void onWindowDeleteRequested(MarkdownWindow *window) {\n removeMarkdownWindow(window);\n \n // Mark canvas as edited since we deleted a markdown window\n if (canvas) {\n canvas->setEdited(true);\n }\n \n // Save current state\n if (canvas) {\n MainWindow *mainWindow = qobject_cast(canvas->parent());\n if (mainWindow) {\n int currentPage = mainWindow->getCurrentPageForCanvas(canvas);\n saveWindowsForPage(currentPage);\n }\n }\n}\n void onWindowFocusChanged(MarkdownWindow *window, bool focused) {\n // qDebug() << \"MarkdownWindowManager::onWindowFocusChanged(\" << window << \", \" << focused << \")\";\n \n if (focused) {\n // A window gained focus - make it opaque immediately and reset timer\n // qDebug() << \"Window gained focus, setting as currently focused\";\n currentlyFocusedWindow = window;\n \n // Make the focused window opaque immediately\n window->setTransparent(false);\n \n // Reset timer to start counting down for making other windows transparent\n resetTransparencyTimer();\n } else {\n // A window lost focus\n // qDebug() << \"Window lost focus\";\n if (currentlyFocusedWindow == window) {\n // qDebug() << \"Clearing currently focused window\";\n currentlyFocusedWindow = nullptr;\n }\n \n // Check if any window still has focus\n bool anyWindowFocused = false;\n for (MarkdownWindow *w : currentWindows) {\n if (w->isEditorFocused()) {\n // qDebug() << \"Found another focused window:\" << w;\n anyWindowFocused = true;\n currentlyFocusedWindow = w;\n // Make the newly focused window opaque\n w->setTransparent(false);\n break;\n }\n }\n \n if (!anyWindowFocused) {\n // qDebug() << \"No window has focus, starting transparency timer\";\n // No window has focus, start transparency timer\n resetTransparencyTimer();\n } else {\n // qDebug() << \"Another window still has focus, resetting timer\";\n // Another window has focus, reset timer\n resetTransparencyTimer();\n }\n }\n}\n void onWindowContentChanged(MarkdownWindow *window) {\n // qDebug() << \"MarkdownWindowManager::onWindowContentChanged(\" << window << \")\";\n \n // Content changed, make this window the focused one and reset transparency timer\n currentlyFocusedWindow = window;\n window->setTransparent(false); // Make the active window opaque\n \n // Reset transparency timer\n resetTransparencyTimer();\n}\n void onTransparencyTimerTimeout() {\n // qDebug() << \"MarkdownWindowManager::onTransparencyTimerTimeout() - Timer expired!\";\n // Make all windows except the focused one semi-transparent\n setWindowsTransparent(true);\n}\n private:\n InkCanvas *canvas;\n bool selectionMode = false;\n QMap> pageWindows;\n QList currentWindows;\n QTimer *transparencyTimer;\n MarkdownWindow *currentlyFocusedWindow = nullptr;\n bool windowsAreTransparent = false;\n QString getWindowDataFilePath(int pageNumber) const {\n QString saveFolder = getSaveFolder();\n QString notebookId = getNotebookId();\n \n if (saveFolder.isEmpty() || notebookId.isEmpty()) {\n return QString();\n }\n \n return saveFolder + QString(\"/.%1_markdown_%2.json\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n}\n void saveWindowData(int pageNumber, const QList &windows) {\n QString filePath = getWindowDataFilePath(pageNumber);\n if (filePath.isEmpty()) return;\n \n QJsonArray windowsArray;\n for (MarkdownWindow *window : windows) {\n QVariantMap windowData = window->serialize();\n windowsArray.append(QJsonObject::fromVariantMap(windowData));\n }\n \n QJsonDocument doc(windowsArray);\n \n QFile file(filePath);\n if (file.open(QIODevice::WriteOnly)) {\n file.write(doc.toJson());\n file.close();\n \n #ifdef Q_OS_WIN\n // Set hidden attribute on Windows\n SetFileAttributesW(reinterpret_cast(filePath.utf16()), FILE_ATTRIBUTE_HIDDEN);\n #endif\n }\n}\n QList loadWindowData(int pageNumber) {\n QList windows;\n \n QString filePath = getWindowDataFilePath(pageNumber);\n if (filePath.isEmpty() || !QFile::exists(filePath)) {\n return windows;\n }\n \n QFile file(filePath);\n if (!file.open(QIODevice::ReadOnly)) {\n return windows;\n }\n \n QByteArray data = file.readAll();\n file.close();\n \n QJsonParseError error;\n QJsonDocument doc = QJsonDocument::fromJson(data, &error);\n if (error.error != QJsonParseError::NoError) {\n qWarning() << \"Failed to parse markdown window data:\" << error.errorString();\n return windows;\n }\n \n QJsonArray windowsArray = doc.array();\n for (const QJsonValue &value : windowsArray) {\n QJsonObject windowObj = value.toObject();\n QVariantMap windowData = windowObj.toVariantMap();\n \n // Create window with default rect (will be updated by deserialize)\n MarkdownWindow *window = new MarkdownWindow(QRect(0, 0, 300, 200), canvas);\n window->deserialize(windowData);\n \n // Connect signals\n connectWindowSignals(window);\n \n windows.append(window);\n window->show();\n }\n \n return windows;\n}\n QString getSaveFolder() const {\n return canvas ? canvas->getSaveFolder() : QString();\n}\n QString getNotebookId() const {\n if (!canvas) return QString();\n \n QString saveFolder = canvas->getSaveFolder();\n if (saveFolder.isEmpty()) return QString();\n \n QString idFile = saveFolder + \"/.notebook_id.txt\";\n if (QFile::exists(idFile)) {\n QFile file(idFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString notebookId = in.readLine().trimmed();\n file.close();\n return notebookId;\n }\n }\n \n return \"notebook\"; // Default fallback\n}\n QRect convertScreenToCanvasRect(const QRect &screenRect) const {\n if (!canvas) {\n // qDebug() << \"MarkdownWindowManager::convertScreenToCanvasRect() - No canvas, returning screen rect:\" << screenRect;\n return screenRect;\n }\n \n // Use the new coordinate conversion methods from InkCanvas\n QRect canvasRect = canvas->mapWidgetToCanvas(screenRect);\n // qDebug() << \"MarkdownWindowManager::convertScreenToCanvasRect() - Screen rect:\" << screenRect << \"-> Canvas rect:\" << canvasRect;\n // qDebug() << \" Canvas size:\" << canvas->getCanvasSize() << \"Zoom:\" << canvas->getZoomFactor() << \"Pan:\" << canvas->getPanOffset();\n return canvasRect;\n}\n void connectWindowSignals(MarkdownWindow *window) {\n // qDebug() << \"MarkdownWindowManager::connectWindowSignals() - Connecting signals for window\" << window;\n \n // Connect existing signals\n connect(window, &MarkdownWindow::deleteRequested, this, &MarkdownWindowManager::onWindowDeleteRequested);\n connect(window, &MarkdownWindow::contentChanged, this, [this, window]() {\n onWindowContentChanged(window);\n \n // Mark canvas as edited since markdown content changed\n if (canvas) {\n canvas->setEdited(true);\n \n // Get current page and save windows\n MainWindow *mainWindow = qobject_cast(canvas->parent());\n if (mainWindow) {\n int currentPage = mainWindow->getCurrentPageForCanvas(canvas);\n saveWindowsForPage(currentPage);\n }\n }\n });\n connect(window, &MarkdownWindow::windowMoved, this, [this, window](MarkdownWindow*) {\n // qDebug() << \"Window moved:\" << window;\n \n // Window was moved, make it the focused one and reset transparency timer\n currentlyFocusedWindow = window;\n window->setTransparent(false); // Make the active window opaque\n resetTransparencyTimer();\n \n // Mark canvas as edited since window was moved\n if (canvas) {\n canvas->setEdited(true);\n }\n });\n connect(window, &MarkdownWindow::windowResized, this, [this, window](MarkdownWindow*) {\n // qDebug() << \"Window resized:\" << window;\n \n // Window was resized, make it the focused one and reset transparency timer\n currentlyFocusedWindow = window;\n window->setTransparent(false); // Make the active window opaque\n resetTransparencyTimer();\n \n // Mark canvas as edited since window was resized\n if (canvas) {\n canvas->setEdited(true);\n }\n });\n \n // Connect new transparency-related signals\n connect(window, &MarkdownWindow::focusChanged, this, &MarkdownWindowManager::onWindowFocusChanged);\n connect(window, &MarkdownWindow::editorFocusChanged, this, &MarkdownWindowManager::onWindowFocusChanged);\n connect(window, &MarkdownWindow::windowInteracted, this, [this, window](MarkdownWindow*) {\n // qDebug() << \"Window interacted:\" << window;\n \n // Window was clicked/interacted with, make it the focused one and reset transparency timer\n currentlyFocusedWindow = window;\n window->setTransparent(false); // Make the active window opaque\n resetTransparencyTimer();\n });\n \n // qDebug() << \"All signals connected for window\" << window;\n}\n public:\n void updateAllWindowPositions() {\n // Update positions of all current windows\n for (MarkdownWindow *window : currentWindows) {\n if (window) {\n window->updateScreenPosition();\n }\n }\n}\n};"], ["/SpeedyNote/markdown/qmarkdowntextedit.h", "class LineNumArea {\n Q_OBJECT\n Q_PROPERTY(\n bool highlighting READ highlightingEnabled WRITE setHighlightingEnabled);\n friend class LineNumArea;\n public:\n enum AutoTextOption {\n None = 0x0000,\n\n // inserts closing characters for brackets and Markdown characters\n BracketClosing = 0x0001,\n\n // removes matching brackets and Markdown characters\n BracketRemoval = 0x0002\n };\n Q_DECLARE_FLAGS(AutoTextOptions, AutoTextOption);\n explicit QMarkdownTextEdit(QWidget *parent = nullptr,\n bool initHighlighter = true) {\n installEventFilter(this);\n viewport()->installEventFilter(this);\n _autoTextOptions = AutoTextOption::BracketClosing;\n\n _lineNumArea = new LineNumArea(this);\n updateLineNumberAreaWidth(0);\n\n // Markdown highlighting is enabled by default\n _highlightingEnabled = initHighlighter;\n if (initHighlighter) {\n _highlighter = new MarkdownHighlighter(document());\n }\n\n QFont font = this->font();\n\n // set the tab stop to the width of 4 spaces in the editor\n constexpr int tabStop = 4;\n QFontMetrics metrics(font);\n\n#if QT_VERSION < QT_VERSION_CHECK(5, 11, 0)\n setTabStopWidth(tabStop * metrics.width(' '));\n#else\n setTabStopDistance(tabStop * metrics.horizontalAdvance(QLatin1Char(' ')));\n#endif\n\n // add shortcuts for duplicating text\n // new QShortcut( QKeySequence( \"Ctrl+D\" ), this, SLOT( duplicateText() )\n // ); new QShortcut( QKeySequence( \"Ctrl+Alt+Down\" ), this, SLOT(\n // duplicateText() ) );\n\n // add a layout to the widget\n auto *layout = new QVBoxLayout(this);\n layout->setContentsMargins(0, 0, 0, 0);\n layout->addStretch();\n this->setLayout(layout);\n\n // add the hidden search widget\n _searchWidget = new QPlainTextEditSearchWidget(this);\n this->layout()->addWidget(_searchWidget);\n\n connect(this, &QPlainTextEdit::textChanged, this,\n &QMarkdownTextEdit::adjustRightMargin);\n connect(this, &QPlainTextEdit::cursorPositionChanged, this,\n &QMarkdownTextEdit::centerTheCursor);\n connect(verticalScrollBar(), &QScrollBar::valueChanged, this,\n [this](int) { _lineNumArea->update(); });\n connect(this, &QPlainTextEdit::cursorPositionChanged, this, [this]() {\n _lineNumArea->update();\n\n auto oldArea = blockBoundingGeometry(_textCursor.block())\n .translated(contentOffset());\n _textCursor = textCursor();\n auto newArea = blockBoundingGeometry(_textCursor.block())\n .translated(contentOffset());\n auto areaToUpdate = oldArea | newArea;\n viewport()->update(areaToUpdate.toRect());\n });\n connect(document(), &QTextDocument::blockCountChanged, this,\n &QMarkdownTextEdit::updateLineNumberAreaWidth);\n connect(this, &QPlainTextEdit::updateRequest, this,\n &QMarkdownTextEdit::updateLineNumberArea);\n\n updateSettings();\n\n // workaround for disabled signals up initialization\n QTimer::singleShot(300, this, &QMarkdownTextEdit::adjustRightMargin);\n}\n MarkdownHighlighter *highlighter();\n QPlainTextEditSearchWidget *searchWidget();\n void setIgnoredClickUrlSchemata(QStringList ignoredUrlSchemata) {\n _ignoredClickUrlSchemata = std::move(ignoredUrlSchemata);\n}\n virtual void openUrl(const QString &urlString) {\n qDebug() << \"QMarkdownTextEdit \" << __func__\n << \" - 'urlString': \" << urlString;\n\n QDesktopServices::openUrl(QUrl(urlString));\n}\n QString getMarkdownUrlAtPosition(const QString &text, int position) {\n QString url;\n\n // get a map of parsed Markdown urls with their link texts as key\n const QMap urlMap = parseMarkdownUrlsFromText(text);\n QMap::const_iterator i = urlMap.constBegin();\n for (; i != urlMap.constEnd(); ++i) {\n const QString &linkText = i.key();\n const QString &urlString = i.value();\n\n const int foundPositionStart = text.indexOf(linkText);\n\n if (foundPositionStart >= 0) {\n // calculate end position of found linkText\n const int foundPositionEnd = foundPositionStart + linkText.size();\n\n // check if position is in found string range\n if ((position >= foundPositionStart) &&\n (position <= foundPositionEnd)) {\n url = urlString;\n break;\n }\n }\n }\n\n return url;\n}\n void initSearchFrame(QWidget *searchFrame, bool darkMode = false) {\n _searchFrame = searchFrame;\n\n // remove the search widget from our layout\n layout()->removeWidget(_searchWidget);\n\n QLayout *layout = _searchFrame->layout();\n\n // create a grid layout for the frame and add the search widget to it\n if (layout == nullptr) {\n layout = new QVBoxLayout(_searchFrame);\n layout->setSpacing(0);\n layout->setContentsMargins(0, 0, 0, 0);\n }\n\n _searchWidget->setDarkMode(darkMode);\n layout->addWidget(_searchWidget);\n _searchFrame->setLayout(layout);\n}\n void setAutoTextOptions(AutoTextOptions options) {\n _autoTextOptions = options;\n}\n static bool isValidUrl(const QString &urlString) {\n static QRegularExpression regex(R\"(^\\w+:\\/\\/.+)\");\n const QRegularExpressionMatch match = regex.match(urlString);\n return match.hasMatch();\n}\n void resetMouseCursor() const {\n QWidget *viewPort = viewport();\n viewPort->setCursor(Qt::IBeamCursor);\n}\n void setReadOnly(bool ro) {\n QPlainTextEdit::setReadOnly(ro);\n\n // attempted to fix a problem with Chinese and Japanese input methods\n // @see https://github.com/pbek/QOwnNotes/issues/976\n setAttribute(Qt::WA_InputMethodEnabled, !isReadOnly());\n}\n void doSearch(QString &searchText,\n QPlainTextEditSearchWidget::SearchMode searchMode =\n QPlainTextEditSearchWidget::SearchMode::PlainTextMode) {\n _searchWidget->setSearchText(searchText);\n _searchWidget->setSearchMode(searchMode);\n _searchWidget->doSearchCount();\n _searchWidget->activate(false);\n}\n void hideSearchWidget(bool reset) {\n _searchWidget->deactivate();\n\n if (reset) {\n _searchWidget->reset();\n }\n}\n void updateSettings() {\n // if true: centers the screen if cursor reaches bottom (but not top)\n searchWidget()->setDebounceDelay(_debounceDelay);\n setCenterOnScroll(_centerCursor);\n}\n void setLineNumbersCurrentLineColor(QColor color) {\n _lineNumArea->setCurrentLineColor(std::move(color));\n}\n void setLineNumbersOtherLineColor(QColor color) {\n _lineNumArea->setOtherLineColor(std::move(color));\n}\n void setSearchWidgetDebounceDelay(uint debounceDelay) {\n _debounceDelay = debounceDelay;\n searchWidget()->setDebounceDelay(_debounceDelay);\n}\n void setHighlightingEnabled(bool enabled) {\n if (_highlightingEnabled == enabled || _highlighter == nullptr) {\n return;\n }\n\n _highlightingEnabled = enabled;\n _highlighter->setDocument(enabled ? document() : Q_NULLPTR);\n\n if (enabled) {\n _highlighter->rehighlight();\n }\n}\n [[nodiscard]] bool highlightingEnabled() const {\n return _highlightingEnabled && _highlighter != nullptr;\n}\n void setHighlightCurrentLine(bool set) {\n _highlightCurrentLine = set;\n}\n bool highlightCurrentLine() { return _highlightCurrentLine; }\n void setCurrentLineHighlightColor(const QColor &c) {\n _currentLineHighlightColor = color;\n}\n QColor currentLineHighlightColor() {\n return _currentLineHighlightColor;\n}\n public:\n void duplicateText() {\n if (isReadOnly()) {\n return;\n }\n\n QTextCursor cursor = this->textCursor();\n QString selectedText = cursor.selectedText();\n\n // duplicate line if no text was selected\n if (selectedText.isEmpty()) {\n const int position = cursor.position();\n\n // select the whole line\n cursor.movePosition(QTextCursor::StartOfBlock);\n cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);\n\n const int positionDiff = cursor.position() - position;\n selectedText = \"\\n\" + cursor.selectedText();\n\n // insert text with new line at end of the selected line\n cursor.setPosition(cursor.selectionEnd());\n cursor.insertText(selectedText);\n\n // set the position to same position it was in the duplicated line\n cursor.setPosition(cursor.position() - positionDiff);\n } else {\n // duplicate selected text\n cursor.setPosition(cursor.selectionEnd());\n const int selectionStart = cursor.position();\n\n // insert selected text\n cursor.insertText(selectedText);\n const int selectionEnd = cursor.position();\n\n // select the inserted text\n cursor.setPosition(selectionStart);\n cursor.setPosition(selectionEnd, QTextCursor::KeepAnchor);\n }\n\n this->setTextCursor(cursor);\n}\n void setText(const QString &text) { setPlainText(text); }\n void setPlainText(const QString &text) {\n // clear the dirty blocks vector to increase performance and prevent\n // a possible crash in QSyntaxHighlighter::rehighlightBlock\n if (_highlighter) _highlighter->clearDirtyBlocks();\n\n QPlainTextEdit::setPlainText(text);\n adjustRightMargin();\n}\n void adjustRightMargin() {\n QMargins margins = layout()->contentsMargins();\n const int rightMargin =\n document()->size().height() > viewport()->size().height() ? 24 : 0;\n margins.setRight(rightMargin);\n layout()->setContentsMargins(margins);\n}\n void hide() {\n _searchWidget->hide();\n QWidget::hide();\n}\n bool openLinkAtCursorPosition() {\n QTextCursor cursor = this->textCursor();\n const int clickedPosition = cursor.position();\n\n // select the text in the clicked block and find out on\n // which position we clicked\n cursor.movePosition(QTextCursor::StartOfBlock);\n const int positionFromStart = clickedPosition - cursor.position();\n cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);\n\n const QString selectedText = cursor.selectedText();\n\n // find out which url in the selected text was clicked\n const QString urlString =\n getMarkdownUrlAtPosition(selectedText, positionFromStart);\n const QUrl url = QUrl(urlString);\n const bool isRelativeFileUrl =\n urlString.startsWith(QLatin1String(\"file://..\"));\n const bool isLegacyAttachmentUrl =\n urlString.startsWith(QLatin1String(\"file://attachments\"));\n\n qDebug() << __func__ << \" - 'emit urlClicked( urlString )': \" << urlString;\n\n Q_EMIT urlClicked(urlString);\n\n if ((url.isValid() && isValidUrl(urlString)) || isRelativeFileUrl ||\n isLegacyAttachmentUrl) {\n // ignore some schemata\n if (!(_ignoredClickUrlSchemata.contains(url.scheme()) ||\n isRelativeFileUrl || isLegacyAttachmentUrl)) {\n // open the url\n openUrl(urlString);\n }\n\n return true;\n }\n\n return false;\n}\n bool handleBackspaceEntered() {\n if (!(_autoTextOptions & AutoTextOption::BracketRemoval) || isReadOnly()) {\n return false;\n }\n\n QTextCursor cursor = textCursor();\n\n // return if some text was selected\n if (!cursor.selectedText().isEmpty()) {\n return false;\n }\n\n int position = cursor.position();\n const int positionInBlock = cursor.positionInBlock();\n int block = cursor.block().blockNumber();\n\n if (_highlighter)\n if (_highlighter->isPosInACodeSpan(block, positionInBlock - 1))\n return false;\n\n // return if backspace was pressed at the beginning of a block\n if (positionInBlock == 0) {\n return false;\n }\n\n // get the current text from the block\n const QString text = cursor.block().text();\n\n char charToRemove{};\n\n // current char\n const char charInFront = text.at(positionInBlock - 1).toLatin1();\n\n if (charInFront == '*')\n return handleCharRemoval(MarkdownHighlighter::RangeType::Emphasis,\n block, positionInBlock - 1);\n else if (charInFront == '`')\n return handleCharRemoval(MarkdownHighlighter::RangeType::CodeSpan,\n block, positionInBlock - 1);\n\n // handle removal of \", ', and brackets\n\n // is it opener?\n int pos = _openingCharacters.indexOf(charInFront);\n // for \" and '\n bool isOpener = false;\n bool isCloser = false;\n if (pos == 5 || pos == 6) {\n isOpener = isQuotOpener(positionInBlock - 1, text);\n } else {\n isOpener = pos != -1;\n }\n if (isOpener) {\n charToRemove = _closingCharacters.at(pos);\n } else {\n // is it closer?\n pos = _closingCharacters.indexOf(charInFront);\n if (pos == 5 || pos == 6)\n isCloser = isQuotCloser(positionInBlock - 1, text);\n else\n isCloser = pos != -1;\n if (isCloser)\n charToRemove = _openingCharacters.at(pos);\n else\n return false;\n }\n\n int charToRemoveIndex = -1;\n if (isOpener) {\n bool closer = true;\n charToRemoveIndex = text.indexOf(charToRemove, positionInBlock);\n if (charToRemoveIndex == -1) return false;\n if (pos == 5 || pos == 6)\n closer = isQuotCloser(charToRemoveIndex, text);\n if (!closer) return false;\n cursor.setPosition(position + (charToRemoveIndex - positionInBlock));\n cursor.deleteChar();\n } else if (isCloser) {\n charToRemoveIndex = text.lastIndexOf(charToRemove, positionInBlock - 2);\n if (charToRemoveIndex == -1) return false;\n bool opener = true;\n if (pos == 5 || pos == 6)\n opener = isQuotOpener(charToRemoveIndex, text);\n if (!opener) return false;\n const int pos = position - (positionInBlock - charToRemoveIndex);\n cursor.setPosition(pos);\n cursor.deleteChar();\n position -= 1;\n } else {\n charToRemoveIndex = text.lastIndexOf(charToRemove, positionInBlock - 2);\n if (charToRemoveIndex == -1) return false;\n const int pos = position - (positionInBlock - charToRemoveIndex);\n cursor.setPosition(pos);\n cursor.deleteChar();\n position -= 1;\n }\n\n // moving the cursor back to the old position so the previous character\n // can be removed\n cursor.setPosition(position);\n setTextCursor(cursor);\n return false;\n}\n void centerTheCursor() {\n if (_mouseButtonDown || !_centerCursor) {\n return;\n }\n\n // Centers the cursor every time, but not on the top and bottom,\n // bottom is done by setCenterOnScroll() in updateSettings()\n centerCursor();\n\n /*\n QRect cursor = cursorRect();\n QRect vp = viewport()->rect();\n\n qDebug() << __func__ << \" - 'cursor.top': \" << cursor.top();\n qDebug() << __func__ << \" - 'cursor.bottom': \" << cursor.bottom();\n qDebug() << __func__ << \" - 'vp': \" << vp.bottom();\n\n int bottom = 0;\n int top = 0;\n\n qDebug() << __func__ << \" - 'viewportMargins().top()': \"\n << viewportMargins().top();\n\n qDebug() << __func__ << \" - 'viewportMargins().bottom()': \"\n << viewportMargins().bottom();\n\n int vpBottom = viewportMargins().top() + viewportMargins().bottom() +\n vp.bottom(); int vpCenter = vpBottom / 2; int cBottom = cursor.bottom() +\n viewportMargins().top();\n\n qDebug() << __func__ << \" - 'vpBottom': \" << vpBottom;\n qDebug() << __func__ << \" - 'vpCenter': \" << vpCenter;\n qDebug() << __func__ << \" - 'cBottom': \" << cBottom;\n\n\n if (cBottom >= vpCenter) {\n bottom = cBottom + viewportMargins().top() / 2 +\n viewportMargins().bottom() / 2 - (vp.bottom() / 2);\n // bottom = cBottom - (vp.bottom() / 2);\n // bottom *= 1.5;\n }\n\n // setStyleSheet(QString(\"QPlainTextEdit {padding-bottom:\n %1px;}\").arg(QString::number(bottom)));\n\n // if (cursor.top() < (vp.bottom() / 2)) {\n // top = (vp.bottom() / 2) - cursor.top() + viewportMargins().top() /\n 2 + viewportMargins().bottom() / 2;\n //// top *= -1;\n //// bottom *= 1.5;\n // }\n qDebug() << __func__ << \" - 'top': \" << top;\n qDebug() << __func__ << \" - 'bottom': \" << bottom;\n setViewportMargins(0,top,0, bottom);\n\n\n // QScrollBar* scrollbar = verticalScrollBar();\n //\n // qDebug() << __func__ << \" - 'scrollbar->value();': \" <<\n scrollbar->value();;\n // qDebug() << __func__ << \" - 'scrollbar->maximum();': \"\n // << scrollbar->maximum();;\n\n\n // scrollbar->setValue(scrollbar->value() - offset.y());\n //\n // setViewportMargins\n\n // setViewportMargins(0, 0, 0, bottom);\n */\n}\n void undo() {\n if (isReadOnly()) {\n return;\n }\n\n QTextCursor cursor = textCursor();\n // if no text selected, call undo\n if (!cursor.hasSelection()) {\n QPlainTextEdit::undo();\n return;\n }\n\n // if text is selected and bracket closing was used\n // we retain our selection\n if (_handleBracketClosingUsed) {\n // get the selection\n int selectionEnd = cursor.selectionEnd();\n int selectionStart = cursor.selectionStart();\n // call undo\n QPlainTextEdit::undo();\n // select again\n cursor.setPosition(selectionStart - 1);\n cursor.setPosition(selectionEnd - 1, QTextCursor::KeepAnchor);\n this->setTextCursor(cursor);\n _handleBracketClosingUsed = false;\n } else {\n // if text was selected but bracket closing wasn't used\n // do normal undo\n QPlainTextEdit::undo();\n return;\n }\n}\n void moveTextUpDown(bool up) {\n if (isReadOnly()) {\n return;\n }\n\n QTextCursor cursor = textCursor();\n QTextCursor move = cursor;\n\n move.setVisualNavigation(false);\n\n move.beginEditBlock(); // open an edit block to keep undo operations sane\n bool hasSelection = cursor.hasSelection();\n\n if (hasSelection) {\n // if there's a selection inside the block, we select the whole block\n move.setPosition(cursor.selectionStart());\n move.movePosition(QTextCursor::StartOfBlock);\n move.setPosition(cursor.selectionEnd(), QTextCursor::KeepAnchor);\n move.movePosition(\n move.atBlockStart() ? QTextCursor::Left : QTextCursor::EndOfBlock,\n QTextCursor::KeepAnchor);\n } else {\n move.movePosition(QTextCursor::StartOfBlock);\n move.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);\n }\n\n // get the text of the current block\n QString text = move.selectedText();\n\n move.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor);\n move.removeSelectedText();\n\n if (up) { // up key\n move.movePosition(QTextCursor::PreviousBlock);\n move.insertBlock();\n move.movePosition(QTextCursor::Left);\n } else { // down key\n move.movePosition(QTextCursor::EndOfBlock);\n if (move.atBlockStart()) { // empty block\n move.movePosition(QTextCursor::NextBlock);\n move.insertBlock();\n move.movePosition(QTextCursor::Left);\n } else {\n move.insertBlock();\n }\n }\n\n int start = move.position();\n move.clearSelection();\n move.insertText(text);\n int end = move.position();\n\n // reselect\n if (hasSelection) {\n move.setPosition(end);\n move.setPosition(start, QTextCursor::KeepAnchor);\n } else {\n move.setPosition(start);\n }\n\n move.endEditBlock();\n\n setTextCursor(move);\n}\n void setLineNumberEnabled(bool enabled) {\n _lineNumArea->setLineNumAreaEnabled(enabled);\n updateLineNumberAreaWidth(0);\n}\n protected:\n QTextCursor _textCursor;\n MarkdownHighlighter *_highlighter = nullptr;\n bool _highlightingEnabled;\n QStringList _ignoredClickUrlSchemata;\n QPlainTextEditSearchWidget *_searchWidget;\n QWidget *_searchFrame;\n AutoTextOptions _autoTextOptions;\n bool _mouseButtonDown = false;\n bool _centerCursor = false;\n bool _highlightCurrentLine = false;\n QColor _currentLineHighlightColor = QColor();\n uint _debounceDelay = 0;\n bool eventFilter(QObject *obj, QEvent *event) override {\n // qDebug() << event->type();\n if (event->type() == QEvent::HoverMove) {\n auto *mouseEvent = static_cast(event);\n\n QWidget *viewPort = this->viewport();\n // toggle cursor when control key has been pressed or released\n viewPort->setCursor(\n mouseEvent->modifiers().testFlag(Qt::ControlModifier)\n ? Qt::PointingHandCursor\n : Qt::IBeamCursor);\n } else if (event->type() == QEvent::KeyPress) {\n auto *keyEvent = static_cast(event);\n\n // set cursor to pointing hand if control key was pressed\n if (keyEvent->modifiers().testFlag(Qt::ControlModifier)) {\n QWidget *viewPort = this->viewport();\n viewPort->setCursor(Qt::PointingHandCursor);\n }\n\n // disallow keys if text edit hasn't focus\n if (!this->hasFocus()) {\n return true;\n }\n\n if ((keyEvent->key() == Qt::Key_Escape) && _searchWidget->isVisible()) {\n _searchWidget->deactivate();\n return true;\n } else if (keyEvent->key() == Qt::Key_Insert &&\n keyEvent->modifiers().testFlag(Qt::NoModifier)) {\n setOverwriteMode(!overwriteMode());\n\n // This solves a UI glitch if the visual cursor was not properly\n // updated when characters have different widths\n QTextCursor cursor = this->textCursor();\n cursor.movePosition(QTextCursor::Right);\n setTextCursor(cursor);\n cursor.movePosition(QTextCursor::Left);\n setTextCursor(cursor);\n\n return false;\n } else if ((keyEvent->key() == Qt::Key_Tab) ||\n (keyEvent->key() == Qt::Key_Backtab)) {\n // handle entered tab and reverse tab keys\n return handleTabEntered(keyEvent->key() == Qt::Key_Backtab);\n } else if ((keyEvent->key() == Qt::Key_F) &&\n keyEvent->modifiers().testFlag(Qt::ControlModifier)) {\n _searchWidget->activate();\n return true;\n } else if ((keyEvent->key() == Qt::Key_R) &&\n keyEvent->modifiers().testFlag(Qt::ControlModifier)) {\n _searchWidget->activateReplace();\n return true;\n // } else if (keyEvent->key() == Qt::Key_Delete) {\n } else if (keyEvent->key() == Qt::Key_Backspace) {\n return handleBackspaceEntered();\n } else if (keyEvent->key() == Qt::Key_Asterisk) {\n return handleBracketClosing(QLatin1Char('*'));\n } else if (keyEvent->key() == Qt::Key_QuoteDbl) {\n return quotationMarkCheck(QLatin1Char('\"'));\n // apostrophe bracket closing is temporary disabled because\n // apostrophes are used in different contexts\n // } else if (keyEvent->key() == Qt::Key_Apostrophe) {\n // return handleBracketClosing(\"'\");\n // underline bracket closing is temporary disabled because\n // underlines are used in different contexts\n // } else if (keyEvent->key() == Qt::Key_Underscore) {\n // return handleBracketClosing(\"_\");\n } else if (keyEvent->key() == Qt::Key_QuoteLeft) {\n return quotationMarkCheck(QLatin1Char('`'));\n } else if (keyEvent->key() == Qt::Key_AsciiTilde) {\n return handleBracketClosing(QLatin1Char('~'));\n#ifdef Q_OS_MAC\n } else if (keyEvent->modifiers().testFlag(Qt::AltModifier) &&\n keyEvent->key() == Qt::Key_ParenLeft) {\n // bracket closing for US keyboard on macOS\n return handleBracketClosing(QLatin1Char('{'), QLatin1Char('}'));\n#endif\n } else if (keyEvent->key() == Qt::Key_ParenLeft) {\n return handleBracketClosing(QLatin1Char('('), QLatin1Char(')'));\n } else if (keyEvent->key() == Qt::Key_BraceLeft) {\n return handleBracketClosing(QLatin1Char('{'), QLatin1Char('}'));\n } else if (keyEvent->key() == Qt::Key_BracketLeft) {\n return handleBracketClosing(QLatin1Char('['), QLatin1Char(']'));\n } else if (keyEvent->key() == Qt::Key_Less) {\n return handleBracketClosing(QLatin1Char('<'), QLatin1Char('>'));\n#ifdef Q_OS_MAC\n } else if (keyEvent->modifiers().testFlag(Qt::AltModifier) &&\n keyEvent->key() == Qt::Key_ParenRight) {\n // bracket closing for US keyboard on macOS\n return bracketClosingCheck(QLatin1Char('{'), QLatin1Char('}'));\n#endif\n } else if (keyEvent->key() == Qt::Key_ParenRight) {\n return bracketClosingCheck(QLatin1Char('('), QLatin1Char(')'));\n } else if (keyEvent->key() == Qt::Key_BraceRight) {\n return bracketClosingCheck(QLatin1Char('{'), QLatin1Char('}'));\n } else if (keyEvent->key() == Qt::Key_BracketRight) {\n return bracketClosingCheck(QLatin1Char('['), QLatin1Char(']'));\n } else if (keyEvent->key() == Qt::Key_Greater) {\n return bracketClosingCheck(QLatin1Char('<'), QLatin1Char('>'));\n } else if ((keyEvent->key() == Qt::Key_Return ||\n keyEvent->key() == Qt::Key_Enter) &&\n !isReadOnly() &&\n keyEvent->modifiers().testFlag(Qt::ShiftModifier)) {\n QTextCursor cursor = this->textCursor();\n cursor.insertText(\" \\n\");\n return true;\n } else if ((keyEvent->key() == Qt::Key_Return ||\n keyEvent->key() == Qt::Key_Enter) &&\n !isReadOnly() &&\n keyEvent->modifiers().testFlag(Qt::ControlModifier)) {\n QTextCursor cursor = this->textCursor();\n cursor.movePosition(QTextCursor::EndOfBlock);\n cursor.insertText(QStringLiteral(\"\\n\"));\n setTextCursor(cursor);\n return true;\n } else if (keyEvent == QKeySequence::Copy ||\n keyEvent == QKeySequence::Cut) {\n QTextCursor cursor = this->textCursor();\n if (!cursor.hasSelection()) {\n QString text;\n if (cursor.block().length() <= 1) // no content\n text = \"\\n\";\n else {\n // cursor.select(QTextCursor::BlockUnderCursor); //\n // negative, it will include the previous paragraph\n // separator\n cursor.movePosition(QTextCursor::StartOfBlock);\n cursor.movePosition(QTextCursor::EndOfBlock,\n QTextCursor::KeepAnchor);\n text = cursor.selectedText();\n if (!cursor.atEnd()) {\n text += \"\\n\";\n // this is the paragraph separator\n cursor.movePosition(QTextCursor::NextCharacter,\n QTextCursor::KeepAnchor, 1);\n }\n }\n if (keyEvent == QKeySequence::Cut) {\n if (!cursor.atEnd() && text == \"\\n\")\n cursor.deletePreviousChar();\n else\n cursor.removeSelectedText();\n cursor.movePosition(QTextCursor::StartOfBlock);\n setTextCursor(cursor);\n }\n qApp->clipboard()->setText(text);\n return true;\n }\n } else if ((keyEvent->key() == Qt::Key_Down) &&\n keyEvent->modifiers().testFlag(Qt::ControlModifier) &&\n keyEvent->modifiers().testFlag(Qt::AltModifier)) {\n // duplicate text with `Ctrl + Alt + Down`\n duplicateText();\n return true;\n#ifndef Q_OS_MAC\n } else if ((keyEvent->key() == Qt::Key_Down) &&\n keyEvent->modifiers().testFlag(Qt::ControlModifier) &&\n !keyEvent->modifiers().testFlag(Qt::ShiftModifier)) {\n // scroll the page down\n auto *scrollBar = verticalScrollBar();\n scrollBar->setSliderPosition(scrollBar->sliderPosition() + 1);\n return true;\n } else if ((keyEvent->key() == Qt::Key_Up) &&\n keyEvent->modifiers().testFlag(Qt::ControlModifier) &&\n !keyEvent->modifiers().testFlag(Qt::ShiftModifier)) {\n // scroll the page up\n auto *scrollBar = verticalScrollBar();\n scrollBar->setSliderPosition(scrollBar->sliderPosition() - 1);\n return true;\n#endif\n } else if ((keyEvent->key() == Qt::Key_Down) &&\n keyEvent->modifiers().testFlag(Qt::NoModifier)) {\n // if you are in the last line and press cursor down the cursor will\n // jump to the end of the line\n QTextCursor cursor = textCursor();\n if (cursor.position() >= document()->lastBlock().position()) {\n cursor.movePosition(QTextCursor::EndOfLine);\n\n // check if we are really in the last line, not only in\n // the last block\n if (cursor.atBlockEnd()) {\n setTextCursor(cursor);\n }\n }\n return QPlainTextEdit::eventFilter(obj, event);\n } else if ((keyEvent->key() == Qt::Key_Up) &&\n keyEvent->modifiers().testFlag(Qt::NoModifier)) {\n // if you are in the first line and press cursor up the cursor will\n // jump to the start of the line\n QTextCursor cursor = textCursor();\n QTextBlock block = document()->firstBlock();\n int endOfFirstLinePos = block.position() + block.length();\n\n if (cursor.position() <= endOfFirstLinePos) {\n cursor.movePosition(QTextCursor::StartOfLine);\n\n // check if we are really in the first line, not only in\n // the first block\n if (cursor.atBlockStart()) {\n setTextCursor(cursor);\n }\n }\n return QPlainTextEdit::eventFilter(obj, event);\n } else if (keyEvent->key() == Qt::Key_Return ||\n keyEvent->key() == Qt::Key_Enter) {\n return handleReturnEntered();\n } else if ((keyEvent->key() == Qt::Key_F3)) {\n _searchWidget->doSearch(\n !keyEvent->modifiers().testFlag(Qt::ShiftModifier));\n return true;\n } else if ((keyEvent->key() == Qt::Key_Z) &&\n (keyEvent->modifiers().testFlag(Qt::ControlModifier)) &&\n !(keyEvent->modifiers().testFlag(Qt::ShiftModifier))) {\n undo();\n return true;\n } else if ((keyEvent->key() == Qt::Key_Down) &&\n (keyEvent->modifiers().testFlag(Qt::ControlModifier)) &&\n (keyEvent->modifiers().testFlag(Qt::ShiftModifier))) {\n moveTextUpDown(false);\n return true;\n } else if ((keyEvent->key() == Qt::Key_Up) &&\n (keyEvent->modifiers().testFlag(Qt::ControlModifier)) &&\n (keyEvent->modifiers().testFlag(Qt::ShiftModifier))) {\n moveTextUpDown(true);\n return true;\n#ifdef Q_OS_MAC\n // https://github.com/pbek/QOwnNotes/issues/1593\n // https://github.com/pbek/QOwnNotes/issues/2643\n } else if (keyEvent->key() == Qt::Key_Home) {\n QTextCursor cursor = textCursor();\n // Meta is Control on macOS\n cursor.movePosition(\n keyEvent->modifiers().testFlag(Qt::MetaModifier)\n ? QTextCursor::Start\n : QTextCursor::StartOfLine,\n keyEvent->modifiers().testFlag(Qt::ShiftModifier)\n ? QTextCursor::KeepAnchor\n : QTextCursor::MoveAnchor);\n this->setTextCursor(cursor);\n return true;\n } else if (keyEvent->key() == Qt::Key_End) {\n QTextCursor cursor = textCursor();\n // Meta is Control on macOS\n cursor.movePosition(\n keyEvent->modifiers().testFlag(Qt::MetaModifier)\n ? QTextCursor::End\n : QTextCursor::EndOfLine,\n keyEvent->modifiers().testFlag(Qt::ShiftModifier)\n ? QTextCursor::KeepAnchor\n : QTextCursor::MoveAnchor);\n this->setTextCursor(cursor);\n return true;\n#endif\n }\n\n return QPlainTextEdit::eventFilter(obj, event);\n } else if (event->type() == QEvent::KeyRelease) {\n auto *keyEvent = static_cast(event);\n\n // reset cursor if control key was released\n if (keyEvent->key() == Qt::Key_Control) {\n resetMouseCursor();\n }\n\n return QPlainTextEdit::eventFilter(obj, event);\n } else if (event->type() == QEvent::MouseButtonRelease) {\n _mouseButtonDown = false;\n auto *mouseEvent = static_cast(event);\n\n // track `Ctrl + Click` in the text edit\n if ((obj == this->viewport()) &&\n (mouseEvent->button() == Qt::LeftButton) &&\n (QGuiApplication::keyboardModifiers() == Qt::ExtraButton24)) {\n // open the link (if any) at the current position\n // in the noteTextEdit\n openLinkAtCursorPosition();\n return true;\n }\n } else if (event->type() == QEvent::MouseButtonPress) {\n _mouseButtonDown = true;\n } else if (event->type() == QEvent::MouseButtonDblClick) {\n _mouseButtonDown = true;\n } else if (event->type() == QEvent::Wheel) {\n auto *wheel = dynamic_cast(event);\n\n // emit zoom signals\n if (wheel->modifiers() == Qt::ControlModifier) {\n if (wheel->angleDelta().y() > 0) {\n Q_EMIT zoomIn();\n } else {\n Q_EMIT zoomOut();\n }\n\n return true;\n }\n }\n\n return QPlainTextEdit::eventFilter(obj, event);\n}\n QMargins viewportMargins() {\n return QPlainTextEdit::viewportMargins();\n}\n bool increaseSelectedTextIndention(\n bool reverse,\n const QString &indentCharacters = QChar::fromLatin1('\\t')) {\n QTextCursor cursor = this->textCursor();\n QString selectedText = cursor.selectedText();\n\n if (!selectedText.isEmpty()) {\n // Start the selection at start of the first block of the selection\n int end = cursor.selectionEnd();\n cursor.setPosition(cursor.selectionStart());\n cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor);\n cursor.setPosition(end, QTextCursor::KeepAnchor);\n this->setTextCursor(cursor);\n selectedText = cursor.selectedText();\n\n // we need this strange newline character we are getting in the\n // selected text for newlines\n const QString newLine =\n QString::fromUtf8(QByteArray::fromHex(QByteArrayLiteral(\"e280a9\")));\n QString newText;\n\n if (reverse) {\n // un-indent text\n\n const int indentSize = indentCharacters == QStringLiteral(\"\\t\")\n ? 4\n : indentCharacters.length();\n\n // remove leading \\t or spaces in following lines\n newText = selectedText.replace(\n QRegularExpression(newLine + QStringLiteral(\"(\\\\t| {1,\") +\n QString::number(indentSize) +\n QStringLiteral(\"})\")),\n QStringLiteral(\"\\n\"));\n\n // remove leading \\t or spaces in first line\n newText.remove(QRegularExpression(QStringLiteral(\"^(\\\\t| {1,\") +\n QString::number(indentSize) +\n QStringLiteral(\"})\")));\n } else {\n // replace trailing new line to prevent an indent of the line after\n // the selection\n newText = selectedText.replace(\n QRegularExpression(QRegularExpression::escape(newLine) +\n QStringLiteral(\"$\")),\n QStringLiteral(\"\\n\"));\n\n // indent text\n newText.replace(newLine, QStringLiteral(\"\\n\") + indentCharacters)\n .prepend(indentCharacters);\n\n // remove trailing \\t\n static QRegularExpression regex1(QStringLiteral(\"\\\\t$\"));\n newText.remove(regex1);\n }\n\n // insert the new text\n cursor.insertText(newText);\n\n // update the selection to the new text\n cursor.setPosition(cursor.position() - newText.size(),\n QTextCursor::KeepAnchor);\n this->setTextCursor(cursor);\n\n return true;\n } else if (reverse) {\n const int indentSize = indentCharacters.length();\n\n // do the check as often as we have characters to un-indent\n for (int i = 1; i <= indentSize; i++) {\n // if nothing was selected but we want to reverse the indention\n // check if there is a \\t in front or after the cursor and remove it\n // if so\n const int position = cursor.position();\n\n if (!cursor.atStart()) {\n // get character in front of cursor\n cursor.setPosition(position - 1, QTextCursor::KeepAnchor);\n }\n\n // check for \\t or space in front of cursor\n static QRegularExpression regex1(QStringLiteral(\"[\\\\t ]\"));\n QRegularExpressionMatch match = regex1.match(cursor.selectedText());\n\n if (!match.hasMatch()) {\n // (select to) check for \\t or space after the cursor\n cursor.setPosition(position);\n\n if (!cursor.atEnd()) {\n cursor.setPosition(position + 1, QTextCursor::KeepAnchor);\n }\n }\n\n match = regex1.match(cursor.selectedText());\n\n if (match.hasMatch()) {\n cursor.removeSelectedText();\n }\n\n cursor = this->textCursor();\n }\n\n return true;\n }\n\n // else just insert indentCharacters\n cursor.insertText(indentCharacters);\n\n return true;\n}\n bool handleTabEntered(bool reverse, const QString &indentCharacters =\n QChar::fromLatin1('\\t')) {\n if (isReadOnly()) {\n return true;\n }\n\n QTextCursor cursor = this->textCursor();\n\n // only check for lists if we haven't a text selected\n if (cursor.selectedText().isEmpty()) {\n cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);\n const QString currentLineText = cursor.selectedText();\n\n // check if we want to indent or un-indent an ordered list\n // Valid listCharacters: '+ ', '-' , '* ', '+ [ ] ', '+ [x] ', '- [ ] ',\n // '- [x] ', '- [-] ', '* [ ] ', '* [x] '.\n static QRegularExpression regex1(\n R\"(^(\\s*)([+|\\-|\\*] \\[(x|-| )\\]|[+\\-\\*])(\\s+)$)\");\n QRegularExpressionMatchIterator i = regex1.globalMatch(currentLineText);\n\n if (i.hasNext()) {\n QRegularExpressionMatch match = i.next();\n QString whitespaces = match.captured(1);\n const QString listCharacter = match.captured(2);\n const QString whitespaceCharacter = match.captured(4);\n\n // add or remove one tabulator key\n if (reverse) {\n // remove one set of indentCharacters or a tabulator\n whitespaces.remove(QRegularExpression(\n QStringLiteral(\"^(\\\\t|\") +\n QRegularExpression::escape(indentCharacters) +\n QStringLiteral(\")\")));\n\n } else {\n whitespaces += indentCharacters;\n }\n\n cursor.insertText(whitespaces + listCharacter +\n whitespaceCharacter);\n return true;\n }\n\n // check if we want to indent or un-indent an ordered list\n static QRegularExpression regex2(R\"(^(\\s*)(\\d+)([\\.|\\)])(\\s+)$)\");\n i = regex2.globalMatch(currentLineText);\n\n if (i.hasNext()) {\n const QRegularExpressionMatch match = i.next();\n QString whitespaces = match.captured(1);\n const QString listCharacter = match.captured(2);\n const QString listMarker = match.captured(3);\n const QString whitespaceCharacter = match.captured(4);\n\n // add or remove one tabulator key\n if (reverse) {\n whitespaces.chop(1);\n } else {\n whitespaces += indentCharacters;\n }\n\n cursor.insertText(whitespaces + listCharacter + listMarker +\n whitespaceCharacter);\n return true;\n }\n }\n\n // check if we want to indent the whole text\n return increaseSelectedTextIndention(reverse, indentCharacters);\n}\n QMap parseMarkdownUrlsFromText(const QString &text) {\n QMap urlMap;\n QRegularExpressionMatchIterator iterator;\n\n // match urls like this: \n // re = QRegularExpression(\"(<(.+?:\\\\/\\\\/.+?)>)\");\n static QRegularExpression regex1(QStringLiteral(\"(<(.+?)>)\"));\n iterator = regex1.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString linkText = match.captured(1);\n QString url = match.captured(2);\n urlMap[linkText] = url;\n }\n\n // match urls like this: [this url](http://mylink)\n // QRegularExpression re(\"(\\\\[.*?\\\\]\\\\((.+?:\\\\/\\\\/.+?)\\\\))\");\n static QRegularExpression regex2(R\"((\\[.*?\\]\\((.+?)\\)))\");\n iterator = regex2.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString linkText = match.captured(1);\n QString url = match.captured(2);\n urlMap[linkText] = url;\n }\n\n // match urls like this: http://mylink\n static QRegularExpression regex3(R\"(\\b\\w+?:\\/\\/[^\\s]+[^\\s>\\)])\");\n iterator = regex3.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString url = match.captured(0);\n urlMap[url] = url;\n }\n\n // match urls like this: www.github.com\n static QRegularExpression regex4(R\"(\\bwww\\.[^\\s]+\\.[^\\s]+\\b)\");\n iterator = regex4.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString url = match.captured(0);\n urlMap[url] = QStringLiteral(\"http://\") + url;\n }\n\n // match reference urls like this: [this url][1] with this later:\n // [1]: http://domain\n static QRegularExpression regex5(R\"((\\[.*?\\]\\[(.+?)\\]))\");\n iterator = regex5.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString linkText = match.captured(1);\n QString referenceId = match.captured(2);\n\n // search for the referenced url in the whole text edit\n // QRegularExpression refRegExp(\n // \"\\\\[\" + QRegularExpression::escape(referenceId) +\n // \"\\\\]: (.+?:\\\\/\\\\/.+)\");\n QRegularExpression refRegExp(QStringLiteral(\"\\\\[\") +\n QRegularExpression::escape(referenceId) +\n QStringLiteral(\"\\\\]: (.+)\"));\n QRegularExpressionMatch urlMatch = refRegExp.match(toPlainText());\n\n if (urlMatch.hasMatch()) {\n QString url = urlMatch.captured(1);\n urlMap[linkText] = url;\n }\n }\n\n return urlMap;\n}\n bool handleReturnEntered() {\n if (isReadOnly()) {\n return true;\n }\n\n // This will be the main cursor to add or remove text\n QTextCursor cursor = this->textCursor();\n\n // We need a 2nd cursor to get the text of the current block without moving\n // the main cursor that is used to remove the selected text\n QTextCursor cursor2 = this->textCursor();\n cursor2.select(QTextCursor::BlockUnderCursor);\n const QString currentLineText = cursor2.selectedText().trimmed();\n\n const int position = cursor.position();\n const bool cursorAtBlockStart = cursor.atBlockStart();\n cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);\n const QString currentLinePartialText = cursor.selectedText();\n\n // if return is pressed and there is just an unordered list symbol then we\n // want to remove the list symbol Valid listCharacters: '+ ', '-' , '* ', '+\n // [ ] ', '+ [x] ', '- [ ] ', '- [-] ', '- [x] ', '* [ ] ', '* [x] '.\n static QRegularExpression regex1(\n R\"(^(\\s*)([+|\\-|\\*] \\[(x|-| |)\\]|[+\\-\\*])(\\s+)$)\");\n QRegularExpressionMatchIterator iterator =\n regex1.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n cursor.removeSelectedText();\n return true;\n }\n\n // if return is pressed and there is just an ordered list symbol then we\n // want to remove the list symbol\n static QRegularExpression regex2(R\"(^(\\s*)(\\d+[\\.|\\)])(\\s+)$)\");\n iterator = regex2.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n qDebug() << cursor.selectedText();\n cursor.removeSelectedText();\n return true;\n }\n\n // Check if we are in an unordered list.\n // We are in a list when we have '* ', '- ' or '+ ', possibly with preceding\n // whitespace. If e.g. user has entered '**text**' and pressed enter - we\n // don't want to do more list-stuff.\n QString currentLine = currentLinePartialText.trimmed();\n QChar char0;\n QChar char1;\n if (currentLine.length() >= 1) char0 = currentLine.at(0);\n if (currentLine.length() >= 2) char1 = currentLine.at(1);\n const bool inList =\n ((char0 == QLatin1Char('*') || char0 == QLatin1Char('-') ||\n char0 == QLatin1Char('+')) &&\n char1 == QLatin1Char(' '));\n\n if (inList) {\n // if the current line starts with a list character (possibly after\n // whitespaces) add the whitespaces at the next line too\n // Valid listCharacters: '+ ', '-' , '* ', '+ [ ] ', '+ [x] ', '- [ ] ',\n // '- [x] ', '- [-] ', '* [ ] ', '* [x] '.\n static QRegularExpression regex3(\n R\"(^(\\s*)([+|\\-|\\*] \\[(x|-| |)\\]|[+\\-\\*])(\\s+))\");\n iterator = regex3.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n const QString whitespaces = match.captured(1);\n QString listCharacter = match.captured(2);\n const QString whitespaceCharacter = match.captured(4);\n\n static QRegularExpression regex4(R\"(^([+|\\-|\\*]) \\[(x| |\\-|)\\])\");\n // start new checkbox list item with an unchecked checkbox\n iterator = regex4.globalMatch(listCharacter);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match1 = iterator.next();\n const QString realListCharacter = match1.captured(1);\n listCharacter = realListCharacter + QStringLiteral(\" [ ]\");\n }\n\n cursor.setPosition(position);\n cursor.insertText(\"\\n\" + whitespaces + listCharacter +\n whitespaceCharacter);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n }\n\n // check for ordered lists and increment the list number in the next line\n static QRegularExpression regex5(R\"(^(\\s*)(\\d+)([\\.|\\)])(\\s+))\");\n iterator = regex5.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n const QString whitespaces = match.captured(1);\n const uint listNumber = match.captured(2).toUInt();\n const QString listMarker = match.captured(3);\n const QString whitespaceCharacter = match.captured(4);\n\n cursor.setPosition(position);\n cursor.insertText(\"\\n\" + whitespaces + QString::number(listNumber + 1) +\n listMarker + whitespaceCharacter);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n\n // intent next line with same whitespaces as in current line\n static QRegularExpression regex6(R\"(^(\\s+))\");\n iterator = regex6.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n const QString whitespaces = match.captured(1);\n\n cursor.setPosition(position);\n cursor.insertText(\"\\n\" + whitespaces);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n\n // Add new list item above current line if we are at the start the line of a\n // list item\n if (cursorAtBlockStart) {\n static QRegularExpression regex7(\n R\"(^([+|\\-|\\*] \\[(x|-| |)\\]|[+\\-\\*])(\\s+))\");\n iterator = regex7.globalMatch(currentLineText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n QString listCharacter = match.captured(1);\n const QString whitespaceCharacter = match.captured(3);\n\n static QRegularExpression regex8(R\"(^([+|\\-|\\*]) \\[(x| |\\-|)\\])\");\n // start new checkbox list item with an unchecked checkbox\n iterator = regex8.globalMatch(listCharacter);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match1 = iterator.next();\n const QString realListCharacter = match1.captured(1);\n listCharacter = realListCharacter + QStringLiteral(\" [ ]\");\n }\n\n cursor.setPosition(position);\n // Enter new list item above current line\n cursor.insertText(listCharacter + whitespaceCharacter + \"\\n\");\n // Move the cursor at the end of the new list item\n cursor.movePosition(QTextCursor::Left);\n setTextCursor(cursor);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n }\n\n return false;\n}\n bool handleBracketClosing(const QChar openingCharacter,\n QChar closingCharacter = QChar()) {\n // check if bracket closing or read-only are enabled\n if (!(_autoTextOptions & AutoTextOption::BracketClosing) || isReadOnly()) {\n return false;\n }\n\n QTextCursor cursor = textCursor();\n\n if (closingCharacter.isNull()) {\n closingCharacter = openingCharacter;\n }\n\n const QString selectedText = cursor.selectedText();\n\n // When user currently has text selected, we prepend the openingCharacter\n // and append the closingCharacter. E.g. 'text' -> '(text)'. We keep the\n // current selectedText selected.\n if (!selectedText.isEmpty()) {\n // Insert. The selectedText is overwritten.\n const QString newText =\n openingCharacter + selectedText + closingCharacter;\n cursor.insertText(newText);\n\n // Re-select the selectedText.\n const int selectionEnd = cursor.position() - 1;\n const int selectionStart = selectionEnd - selectedText.length();\n\n cursor.setPosition(selectionStart);\n cursor.setPosition(selectionEnd, QTextCursor::KeepAnchor);\n this->setTextCursor(cursor);\n _handleBracketClosingUsed = true;\n return true;\n }\n\n // get the current text from the block (inserted character not included)\n // Remove whitespace at start of string (e.g. in multilevel-lists).\n static QRegularExpression regex1(\"^\\\\s+\");\n const QString text = cursor.block().text().remove(regex1);\n\n const int pib = cursor.positionInBlock();\n bool isPreviousAsterisk =\n pib > 0 && pib < text.length() && text.at(pib - 1) == '*';\n bool isNextAsterisk = pib < text.length() && text.at(pib) == '*';\n bool isMaybeBold = isPreviousAsterisk && isNextAsterisk;\n if (pib < text.length() && !isMaybeBold && !text.at(pib).isSpace()) {\n return false;\n }\n\n // Default positions to move the cursor back.\n int cursorSubtract = 1;\n // Special handling for `*` opening character, as this could be:\n // - start of a list (or sublist);\n // - start of a bold text;\n if (openingCharacter == QLatin1Char('*')) {\n // don't auto complete in code block\n bool isInCode =\n MarkdownHighlighter::isCodeBlock(cursor.block().userState());\n // we only do auto completion if there is a space before the cursor pos\n bool hasSpaceOrAsteriskBefore = !text.isEmpty() && pib > 0 &&\n (text.at(pib - 1).isSpace() ||\n text.at(pib - 1) == QLatin1Char('*'));\n // This could be the start of a list, don't autocomplete.\n bool isEmpty = text.isEmpty();\n\n if (isInCode || !hasSpaceOrAsteriskBefore || isEmpty) {\n return false;\n }\n\n // bold\n if (isPreviousAsterisk && isNextAsterisk) {\n cursorSubtract = 1;\n }\n\n // User wants: '**'.\n // Not the start of a list, probably bold text. We autocomplete with\n // extra closingCharacter and cursorSubtract to 'catchup'.\n if (text == QLatin1String(\"*\")) {\n cursor.insertText(QStringLiteral(\"*\"));\n cursorSubtract = 2;\n }\n }\n\n // Auto-completion for ``` pair\n if (openingCharacter == QLatin1Char('`')) {\n#if QT_VERSION < QT_VERSION_CHECK(5, 12, 0)\n if (QRegExp(QStringLiteral(\"[^`]*``\")).exactMatch(text)) {\n#else\n if (QRegularExpression(\n QRegularExpression::anchoredPattern(QStringLiteral(\"[^`]*``\")))\n .match(text)\n .hasMatch()) {\n#endif\n cursor.insertText(QStringLiteral(\"``\"));\n cursorSubtract = 3;\n }\n }\n\n // don't auto complete in code block\n if (openingCharacter == QLatin1Char('<') &&\n MarkdownHighlighter::isCodeBlock(cursor.block().userState())) {\n return false;\n }\n\n cursor.beginEditBlock();\n cursor.insertText(openingCharacter);\n cursor.insertText(closingCharacter);\n cursor.setPosition(cursor.position() - cursorSubtract);\n cursor.endEditBlock();\n\n setTextCursor(cursor);\n return true;\n}\n\n/**\n * Checks if the closing character should be output or not\n *\n * @param openingCharacter\n * @param closingCharacter\n * @return\n */\nbool QMarkdownTextEdit::bracketClosingCheck(const QChar openingCharacter,\n QChar closingCharacter) {\n // check if bracket closing or read-only are enabled\n if (!(_autoTextOptions & AutoTextOption::BracketClosing) || isReadOnly()) {\n return false;\n }\n\n if (closingCharacter.isNull()) {\n closingCharacter = openingCharacter;\n }\n\n QTextCursor cursor = textCursor();\n const int positionInBlock = cursor.positionInBlock();\n\n // get the current text from the block\n const QString text = cursor.block().text();\n const int textLength = text.length();\n\n // if we are at the end of the line we just want to enter the character\n if (positionInBlock >= textLength) {\n return false;\n }\n\n const QChar currentChar = text.at(positionInBlock);\n\n // if (closingCharacter == openingCharacter) {\n\n // }\n\n qDebug() << __func__ << \" - 'currentChar': \" << currentChar;\n\n // if the current character is not the closing character we just want to\n // enter the character\n if (currentChar != closingCharacter) {\n return false;\n }\n\n const QString leftText = text.left(positionInBlock);\n const int openingCharacterCount = leftText.count(openingCharacter);\n const int closingCharacterCount = leftText.count(closingCharacter);\n\n // if there were enough opening characters just enter the character\n if (openingCharacterCount < (closingCharacterCount + 1)) {\n return false;\n }\n\n // move the cursor to the right and don't enter the character\n cursor.movePosition(QTextCursor::Right);\n setTextCursor(cursor);\n return true;\n}\n\n/**\n * Checks if the closing character should be output or not or if a closing\n * character after an opening character if needed\n *\n * @param quotationCharacter\n * @return\n */\nbool QMarkdownTextEdit::quotationMarkCheck(const QChar quotationCharacter) {\n // check if bracket closing or read-only are enabled\n if (!(_autoTextOptions & AutoTextOption::BracketClosing) || isReadOnly()) {\n return false;\n }\n\n QTextCursor cursor = textCursor();\n const int positionInBlock = cursor.positionInBlock();\n\n // get the current text from the block\n const QString text = cursor.block().text();\n const int textLength = text.length();\n\n // if last char is not space, we are at word end, no autocompletion\n const bool isBacktick = quotationCharacter == '`';\n if (!isBacktick && positionInBlock != 0 &&\n !text.at(positionInBlock - 1).isSpace()) {\n return false;\n }\n\n // if we are at the end of the line we just want to enter the character\n if (positionInBlock >= textLength) {\n return handleBracketClosing(quotationCharacter);\n }\n\n const QChar currentChar = text.at(positionInBlock);\n\n // if the current character is not the quotation character we just want to\n // enter the character\n if (currentChar != quotationCharacter) {\n return handleBracketClosing(quotationCharacter);\n }\n\n // move the cursor to the right and don't enter the character\n cursor.movePosition(QTextCursor::Right);\n setTextCursor(cursor);\n return true;\n}\n\n/***********************************\n * helper methods for char removal\n * Rules for (') and (\"):\n * if [sp]\" -> opener (sp = space)\n * if \"[sp] -> closer\n ***********************************/\nbool isQuotOpener(int position, const QString &text) {\n if (position == 0) return true;\n const int prevCharPos = position - 1;\n return text.at(prevCharPos).isSpace();\n}\nbool isQuotCloser(int position, const QString &text) {\n const int nextCharPos = position + 1;\n if (nextCharPos >= text.length()) return true;\n return text.at(nextCharPos).isSpace();\n}\n\n/**\n * Handles removing of matching brackets and other Markdown characters\n * Only works with backspace to remove text\n *\n * @return\n */\nbool QMarkdownTextEdit::handleBackspaceEntered() {\n if (!(_autoTextOptions & AutoTextOption::BracketRemoval) || isReadOnly()) {\n return false;\n }\n\n QTextCursor cursor = textCursor();\n\n // return if some text was selected\n if (!cursor.selectedText().isEmpty()) {\n return false;\n }\n\n int position = cursor.position();\n const int positionInBlock = cursor.positionInBlock();\n int block = cursor.block().blockNumber();\n\n if (_highlighter)\n if (_highlighter->isPosInACodeSpan(block, positionInBlock - 1))\n return false;\n\n // return if backspace was pressed at the beginning of a block\n if (positionInBlock == 0) {\n return false;\n }\n\n // get the current text from the block\n const QString text = cursor.block().text();\n\n char charToRemove{};\n\n // current char\n const char charInFront = text.at(positionInBlock - 1).toLatin1();\n\n if (charInFront == '*')\n return handleCharRemoval(MarkdownHighlighter::RangeType::Emphasis,\n block, positionInBlock - 1);\n else if (charInFront == '`')\n return handleCharRemoval(MarkdownHighlighter::RangeType::CodeSpan,\n block, positionInBlock - 1);\n\n // handle removal of \", ', and brackets\n\n // is it opener?\n int pos = _openingCharacters.indexOf(charInFront);\n // for \" and '\n bool isOpener = false;\n bool isCloser = false;\n if (pos == 5 || pos == 6) {\n isOpener = isQuotOpener(positionInBlock - 1, text);\n } else {\n isOpener = pos != -1;\n }\n if (isOpener) {\n charToRemove = _closingCharacters.at(pos);\n } else {\n // is it closer?\n pos = _closingCharacters.indexOf(charInFront);\n if (pos == 5 || pos == 6)\n isCloser = isQuotCloser(positionInBlock - 1, text);\n else\n isCloser = pos != -1;\n if (isCloser)\n charToRemove = _openingCharacters.at(pos);\n else\n return false;\n }\n\n int charToRemoveIndex = -1;\n if (isOpener) {\n bool closer = true;\n charToRemoveIndex = text.indexOf(charToRemove, positionInBlock);\n if (charToRemoveIndex == -1) return false;\n if (pos == 5 || pos == 6)\n closer = isQuotCloser(charToRemoveIndex, text);\n if (!closer) return false;\n cursor.setPosition(position + (charToRemoveIndex - positionInBlock));\n cursor.deleteChar();\n } else if (isCloser) {\n charToRemoveIndex = text.lastIndexOf(charToRemove, positionInBlock - 2);\n if (charToRemoveIndex == -1) return false;\n bool opener = true;\n if (pos == 5 || pos == 6)\n opener = isQuotOpener(charToRemoveIndex, text);\n if (!opener) return false;\n const int pos = position - (positionInBlock - charToRemoveIndex);\n cursor.setPosition(pos);\n cursor.deleteChar();\n position -= 1;\n } else {\n charToRemoveIndex = text.lastIndexOf(charToRemove, positionInBlock - 2);\n if (charToRemoveIndex == -1) return false;\n const int pos = position - (positionInBlock - charToRemoveIndex);\n cursor.setPosition(pos);\n cursor.deleteChar();\n position -= 1;\n }\n\n // moving the cursor back to the old position so the previous character\n // can be removed\n cursor.setPosition(position);\n setTextCursor(cursor);\n return false;\n}\n\nbool QMarkdownTextEdit::handleCharRemoval(MarkdownHighlighter::RangeType type,\n int block, int position) {\n if (!_highlighter) return false;\n\n auto range = _highlighter->findPositionInRanges(type, block, position);\n if (range == QPair{-1, -1}) return false;\n\n int charToRemovePos = range.first;\n if (position == range.first) charToRemovePos = range.second;\n\n QTextCursor cursor = textCursor();\n auto gpos = cursor.position();\n\n if (charToRemovePos > position) {\n cursor.setPosition(gpos + (charToRemovePos - (position + 1)));\n } else {\n cursor.setPosition(gpos - (position - charToRemovePos + 1));\n gpos--;\n }\n\n cursor.deleteChar();\n cursor.setPosition(gpos);\n setTextCursor(cursor);\n return false;\n}\n\nvoid QMarkdownTextEdit::updateLineNumAreaGeometry() {\n const auto contentsRect = this->contentsRect();\n const QRect newGeometry = {contentsRect.left(), contentsRect.top(),\n _lineNumArea->sizeHint().width(),\n contentsRect.height()};\n auto oldGeometry = _lineNumArea->geometry();\n if (newGeometry != oldGeometry) {\n _lineNumArea->setGeometry(newGeometry);\n }\n}\n\nvoid QMarkdownTextEdit::resizeEvent(QResizeEvent *event) {\n QPlainTextEdit::resizeEvent(event);\n updateLineNumAreaGeometry();\n}\n\n/**\n * Increases (or decreases) the indention of the selected text\n * (if there is a text selected) in the noteTextEdit\n * @return\n */\nbool QMarkdownTextEdit::increaseSelectedTextIndention(\n bool reverse, const QString &indentCharacters) {\n QTextCursor cursor = this->textCursor();\n QString selectedText = cursor.selectedText();\n\n if (!selectedText.isEmpty()) {\n // Start the selection at start of the first block of the selection\n int end = cursor.selectionEnd();\n cursor.setPosition(cursor.selectionStart());\n cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor);\n cursor.setPosition(end, QTextCursor::KeepAnchor);\n this->setTextCursor(cursor);\n selectedText = cursor.selectedText();\n\n // we need this strange newline character we are getting in the\n // selected text for newlines\n const QString newLine =\n QString::fromUtf8(QByteArray::fromHex(QByteArrayLiteral(\"e280a9\")));\n QString newText;\n\n if (reverse) {\n // un-indent text\n\n const int indentSize = indentCharacters == QStringLiteral(\"\\t\")\n ? 4\n : indentCharacters.length();\n\n // remove leading \\t or spaces in following lines\n newText = selectedText.replace(\n QRegularExpression(newLine + QStringLiteral(\"(\\\\t| {1,\") +\n QString::number(indentSize) +\n QStringLiteral(\"})\")),\n QStringLiteral(\"\\n\"));\n\n // remove leading \\t or spaces in first line\n newText.remove(QRegularExpression(QStringLiteral(\"^(\\\\t| {1,\") +\n QString::number(indentSize) +\n QStringLiteral(\"})\")));\n } else {\n // replace trailing new line to prevent an indent of the line after\n // the selection\n newText = selectedText.replace(\n QRegularExpression(QRegularExpression::escape(newLine) +\n QStringLiteral(\"$\")),\n QStringLiteral(\"\\n\"));\n\n // indent text\n newText.replace(newLine, QStringLiteral(\"\\n\") + indentCharacters)\n .prepend(indentCharacters);\n\n // remove trailing \\t\n static QRegularExpression regex1(QStringLiteral(\"\\\\t$\"));\n newText.remove(regex1);\n }\n\n // insert the new text\n cursor.insertText(newText);\n\n // update the selection to the new text\n cursor.setPosition(cursor.position() - newText.size(),\n QTextCursor::KeepAnchor);\n this->setTextCursor(cursor);\n\n return true;\n } else if (reverse) {\n const int indentSize = indentCharacters.length();\n\n // do the check as often as we have characters to un-indent\n for (int i = 1; i <= indentSize; i++) {\n // if nothing was selected but we want to reverse the indention\n // check if there is a \\t in front or after the cursor and remove it\n // if so\n const int position = cursor.position();\n\n if (!cursor.atStart()) {\n // get character in front of cursor\n cursor.setPosition(position - 1, QTextCursor::KeepAnchor);\n }\n\n // check for \\t or space in front of cursor\n static QRegularExpression regex1(QStringLiteral(\"[\\\\t ]\"));\n QRegularExpressionMatch match = regex1.match(cursor.selectedText());\n\n if (!match.hasMatch()) {\n // (select to) check for \\t or space after the cursor\n cursor.setPosition(position);\n\n if (!cursor.atEnd()) {\n cursor.setPosition(position + 1, QTextCursor::KeepAnchor);\n }\n }\n\n match = regex1.match(cursor.selectedText());\n\n if (match.hasMatch()) {\n cursor.removeSelectedText();\n }\n\n cursor = this->textCursor();\n }\n\n return true;\n }\n\n // else just insert indentCharacters\n cursor.insertText(indentCharacters);\n\n return true;\n}\n\n/**\n * @brief Opens the link (if any) at the current cursor position\n */\nbool QMarkdownTextEdit::openLinkAtCursorPosition() {\n QTextCursor cursor = this->textCursor();\n const int clickedPosition = cursor.position();\n\n // select the text in the clicked block and find out on\n // which position we clicked\n cursor.movePosition(QTextCursor::StartOfBlock);\n const int positionFromStart = clickedPosition - cursor.position();\n cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);\n\n const QString selectedText = cursor.selectedText();\n\n // find out which url in the selected text was clicked\n const QString urlString =\n getMarkdownUrlAtPosition(selectedText, positionFromStart);\n const QUrl url = QUrl(urlString);\n const bool isRelativeFileUrl =\n urlString.startsWith(QLatin1String(\"file://..\"));\n const bool isLegacyAttachmentUrl =\n urlString.startsWith(QLatin1String(\"file://attachments\"));\n\n qDebug() << __func__ << \" - 'emit urlClicked( urlString )': \" << urlString;\n\n Q_EMIT urlClicked(urlString);\n\n if ((url.isValid() && isValidUrl(urlString)) || isRelativeFileUrl ||\n isLegacyAttachmentUrl) {\n // ignore some schemata\n if (!(_ignoredClickUrlSchemata.contains(url.scheme()) ||\n isRelativeFileUrl || isLegacyAttachmentUrl)) {\n // open the url\n openUrl(urlString);\n }\n\n return true;\n }\n\n return false;\n}\n\n/**\n * Checks if urlString is a valid url\n *\n * @param urlString\n * @return\n */\nbool QMarkdownTextEdit::isValidUrl(const QString &urlString) {\n static QRegularExpression regex(R\"(^\\w+:\\/\\/.+)\");\n const QRegularExpressionMatch match = regex.match(urlString);\n return match.hasMatch();\n}\n\n/**\n * Handles clicked urls\n *\n * examples:\n * - opens the webpage\n * - opens the file\n * \"/path/to/my/file/QOwnNotes.pdf\" if the operating system supports that\n * handler\n */\nvoid QMarkdownTextEdit::openUrl(const QString &urlString) {\n qDebug() << \"QMarkdownTextEdit \" << __func__\n << \" - 'urlString': \" << urlString;\n\n QDesktopServices::openUrl(QUrl(urlString));\n}\n\n/**\n * @brief Returns the highlighter instance\n * @return\n */\nMarkdownHighlighter *QMarkdownTextEdit::highlighter() { return _highlighter; }\n\n/**\n * @brief Returns the searchWidget instance\n * @return\n */\nQPlainTextEditSearchWidget *QMarkdownTextEdit::searchWidget() {\n return _searchWidget;\n}\n\n/**\n * @brief Sets url schemata that will be ignored when clicked on\n * @param urlSchemes\n */\nvoid QMarkdownTextEdit::setIgnoredClickUrlSchemata(\n QStringList ignoredUrlSchemata) {\n _ignoredClickUrlSchemata = std::move(ignoredUrlSchemata);\n}\n\n/**\n * @brief Returns a map of parsed Markdown urls with their link texts as key\n *\n * @param text\n * @return parsed urls\n */\nQMap QMarkdownTextEdit::parseMarkdownUrlsFromText(\n const QString &text) {\n QMap urlMap;\n QRegularExpressionMatchIterator iterator;\n\n // match urls like this: \n // re = QRegularExpression(\"(<(.+?:\\\\/\\\\/.+?)>)\");\n static QRegularExpression regex1(QStringLiteral(\"(<(.+?)>)\"));\n iterator = regex1.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString linkText = match.captured(1);\n QString url = match.captured(2);\n urlMap[linkText] = url;\n }\n\n // match urls like this: [this url](http://mylink)\n // QRegularExpression re(\"(\\\\[.*?\\\\]\\\\((.+?:\\\\/\\\\/.+?)\\\\))\");\n static QRegularExpression regex2(R\"((\\[.*?\\]\\((.+?)\\)))\");\n iterator = regex2.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString linkText = match.captured(1);\n QString url = match.captured(2);\n urlMap[linkText] = url;\n }\n\n // match urls like this: http://mylink\n static QRegularExpression regex3(R\"(\\b\\w+?:\\/\\/[^\\s]+[^\\s>\\)])\");\n iterator = regex3.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString url = match.captured(0);\n urlMap[url] = url;\n }\n\n // match urls like this: www.github.com\n static QRegularExpression regex4(R\"(\\bwww\\.[^\\s]+\\.[^\\s]+\\b)\");\n iterator = regex4.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString url = match.captured(0);\n urlMap[url] = QStringLiteral(\"http://\") + url;\n }\n\n // match reference urls like this: [this url][1] with this later:\n // [1]: http://domain\n static QRegularExpression regex5(R\"((\\[.*?\\]\\[(.+?)\\]))\");\n iterator = regex5.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString linkText = match.captured(1);\n QString referenceId = match.captured(2);\n\n // search for the referenced url in the whole text edit\n // QRegularExpression refRegExp(\n // \"\\\\[\" + QRegularExpression::escape(referenceId) +\n // \"\\\\]: (.+?:\\\\/\\\\/.+)\");\n QRegularExpression refRegExp(QStringLiteral(\"\\\\[\") +\n QRegularExpression::escape(referenceId) +\n QStringLiteral(\"\\\\]: (.+)\"));\n QRegularExpressionMatch urlMatch = refRegExp.match(toPlainText());\n\n if (urlMatch.hasMatch()) {\n QString url = urlMatch.captured(1);\n urlMap[linkText] = url;\n }\n }\n\n return urlMap;\n}\n\n/**\n * @brief Returns the Markdown url at position\n * @param text\n * @param position\n * @return url string\n */\nQString QMarkdownTextEdit::getMarkdownUrlAtPosition(const QString &text,\n int position) {\n QString url;\n\n // get a map of parsed Markdown urls with their link texts as key\n const QMap urlMap = parseMarkdownUrlsFromText(text);\n QMap::const_iterator i = urlMap.constBegin();\n for (; i != urlMap.constEnd(); ++i) {\n const QString &linkText = i.key();\n const QString &urlString = i.value();\n\n const int foundPositionStart = text.indexOf(linkText);\n\n if (foundPositionStart >= 0) {\n // calculate end position of found linkText\n const int foundPositionEnd = foundPositionStart + linkText.size();\n\n // check if position is in found string range\n if ((position >= foundPositionStart) &&\n (position <= foundPositionEnd)) {\n url = urlString;\n break;\n }\n }\n }\n\n return url;\n}\n\n/**\n * @brief Duplicates the text in the text edit\n */\nvoid QMarkdownTextEdit::duplicateText() {\n if (isReadOnly()) {\n return;\n }\n\n QTextCursor cursor = this->textCursor();\n QString selectedText = cursor.selectedText();\n\n // duplicate line if no text was selected\n if (selectedText.isEmpty()) {\n const int position = cursor.position();\n\n // select the whole line\n cursor.movePosition(QTextCursor::StartOfBlock);\n cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);\n\n const int positionDiff = cursor.position() - position;\n selectedText = \"\\n\" + cursor.selectedText();\n\n // insert text with new line at end of the selected line\n cursor.setPosition(cursor.selectionEnd());\n cursor.insertText(selectedText);\n\n // set the position to same position it was in the duplicated line\n cursor.setPosition(cursor.position() - positionDiff);\n } else {\n // duplicate selected text\n cursor.setPosition(cursor.selectionEnd());\n const int selectionStart = cursor.position();\n\n // insert selected text\n cursor.insertText(selectedText);\n const int selectionEnd = cursor.position();\n\n // select the inserted text\n cursor.setPosition(selectionStart);\n cursor.setPosition(selectionEnd, QTextCursor::KeepAnchor);\n }\n\n this->setTextCursor(cursor);\n}\n\nvoid QMarkdownTextEdit::setText(const QString &text) { setPlainText(text); }\n\nvoid QMarkdownTextEdit::setPlainText(const QString &text) {\n // clear the dirty blocks vector to increase performance and prevent\n // a possible crash in QSyntaxHighlighter::rehighlightBlock\n if (_highlighter) _highlighter->clearDirtyBlocks();\n\n QPlainTextEdit::setPlainText(text);\n adjustRightMargin();\n}\n\n/**\n * Uses another widget as parent for the search widget\n */\nvoid QMarkdownTextEdit::initSearchFrame(QWidget *searchFrame, bool darkMode) {\n _searchFrame = searchFrame;\n\n // remove the search widget from our layout\n layout()->removeWidget(_searchWidget);\n\n QLayout *layout = _searchFrame->layout();\n\n // create a grid layout for the frame and add the search widget to it\n if (layout == nullptr) {\n layout = new QVBoxLayout(_searchFrame);\n layout->setSpacing(0);\n layout->setContentsMargins(0, 0, 0, 0);\n }\n\n _searchWidget->setDarkMode(darkMode);\n layout->addWidget(_searchWidget);\n _searchFrame->setLayout(layout);\n}\n\n/**\n * Hides the text edit and the search widget\n */\nvoid QMarkdownTextEdit::hide() {\n _searchWidget->hide();\n QWidget::hide();\n}\n\n/**\n * Handles an entered return key\n */\nbool QMarkdownTextEdit::handleReturnEntered() {\n if (isReadOnly()) {\n return true;\n }\n\n // This will be the main cursor to add or remove text\n QTextCursor cursor = this->textCursor();\n\n // We need a 2nd cursor to get the text of the current block without moving\n // the main cursor that is used to remove the selected text\n QTextCursor cursor2 = this->textCursor();\n cursor2.select(QTextCursor::BlockUnderCursor);\n const QString currentLineText = cursor2.selectedText().trimmed();\n\n const int position = cursor.position();\n const bool cursorAtBlockStart = cursor.atBlockStart();\n cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);\n const QString currentLinePartialText = cursor.selectedText();\n\n // if return is pressed and there is just an unordered list symbol then we\n // want to remove the list symbol Valid listCharacters: '+ ', '-' , '* ', '+\n // [ ] ', '+ [x] ', '- [ ] ', '- [-] ', '- [x] ', '* [ ] ', '* [x] '.\n static QRegularExpression regex1(\n R\"(^(\\s*)([+|\\-|\\*] \\[(x|-| |)\\]|[+\\-\\*])(\\s+)$)\");\n QRegularExpressionMatchIterator iterator =\n regex1.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n cursor.removeSelectedText();\n return true;\n }\n\n // if return is pressed and there is just an ordered list symbol then we\n // want to remove the list symbol\n static QRegularExpression regex2(R\"(^(\\s*)(\\d+[\\.|\\)])(\\s+)$)\");\n iterator = regex2.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n qDebug() << cursor.selectedText();\n cursor.removeSelectedText();\n return true;\n }\n\n // Check if we are in an unordered list.\n // We are in a list when we have '* ', '- ' or '+ ', possibly with preceding\n // whitespace. If e.g. user has entered '**text**' and pressed enter - we\n // don't want to do more list-stuff.\n QString currentLine = currentLinePartialText.trimmed();\n QChar char0;\n QChar char1;\n if (currentLine.length() >= 1) char0 = currentLine.at(0);\n if (currentLine.length() >= 2) char1 = currentLine.at(1);\n const bool inList =\n ((char0 == QLatin1Char('*') || char0 == QLatin1Char('-') ||\n char0 == QLatin1Char('+')) &&\n char1 == QLatin1Char(' '));\n\n if (inList) {\n // if the current line starts with a list character (possibly after\n // whitespaces) add the whitespaces at the next line too\n // Valid listCharacters: '+ ', '-' , '* ', '+ [ ] ', '+ [x] ', '- [ ] ',\n // '- [x] ', '- [-] ', '* [ ] ', '* [x] '.\n static QRegularExpression regex3(\n R\"(^(\\s*)([+|\\-|\\*] \\[(x|-| |)\\]|[+\\-\\*])(\\s+))\");\n iterator = regex3.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n const QString whitespaces = match.captured(1);\n QString listCharacter = match.captured(2);\n const QString whitespaceCharacter = match.captured(4);\n\n static QRegularExpression regex4(R\"(^([+|\\-|\\*]) \\[(x| |\\-|)\\])\");\n // start new checkbox list item with an unchecked checkbox\n iterator = regex4.globalMatch(listCharacter);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match1 = iterator.next();\n const QString realListCharacter = match1.captured(1);\n listCharacter = realListCharacter + QStringLiteral(\" [ ]\");\n }\n\n cursor.setPosition(position);\n cursor.insertText(\"\\n\" + whitespaces + listCharacter +\n whitespaceCharacter);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n }\n\n // check for ordered lists and increment the list number in the next line\n static QRegularExpression regex5(R\"(^(\\s*)(\\d+)([\\.|\\)])(\\s+))\");\n iterator = regex5.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n const QString whitespaces = match.captured(1);\n const uint listNumber = match.captured(2).toUInt();\n const QString listMarker = match.captured(3);\n const QString whitespaceCharacter = match.captured(4);\n\n cursor.setPosition(position);\n cursor.insertText(\"\\n\" + whitespaces + QString::number(listNumber + 1) +\n listMarker + whitespaceCharacter);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n\n // intent next line with same whitespaces as in current line\n static QRegularExpression regex6(R\"(^(\\s+))\");\n iterator = regex6.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n const QString whitespaces = match.captured(1);\n\n cursor.setPosition(position);\n cursor.insertText(\"\\n\" + whitespaces);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n\n // Add new list item above current line if we are at the start the line of a\n // list item\n if (cursorAtBlockStart) {\n static QRegularExpression regex7(\n R\"(^([+|\\-|\\*] \\[(x|-| |)\\]|[+\\-\\*])(\\s+))\");\n iterator = regex7.globalMatch(currentLineText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n QString listCharacter = match.captured(1);\n const QString whitespaceCharacter = match.captured(3);\n\n static QRegularExpression regex8(R\"(^([+|\\-|\\*]) \\[(x| |\\-|)\\])\");\n // start new checkbox list item with an unchecked checkbox\n iterator = regex8.globalMatch(listCharacter);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match1 = iterator.next();\n const QString realListCharacter = match1.captured(1);\n listCharacter = realListCharacter + QStringLiteral(\" [ ]\");\n }\n\n cursor.setPosition(position);\n // Enter new list item above current line\n cursor.insertText(listCharacter + whitespaceCharacter + \"\\n\");\n // Move the cursor at the end of the new list item\n cursor.movePosition(QTextCursor::Left);\n setTextCursor(cursor);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Handles entered tab or reverse tab keys\n */\nbool QMarkdownTextEdit::handleTabEntered(bool reverse,\n const QString &indentCharacters) {\n if (isReadOnly()) {\n return true;\n }\n\n QTextCursor cursor = this->textCursor();\n\n // only check for lists if we haven't a text selected\n if (cursor.selectedText().isEmpty()) {\n cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);\n const QString currentLineText = cursor.selectedText();\n\n // check if we want to indent or un-indent an ordered list\n // Valid listCharacters: '+ ', '-' , '* ', '+ [ ] ', '+ [x] ', '- [ ] ',\n // '- [x] ', '- [-] ', '* [ ] ', '* [x] '.\n static QRegularExpression regex1(\n R\"(^(\\s*)([+|\\-|\\*] \\[(x|-| )\\]|[+\\-\\*])(\\s+)$)\");\n QRegularExpressionMatchIterator i = regex1.globalMatch(currentLineText);\n\n if (i.hasNext()) {\n QRegularExpressionMatch match = i.next();\n QString whitespaces = match.captured(1);\n const QString listCharacter = match.captured(2);\n const QString whitespaceCharacter = match.captured(4);\n\n // add or remove one tabulator key\n if (reverse) {\n // remove one set of indentCharacters or a tabulator\n whitespaces.remove(QRegularExpression(\n QStringLiteral(\"^(\\\\t|\") +\n QRegularExpression::escape(indentCharacters) +\n QStringLiteral(\")\")));\n\n } else {\n whitespaces += indentCharacters;\n }\n\n cursor.insertText(whitespaces + listCharacter +\n whitespaceCharacter);\n return true;\n }\n\n // check if we want to indent or un-indent an ordered list\n static QRegularExpression regex2(R\"(^(\\s*)(\\d+)([\\.|\\)])(\\s+)$)\");\n i = regex2.globalMatch(currentLineText);\n\n if (i.hasNext()) {\n const QRegularExpressionMatch match = i.next();\n QString whitespaces = match.captured(1);\n const QString listCharacter = match.captured(2);\n const QString listMarker = match.captured(3);\n const QString whitespaceCharacter = match.captured(4);\n\n // add or remove one tabulator key\n if (reverse) {\n whitespaces.chop(1);\n } else {\n whitespaces += indentCharacters;\n }\n\n cursor.insertText(whitespaces + listCharacter + listMarker +\n whitespaceCharacter);\n return true;\n }\n }\n\n // check if we want to indent the whole text\n return increaseSelectedTextIndention(reverse, indentCharacters);\n}\n\n/**\n * Sets the auto text options\n */\nvoid QMarkdownTextEdit::setAutoTextOptions(AutoTextOptions options) {\n _autoTextOptions = options;\n}\n\nvoid QMarkdownTextEdit::updateLineNumberArea(const QRect rect, int dy) {\n if (dy)\n _lineNumArea->scroll(0, dy);\n else\n _lineNumArea->update(0, rect.y(), _lineNumArea->sizeHint().width(),\n rect.height());\n\n updateLineNumAreaGeometry();\n\n if (rect.contains(viewport()->rect())) {\n updateLineNumberAreaWidth(0);\n }\n}\n\nvoid QMarkdownTextEdit::updateLineNumberAreaWidth(int) {\n QSignalBlocker blocker(this);\n const auto oldMargins = viewportMargins();\n const int width =\n _lineNumArea->isLineNumAreaEnabled()\n ? _lineNumArea->sizeHint().width() + _lineNumberLeftMarginOffset\n : oldMargins.left();\n const auto newMargins = QMargins{width, oldMargins.top(),\n oldMargins.right(), oldMargins.bottom()};\n\n if (newMargins != oldMargins) {\n setViewportMargins(newMargins);\n }\n\n // Grow lineNumArea font-size with the font size of the editor\n const int pointSize = this->font().pointSize();\n if (pointSize > 0) {\n QFont font = _lineNumArea->font();\n font.setPointSize(pointSize);\n _lineNumArea->setFont(font);\n }\n}\n\n/**\n * @param e\n * @details This does two things\n * 1. Overrides QPlainTextEdit::paintEvent to fix the RTL bug of QPlainTextEdit\n * 2. Paints a rectangle around code block fences [Code taken from\n * ghostwriter(which in turn is based on QPlaintextEdit::paintEvent() with\n * modifications and minor improvements for our use\n */\nvoid QMarkdownTextEdit::paintEvent(QPaintEvent *e) {\n QTextBlock block = firstVisibleBlock();\n\n QPainter painter(viewport());\n const QRect viewportRect = viewport()->rect();\n // painter.fillRect(viewportRect, Qt::transparent);\n bool firstVisible = true;\n QPointF offset(contentOffset());\n QRectF blockAreaRect; // Code or block quote rect.\n bool inBlockArea = false;\n\n bool clipTop = false;\n bool drawBlock = false;\n qreal dy = 0.0;\n bool done = false;\n\n const QColor &color = MarkdownHighlighter::codeBlockBackgroundColor();\n const int cornerRadius = 5;\n\n while (block.isValid() && !done) {\n const QRectF r = blockBoundingRect(block).translated(offset);\n const int state = block.userState();\n\n if (!inBlockArea && MarkdownHighlighter::isCodeBlock(state)) {\n // skip the backticks\n if (!block.text().startsWith(QLatin1String(\"```\")) &&\n !block.text().startsWith(QLatin1String(\"~~~\"))) {\n blockAreaRect = r;\n dy = 0.0;\n inBlockArea = true;\n }\n\n // If this is the first visible block within the viewport\n // and if the previous block is part of the text block area,\n // then the rectangle to draw for the block area will have\n // its top clipped by the viewport and will need to be\n // drawn specially.\n const int prevBlockState = block.previous().userState();\n if (firstVisible &&\n MarkdownHighlighter::isCodeBlock(prevBlockState)) {\n clipTop = true;\n }\n }\n // Else if the block ends a text block area...\n else if (inBlockArea && MarkdownHighlighter::isCodeBlockEnd(state)) {\n drawBlock = true;\n inBlockArea = false;\n blockAreaRect.setHeight(dy);\n }\n // If the block is at the end of the document and ends a text\n // block area...\n //\n if (inBlockArea && block == this->document()->lastBlock()) {\n drawBlock = true;\n inBlockArea = false;\n dy += r.height();\n blockAreaRect.setHeight(dy);\n }\n offset.ry() += r.height();\n dy += r.height();\n\n // If this is the last text block visible within the viewport...\n if (offset.y() > viewportRect.height()) {\n if (inBlockArea) {\n blockAreaRect.setHeight(dy);\n drawBlock = true;\n }\n\n // Finished drawing.\n done = true;\n }\n // If this is the last text block visible within the viewport...\n if (offset.y() > viewportRect.height()) {\n if (inBlockArea) {\n blockAreaRect.setHeight(dy);\n drawBlock = true;\n }\n // Finished drawing.\n done = true;\n }\n\n if (drawBlock) {\n painter.setCompositionMode(QPainter::CompositionMode_SourceOver);\n painter.setPen(Qt::NoPen);\n painter.setBrush(QBrush(color));\n\n // If the first visible block is \"clipped\" such that the previous\n // block is part of the text block area, then only draw a rectangle\n // with the bottom corners rounded, and with the top corners square\n // to reflect that the first visible block is part of a larger block\n // of text.\n //\n if (clipTop) {\n QPainterPath path;\n path.setFillRule(Qt::WindingFill);\n path.addRoundedRect(blockAreaRect, cornerRadius, cornerRadius);\n qreal adjustedHeight = blockAreaRect.height() / 2;\n path.addRect(blockAreaRect.adjusted(0, 0, 0, -adjustedHeight));\n painter.drawPath(path.simplified());\n clipTop = false;\n }\n // Else draw the entire rectangle with all corners rounded.\n else {\n painter.drawRoundedRect(blockAreaRect, cornerRadius,\n cornerRadius);\n }\n\n drawBlock = false;\n }\n\n // this fixes the RTL bug of QPlainTextEdit\n // https://bugreports.qt.io/browse/QTBUG-7516\n if (block.text().isRightToLeft()) {\n QTextLayout *layout = block.layout();\n // opt = document()->defaultTextOption();\n QTextOption opt = QTextOption(Qt::AlignRight);\n opt.setTextDirection(Qt::RightToLeft);\n layout->setTextOption(opt);\n }\n\n // Current line highlight\n QTextCursor cursor = textCursor();\n if (highlightCurrentLine() && cursor.block() == block) {\n QTextLine line =\n block.layout()->lineForTextPosition(cursor.positionInBlock());\n QRectF lineRect = line.rect();\n lineRect.moveTop(lineRect.top() + r.top());\n lineRect.setLeft(0.);\n lineRect.setRight(viewportRect.width());\n painter.fillRect(lineRect.toAlignedRect(),\n currentLineHighlightColor());\n }\n\n block = block.next();\n firstVisible = false;\n }\n\n painter.end();\n QPlainTextEdit::paintEvent(e);\n}\n\n/**\n * Overrides QPlainTextEdit::setReadOnly to fix a problem with Chinese and\n * Japanese input methods\n *\n * @param ro\n */\nvoid QMarkdownTextEdit::setReadOnly(bool ro) {\n QPlainTextEdit::setReadOnly(ro);\n\n // attempted to fix a problem with Chinese and Japanese input methods\n // @see https://github.com/pbek/QOwnNotes/issues/976\n setAttribute(Qt::WA_InputMethodEnabled, !isReadOnly());\n}\n\nvoid QMarkdownTextEdit::doSearch(\n QString &searchText, QPlainTextEditSearchWidget::SearchMode searchMode) {\n _searchWidget->setSearchText(searchText);\n _searchWidget->setSearchMode(searchMode);\n _searchWidget->doSearchCount();\n _searchWidget->activate(false);\n}\n\nvoid QMarkdownTextEdit::hideSearchWidget(bool reset) {\n _searchWidget->deactivate();\n\n if (reset) {\n _searchWidget->reset();\n }\n}\n\nvoid QMarkdownTextEdit::updateSettings() {\n // if true: centers the screen if cursor reaches bottom (but not top)\n searchWidget()->setDebounceDelay(_debounceDelay);\n setCenterOnScroll(_centerCursor);\n}\n\nvoid QMarkdownTextEdit::setLineNumberLeftMarginOffset(int offset) {\n _lineNumberLeftMarginOffset = offset;\n}\n\nQMargins QMarkdownTextEdit::viewportMargins() {\n return QPlainTextEdit::viewportMargins();\n}\n bool bracketClosingCheck(const QChar openingCharacter,\n QChar closingCharacter) {\n // check if bracket closing or read-only are enabled\n if (!(_autoTextOptions & AutoTextOption::BracketClosing) || isReadOnly()) {\n return false;\n }\n\n if (closingCharacter.isNull()) {\n closingCharacter = openingCharacter;\n }\n\n QTextCursor cursor = textCursor();\n const int positionInBlock = cursor.positionInBlock();\n\n // get the current text from the block\n const QString text = cursor.block().text();\n const int textLength = text.length();\n\n // if we are at the end of the line we just want to enter the character\n if (positionInBlock >= textLength) {\n return false;\n }\n\n const QChar currentChar = text.at(positionInBlock);\n\n // if (closingCharacter == openingCharacter) {\n\n // }\n\n qDebug() << __func__ << \" - 'currentChar': \" << currentChar;\n\n // if the current character is not the closing character we just want to\n // enter the character\n if (currentChar != closingCharacter) {\n return false;\n }\n\n const QString leftText = text.left(positionInBlock);\n const int openingCharacterCount = leftText.count(openingCharacter);\n const int closingCharacterCount = leftText.count(closingCharacter);\n\n // if there were enough opening characters just enter the character\n if (openingCharacterCount < (closingCharacterCount + 1)) {\n return false;\n }\n\n // move the cursor to the right and don't enter the character\n cursor.movePosition(QTextCursor::Right);\n setTextCursor(cursor);\n return true;\n}\n bool quotationMarkCheck(const QChar quotationCharacter) {\n // check if bracket closing or read-only are enabled\n if (!(_autoTextOptions & AutoTextOption::BracketClosing) || isReadOnly()) {\n return false;\n }\n\n QTextCursor cursor = textCursor();\n const int positionInBlock = cursor.positionInBlock();\n\n // get the current text from the block\n const QString text = cursor.block().text();\n const int textLength = text.length();\n\n // if last char is not space, we are at word end, no autocompletion\n const bool isBacktick = quotationCharacter == '`';\n if (!isBacktick && positionInBlock != 0 &&\n !text.at(positionInBlock - 1).isSpace()) {\n return false;\n }\n\n // if we are at the end of the line we just want to enter the character\n if (positionInBlock >= textLength) {\n return handleBracketClosing(quotationCharacter);\n }\n\n const QChar currentChar = text.at(positionInBlock);\n\n // if the current character is not the quotation character we just want to\n // enter the character\n if (currentChar != quotationCharacter) {\n return handleBracketClosing(quotationCharacter);\n }\n\n // move the cursor to the right and don't enter the character\n cursor.movePosition(QTextCursor::Right);\n setTextCursor(cursor);\n return true;\n}\n void focusOutEvent(QFocusEvent *event) override {\n resetMouseCursor();\n QPlainTextEdit::focusOutEvent(event);\n}\n void paintEvent(QPaintEvent *e) override {\n QTextBlock block = firstVisibleBlock();\n\n QPainter painter(viewport());\n const QRect viewportRect = viewport()->rect();\n // painter.fillRect(viewportRect, Qt::transparent);\n bool firstVisible = true;\n QPointF offset(contentOffset());\n QRectF blockAreaRect; // Code or block quote rect.\n bool inBlockArea = false;\n\n bool clipTop = false;\n bool drawBlock = false;\n qreal dy = 0.0;\n bool done = false;\n\n const QColor &color = MarkdownHighlighter::codeBlockBackgroundColor();\n const int cornerRadius = 5;\n\n while (block.isValid() && !done) {\n const QRectF r = blockBoundingRect(block).translated(offset);\n const int state = block.userState();\n\n if (!inBlockArea && MarkdownHighlighter::isCodeBlock(state)) {\n // skip the backticks\n if (!block.text().startsWith(QLatin1String(\"```\")) &&\n !block.text().startsWith(QLatin1String(\"~~~\"))) {\n blockAreaRect = r;\n dy = 0.0;\n inBlockArea = true;\n }\n\n // If this is the first visible block within the viewport\n // and if the previous block is part of the text block area,\n // then the rectangle to draw for the block area will have\n // its top clipped by the viewport and will need to be\n // drawn specially.\n const int prevBlockState = block.previous().userState();\n if (firstVisible &&\n MarkdownHighlighter::isCodeBlock(prevBlockState)) {\n clipTop = true;\n }\n }\n // Else if the block ends a text block area...\n else if (inBlockArea && MarkdownHighlighter::isCodeBlockEnd(state)) {\n drawBlock = true;\n inBlockArea = false;\n blockAreaRect.setHeight(dy);\n }\n // If the block is at the end of the document and ends a text\n // block area...\n //\n if (inBlockArea && block == this->document()->lastBlock()) {\n drawBlock = true;\n inBlockArea = false;\n dy += r.height();\n blockAreaRect.setHeight(dy);\n }\n offset.ry() += r.height();\n dy += r.height();\n\n // If this is the last text block visible within the viewport...\n if (offset.y() > viewportRect.height()) {\n if (inBlockArea) {\n blockAreaRect.setHeight(dy);\n drawBlock = true;\n }\n\n // Finished drawing.\n done = true;\n }\n // If this is the last text block visible within the viewport...\n if (offset.y() > viewportRect.height()) {\n if (inBlockArea) {\n blockAreaRect.setHeight(dy);\n drawBlock = true;\n }\n // Finished drawing.\n done = true;\n }\n\n if (drawBlock) {\n painter.setCompositionMode(QPainter::CompositionMode_SourceOver);\n painter.setPen(Qt::NoPen);\n painter.setBrush(QBrush(color));\n\n // If the first visible block is \"clipped\" such that the previous\n // block is part of the text block area, then only draw a rectangle\n // with the bottom corners rounded, and with the top corners square\n // to reflect that the first visible block is part of a larger block\n // of text.\n //\n if (clipTop) {\n QPainterPath path;\n path.setFillRule(Qt::WindingFill);\n path.addRoundedRect(blockAreaRect, cornerRadius, cornerRadius);\n qreal adjustedHeight = blockAreaRect.height() / 2;\n path.addRect(blockAreaRect.adjusted(0, 0, 0, -adjustedHeight));\n painter.drawPath(path.simplified());\n clipTop = false;\n }\n // Else draw the entire rectangle with all corners rounded.\n else {\n painter.drawRoundedRect(blockAreaRect, cornerRadius,\n cornerRadius);\n }\n\n drawBlock = false;\n }\n\n // this fixes the RTL bug of QPlainTextEdit\n // https://bugreports.qt.io/browse/QTBUG-7516\n if (block.text().isRightToLeft()) {\n QTextLayout *layout = block.layout();\n // opt = document()->defaultTextOption();\n QTextOption opt = QTextOption(Qt::AlignRight);\n opt.setTextDirection(Qt::RightToLeft);\n layout->setTextOption(opt);\n }\n\n // Current line highlight\n QTextCursor cursor = textCursor();\n if (highlightCurrentLine() && cursor.block() == block) {\n QTextLine line =\n block.layout()->lineForTextPosition(cursor.positionInBlock());\n QRectF lineRect = line.rect();\n lineRect.moveTop(lineRect.top() + r.top());\n lineRect.setLeft(0.);\n lineRect.setRight(viewportRect.width());\n painter.fillRect(lineRect.toAlignedRect(),\n currentLineHighlightColor());\n }\n\n block = block.next();\n firstVisible = false;\n }\n\n painter.end();\n QPlainTextEdit::paintEvent(e);\n}\n bool handleCharRemoval(MarkdownHighlighter::RangeType type, int block,\n int position) {\n if (!_highlighter) return false;\n\n auto range = _highlighter->findPositionInRanges(type, block, position);\n if (range == QPair{-1, -1}) return false;\n\n int charToRemovePos = range.first;\n if (position == range.first) charToRemovePos = range.second;\n\n QTextCursor cursor = textCursor();\n auto gpos = cursor.position();\n\n if (charToRemovePos > position) {\n cursor.setPosition(gpos + (charToRemovePos - (position + 1)));\n } else {\n cursor.setPosition(gpos - (position - charToRemovePos + 1));\n gpos--;\n }\n\n cursor.deleteChar();\n cursor.setPosition(gpos);\n setTextCursor(cursor);\n return false;\n}\n void resizeEvent(QResizeEvent *event) override {\n QPlainTextEdit::resizeEvent(event);\n updateLineNumAreaGeometry();\n}\n void setLineNumberLeftMarginOffset(int offset) {\n _lineNumberLeftMarginOffset = offset;\n}\n int _lineNumberLeftMarginOffset = 0;\n void updateLineNumAreaGeometry() {\n const auto contentsRect = this->contentsRect();\n const QRect newGeometry = {contentsRect.left(), contentsRect.top(),\n _lineNumArea->sizeHint().width(),\n contentsRect.height()};\n auto oldGeometry = _lineNumArea->geometry();\n if (newGeometry != oldGeometry) {\n _lineNumArea->setGeometry(newGeometry);\n }\n}\n void updateLineNumberArea(const QRect rect, int dy) {\n if (dy)\n _lineNumArea->scroll(0, dy);\n else\n _lineNumArea->update(0, rect.y(), _lineNumArea->sizeHint().width(),\n rect.height());\n\n updateLineNumAreaGeometry();\n\n if (rect.contains(viewport()->rect())) {\n updateLineNumberAreaWidth(0);\n }\n}\n Q_SLOT void updateLineNumberAreaWidth(int) {\n QSignalBlocker blocker(this);\n const auto oldMargins = viewportMargins();\n const int width =\n _lineNumArea->isLineNumAreaEnabled()\n ? _lineNumArea->sizeHint().width() + _lineNumberLeftMarginOffset\n : oldMargins.left();\n const auto newMargins = QMargins{width, oldMargins.top(),\n oldMargins.right(), oldMargins.bottom()};\n\n if (newMargins != oldMargins) {\n setViewportMargins(newMargins);\n }\n\n // Grow lineNumArea font-size with the font size of the editor\n const int pointSize = this->font().pointSize();\n if (pointSize > 0) {\n QFont font = _lineNumArea->font();\n font.setPointSize(pointSize);\n _lineNumArea->setFont(font);\n }\n}\n bool _handleBracketClosingUsed;\n LineNumArea *_lineNumArea;\n void urlClicked(QString url);\n void zoomIn();\n void zoomOut();\n};"], ["/SpeedyNote/source/MarkdownWindow.h", "class QMarkdownTextEdit {\n Q_OBJECT\n\npublic:\n explicit MarkdownWindow(const QRect &rect, QWidget *parent = nullptr);\n ~MarkdownWindow() = default;\n QString getMarkdownContent() const {\n return markdownEditor ? markdownEditor->toPlainText() : QString();\n}\n void setMarkdownContent(const QString &content) {\n if (markdownEditor) {\n markdownEditor->setPlainText(content);\n }\n}\n QRect getWindowRect() const {\n return geometry();\n}\n void setWindowRect(const QRect &rect) {\n setGeometry(rect);\n}\n QRect getCanvasRect() const {\n return canvasRect;\n}\n void setCanvasRect(const QRect &canvasRect) {\n canvasRect = rect;\n updateScreenPosition();\n}\n void updateScreenPosition() {\n // Prevent recursive updates\n if (isUpdatingPosition) return;\n isUpdatingPosition = true;\n \n // Debug: Log when this is called due to external changes (not during mouse movement)\n if (!dragging && !resizing) {\n // qDebug() << \"MarkdownWindow::updateScreenPosition() called for window\" << this << \"Canvas rect:\" << canvasRect;\n }\n \n // Get the canvas parent to access coordinate conversion methods\n if (QWidget *canvas = parentWidget()) {\n // Try to cast to InkCanvas to use the new coordinate methods\n if (InkCanvas *inkCanvas = qobject_cast(canvas)) {\n // Use the new coordinate conversion methods\n QRect screenRect = inkCanvas->mapCanvasToWidget(canvasRect);\n // qDebug() << \"MarkdownWindow::updateScreenPosition() - Canvas rect:\" << canvasRect << \"-> Screen rect:\" << screenRect;\n // qDebug() << \" Canvas size:\" << inkCanvas->getCanvasSize() << \"Zoom:\" << inkCanvas->getZoomFactor() << \"Pan:\" << inkCanvas->getPanOffset();\n setGeometry(screenRect);\n } else {\n // Fallback: use canvas coordinates directly\n // qDebug() << \"MarkdownWindow::updateScreenPosition() - No InkCanvas parent, using canvas rect directly:\" << canvasRect;\n setGeometry(canvasRect);\n }\n } else {\n // No parent, use canvas coordinates directly\n // qDebug() << \"MarkdownWindow::updateScreenPosition() - No parent, using canvas rect directly:\" << canvasRect;\n setGeometry(canvasRect);\n }\n \n isUpdatingPosition = false;\n}\n QVariantMap serialize() const {\n QVariantMap data;\n data[\"canvas_x\"] = canvasRect.x();\n data[\"canvas_y\"] = canvasRect.y();\n data[\"canvas_width\"] = canvasRect.width();\n data[\"canvas_height\"] = canvasRect.height();\n data[\"content\"] = getMarkdownContent();\n \n // Add canvas size information for debugging and consistency checks\n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n QSize canvasSize = inkCanvas->getCanvasSize();\n data[\"canvas_buffer_width\"] = canvasSize.width();\n data[\"canvas_buffer_height\"] = canvasSize.height();\n data[\"zoom_factor\"] = inkCanvas->getZoomFactor();\n QPointF panOffset = inkCanvas->getPanOffset();\n data[\"pan_x\"] = panOffset.x();\n data[\"pan_y\"] = panOffset.y();\n }\n \n return data;\n}\n void deserialize(const QVariantMap &data) {\n int x = data.value(\"canvas_x\", 0).toInt();\n int y = data.value(\"canvas_y\", 0).toInt();\n int width = data.value(\"canvas_width\", 300).toInt();\n int height = data.value(\"canvas_height\", 200).toInt();\n QString content = data.value(\"content\", \"# New Markdown Window\").toString();\n \n QRect loadedRect = QRect(x, y, width, height);\n // qDebug() << \"MarkdownWindow::deserialize() - Loaded canvas rect:\" << loadedRect;\n // qDebug() << \" Original canvas size:\" << data.value(\"canvas_buffer_width\", -1).toInt() << \"x\" << data.value(\"canvas_buffer_height\", -1).toInt();\n \n // Apply bounds checking to loaded coordinates\n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n QRect canvasBounds = inkCanvas->getCanvasRect();\n \n // Ensure window stays within canvas bounds\n int maxX = canvasBounds.width() - loadedRect.width();\n int maxY = canvasBounds.height() - loadedRect.height();\n \n loadedRect.setX(qMax(0, qMin(loadedRect.x(), maxX)));\n loadedRect.setY(qMax(0, qMin(loadedRect.y(), maxY)));\n \n if (loadedRect != QRect(x, y, width, height)) {\n // qDebug() << \" Bounds-corrected canvas rect:\" << loadedRect << \"Canvas bounds:\" << canvasBounds;\n }\n }\n \n canvasRect = loadedRect;\n setMarkdownContent(content);\n \n // Ensure canvas connections are set up\n ensureCanvasConnections();\n \n updateScreenPosition();\n}\n void focusEditor() {\n if (markdownEditor) {\n markdownEditor->setFocus();\n }\n}\n bool isEditorFocused() const {\n return markdownEditor && markdownEditor->hasFocus();\n}\n void setTransparent(bool transparent) {\n if (isTransparentState == transparent) return;\n \n // qDebug() << \"MarkdownWindow::setTransparent(\" << transparent << \") for window\" << this;\n isTransparentState = transparent;\n \n // Apply transparency effect by changing the background style\n if (transparent) {\n // qDebug() << \"Setting window background to semi-transparent\";\n applyTransparentStyle();\n } else {\n // qDebug() << \"Setting window background to opaque\";\n applyStyle(); // Restore normal style\n }\n}\n bool isTransparent() const {\n return isTransparentState;\n}\n bool isValidForCanvas() const {\n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n QRect canvasBounds = inkCanvas->getCanvasRect();\n \n // Check if the window is at least partially within the canvas bounds\n return canvasBounds.intersects(canvasRect);\n }\n \n // If no canvas parent, assume valid\n return true;\n}\n QString getCoordinateInfo() const {\n QString info;\n info += QString(\"Canvas Coordinates: (%1, %2) %3x%4\\n\")\n .arg(canvasRect.x()).arg(canvasRect.y())\n .arg(canvasRect.width()).arg(canvasRect.height());\n \n QRect screenRect = geometry();\n info += QString(\"Screen Coordinates: (%1, %2) %3x%4\\n\")\n .arg(screenRect.x()).arg(screenRect.y())\n .arg(screenRect.width()).arg(screenRect.height());\n \n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n QSize canvasSize = inkCanvas->getCanvasSize();\n info += QString(\"Canvas Size: %1x%2\\n\")\n .arg(canvasSize.width()).arg(canvasSize.height());\n \n info += QString(\"Zoom Factor: %1\\n\").arg(inkCanvas->getZoomFactor());\n \n QPointF panOffset = inkCanvas->getPanOffset();\n info += QString(\"Pan Offset: (%1, %2)\\n\")\n .arg(panOffset.x()).arg(panOffset.y());\n \n info += QString(\"Valid for Canvas: %1\\n\").arg(isValidForCanvas() ? \"Yes\" : \"No\");\n } else {\n info += \"No InkCanvas parent found\\n\";\n }\n \n return info;\n}\n void ensureCanvasConnections() {\n // Connect to canvas pan/zoom changes to update position\n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n // Disconnect any existing connections to avoid duplicates\n disconnect(inkCanvas, &InkCanvas::panChanged, this, &MarkdownWindow::updateScreenPosition);\n disconnect(inkCanvas, &InkCanvas::zoomChanged, this, &MarkdownWindow::updateScreenPosition);\n \n // Reconnect\n connect(inkCanvas, &InkCanvas::panChanged, this, &MarkdownWindow::updateScreenPosition);\n connect(inkCanvas, &InkCanvas::zoomChanged, this, &MarkdownWindow::updateScreenPosition);\n \n // Install event filter to handle canvas resize events (for layout changes)\n inkCanvas->installEventFilter(this);\n \n // qDebug() << \"MarkdownWindow::ensureCanvasConnections() - Connected to canvas signals for window\" << this;\n } else {\n // qDebug() << \"MarkdownWindow::ensureCanvasConnections() - No InkCanvas parent found for window\" << this;\n }\n}\n void deleteRequested(MarkdownWindow *window);\n void contentChanged();\n void windowMoved(MarkdownWindow *window);\n void windowResized(MarkdownWindow *window);\n void focusChanged(MarkdownWindow *window, bool focused);\n void editorFocusChanged(MarkdownWindow *window, bool focused);\n void windowInteracted(MarkdownWindow *window);\n protected:\n void mousePressEvent(QMouseEvent *event) override {\n if (event->button() == Qt::LeftButton) {\n // Emit signal to indicate window interaction\n emit windowInteracted(this);\n \n ResizeHandle handle = getResizeHandle(event->pos());\n \n if (handle != None) {\n // Start resizing\n resizing = true;\n isUserInteracting = true;\n currentResizeHandle = handle;\n resizeStartPosition = event->globalPosition().toPoint();\n resizeStartRect = geometry();\n } else if (event->pos().y() < 24) { // Header area\n // Start dragging\n dragging = true;\n isUserInteracting = true;\n dragStartPosition = event->globalPosition().toPoint();\n windowStartPosition = pos();\n }\n }\n \n QWidget::mousePressEvent(event);\n}\n void mouseMoveEvent(QMouseEvent *event) override {\n if (resizing) {\n QPoint delta = event->globalPosition().toPoint() - resizeStartPosition;\n QRect newRect = resizeStartRect;\n \n // Apply resize based on the stored handle\n switch (currentResizeHandle) {\n case TopLeft:\n newRect.setTopLeft(newRect.topLeft() + delta);\n break;\n case TopRight:\n newRect.setTopRight(newRect.topRight() + delta);\n break;\n case BottomLeft:\n newRect.setBottomLeft(newRect.bottomLeft() + delta);\n break;\n case BottomRight:\n newRect.setBottomRight(newRect.bottomRight() + delta);\n break;\n case Top:\n newRect.setTop(newRect.top() + delta.y());\n break;\n case Bottom:\n newRect.setBottom(newRect.bottom() + delta.y());\n break;\n case Left:\n newRect.setLeft(newRect.left() + delta.x());\n break;\n case Right:\n newRect.setRight(newRect.right() + delta.x());\n break;\n default:\n break;\n }\n \n // Enforce minimum size\n newRect.setSize(newRect.size().expandedTo(QSize(200, 150)));\n \n // Keep resized window within canvas bounds\n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n // Convert to canvas coordinates to check bounds\n QRect tempCanvasRect = inkCanvas->mapWidgetToCanvas(newRect);\n QRect canvasBounds = inkCanvas->getCanvasRect();\n \n // Apply canvas bounds constraints\n int maxCanvasX = canvasBounds.width() - tempCanvasRect.width();\n int maxCanvasY = canvasBounds.height() - tempCanvasRect.height();\n \n tempCanvasRect.setX(qMax(0, qMin(tempCanvasRect.x(), maxCanvasX)));\n tempCanvasRect.setY(qMax(0, qMin(tempCanvasRect.y(), maxCanvasY)));\n \n // Also ensure the window doesn't get resized beyond canvas bounds\n if (tempCanvasRect.right() > canvasBounds.width()) {\n tempCanvasRect.setWidth(canvasBounds.width() - tempCanvasRect.x());\n }\n if (tempCanvasRect.bottom() > canvasBounds.height()) {\n tempCanvasRect.setHeight(canvasBounds.height() - tempCanvasRect.y());\n }\n \n // Convert back to screen coordinates for the constrained geometry\n newRect = inkCanvas->mapCanvasToWidget(tempCanvasRect);\n }\n \n // Update the widget geometry directly during resizing\n setGeometry(newRect);\n \n // Convert screen coordinates back to canvas coordinates\n convertScreenToCanvasRect(newRect);\n emit windowResized(this);\n } else if (dragging) {\n QPoint delta = event->globalPosition().toPoint() - dragStartPosition;\n QPoint newPos = windowStartPosition + delta;\n \n // Keep window within canvas bounds (not just parent widget bounds)\n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n // Convert current position to canvas coordinates to check bounds\n QRect tempScreenRect(newPos, size());\n QRect tempCanvasRect = inkCanvas->mapWidgetToCanvas(tempScreenRect);\n QRect canvasBounds = inkCanvas->getCanvasRect();\n \n // Apply canvas bounds constraints\n int maxCanvasX = canvasBounds.width() - tempCanvasRect.width();\n int maxCanvasY = canvasBounds.height() - tempCanvasRect.height();\n \n tempCanvasRect.setX(qMax(0, qMin(tempCanvasRect.x(), maxCanvasX)));\n tempCanvasRect.setY(qMax(0, qMin(tempCanvasRect.y(), maxCanvasY)));\n \n // Convert back to screen coordinates for the constrained position\n QRect constrainedScreenRect = inkCanvas->mapCanvasToWidget(tempCanvasRect);\n newPos = constrainedScreenRect.topLeft();\n \n // Debug: Log when position is constrained\n if (tempCanvasRect != inkCanvas->mapWidgetToCanvas(QRect(windowStartPosition + delta, size()))) {\n // qDebug() << \"MarkdownWindow: Constraining position to canvas bounds. Canvas rect:\" << tempCanvasRect;\n }\n } else {\n // Fallback: Keep window within parent bounds\n if (parentWidget()) {\n QRect parentRect = parentWidget()->rect();\n newPos.setX(qMax(0, qMin(newPos.x(), parentRect.width() - width())));\n newPos.setY(qMax(0, qMin(newPos.y(), parentRect.height() - height())));\n }\n }\n \n // Update the widget position directly during dragging\n move(newPos);\n \n // Convert screen position back to canvas coordinates\n QRect newScreenRect(newPos, size());\n convertScreenToCanvasRect(newScreenRect);\n emit windowMoved(this);\n } else {\n // Update cursor for resize handles\n updateCursor(event->pos());\n }\n \n QWidget::mouseMoveEvent(event);\n}\n void mouseReleaseEvent(QMouseEvent *event) override {\n if (event->button() == Qt::LeftButton) {\n resizing = false;\n dragging = false;\n isUserInteracting = false;\n currentResizeHandle = None;\n }\n \n QWidget::mouseReleaseEvent(event);\n}\n void resizeEvent(QResizeEvent *event) override {\n QWidget::resizeEvent(event);\n \n // Emit windowResized if this is a user-initiated resize or if we're not updating position due to canvas changes\n if (isUserInteracting || !isUpdatingPosition) {\n emit windowResized(this);\n }\n}\n void paintEvent(QPaintEvent *event) override {\n QWidget::paintEvent(event);\n \n // Draw resize handles\n QPainter painter(this);\n painter.setRenderHint(QPainter::Antialiasing);\n \n QColor handleColor = hasFocus() ? QColor(74, 144, 226) : QColor(180, 180, 180);\n painter.setPen(QPen(handleColor, 2));\n painter.setBrush(QBrush(handleColor));\n \n // Draw corner handles\n int handleSize = 6;\n painter.drawEllipse(0, 0, handleSize, handleSize); // Top-left\n painter.drawEllipse(width() - handleSize, 0, handleSize, handleSize); // Top-right\n painter.drawEllipse(0, height() - handleSize, handleSize, handleSize); // Bottom-left\n painter.drawEllipse(width() - handleSize, height() - handleSize, handleSize, handleSize); // Bottom-right\n}\n void focusInEvent(QFocusEvent *event) override {\n // qDebug() << \"MarkdownWindow::focusInEvent() - Window\" << this << \"gained focus\";\n QWidget::focusInEvent(event);\n emit focusChanged(this, true);\n}\n void focusOutEvent(QFocusEvent *event) override {\n // qDebug() << \"MarkdownWindow::focusOutEvent() - Window\" << this << \"lost focus\";\n QWidget::focusOutEvent(event);\n emit focusChanged(this, false);\n}\n bool eventFilter(QObject *obj, QEvent *event) override {\n if (obj == markdownEditor) {\n if (event->type() == QEvent::FocusIn) {\n // qDebug() << \"MarkdownWindow::eventFilter() - Editor gained focus in window\" << this;\n emit editorFocusChanged(this, true);\n } else if (event->type() == QEvent::FocusOut) {\n // qDebug() << \"MarkdownWindow::eventFilter() - Editor lost focus in window\" << this;\n emit editorFocusChanged(this, false);\n }\n } else if (obj == parentWidget() && event->type() == QEvent::Resize) {\n // Canvas widget was resized (likely due to layout changes like showing/hiding sidebars)\n // Update our screen position to maintain canvas position\n QTimer::singleShot(0, this, [this]() {\n updateScreenPosition();\n });\n }\n return QWidget::eventFilter(obj, event);\n}\n private:\n void onDeleteClicked() {\n emit deleteRequested(this);\n}\n void onMarkdownTextChanged() {\n emit contentChanged();\n}\n private:\n enum ResizeHandle {\n None,\n TopLeft,\n TopRight,\n BottomLeft,\n BottomRight,\n Top,\n Bottom,\n Left,\n Right\n };\n QMarkdownTextEdit *markdownEditor;\n QPushButton *deleteButton;\n QLabel *titleLabel;\n QVBoxLayout *mainLayout;\n QHBoxLayout *headerLayout;\n bool dragging = false;\n QPoint dragStartPosition;\n QPoint windowStartPosition;\n bool resizing = false;\n QPoint resizeStartPosition;\n QRect resizeStartRect;\n ResizeHandle currentResizeHandle = None;\n QRect canvasRect;\n bool isTransparentState = false;\n bool isUpdatingPosition = false;\n bool isUserInteracting = false;\n ResizeHandle getResizeHandle(const QPoint &pos) const {\n const int handleSize = 8;\n const QRect rect = this->rect();\n \n // Check corner handles first\n if (QRect(0, 0, handleSize, handleSize).contains(pos))\n return TopLeft;\n if (QRect(rect.width() - handleSize, 0, handleSize, handleSize).contains(pos))\n return TopRight;\n if (QRect(0, rect.height() - handleSize, handleSize, handleSize).contains(pos))\n return BottomLeft;\n if (QRect(rect.width() - handleSize, rect.height() - handleSize, handleSize, handleSize).contains(pos))\n return BottomRight;\n \n // Check edge handles\n if (QRect(0, 0, rect.width(), handleSize).contains(pos))\n return Top;\n if (QRect(0, rect.height() - handleSize, rect.width(), handleSize).contains(pos))\n return Bottom;\n if (QRect(0, 0, handleSize, rect.height()).contains(pos))\n return Left;\n if (QRect(rect.width() - handleSize, 0, handleSize, rect.height()).contains(pos))\n return Right;\n \n return None;\n}\n void updateCursor(const QPoint &pos) {\n ResizeHandle handle = getResizeHandle(pos);\n \n switch (handle) {\n case TopLeft:\n case BottomRight:\n setCursor(Qt::SizeFDiagCursor);\n break;\n case TopRight:\n case BottomLeft:\n setCursor(Qt::SizeBDiagCursor);\n break;\n case Top:\n case Bottom:\n setCursor(Qt::SizeVerCursor);\n break;\n case Left:\n case Right:\n setCursor(Qt::SizeHorCursor);\n break;\n default:\n if (pos.y() < 24) { // Header area\n setCursor(Qt::SizeAllCursor);\n } else {\n setCursor(Qt::ArrowCursor);\n }\n break;\n }\n}\n void setupUI() {\n mainLayout = new QVBoxLayout(this);\n mainLayout->setContentsMargins(2, 2, 2, 2);\n mainLayout->setSpacing(0);\n \n // Header with title and delete button\n headerLayout = new QHBoxLayout();\n headerLayout->setContentsMargins(4, 2, 4, 2);\n headerLayout->setSpacing(4);\n \n titleLabel = new QLabel(\"Markdown\", this);\n titleLabel->setStyleSheet(\"font-weight: bold; color: #333;\");\n \n deleteButton = new QPushButton(\"×\", this);\n deleteButton->setFixedSize(16, 16);\n deleteButton->setStyleSheet(R\"(\n QPushButton {\n background-color: #ff4444;\n color: white;\n border: none;\n border-radius: 8px;\n font-weight: bold;\n font-size: 10px;\n }\n QPushButton:hover {\n background-color: #ff6666;\n }\n QPushButton:pressed {\n background-color: #cc2222;\n }\n )\");\n \n connect(deleteButton, &QPushButton::clicked, this, &MarkdownWindow::onDeleteClicked);\n \n headerLayout->addWidget(titleLabel);\n headerLayout->addStretch();\n headerLayout->addWidget(deleteButton);\n \n // Markdown editor\n markdownEditor = new QMarkdownTextEdit(this);\n markdownEditor->setPlainText(\"\"); // Start with empty content\n \n connect(markdownEditor, &QMarkdownTextEdit::textChanged, this, &MarkdownWindow::onMarkdownTextChanged);\n \n // Connect editor focus events using event filter\n markdownEditor->installEventFilter(this);\n \n mainLayout->addLayout(headerLayout);\n mainLayout->addWidget(markdownEditor);\n}\n void applyStyle() {\n // Detect dark mode using the same method as MainWindow\n bool isDarkMode = palette().color(QPalette::Window).lightness() < 128;\n \n QString backgroundColor = isDarkMode ? \"#2b2b2b\" : \"white\";\n QString borderColor = isDarkMode ? \"#555555\" : \"#cccccc\";\n QString headerBackgroundColor = isDarkMode ? \"#3c3c3c\" : \"#f0f0f0\";\n QString focusBorderColor = isDarkMode ? \"#6ca9dc\" : \"#4a90e2\";\n \n setStyleSheet(QString(R\"(\n MarkdownWindow {\n background-color: %1;\n border: 2px solid %2;\n border-radius: 4px;\n }\n MarkdownWindow:focus {\n border-color: %3;\n }\n )\").arg(backgroundColor, borderColor, focusBorderColor));\n \n // Style the header\n if (headerLayout && headerLayout->parentWidget()) {\n headerLayout->parentWidget()->setStyleSheet(QString(R\"(\n background-color: %1;\n border-bottom: 1px solid %2;\n )\").arg(headerBackgroundColor, borderColor));\n }\n \n // Reset the markdown editor style to default (opaque)\n if (markdownEditor) {\n markdownEditor->setStyleSheet(\"\"); // Clear any custom styles\n }\n}\n void applyTransparentStyle() {\n // Detect dark mode using the same method as MainWindow\n bool isDarkMode = palette().color(QPalette::Window).lightness() < 128;\n \n QString backgroundColor = isDarkMode ? \"rgba(43, 43, 43, 0.3)\" : \"rgba(255, 255, 255, 0.3)\"; // 30% opacity\n QString borderColor = isDarkMode ? \"#555555\" : \"#cccccc\";\n QString headerBackgroundColor = isDarkMode ? \"rgba(60, 60, 60, 0.3)\" : \"rgba(240, 240, 240, 0.3)\"; // 30% opacity\n QString focusBorderColor = isDarkMode ? \"#6ca9dc\" : \"#4a90e2\";\n \n setStyleSheet(QString(R\"(\n MarkdownWindow {\n background-color: %1;\n border: 2px solid %2;\n border-radius: 4px;\n }\n MarkdownWindow:focus {\n border-color: %3;\n }\n )\").arg(backgroundColor, borderColor, focusBorderColor));\n \n // Style the header with transparency\n if (headerLayout && headerLayout->parentWidget()) {\n headerLayout->parentWidget()->setStyleSheet(QString(R\"(\n background-color: %1;\n border-bottom: 1px solid %2;\n )\").arg(headerBackgroundColor, borderColor));\n }\n \n // Make the markdown editor background semi-transparent too\n if (markdownEditor) {\n QString editorBg = isDarkMode ? \"rgba(43, 43, 43, 0.3)\" : \"rgba(255, 255, 255, 0.3)\";\n markdownEditor->setStyleSheet(QString(R\"(\n QMarkdownTextEdit {\n background-color: %1;\n border: none;\n }\n )\").arg(editorBg));\n }\n}\n void convertScreenToCanvasRect(const QRect &screenRect) {\n // Get the canvas parent to access coordinate conversion methods\n if (QWidget *canvas = parentWidget()) {\n // Try to cast to InkCanvas to use the new coordinate methods\n if (InkCanvas *inkCanvas = qobject_cast(canvas)) {\n // Use the new coordinate conversion methods\n QRect oldCanvasRect = canvasRect;\n QRect newCanvasRect = inkCanvas->mapWidgetToCanvas(screenRect);\n \n // Store the converted canvas coordinates without bounds checking\n // Bounds checking should only happen during user interaction (dragging/resizing)\n canvasRect = newCanvasRect;\n // Only log if there was a significant change (and not during mouse movement)\n if ((canvasRect.topLeft() - oldCanvasRect.topLeft()).manhattanLength() > 10 && !dragging && !resizing) {\n // qDebug() << \"MarkdownWindow::convertScreenToCanvasRect() - Screen rect:\" << screenRect << \"-> Canvas rect:\" << canvasRect;\n // qDebug() << \" Old canvas rect:\" << oldCanvasRect;\n }\n } else {\n // Fallback: use screen coordinates directly\n // qDebug() << \"MarkdownWindow::convertScreenToCanvasRect() - No InkCanvas parent, using screen rect directly:\" << screenRect;\n canvasRect = screenRect;\n }\n } else {\n // No parent, use screen coordinates directly\n // qDebug() << \"MarkdownWindow::convertScreenToCanvasRect() - No parent, using screen rect directly:\" << screenRect;\n canvasRect = screenRect;\n }\n}\n};"], ["/SpeedyNote/source/ControlPanelDialog.h", "class ControlPanelDialog {\n Q_OBJECT\n\npublic:\n explicit ControlPanelDialog(MainWindow *mainWindow, InkCanvas *targetCanvas, QWidget *parent = nullptr);\n private:\n void applyChanges() {\n if (!canvas) return;\n\n BackgroundStyle style = static_cast(\n styleCombo->currentData().toInt()\n );\n\n canvas->setBackgroundStyle(style);\n canvas->setBackgroundColor(selectedColor);\n canvas->setBackgroundDensity(densitySpin->value());\n canvas->update();\n canvas->saveBackgroundMetadata();\n\n // ✅ Save these settings as defaults for new tabs\n if (mainWindowRef) {\n mainWindowRef->saveDefaultBackgroundSettings(style, selectedColor, densitySpin->value());\n }\n\n // ✅ Apply button mappings back to MainWindow with internal keys\n if (mainWindowRef) {\n for (const QString &buttonKey : holdMappingCombos.keys()) {\n QString displayString = holdMappingCombos[buttonKey]->currentText();\n QString internalKey = ButtonMappingHelper::displayToInternalKey(displayString, true); // true = isDialMode\n mainWindowRef->setHoldMapping(buttonKey, internalKey);\n }\n for (const QString &buttonKey : pressMappingCombos.keys()) {\n QString displayString = pressMappingCombos[buttonKey]->currentText();\n QString internalKey = ButtonMappingHelper::displayToInternalKey(displayString, false); // false = isAction\n mainWindowRef->setPressMapping(buttonKey, internalKey);\n }\n\n // ✅ Save to persistent settings\n mainWindowRef->saveButtonMappings();\n \n // ✅ Apply theme settings\n mainWindowRef->setUseCustomAccentColor(useCustomAccentCheckbox->isChecked());\n if (selectedAccentColor.isValid()) {\n mainWindowRef->setCustomAccentColor(selectedAccentColor);\n }\n \n // ✅ Apply color palette setting\n mainWindowRef->setUseBrighterPalette(useBrighterPaletteCheckbox->isChecked());\n }\n}\n void chooseColor() {\n QColor chosen = QColorDialog::getColor(selectedColor, this, tr(\"Select Background Color\"));\n if (chosen.isValid()) {\n selectedColor = chosen;\n colorButton->setStyleSheet(QString(\"background-color: %1\").arg(selectedColor.name()));\n }\n}\n void addKeyboardMapping() {\n // Step 1: Capture key sequence\n KeyCaptureDialog captureDialog(this);\n if (captureDialog.exec() != QDialog::Accepted) {\n return;\n }\n \n QString keySequence = captureDialog.getCapturedKeySequence();\n if (keySequence.isEmpty()) {\n return;\n }\n \n // Check if key sequence already exists\n if (mainWindowRef && mainWindowRef->getKeyboardMappings().contains(keySequence)) {\n QMessageBox::warning(this, tr(\"Key Already Mapped\"), \n tr(\"The key sequence '%1' is already mapped. Please choose a different key combination.\").arg(keySequence));\n return;\n }\n \n // Step 2: Choose action\n QStringList actions = ButtonMappingHelper::getTranslatedActions();\n bool ok;\n QString selectedAction = QInputDialog::getItem(this, tr(\"Select Action\"), \n tr(\"Choose the action to perform when '%1' is pressed:\").arg(keySequence), \n actions, 0, false, &ok);\n \n if (!ok || selectedAction.isEmpty()) {\n return;\n }\n \n // Convert display name to internal key\n QString internalKey = ButtonMappingHelper::displayToInternalKey(selectedAction, false);\n \n // Add the mapping\n if (mainWindowRef) {\n mainWindowRef->addKeyboardMapping(keySequence, internalKey);\n \n // Update table\n int row = keyboardTable->rowCount();\n keyboardTable->insertRow(row);\n keyboardTable->setItem(row, 0, new QTableWidgetItem(keySequence));\n keyboardTable->setItem(row, 1, new QTableWidgetItem(selectedAction));\n }\n}\n void removeKeyboardMapping() {\n int currentRow = keyboardTable->currentRow();\n if (currentRow < 0) {\n QMessageBox::information(this, tr(\"No Selection\"), tr(\"Please select a mapping to remove.\"));\n return;\n }\n \n QTableWidgetItem *keyItem = keyboardTable->item(currentRow, 0);\n if (!keyItem) return;\n \n QString keySequence = keyItem->text();\n \n // Confirm removal\n int ret = QMessageBox::question(this, tr(\"Remove Mapping\"), \n tr(\"Are you sure you want to remove the keyboard shortcut '%1'?\").arg(keySequence),\n QMessageBox::Yes | QMessageBox::No, QMessageBox::No);\n \n if (ret == QMessageBox::Yes) {\n // Remove from MainWindow\n if (mainWindowRef) {\n mainWindowRef->removeKeyboardMapping(keySequence);\n }\n \n // Remove from table\n keyboardTable->removeRow(currentRow);\n }\n}\n void openControllerMapping() {\n if (!mainWindowRef) {\n QMessageBox::warning(this, tr(\"Error\"), tr(\"MainWindow reference not available.\"));\n return;\n }\n \n SDLControllerManager *controllerManager = mainWindowRef->getControllerManager();\n if (!controllerManager) {\n QMessageBox::warning(this, tr(\"Controller Not Available\"), \n tr(\"Controller manager is not available. Please ensure a controller is connected and restart the application.\"));\n return;\n }\n \n if (!controllerManager->getJoystick()) {\n QMessageBox::warning(this, tr(\"No Controller Detected\"), \n tr(\"No controller is currently connected. Please connect your controller and restart the application.\"));\n return;\n }\n \n ControllerMappingDialog dialog(controllerManager, this);\n dialog.exec();\n}\n void reconnectController() {\n if (!mainWindowRef) {\n QMessageBox::warning(this, tr(\"Error\"), tr(\"MainWindow reference not available.\"));\n return;\n }\n \n SDLControllerManager *controllerManager = mainWindowRef->getControllerManager();\n if (!controllerManager) {\n QMessageBox::warning(this, tr(\"Controller Not Available\"), \n tr(\"Controller manager is not available.\"));\n return;\n }\n \n // Show reconnecting message\n controllerStatusLabel->setText(tr(\"🔄 Reconnecting...\"));\n controllerStatusLabel->setStyleSheet(\"color: orange;\");\n \n // Force the UI to update immediately\n QApplication::processEvents();\n \n // Attempt to reconnect using thread-safe method\n QMetaObject::invokeMethod(controllerManager, \"reconnect\", Qt::BlockingQueuedConnection);\n \n // Update status after reconnection attempt\n updateControllerStatus();\n \n // Show result message\n if (controllerManager->getJoystick()) {\n // Reconnect the controller signals in MainWindow\n mainWindowRef->reconnectControllerSignals();\n \n QMessageBox::information(this, tr(\"Reconnection Successful\"), \n tr(\"Controller has been successfully reconnected!\"));\n } else {\n QMessageBox::warning(this, tr(\"Reconnection Failed\"), \n tr(\"Failed to reconnect controller. Please ensure your controller is powered on and in pairing mode, then try again.\"));\n }\n}\n private:\n InkCanvas *canvas;\n QTabWidget *tabWidget;\n QWidget *backgroundTab;\n QComboBox *styleCombo;\n QPushButton *colorButton;\n QSpinBox *densitySpin;\n QPushButton *applyButton;\n QPushButton *okButton;\n QPushButton *cancelButton;\n QColor selectedColor;\n void createBackgroundTab() {\n backgroundTab = new QWidget(this);\n\n QLabel *styleLabel = new QLabel(tr(\"Background Style:\"));\n styleCombo = new QComboBox();\n styleCombo->addItem(tr(\"None\"), static_cast(BackgroundStyle::None));\n styleCombo->addItem(tr(\"Grid\"), static_cast(BackgroundStyle::Grid));\n styleCombo->addItem(tr(\"Lines\"), static_cast(BackgroundStyle::Lines));\n\n QLabel *colorLabel = new QLabel(tr(\"Background Color:\"));\n colorButton = new QPushButton();\n connect(colorButton, &QPushButton::clicked, this, &ControlPanelDialog::chooseColor);\n\n QLabel *densityLabel = new QLabel(tr(\"Density:\"));\n densitySpin = new QSpinBox();\n densitySpin->setRange(10, 200);\n densitySpin->setSuffix(\" px\");\n densitySpin->setSingleStep(5);\n\n QGridLayout *layout = new QGridLayout(backgroundTab);\n layout->addWidget(styleLabel, 0, 0);\n layout->addWidget(styleCombo, 0, 1);\n layout->addWidget(colorLabel, 1, 0);\n layout->addWidget(colorButton, 1, 1);\n layout->addWidget(densityLabel, 2, 0);\n layout->addWidget(densitySpin, 2, 1);\n // layout->setColumnStretch(1, 1); // Stretch the second column\n layout->setRowStretch(3, 1); // Stretch the last row\n}\n void loadFromCanvas() {\n styleCombo->setCurrentIndex(static_cast(canvas->getBackgroundStyle()));\n densitySpin->setValue(canvas->getBackgroundDensity());\n selectedColor = canvas->getBackgroundColor();\n\n colorButton->setStyleSheet(QString(\"background-color: %1\").arg(selectedColor.name()));\n\n if (mainWindowRef) {\n for (const QString &buttonKey : holdMappingCombos.keys()) {\n QString internalKey = mainWindowRef->getHoldMapping(buttonKey);\n QString displayString = ButtonMappingHelper::internalKeyToDisplay(internalKey, true); // true = isDialMode\n int index = holdMappingCombos[buttonKey]->findText(displayString);\n if (index >= 0) holdMappingCombos[buttonKey]->setCurrentIndex(index);\n }\n\n for (const QString &buttonKey : pressMappingCombos.keys()) {\n QString internalKey = mainWindowRef->getPressMapping(buttonKey);\n QString displayString = ButtonMappingHelper::internalKeyToDisplay(internalKey, false); // false = isAction\n int index = pressMappingCombos[buttonKey]->findText(displayString);\n if (index >= 0) pressMappingCombos[buttonKey]->setCurrentIndex(index);\n }\n \n // Load theme settings\n useCustomAccentCheckbox->setChecked(mainWindowRef->isUsingCustomAccentColor());\n \n // Get the stored custom accent color\n selectedAccentColor = mainWindowRef->getCustomAccentColor();\n \n accentColorButton->setStyleSheet(QString(\"background-color: %1\").arg(selectedAccentColor.name()));\n accentColorButton->setEnabled(useCustomAccentCheckbox->isChecked());\n \n // Load color palette setting\n useBrighterPaletteCheckbox->setChecked(mainWindowRef->isUsingBrighterPalette());\n }\n}\n MainWindow *mainWindowRef;\n InkCanvas *canvasRef;\n QWidget *performanceTab;\n QWidget *toolbarTab;\n void createToolbarTab() {\n toolbarTab = new QWidget(this);\n QVBoxLayout *toolbarLayout = new QVBoxLayout(toolbarTab);\n\n // ✅ Checkbox to show/hide benchmark controls\n QCheckBox *benchmarkVisibilityCheckbox = new QCheckBox(tr(\"Show Benchmark Controls\"), toolbarTab);\n benchmarkVisibilityCheckbox->setChecked(mainWindowRef->areBenchmarkControlsVisible());\n toolbarLayout->addWidget(benchmarkVisibilityCheckbox);\n QLabel *benchmarkNote = new QLabel(tr(\"This will show/hide the benchmark controls on the toolbar. Press the clock button to start/stop the benchmark.\"));\n benchmarkNote->setWordWrap(true);\n benchmarkNote->setStyleSheet(\"color: gray; font-size: 10px;\");\n toolbarLayout->addWidget(benchmarkNote);\n\n // ✅ Checkbox to show/hide zoom buttons\n QCheckBox *zoomButtonsVisibilityCheckbox = new QCheckBox(tr(\"Show Zoom Buttons\"), toolbarTab);\n zoomButtonsVisibilityCheckbox->setChecked(mainWindowRef->areZoomButtonsVisible());\n toolbarLayout->addWidget(zoomButtonsVisibilityCheckbox);\n QLabel *zoomButtonsNote = new QLabel(tr(\"This will show/hide the 0.5x, 1x, and 2x zoom buttons on the toolbar\"));\n zoomButtonsNote->setWordWrap(true);\n zoomButtonsNote->setStyleSheet(\"color: gray; font-size: 10px;\");\n toolbarLayout->addWidget(zoomButtonsNote);\n\n QCheckBox *scrollOnTopCheckBox = new QCheckBox(tr(\"Scroll on Top after Page Switching\"), toolbarTab);\n scrollOnTopCheckBox->setChecked(mainWindowRef->isScrollOnTopEnabled());\n toolbarLayout->addWidget(scrollOnTopCheckBox);\n QLabel *scrollNote = new QLabel(tr(\"Enabling this will make the page scroll to the top after switching to a new page.\"));\n scrollNote->setWordWrap(true);\n scrollNote->setStyleSheet(\"color: gray; font-size: 10px;\");\n toolbarLayout->addWidget(scrollNote);\n \n toolbarLayout->addStretch();\n toolbarTab->setLayout(toolbarLayout);\n tabWidget->addTab(toolbarTab, tr(\"Features\"));\n\n\n // Connect the checkbox\n connect(benchmarkVisibilityCheckbox, &QCheckBox::toggled, mainWindowRef, &MainWindow::setBenchmarkControlsVisible);\n connect(zoomButtonsVisibilityCheckbox, &QCheckBox::toggled, mainWindowRef, &MainWindow::setZoomButtonsVisible);\n connect(scrollOnTopCheckBox, &QCheckBox::toggled, mainWindowRef, &MainWindow::setScrollOnTopEnabled);\n}\n void createPerformanceTab() {\n performanceTab = new QWidget();\n QVBoxLayout *layout = new QVBoxLayout(performanceTab);\n\n QCheckBox *previewToggle = new QCheckBox(tr(\"Enable Low-Resolution PDF Previews\"));\n previewToggle->setChecked(mainWindowRef->isLowResPreviewEnabled());\n\n connect(previewToggle, &QCheckBox::toggled, mainWindowRef, &MainWindow::setLowResPreviewEnabled);\n\n QLabel *note = new QLabel(tr(\"Disabling this may improve dial smoothness on low-end devices.\"));\n note->setWordWrap(true);\n note->setStyleSheet(\"color: gray; font-size: 10px;\");\n\n QLabel *dpiLabel = new QLabel(tr(\"PDF Rendering DPI:\"));\n QComboBox *dpiSelector = new QComboBox();\n dpiSelector->addItems({\"96\", \"192\", \"288\", \"384\", \"480\"});\n dpiSelector->setCurrentText(QString::number(mainWindowRef->getPdfDPI()));\n\n connect(dpiSelector, &QComboBox::currentTextChanged, this, [=](const QString &value) {\n mainWindowRef->setPdfDPI(value.toInt());\n });\n\n QLabel *notePDF = new QLabel(tr(\"Adjust how the PDF is rendered. Higher DPI means better quality but slower performance. DO NOT CHANGE THIS OPTION WHEN MULTIPLE TABS ARE OPEN. THIS MAY LEAD TO UNDEFINED BEHAVIOR!\"));\n notePDF->setWordWrap(true);\n notePDF->setStyleSheet(\"color: gray; font-size: 10px;\");\n\n\n layout->addWidget(previewToggle);\n layout->addWidget(note);\n layout->addWidget(dpiLabel);\n layout->addWidget(dpiSelector);\n layout->addWidget(notePDF);\n\n layout->addStretch();\n\n // return performanceTab;\n}\n QWidget *controllerMappingTab;\n QPushButton *reconnectButton;\n QLabel *controllerStatusLabel;\n QMap holdMappingCombos;\n QMap pressMappingCombos;\n void createButtonMappingTab() {\n QWidget *buttonTab = new QWidget(this);\n QVBoxLayout *layout = new QVBoxLayout(buttonTab);\n\n QStringList buttonKeys = ButtonMappingHelper::getInternalButtonKeys();\n QStringList buttonDisplayNames = ButtonMappingHelper::getTranslatedButtons();\n QStringList dialModes = ButtonMappingHelper::getTranslatedDialModes();\n QStringList actions = ButtonMappingHelper::getTranslatedActions();\n\n for (int i = 0; i < buttonKeys.size(); ++i) {\n const QString &buttonKey = buttonKeys[i];\n const QString &buttonDisplayName = buttonDisplayNames[i];\n \n QHBoxLayout *h = new QHBoxLayout();\n h->addWidget(new QLabel(buttonDisplayName)); // Use translated button name\n\n QComboBox *holdCombo = new QComboBox();\n holdCombo->addItems(dialModes); // Add translated dial mode names\n holdMappingCombos[buttonKey] = holdCombo;\n h->addWidget(new QLabel(tr(\"Hold:\")));\n h->addWidget(holdCombo);\n\n QComboBox *pressCombo = new QComboBox();\n pressCombo->addItems(actions); // Add translated action names\n pressMappingCombos[buttonKey] = pressCombo;\n h->addWidget(new QLabel(tr(\"Press:\")));\n h->addWidget(pressCombo);\n\n layout->addLayout(h);\n }\n\n layout->addStretch();\n buttonTab->setLayout(layout);\n tabWidget->addTab(buttonTab, tr(\"Button Mapping\"));\n}\n void createControllerMappingTab() {\n controllerMappingTab = new QWidget(this);\n QVBoxLayout *layout = new QVBoxLayout(controllerMappingTab);\n \n // Instructions\n QLabel *instructionLabel = new QLabel(tr(\"Configure physical controller button mappings for your Joy-Con or other controller:\"), controllerMappingTab);\n instructionLabel->setWordWrap(true);\n layout->addWidget(instructionLabel);\n \n QLabel *noteLabel = new QLabel(tr(\"Note: This maps your physical controller buttons to the logical Joy-Con functions used by the application. \"\n \"After setting up the physical mapping, you can configure what actions each logical button performs in the 'Button Mapping' tab.\"), controllerMappingTab);\n noteLabel->setWordWrap(true);\n noteLabel->setStyleSheet(\"color: gray; font-size: 10px; margin-bottom: 10px;\");\n layout->addWidget(noteLabel);\n \n // Button to open controller mapping dialog\n QPushButton *openMappingButton = new QPushButton(tr(\"Configure Controller Mapping\"), controllerMappingTab);\n openMappingButton->setMinimumHeight(40);\n connect(openMappingButton, &QPushButton::clicked, this, &ControlPanelDialog::openControllerMapping);\n layout->addWidget(openMappingButton);\n \n // Button to reconnect controller\n reconnectButton = new QPushButton(tr(\"Reconnect Controller\"), controllerMappingTab);\n reconnectButton->setMinimumHeight(40);\n reconnectButton->setStyleSheet(\"QPushButton { background-color: #4CAF50; color: white; font-weight: bold; }\");\n connect(reconnectButton, &QPushButton::clicked, this, &ControlPanelDialog::reconnectController);\n layout->addWidget(reconnectButton);\n \n // Status information\n QLabel *statusLabel = new QLabel(tr(\"Current controller status:\"), controllerMappingTab);\n statusLabel->setStyleSheet(\"font-weight: bold; margin-top: 20px;\");\n layout->addWidget(statusLabel);\n \n // Dynamic status label\n controllerStatusLabel = new QLabel(controllerMappingTab);\n updateControllerStatus();\n layout->addWidget(controllerStatusLabel);\n \n layout->addStretch();\n \n tabWidget->addTab(controllerMappingTab, tr(\"Controller Mapping\"));\n}\n void createKeyboardMappingTab() {\n keyboardTab = new QWidget(this);\n QVBoxLayout *layout = new QVBoxLayout(keyboardTab);\n \n // Instructions\n QLabel *instructionLabel = new QLabel(tr(\"Configure custom keyboard shortcuts for application actions:\"), keyboardTab);\n instructionLabel->setWordWrap(true);\n layout->addWidget(instructionLabel);\n \n // Table to show current mappings\n keyboardTable = new QTableWidget(0, 2, keyboardTab);\n keyboardTable->setHorizontalHeaderLabels({tr(\"Key Sequence\"), tr(\"Action\")});\n keyboardTable->horizontalHeader()->setStretchLastSection(true);\n keyboardTable->setSelectionBehavior(QAbstractItemView::SelectRows);\n keyboardTable->setEditTriggers(QAbstractItemView::NoEditTriggers);\n layout->addWidget(keyboardTable);\n \n // Buttons\n QHBoxLayout *buttonLayout = new QHBoxLayout();\n addKeyboardMappingButton = new QPushButton(tr(\"Add Mapping\"), keyboardTab);\n removeKeyboardMappingButton = new QPushButton(tr(\"Remove Mapping\"), keyboardTab);\n \n buttonLayout->addWidget(addKeyboardMappingButton);\n buttonLayout->addWidget(removeKeyboardMappingButton);\n buttonLayout->addStretch();\n \n layout->addLayout(buttonLayout);\n \n // Connections\n connect(addKeyboardMappingButton, &QPushButton::clicked, this, &ControlPanelDialog::addKeyboardMapping);\n connect(removeKeyboardMappingButton, &QPushButton::clicked, this, &ControlPanelDialog::removeKeyboardMapping);\n \n // Load current mappings\n if (mainWindowRef) {\n QMap mappings = mainWindowRef->getKeyboardMappings();\n keyboardTable->setRowCount(mappings.size());\n int row = 0;\n for (auto it = mappings.begin(); it != mappings.end(); ++it) {\n keyboardTable->setItem(row, 0, new QTableWidgetItem(it.key()));\n QString displayAction = ButtonMappingHelper::internalKeyToDisplay(it.value(), false);\n keyboardTable->setItem(row, 1, new QTableWidgetItem(displayAction));\n row++;\n }\n }\n \n tabWidget->addTab(keyboardTab, tr(\"Keyboard Shortcuts\"));\n}\n QWidget *keyboardTab;\n QTableWidget *keyboardTable;\n QPushButton *addKeyboardMappingButton;\n QPushButton *removeKeyboardMappingButton;\n QWidget *themeTab;\n QCheckBox *useCustomAccentCheckbox;\n QPushButton *accentColorButton;\n QColor selectedAccentColor;\n QCheckBox *useBrighterPaletteCheckbox;\n void createThemeTab() {\n themeTab = new QWidget(this);\n QVBoxLayout *layout = new QVBoxLayout(themeTab);\n \n // Custom accent color\n useCustomAccentCheckbox = new QCheckBox(tr(\"Use Custom Accent Color\"), themeTab);\n layout->addWidget(useCustomAccentCheckbox);\n \n QLabel *accentColorLabel = new QLabel(tr(\"Accent Color:\"), themeTab);\n accentColorButton = new QPushButton(themeTab);\n accentColorButton->setFixedSize(100, 30);\n connect(accentColorButton, &QPushButton::clicked, this, &ControlPanelDialog::chooseAccentColor);\n \n QHBoxLayout *accentColorLayout = new QHBoxLayout();\n accentColorLayout->addWidget(accentColorLabel);\n accentColorLayout->addWidget(accentColorButton);\n accentColorLayout->addStretch();\n layout->addLayout(accentColorLayout);\n \n QLabel *accentColorNote = new QLabel(tr(\"When enabled, use a custom accent color instead of the system accent color for the toolbar, dial, and tab selection.\"));\n accentColorNote->setWordWrap(true);\n accentColorNote->setStyleSheet(\"color: gray; font-size: 10px;\");\n layout->addWidget(accentColorNote);\n \n // Enable/disable accent color button based on checkbox\n connect(useCustomAccentCheckbox, &QCheckBox::toggled, accentColorButton, &QPushButton::setEnabled);\n connect(useCustomAccentCheckbox, &QCheckBox::toggled, accentColorLabel, &QLabel::setEnabled);\n \n // Color palette preference\n useBrighterPaletteCheckbox = new QCheckBox(tr(\"Use Brighter Color Palette\"), themeTab);\n layout->addWidget(useBrighterPaletteCheckbox);\n \n QLabel *paletteNote = new QLabel(tr(\"When enabled, use brighter colors (good for dark PDF backgrounds). When disabled, use darker colors (good for light PDF backgrounds). This setting is independent of the UI theme.\"));\n paletteNote->setWordWrap(true);\n paletteNote->setStyleSheet(\"color: gray; font-size: 10px;\");\n layout->addWidget(paletteNote);\n \n layout->addStretch();\n \n tabWidget->addTab(themeTab, tr(\"Theme\"));\n}\n void chooseAccentColor() {\n QColor chosen = QColorDialog::getColor(selectedAccentColor, this, tr(\"Select Accent Color\"));\n if (chosen.isValid()) {\n selectedAccentColor = chosen;\n accentColorButton->setStyleSheet(QString(\"background-color: %1\").arg(selectedAccentColor.name()));\n }\n}\n void updateControllerStatus() {\n if (!mainWindowRef || !controllerStatusLabel) return;\n \n SDLControllerManager *controllerManager = mainWindowRef->getControllerManager();\n if (!controllerManager) {\n controllerStatusLabel->setText(tr(\"✗ Controller manager not available\"));\n controllerStatusLabel->setStyleSheet(\"color: red;\");\n return;\n }\n \n if (controllerManager->getJoystick()) {\n controllerStatusLabel->setText(tr(\"✓ Controller connected\"));\n controllerStatusLabel->setStyleSheet(\"color: green; font-weight: bold;\");\n } else {\n controllerStatusLabel->setText(tr(\"✗ No controller detected\"));\n controllerStatusLabel->setStyleSheet(\"color: red; font-weight: bold;\");\n }\n}\n};"], ["/SpeedyNote/source/Main.cpp", "#ifdef _WIN32\n#include \n#endif\n\n#include \n#include \n#include \n#include \"MainWindow.h\"\n\nint main(int argc, char *argv[]) {\n#ifdef _WIN32\n FreeConsole(); // Hide console safely on Windows\n\n /*\n AllocConsole();\n freopen(\"CONOUT$\", \"w\", stdout);\n freopen(\"CONOUT$\", \"w\", stderr);\n */\n \n \n // to show console for debugging\n \n \n#endif\n SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI, \"1\");\n SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_SWITCH, \"1\");\n SDL_Init(SDL_INIT_GAMECONTROLLER | SDL_INIT_JOYSTICK);\n\n /*\n qDebug() << \"SDL2 version:\" << SDL_GetRevision();\n qDebug() << \"Num Joysticks:\" << SDL_NumJoysticks();\n\n for (int i = 0; i < SDL_NumJoysticks(); ++i) {\n if (SDL_IsGameController(i)) {\n qDebug() << \"Controller\" << i << \"is\" << SDL_GameControllerNameForIndex(i);\n } else {\n qDebug() << \"Joystick\" << i << \"is not a recognized controller\";\n }\n }\n */ // For sdl2 debugging\n \n\n\n // Enable Windows IME support for multi-language input\n QApplication app(argc, argv);\n \n // Ensure IME is properly enabled for Windows\n #ifdef _WIN32\n app.setAttribute(Qt::AA_EnableHighDpiScaling, true);\n app.setAttribute(Qt::AA_UseHighDpiPixmaps, true);\n #endif\n\n \n QTranslator translator;\n QString locale = QLocale::system().name(); // e.g., \"zh_CN\", \"es_ES\"\n QString langCode = locale.section('_', 0, 0); // e.g., \"zh\"\n\n // printf(\"Locale: %s\\n\", locale.toStdString().c_str());\n // printf(\"Language Code: %s\\n\", langCode.toStdString().c_str());\n\n // QString locale = \"es-ES\"; // e.g., \"zh_CN\", \"es_ES\"\n // QString langCode = \"es\"; // e.g., \"zh\"\n QString translationsPath = QCoreApplication::applicationDirPath();\n\n if (translator.load(translationsPath + \"/app_\" + langCode + \".qm\")) {\n app.installTranslator(&translator);\n }\n\n QString inputFile;\n if (argc >= 2) {\n inputFile = QString::fromLocal8Bit(argv[1]);\n // qDebug() << \"Input file received:\" << inputFile;\n }\n\n MainWindow w;\n if (!inputFile.isEmpty()) {\n // Check file extension to determine how to handle it\n if (inputFile.toLower().endsWith(\".pdf\")) {\n // Handle PDF file association\n w.show(); // Show window first for dialog parent\n w.openPdfFile(inputFile);\n } else if (inputFile.toLower().endsWith(\".snpkg\")) {\n // Handle notebook package import\n w.importNotebookFromFile(inputFile);\n w.show();\n } else {\n // Unknown file type, just show the application\n w.show();\n }\n } else {\n w.show();\n }\n return app.exec();\n}\n"], ["/SpeedyNote/source/ControllerMappingDialog.h", "class SDLControllerManager {\n Q_OBJECT\n\npublic:\n explicit ControllerMappingDialog(SDLControllerManager *controllerManager, QWidget *parent = nullptr);\n private:\n void startButtonMapping(const QString &logicalButton) {\n if (!controller) return;\n \n // Disable all mapping buttons during mapping\n for (auto button : mappingButtons) {\n button->setEnabled(false);\n }\n \n // Update the current button being mapped\n currentMappingButton = logicalButton;\n mappingButtons[logicalButton]->setText(tr(\"Press button...\"));\n \n // Start button detection mode\n controller->startButtonDetection();\n \n // Start timeout timer\n mappingTimeoutTimer->start();\n \n // Show status message\n QApplication::setOverrideCursor(Qt::WaitCursor);\n}\n void onRawButtonPressed(int sdlButton, const QString &buttonName) {\n if (currentMappingButton.isEmpty()) return;\n \n // Stop detection and timeout\n controller->stopButtonDetection();\n mappingTimeoutTimer->stop();\n QApplication::restoreOverrideCursor();\n \n // Check if this button is already mapped to another function\n QMap currentMappings = controller->getAllPhysicalMappings();\n QString conflictingButton;\n for (auto it = currentMappings.begin(); it != currentMappings.end(); ++it) {\n if (it.value() == sdlButton && it.key() != currentMappingButton) {\n conflictingButton = it.key();\n break;\n }\n }\n \n if (!conflictingButton.isEmpty()) {\n int ret = QMessageBox::question(this, tr(\"Button Conflict\"), \n tr(\"The button '%1' is already mapped to '%2'.\\n\\nDo you want to reassign it to '%3'?\")\n .arg(buttonName).arg(conflictingButton).arg(currentMappingButton),\n QMessageBox::Yes | QMessageBox::No);\n \n if (ret != QMessageBox::Yes) {\n // Reset UI and return\n mappingButtons[currentMappingButton]->setText(tr(\"Map\"));\n for (auto button : mappingButtons) {\n button->setEnabled(true);\n }\n currentMappingButton.clear();\n return;\n }\n \n // Clear the conflicting mapping\n controller->setPhysicalButtonMapping(conflictingButton, -1);\n currentMappingLabels[conflictingButton]->setText(\"Not mapped\");\n currentMappingLabels[conflictingButton]->setStyleSheet(\"color: gray;\");\n }\n \n // Set the new mapping\n controller->setPhysicalButtonMapping(currentMappingButton, sdlButton);\n \n // Get appropriate text color for current theme\n QString textColor = isDarkMode() ? \"white\" : \"black\";\n \n // Update UI\n currentMappingLabels[currentMappingButton]->setText(buttonName);\n currentMappingLabels[currentMappingButton]->setStyleSheet(QString(\"color: %1; font-weight: bold;\").arg(textColor));\n mappingButtons[currentMappingButton]->setText(tr(\"Map\"));\n \n // Re-enable all buttons\n for (auto button : mappingButtons) {\n button->setEnabled(true);\n }\n \n currentMappingButton.clear();\n \n QMessageBox::information(this, tr(\"Mapping Complete\"), \n tr(\"Button '%1' has been successfully mapped!\").arg(buttonName));\n}\n void resetToDefaults() {\n int ret = QMessageBox::question(this, tr(\"Reset to Defaults\"), \n tr(\"Are you sure you want to reset all button mappings to their default values?\\n\\nThis will overwrite your current configuration.\"),\n QMessageBox::Yes | QMessageBox::No);\n \n if (ret == QMessageBox::Yes) {\n // Get default mappings and apply them\n QMap defaults = controller->getDefaultMappings();\n for (auto it = defaults.begin(); it != defaults.end(); ++it) {\n controller->setPhysicalButtonMapping(it.key(), it.value());\n }\n \n // Update display\n updateMappingDisplay();\n \n QMessageBox::information(this, tr(\"Reset Complete\"), \n tr(\"All button mappings have been reset to their default values.\"));\n }\n}\n void applyMappings() {\n // Mappings are already applied in real-time, just close the dialog\n accept();\n}\n private:\n SDLControllerManager *controller;\n QGridLayout *mappingLayout;\n QMap buttonLabels;\n QMap currentMappingLabels;\n QMap mappingButtons;\n QPushButton *resetButton;\n QPushButton *applyButton;\n QPushButton *cancelButton;\n QString currentMappingButton;\n QTimer *mappingTimeoutTimer;\n void setupUI() {\n QVBoxLayout *mainLayout = new QVBoxLayout(this);\n \n // Instructions\n QLabel *instructionLabel = new QLabel(tr(\"Map your physical controller buttons to Joy-Con functions.\\n\"\n \"Click 'Map' next to each function, then press the corresponding button on your controller.\"), this);\n instructionLabel->setWordWrap(true);\n instructionLabel->setStyleSheet(\"font-weight: bold; margin-bottom: 10px;\");\n mainLayout->addWidget(instructionLabel);\n \n // Mapping grid\n QWidget *mappingWidget = new QWidget(this);\n mappingLayout = new QGridLayout(mappingWidget);\n \n // Headers\n mappingLayout->addWidget(new QLabel(tr(\"Joy-Con Function\"), this), 0, 0);\n mappingLayout->addWidget(new QLabel(tr(\"Description\"), this), 0, 1);\n mappingLayout->addWidget(new QLabel(tr(\"Current Mapping\"), this), 0, 2);\n mappingLayout->addWidget(new QLabel(tr(\"Action\"), this), 0, 3);\n \n // Get logical button descriptions\n QMap descriptions = getLogicalButtonDescriptions();\n \n // Create mapping rows for each logical button\n QStringList logicalButtons = {\"LEFTSHOULDER\", \"RIGHTSHOULDER\", \"PADDLE2\", \"PADDLE4\", \n \"Y\", \"A\", \"B\", \"X\", \"LEFTSTICK\", \"START\", \"GUIDE\"};\n \n int row = 1;\n for (const QString &logicalButton : logicalButtons) {\n // Function name\n QLabel *functionLabel = new QLabel(logicalButton, this);\n functionLabel->setStyleSheet(\"font-weight: bold;\");\n buttonLabels[logicalButton] = functionLabel;\n mappingLayout->addWidget(functionLabel, row, 0);\n \n // Description\n QLabel *descLabel = new QLabel(descriptions.value(logicalButton, \"Unknown\"), this);\n descLabel->setWordWrap(true);\n mappingLayout->addWidget(descLabel, row, 1);\n \n // Current mapping display\n QLabel *currentLabel = new QLabel(\"Not mapped\", this);\n currentLabel->setStyleSheet(\"color: gray;\");\n currentMappingLabels[logicalButton] = currentLabel;\n mappingLayout->addWidget(currentLabel, row, 2);\n \n // Map button\n QPushButton *mapButton = new QPushButton(tr(\"Map\"), this);\n mappingButtons[logicalButton] = mapButton;\n connect(mapButton, &QPushButton::clicked, this, [this, logicalButton]() {\n startButtonMapping(logicalButton);\n });\n mappingLayout->addWidget(mapButton, row, 3);\n \n row++;\n }\n \n mainLayout->addWidget(mappingWidget);\n \n // Buttons\n QHBoxLayout *buttonLayout = new QHBoxLayout();\n \n resetButton = new QPushButton(tr(\"Reset to Defaults\"), this);\n connect(resetButton, &QPushButton::clicked, this, &ControllerMappingDialog::resetToDefaults);\n buttonLayout->addWidget(resetButton);\n \n buttonLayout->addStretch();\n \n applyButton = new QPushButton(tr(\"Apply\"), this);\n connect(applyButton, &QPushButton::clicked, this, &ControllerMappingDialog::applyMappings);\n buttonLayout->addWidget(applyButton);\n \n cancelButton = new QPushButton(tr(\"Cancel\"), this);\n connect(cancelButton, &QPushButton::clicked, this, &QDialog::reject);\n buttonLayout->addWidget(cancelButton);\n \n mainLayout->addLayout(buttonLayout);\n}\n QMap getLogicalButtonDescriptions() const {\n QMap descriptions;\n descriptions[\"LEFTSHOULDER\"] = tr(\"L Button (Left Shoulder)\");\n descriptions[\"RIGHTSHOULDER\"] = tr(\"ZL Button (Left Trigger)\");\n descriptions[\"PADDLE2\"] = tr(\"SL Button (Side Left)\");\n descriptions[\"PADDLE4\"] = tr(\"SR Button (Side Right)\");\n descriptions[\"Y\"] = tr(\"Up Arrow (D-Pad Up)\");\n descriptions[\"A\"] = tr(\"Down Arrow (D-Pad Down)\");\n descriptions[\"B\"] = tr(\"Left Arrow (D-Pad Left)\");\n descriptions[\"X\"] = tr(\"Right Arrow (D-Pad Right)\");\n descriptions[\"LEFTSTICK\"] = tr(\"Analog Stick Press\");\n descriptions[\"START\"] = tr(\"Minus Button (-)\");\n descriptions[\"GUIDE\"] = tr(\"Screenshot Button\");\n return descriptions;\n}\n void loadCurrentMappings() {\n QMap currentMappings = controller->getAllPhysicalMappings();\n \n // Get appropriate text color for current theme\n QString textColor = isDarkMode() ? \"white\" : \"black\";\n \n for (auto it = currentMappings.begin(); it != currentMappings.end(); ++it) {\n const QString &logicalButton = it.key();\n int physicalButton = it.value();\n \n if (currentMappingLabels.contains(logicalButton)) {\n QString physicalName = controller->getPhysicalButtonName(physicalButton);\n currentMappingLabels[logicalButton]->setText(physicalName);\n currentMappingLabels[logicalButton]->setStyleSheet(QString(\"color: %1; font-weight: bold;\").arg(textColor));\n }\n }\n}\n void updateMappingDisplay() {\n loadCurrentMappings();\n}\n bool isDarkMode() const {\n // Same logic as MainWindow::isDarkMode()\n QColor bg = palette().color(QPalette::Window);\n return bg.lightness() < 128; // Lightness scale: 0 (black) - 255 (white)\n}\n};"], ["/SpeedyNote/source/SDLControllerManager.h", "class SDLControllerManager {\n Q_OBJECT\npublic:\n explicit SDLControllerManager(QObject *parent = nullptr);\n ~SDLControllerManager() {\n if (joystick) SDL_JoystickClose(joystick);\n if (sdlInitialized) SDL_QuitSubSystem(SDL_INIT_JOYSTICK);\n}\n void setPhysicalButtonMapping(const QString &logicalButton, int physicalSDLButton) {\n physicalButtonMappings[logicalButton] = physicalSDLButton;\n saveControllerMappings();\n}\n int getPhysicalButtonMapping(const QString &logicalButton) const {\n return physicalButtonMappings.value(logicalButton, -1);\n}\n QMap getAllPhysicalMappings() const {\n return physicalButtonMappings;\n}\n void saveControllerMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.beginGroup(\"ControllerPhysicalMappings\");\n for (auto it = physicalButtonMappings.begin(); it != physicalButtonMappings.end(); ++it) {\n settings.setValue(it.key(), it.value());\n }\n settings.endGroup();\n}\n void loadControllerMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.beginGroup(\"ControllerPhysicalMappings\");\n QStringList keys = settings.allKeys();\n \n if (keys.isEmpty()) {\n // No saved mappings, use defaults\n physicalButtonMappings = getDefaultMappings();\n saveControllerMappings(); // Save defaults for next time\n } else {\n // Load saved mappings\n for (const QString &key : keys) {\n physicalButtonMappings[key] = settings.value(key).toInt();\n }\n }\n settings.endGroup();\n}\n QStringList getAvailablePhysicalButtons() const {\n QStringList buttons;\n if (joystick) {\n int buttonCount = SDL_JoystickNumButtons(joystick);\n for (int i = 0; i < buttonCount; ++i) {\n buttons << getPhysicalButtonName(i);\n }\n } else {\n // If no joystick connected, show a reasonable range\n for (int i = 0; i < 20; ++i) {\n buttons << getPhysicalButtonName(i);\n }\n }\n return buttons;\n}\n QString getPhysicalButtonName(int sdlButton) const {\n // Return human-readable names for physical SDL joystick buttons\n // Since we're using raw joystick buttons, we'll use generic names\n return QString(\"Button %1\").arg(sdlButton);\n}\n int getJoystickButtonCount() const {\n if (joystick) {\n return SDL_JoystickNumButtons(joystick);\n }\n return 0;\n}\n QMap getDefaultMappings() const {\n // Default mappings for Joy-Con L using raw button indices\n // These will need to be adjusted based on actual Joy-Con button indices\n QMap defaults;\n defaults[\"LEFTSHOULDER\"] = 4; // L button\n defaults[\"RIGHTSHOULDER\"] = 6; // ZL button \n defaults[\"PADDLE2\"] = 14; // SL button\n defaults[\"PADDLE4\"] = 15; // SR button\n defaults[\"Y\"] = 0; // Up arrow\n defaults[\"A\"] = 1; // Down arrow\n defaults[\"B\"] = 2; // Left arrow\n defaults[\"X\"] = 3; // Right arrow\n defaults[\"LEFTSTICK\"] = 10; // Stick press\n defaults[\"START\"] = 8; // Minus button\n defaults[\"GUIDE\"] = 13; // Screenshot button\n return defaults;\n}\n void buttonHeld(QString buttonName);\n void buttonReleased(QString buttonName);\n void buttonSinglePress(QString buttonName);\n void leftStickAngleChanged(int angle);\n void leftStickReleased();\n void rawButtonPressed(int sdlButton, QString buttonName);\n public:\n void start() {\n if (!sdlInitialized) {\n if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) != 0) {\n qWarning() << \"Failed to initialize SDL joystick subsystem:\" << SDL_GetError();\n return;\n }\n sdlInitialized = true;\n }\n\n SDL_JoystickEventState(SDL_ENABLE); // ✅ Enable joystick events\n\n // Look for any available joystick\n int numJoysticks = SDL_NumJoysticks();\n // qDebug() << \"Found\" << numJoysticks << \"joystick(s)\";\n \n for (int i = 0; i < numJoysticks; ++i) {\n const char* joystickName = SDL_JoystickNameForIndex(i);\n // qDebug() << \"Joystick\" << i << \":\" << (joystickName ? joystickName : \"Unknown\");\n \n joystick = SDL_JoystickOpen(i);\n if (joystick) {\n // qDebug() << \"Joystick connected!\";\n // qDebug() << \"Number of buttons:\" << SDL_JoystickNumButtons(joystick);\n // qDebug() << \"Number of axes:\" << SDL_JoystickNumAxes(joystick);\n // qDebug() << \"Number of hats:\" << SDL_JoystickNumHats(joystick);\n break;\n }\n }\n\n if (!joystick) {\n qWarning() << \"No joystick could be opened\";\n }\n\n pollTimer->start(16); // 60 FPS polling\n}\n void stop() {\n pollTimer->stop();\n}\n void reconnect() {\n // Stop current polling\n pollTimer->stop();\n \n // Close existing joystick if open\n if (joystick) {\n SDL_JoystickClose(joystick);\n joystick = nullptr;\n }\n \n // Clear any cached state\n buttonPressTime.clear();\n buttonHeldEmitted.clear();\n lastAngle = -1;\n leftStickActive = false;\n buttonDetectionMode = false;\n \n // Re-initialize SDL joystick subsystem\n SDL_QuitSubSystem(SDL_INIT_JOYSTICK);\n if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) != 0) {\n qWarning() << \"Failed to re-initialize SDL joystick subsystem:\" << SDL_GetError();\n sdlInitialized = false;\n return;\n }\n sdlInitialized = true;\n \n SDL_JoystickEventState(SDL_ENABLE);\n \n // Look for any available joystick\n int numJoysticks = SDL_NumJoysticks();\n qDebug() << \"Reconnect: Found\" << numJoysticks << \"joystick(s)\";\n \n for (int i = 0; i < numJoysticks; ++i) {\n const char* joystickName = SDL_JoystickNameForIndex(i);\n qDebug() << \"Reconnect: Trying joystick\" << i << \":\" << (joystickName ? joystickName : \"Unknown\");\n \n joystick = SDL_JoystickOpen(i);\n if (joystick) {\n qDebug() << \"Reconnect: Joystick connected successfully!\";\n qDebug() << \"Number of buttons:\" << SDL_JoystickNumButtons(joystick);\n qDebug() << \"Number of axes:\" << SDL_JoystickNumAxes(joystick);\n qDebug() << \"Number of hats:\" << SDL_JoystickNumHats(joystick);\n break;\n }\n }\n \n if (!joystick) {\n qWarning() << \"Reconnect: No joystick could be opened\";\n }\n \n // Restart polling\n pollTimer->start(16); // 60 FPS polling\n}\n void startButtonDetection() {\n buttonDetectionMode = true;\n}\n void stopButtonDetection() {\n buttonDetectionMode = false;\n}\n private:\n QTimer *pollTimer;\n SDL_Joystick *joystick = nullptr;\n bool sdlInitialized = false;\n bool leftStickActive = false;\n bool buttonDetectionMode = false;\n int lastAngle = -1;\n QString getButtonName(Uint8 sdlButton) {\n // This method is now deprecated in favor of getLogicalButtonName\n return getLogicalButtonName(sdlButton);\n}\n QString getLogicalButtonName(Uint8 sdlButton) {\n // Find which logical button this physical button is mapped to\n for (auto it = physicalButtonMappings.begin(); it != physicalButtonMappings.end(); ++it) {\n if (it.value() == sdlButton) {\n return it.key(); // Return the logical button name\n }\n }\n return QString(); // Return empty string if not mapped\n}\n QMap physicalButtonMappings;\n QMap buttonPressTime;\n QMap buttonHeldEmitted;\n const quint32 HOLD_THRESHOLD = 300;\n const quint32 POLL_INTERVAL = 16;\n};"], ["/SpeedyNote/markdown/qplaintexteditsearchwidget.h", "class QPlainTextEditSearchWidget {\n Q_OBJECT\n\n public:\n enum SearchMode { PlainTextMode, WholeWordsMode, RegularExpressionMode };\n explicit QPlainTextEditSearchWidget(QPlainTextEdit *parent = nullptr) {\n ui->setupUi(this);\n _textEdit = parent;\n _darkMode = false;\n hide();\n ui->searchCountLabel->setStyleSheet(QStringLiteral(\"* {color: grey}\"));\n // hiding will leave a open space in the horizontal layout\n ui->searchCountLabel->setEnabled(false);\n _currentSearchResult = 0;\n _searchResultCount = 0;\n\n connect(ui->closeButton, &QPushButton::clicked, this,\n &QPlainTextEditSearchWidget::deactivate);\n connect(ui->searchLineEdit, &QLineEdit::textChanged, this,\n &QPlainTextEditSearchWidget::searchLineEditTextChanged);\n connect(ui->searchDownButton, &QPushButton::clicked, this,\n &QPlainTextEditSearchWidget::doSearchDown);\n connect(ui->searchUpButton, &QPushButton::clicked, this,\n &QPlainTextEditSearchWidget::doSearchUp);\n connect(ui->replaceToggleButton, &QPushButton::toggled, this,\n &QPlainTextEditSearchWidget::setReplaceMode);\n connect(ui->replaceButton, &QPushButton::clicked, this,\n &QPlainTextEditSearchWidget::doReplace);\n connect(ui->replaceAllButton, &QPushButton::clicked, this,\n &QPlainTextEditSearchWidget::doReplaceAll);\n\n connect(&_debounceTimer, &QTimer::timeout, this,\n &QPlainTextEditSearchWidget::performSearch);\n\n installEventFilter(this);\n ui->searchLineEdit->installEventFilter(this);\n ui->replaceLineEdit->installEventFilter(this);\n\n#ifdef Q_OS_MAC\n // set the spacing to 8 for OS X\n layout()->setSpacing(8);\n ui->buttonFrame->layout()->setSpacing(9);\n\n // set the margin to 0 for the top buttons for OS X\n QString buttonStyle = QStringLiteral(\"QPushButton {margin: 0}\");\n ui->closeButton->setStyleSheet(buttonStyle);\n ui->searchDownButton->setStyleSheet(buttonStyle);\n ui->searchUpButton->setStyleSheet(buttonStyle);\n ui->replaceToggleButton->setStyleSheet(buttonStyle);\n ui->matchCaseSensitiveButton->setStyleSheet(buttonStyle);\n#endif\n}\n bool doSearch(bool searchDown = true, bool allowRestartAtTop = true,\n bool updateUI = true) {\n if (_debounceTimer.isActive()) {\n stopDebounce();\n }\n\n const QString text = ui->searchLineEdit->text();\n\n if (text.isEmpty()) {\n if (updateUI) {\n ui->searchLineEdit->setStyleSheet(QLatin1String(\"\"));\n }\n\n return false;\n }\n\n const int searchMode = ui->modeComboBox->currentIndex();\n const bool caseSensitive = ui->matchCaseSensitiveButton->isChecked();\n\n QFlags options =\n searchDown ? QTextDocument::FindFlag(0) : QTextDocument::FindBackward;\n if (searchMode == WholeWordsMode) {\n options |= QTextDocument::FindWholeWords;\n }\n\n if (caseSensitive) {\n options |= QTextDocument::FindCaseSensitively;\n }\n\n // block signal to reduce too many signals being fired and too many updates\n _textEdit->blockSignals(true);\n\n bool found =\n searchMode == RegularExpressionMode\n ?\n#if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0))\n _textEdit->find(\n QRegularExpression(\n text, caseSensitive\n ? QRegularExpression::NoPatternOption\n : QRegularExpression::CaseInsensitiveOption),\n options)\n :\n#else\n _textEdit->find(QRegExp(text, caseSensitive ? Qt::CaseSensitive\n : Qt::CaseInsensitive),\n options)\n :\n#endif\n _textEdit->find(text, options);\n\n _textEdit->blockSignals(false);\n\n if (found) {\n const int result =\n searchDown ? ++_currentSearchResult : --_currentSearchResult;\n _currentSearchResult = std::min(result, _searchResultCount);\n\n updateSearchCountLabelText();\n }\n\n // start at the top (or bottom) if not found\n if (!found && allowRestartAtTop) {\n _textEdit->moveCursor(searchDown ? QTextCursor::Start\n : QTextCursor::End);\n found =\n searchMode == RegularExpressionMode\n ?\n#if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0))\n _textEdit->find(\n QRegularExpression(\n text, caseSensitive\n ? QRegularExpression::NoPatternOption\n : QRegularExpression::CaseInsensitiveOption),\n options)\n :\n#else\n _textEdit->find(\n QRegExp(text, caseSensitive ? Qt::CaseSensitive\n : Qt::CaseInsensitive),\n options)\n :\n#endif\n _textEdit->find(text, options);\n\n if (found && updateUI) {\n _currentSearchResult = searchDown ? 1 : _searchResultCount;\n updateSearchCountLabelText();\n }\n }\n\n if (updateUI) {\n const QRect rect = _textEdit->cursorRect();\n QMargins margins = _textEdit->layout()->contentsMargins();\n const int searchWidgetHotArea = _textEdit->height() - this->height();\n const int marginBottom =\n (rect.y() > searchWidgetHotArea) ? (this->height() + 10) : 0;\n\n // move the search box a bit up if we would block the search result\n if (margins.bottom() != marginBottom) {\n margins.setBottom(marginBottom);\n _textEdit->layout()->setContentsMargins(margins);\n }\n\n // add a background color according if we found the text or not\n const QString bgColorCode = _darkMode\n ? (found ? QStringLiteral(\"#135a13\")\n : QStringLiteral(\"#8d2b36\"))\n : found ? QStringLiteral(\"#D5FAE2\")\n : QStringLiteral(\"#FAE9EB\");\n const QString fgColorCode =\n _darkMode ? QStringLiteral(\"#cccccc\") : QStringLiteral(\"#404040\");\n\n ui->searchLineEdit->setStyleSheet(\n QStringLiteral(\"* { background: \") + bgColorCode +\n QStringLiteral(\"; color: \") + fgColorCode + QStringLiteral(\"; }\"));\n\n // restore the search extra selections after the find command\n this->setSearchExtraSelections();\n }\n\n return found;\n}\n void setDarkMode(bool enabled) {\n _darkMode = enabled;\n}\n ~QPlainTextEditSearchWidget() { delete ui; }\n void setSearchText(const QString &searchText) {\n ui->searchLineEdit->setText(searchText);\n}\n void setSearchMode(SearchMode searchMode) {\n ui->modeComboBox->setCurrentIndex(searchMode);\n}\n void setDebounceDelay(uint debounceDelay) {\n _debounceTimer.setInterval(static_cast(debounceDelay));\n}\n void activate(bool focus) {\n setReplaceMode(ui->modeComboBox->currentIndex() !=\n SearchMode::PlainTextMode);\n show();\n\n // preset the selected text as search text if there is any and there is no\n // other search text\n const QString selectedText = _textEdit->textCursor().selectedText();\n if (!selectedText.isEmpty() && ui->searchLineEdit->text().isEmpty()) {\n ui->searchLineEdit->setText(selectedText);\n }\n\n if (focus) {\n ui->searchLineEdit->setFocus();\n }\n\n ui->searchLineEdit->selectAll();\n updateSearchExtraSelections();\n doSearchDown();\n}\n void clearSearchExtraSelections() {\n _searchExtraSelections.clear();\n setSearchExtraSelections();\n}\n void updateSearchExtraSelections() {\n _searchExtraSelections.clear();\n const auto textCursor = _textEdit->textCursor();\n _textEdit->moveCursor(QTextCursor::Start);\n const QColor color = selectionColor;\n QTextCharFormat extraFmt;\n extraFmt.setBackground(color);\n int findCounter = 0;\n const int searchMode = ui->modeComboBox->currentIndex();\n\n while (doSearch(true, false, false)) {\n findCounter++;\n\n // prevent infinite loops from regular expression searches like \"$\", \"^\"\n // or \"\\b\"\n if (searchMode == RegularExpressionMode && findCounter >= 10000) {\n break;\n }\n\n QTextEdit::ExtraSelection extra = QTextEdit::ExtraSelection();\n extra.format = extraFmt;\n\n extra.cursor = _textEdit->textCursor();\n _searchExtraSelections.append(extra);\n }\n\n _textEdit->setTextCursor(textCursor);\n this->setSearchExtraSelections();\n}\n private:\n Ui::QPlainTextEditSearchWidget *ui;\n int _searchResultCount;\n int _currentSearchResult;\n QList _searchExtraSelections;\n QColor selectionColor;\n QTimer _debounceTimer;\n QString _searchTerm;\n void setSearchExtraSelections() const {\n this->_textEdit->setExtraSelections(this->_searchExtraSelections);\n}\n void stopDebounce() {\n _debounceTimer.stop();\n ui->searchDownButton->setEnabled(true);\n ui->searchUpButton->setEnabled(true);\n}\n protected:\n QPlainTextEdit *_textEdit;\n bool _darkMode;\n bool eventFilter(QObject *obj, QEvent *event) override {\n if (event->type() == QEvent::KeyPress) {\n auto *keyEvent = static_cast(event);\n\n if (keyEvent->key() == Qt::Key_Escape) {\n deactivate();\n return true;\n } else if ((!_debounceTimer.isActive() &&\n keyEvent->modifiers().testFlag(Qt::ShiftModifier) &&\n (keyEvent->key() == Qt::Key_Return)) ||\n (keyEvent->key() == Qt::Key_Up)) {\n doSearchUp();\n return true;\n } else if (!_debounceTimer.isActive() &&\n ((keyEvent->key() == Qt::Key_Return) ||\n (keyEvent->key() == Qt::Key_Down))) {\n doSearchDown();\n return true;\n } else if (!_debounceTimer.isActive() &&\n keyEvent->key() == Qt::Key_F3) {\n doSearch(!keyEvent->modifiers().testFlag(Qt::ShiftModifier));\n return true;\n }\n\n // if ((obj == ui->replaceLineEdit) && (keyEvent->key() ==\n // Qt::Key_Tab)\n // && ui->replaceToggleButton->isChecked()) {\n // ui->replaceLineEdit->setFocus();\n // }\n\n return false;\n }\n\n return QWidget::eventFilter(obj, event);\n}\n public:\n void activate() {\n setReplaceMode(ui->modeComboBox->currentIndex() !=\n SearchMode::PlainTextMode);\n show();\n\n // preset the selected text as search text if there is any and there is no\n // other search text\n const QString selectedText = _textEdit->textCursor().selectedText();\n if (!selectedText.isEmpty() && ui->searchLineEdit->text().isEmpty()) {\n ui->searchLineEdit->setText(selectedText);\n }\n\n if (focus) {\n ui->searchLineEdit->setFocus();\n }\n\n ui->searchLineEdit->selectAll();\n updateSearchExtraSelections();\n doSearchDown();\n}\n void deactivate() {\n stopDebounce();\n\n hide();\n\n // Clear the search extra selections when closing the search bar\n clearSearchExtraSelections();\n\n _textEdit->setFocus();\n}\n void doSearchDown() { doSearch(true); }\n void doSearchUp() { doSearch(false); }\n void setReplaceMode(bool enabled) {\n ui->replaceToggleButton->setChecked(enabled);\n ui->replaceLabel->setVisible(enabled);\n ui->replaceLineEdit->setVisible(enabled);\n ui->modeLabel->setVisible(enabled);\n ui->buttonFrame->setVisible(enabled);\n ui->matchCaseSensitiveButton->setVisible(enabled);\n}\n void activateReplace() {\n // replacing is prohibited if the text edit is readonly\n if (_textEdit->isReadOnly()) {\n return;\n }\n\n ui->searchLineEdit->setText(_textEdit->textCursor().selectedText());\n ui->searchLineEdit->selectAll();\n activate();\n setReplaceMode(true);\n}\n bool doReplace(bool forAll = false) {\n if (_textEdit->isReadOnly()) {\n return false;\n }\n\n QTextCursor cursor = _textEdit->textCursor();\n\n if (!forAll && cursor.selectedText().isEmpty()) {\n return false;\n }\n\n const int searchMode = ui->modeComboBox->currentIndex();\n if (searchMode == RegularExpressionMode) {\n QString text = cursor.selectedText();\n text.replace(QRegularExpression(ui->searchLineEdit->text()),\n ui->replaceLineEdit->text());\n cursor.insertText(text);\n } else {\n cursor.insertText(ui->replaceLineEdit->text());\n }\n\n if (!forAll) {\n const int position = cursor.position();\n\n if (!doSearch(true)) {\n // restore the last cursor position if text wasn't found any more\n cursor.setPosition(position);\n _textEdit->setTextCursor(cursor);\n }\n }\n\n return true;\n}\n void doReplaceAll() {\n if (_textEdit->isReadOnly()) {\n return;\n }\n\n // start at the top\n _textEdit->moveCursor(QTextCursor::Start);\n\n // replace until everything to the bottom is replaced\n while (doSearch(true, false) && doReplace(true)) {\n }\n}\n void reset() {\n ui->searchLineEdit->clear();\n setSearchMode(SearchMode::PlainTextMode);\n setReplaceMode(false);\n ui->searchCountLabel->setEnabled(false);\n}\n void doSearchCount() {\n // Note that we are moving the anchor, so the search will start from the top\n // again! Alternative: Restore cursor position afterward, but then we will\n // not know\n // at what _currentSearchResult we currently are\n _textEdit->moveCursor(QTextCursor::Start, QTextCursor::MoveAnchor);\n\n bool found;\n _searchResultCount = 0;\n _currentSearchResult = 0;\n const int searchMode = ui->modeComboBox->currentIndex();\n\n do {\n found = doSearch(true, false, false);\n if (found) {\n _searchResultCount++;\n }\n\n // prevent infinite loops from regular expression searches like \"$\", \"^\"\n // or \"\\b\"\n if (searchMode == RegularExpressionMode &&\n _searchResultCount >= 10000) {\n break;\n }\n } while (found);\n\n updateSearchCountLabelText();\n}\n protected:\n void searchLineEditTextChanged(const QString &arg1) {\n _searchTerm = arg1;\n\n if (_debounceTimer.interval() != 0 && !_searchTerm.isEmpty()) {\n _debounceTimer.start();\n ui->searchDownButton->setEnabled(false);\n ui->searchUpButton->setEnabled(false);\n } else {\n performSearch();\n }\n}\n void performSearch() {\n doSearchCount();\n updateSearchExtraSelections();\n doSearchDown();\n}\n void updateSearchCountLabelText() {\n ui->searchCountLabel->setEnabled(true);\n ui->searchCountLabel->setText(QStringLiteral(\"%1/%2\").arg(\n _currentSearchResult == 0 ? QChar('-')\n : QString::number(_currentSearchResult),\n _searchResultCount == 0 ? QChar('-')\n : QString::number(_searchResultCount)));\n}\n void setSearchSelectionColor(const QColor &color) {\n selectionColor = color;\n}\n private:\n void on_modeComboBox_currentIndexChanged(int index) {\n Q_UNUSED(index)\n doSearchCount();\n doSearchDown();\n}\n void on_matchCaseSensitiveButton_toggled(bool checked) {\n Q_UNUSED(checked)\n doSearchCount();\n doSearchDown();\n}\n};"], ["/SpeedyNote/markdown/linenumberarea.h", "#ifndef LINENUMBERAREA_H\n#define LINENUMBERAREA_H\n\n#include \n#include \n#include \n#include \n\n#include \"qmarkdowntextedit.h\"\n\nclass LineNumArea final : public QWidget {\n Q_OBJECT\n\n public:\n explicit LineNumArea(QMarkdownTextEdit *parent)\n : QWidget(parent), textEdit(parent) {\n Q_ASSERT(parent);\n\n _currentLineColor = QColor(QStringLiteral(\"#eef067\"));\n _otherLinesColor = QColor(QStringLiteral(\"#a6a6a6\"));\n setHidden(true);\n\n // We always use fixed font to avoid \"width\" issues\n setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont));\n }\n\n void setCurrentLineColor(QColor color) { _currentLineColor = color; }\n\n void setOtherLineColor(QColor color) {\n _otherLinesColor = std::move(color);\n }\n\n int lineNumAreaWidth() const {\n if (!enabled) {\n return 0;\n }\n\n int digits = 2;\n int max = std::max(1, textEdit->blockCount());\n while (max >= 10) {\n max /= 10;\n ++digits;\n }\n\n#if QT_VERSION >= 0x050B00\n int space =\n 13 + textEdit->fontMetrics().horizontalAdvance(u'9') * digits;\n#else\n int space =\n 13 + textEdit->fontMetrics().width(QLatin1Char('9')) * digits;\n#endif\n\n return space;\n }\n\n bool isLineNumAreaEnabled() const { return enabled; }\n\n void setLineNumAreaEnabled(bool e) {\n enabled = e;\n setHidden(!e);\n }\n\n QSize sizeHint() const override { return {lineNumAreaWidth(), 0}; }\n\n protected:\n void paintEvent(QPaintEvent *event) override {\n QPainter painter(this);\n\n painter.fillRect(event->rect(),\n palette().color(QPalette::Active, QPalette::Window));\n\n auto block = textEdit->firstVisibleBlock();\n int blockNumber = block.blockNumber();\n qreal top = textEdit->blockBoundingGeometry(block)\n .translated(textEdit->contentOffset())\n .top();\n // Maybe the top is not 0?\n top += textEdit->viewportMargins().top();\n qreal bottom = top;\n\n const QPen currentLine = _currentLineColor;\n const QPen otherLines = _otherLinesColor;\n painter.setFont(font());\n\n while (block.isValid() && top <= event->rect().bottom()) {\n top = bottom;\n bottom = top + textEdit->blockBoundingRect(block).height();\n if (block.isVisible() && bottom >= event->rect().top()) {\n QString number = QString::number(blockNumber + 1);\n\n auto isCurrentLine =\n textEdit->textCursor().blockNumber() == blockNumber;\n painter.setPen(isCurrentLine ? currentLine : otherLines);\n\n painter.drawText(-5, top, sizeHint().width(),\n textEdit->fontMetrics().height(),\n Qt::AlignRight, number);\n }\n\n block = block.next();\n ++blockNumber;\n }\n }\n\n private:\n bool enabled = false;\n QMarkdownTextEdit *textEdit;\n QColor _currentLineColor;\n QColor _otherLinesColor;\n};\n\n#endif // LINENUMBERAREA_H\n"], ["/SpeedyNote/source/ButtonMappingTypes.h", "class InternalDialMode {\n Q_DECLARE_TR_FUNCTIONS(ButtonMappingHelper)\n public:\n static QString dialModeToInternalKey(InternalDialMode mode) {\n switch (mode) {\n case InternalDialMode::None: return \"none\";\n case InternalDialMode::PageSwitching: return \"page_switching\";\n case InternalDialMode::ZoomControl: return \"zoom_control\";\n case InternalDialMode::ThicknessControl: return \"thickness_control\";\n\n case InternalDialMode::ToolSwitching: return \"tool_switching\";\n case InternalDialMode::PresetSelection: return \"preset_selection\";\n case InternalDialMode::PanAndPageScroll: return \"pan_and_page_scroll\";\n }\n return \"none\";\n}\n static QString actionToInternalKey(InternalControllerAction action) {\n switch (action) {\n case InternalControllerAction::None: return \"none\";\n case InternalControllerAction::ToggleFullscreen: return \"toggle_fullscreen\";\n case InternalControllerAction::ToggleDial: return \"toggle_dial\";\n case InternalControllerAction::Zoom50: return \"zoom_50\";\n case InternalControllerAction::ZoomOut: return \"zoom_out\";\n case InternalControllerAction::Zoom200: return \"zoom_200\";\n case InternalControllerAction::AddPreset: return \"add_preset\";\n case InternalControllerAction::DeletePage: return \"delete_page\";\n case InternalControllerAction::FastForward: return \"fast_forward\";\n case InternalControllerAction::OpenControlPanel: return \"open_control_panel\";\n case InternalControllerAction::RedColor: return \"red_color\";\n case InternalControllerAction::BlueColor: return \"blue_color\";\n case InternalControllerAction::YellowColor: return \"yellow_color\";\n case InternalControllerAction::GreenColor: return \"green_color\";\n case InternalControllerAction::BlackColor: return \"black_color\";\n case InternalControllerAction::WhiteColor: return \"white_color\";\n case InternalControllerAction::CustomColor: return \"custom_color\";\n case InternalControllerAction::ToggleSidebar: return \"toggle_sidebar\";\n case InternalControllerAction::Save: return \"save\";\n case InternalControllerAction::StraightLineTool: return \"straight_line_tool\";\n case InternalControllerAction::RopeTool: return \"rope_tool\";\n case InternalControllerAction::SetPenTool: return \"set_pen_tool\";\n case InternalControllerAction::SetMarkerTool: return \"set_marker_tool\";\n case InternalControllerAction::SetEraserTool: return \"set_eraser_tool\";\n case InternalControllerAction::TogglePdfTextSelection: return \"toggle_pdf_text_selection\";\n case InternalControllerAction::ToggleOutline: return \"toggle_outline\";\n case InternalControllerAction::ToggleBookmarks: return \"toggle_bookmarks\";\n case InternalControllerAction::AddBookmark: return \"add_bookmark\";\n case InternalControllerAction::ToggleTouchGestures: return \"toggle_touch_gestures\";\n }\n return \"none\";\n}\n static InternalDialMode internalKeyToDialMode(const QString &key) {\n if (key == \"none\") return InternalDialMode::None;\n if (key == \"page_switching\") return InternalDialMode::PageSwitching;\n if (key == \"zoom_control\") return InternalDialMode::ZoomControl;\n if (key == \"thickness_control\") return InternalDialMode::ThicknessControl;\n\n if (key == \"tool_switching\") return InternalDialMode::ToolSwitching;\n if (key == \"preset_selection\") return InternalDialMode::PresetSelection;\n if (key == \"pan_and_page_scroll\") return InternalDialMode::PanAndPageScroll;\n return InternalDialMode::None;\n}\n static InternalControllerAction internalKeyToAction(const QString &key) {\n if (key == \"none\") return InternalControllerAction::None;\n if (key == \"toggle_fullscreen\") return InternalControllerAction::ToggleFullscreen;\n if (key == \"toggle_dial\") return InternalControllerAction::ToggleDial;\n if (key == \"zoom_50\") return InternalControllerAction::Zoom50;\n if (key == \"zoom_out\") return InternalControllerAction::ZoomOut;\n if (key == \"zoom_200\") return InternalControllerAction::Zoom200;\n if (key == \"add_preset\") return InternalControllerAction::AddPreset;\n if (key == \"delete_page\") return InternalControllerAction::DeletePage;\n if (key == \"fast_forward\") return InternalControllerAction::FastForward;\n if (key == \"open_control_panel\") return InternalControllerAction::OpenControlPanel;\n if (key == \"red_color\") return InternalControllerAction::RedColor;\n if (key == \"blue_color\") return InternalControllerAction::BlueColor;\n if (key == \"yellow_color\") return InternalControllerAction::YellowColor;\n if (key == \"green_color\") return InternalControllerAction::GreenColor;\n if (key == \"black_color\") return InternalControllerAction::BlackColor;\n if (key == \"white_color\") return InternalControllerAction::WhiteColor;\n if (key == \"custom_color\") return InternalControllerAction::CustomColor;\n if (key == \"toggle_sidebar\") return InternalControllerAction::ToggleSidebar;\n if (key == \"save\") return InternalControllerAction::Save;\n if (key == \"straight_line_tool\") return InternalControllerAction::StraightLineTool;\n if (key == \"rope_tool\") return InternalControllerAction::RopeTool;\n if (key == \"set_pen_tool\") return InternalControllerAction::SetPenTool;\n if (key == \"set_marker_tool\") return InternalControllerAction::SetMarkerTool;\n if (key == \"set_eraser_tool\") return InternalControllerAction::SetEraserTool;\n if (key == \"toggle_pdf_text_selection\") return InternalControllerAction::TogglePdfTextSelection;\n if (key == \"toggle_outline\") return InternalControllerAction::ToggleOutline;\n if (key == \"toggle_bookmarks\") return InternalControllerAction::ToggleBookmarks;\n if (key == \"add_bookmark\") return InternalControllerAction::AddBookmark;\n if (key == \"toggle_touch_gestures\") return InternalControllerAction::ToggleTouchGestures;\n return InternalControllerAction::None;\n}\n static QStringList getTranslatedDialModes() {\n return {\n tr(\"None\"),\n tr(\"Page Switching\"),\n tr(\"Zoom Control\"),\n tr(\"Thickness Control\"),\n\n tr(\"Tool Switching\"),\n tr(\"Preset Selection\"),\n tr(\"Pan and Page Scroll\")\n };\n}\n static QStringList getTranslatedActions() {\n return {\n tr(\"None\"),\n tr(\"Toggle Fullscreen\"),\n tr(\"Toggle Dial\"),\n tr(\"Zoom 50%\"),\n tr(\"Zoom Out\"),\n tr(\"Zoom 200%\"),\n tr(\"Add Preset\"),\n tr(\"Delete Page\"),\n tr(\"Fast Forward\"),\n tr(\"Open Control Panel\"),\n tr(\"Red\"),\n tr(\"Blue\"),\n tr(\"Yellow\"),\n tr(\"Green\"),\n tr(\"Black\"),\n tr(\"White\"),\n tr(\"Custom Color\"),\n tr(\"Toggle Sidebar\"),\n tr(\"Save\"),\n tr(\"Straight Line Tool\"),\n tr(\"Rope Tool\"),\n tr(\"Set Pen Tool\"),\n tr(\"Set Marker Tool\"),\n tr(\"Set Eraser Tool\"),\n tr(\"Toggle PDF Text Selection\"),\n tr(\"Toggle PDF Outline\"),\n tr(\"Toggle Bookmarks\"),\n tr(\"Add/Remove Bookmark\"),\n tr(\"Toggle Touch Gestures\")\n };\n}\n static QStringList getTranslatedButtons() {\n return {\n tr(\"Left Shoulder\"),\n tr(\"Right Shoulder\"),\n tr(\"Paddle 2\"),\n tr(\"Paddle 4\"),\n tr(\"Y Button\"),\n tr(\"A Button\"),\n tr(\"B Button\"),\n tr(\"X Button\"),\n tr(\"Left Stick\"),\n tr(\"Start Button\"),\n tr(\"Guide Button\")\n };\n}\n static QStringList getInternalDialModeKeys() {\n return {\n \"none\",\n \"page_switching\",\n \"zoom_control\",\n \"thickness_control\",\n\n \"tool_switching\",\n \"preset_selection\",\n \"pan_and_page_scroll\"\n };\n}\n static QStringList getInternalActionKeys() {\n return {\n \"none\",\n \"toggle_fullscreen\",\n \"toggle_dial\",\n \"zoom_50\",\n \"zoom_out\",\n \"zoom_200\",\n \"add_preset\",\n \"delete_page\",\n \"fast_forward\",\n \"open_control_panel\",\n \"red_color\",\n \"blue_color\",\n \"yellow_color\",\n \"green_color\",\n \"black_color\",\n \"white_color\",\n \"custom_color\",\n \"toggle_sidebar\",\n \"save\",\n \"straight_line_tool\",\n \"rope_tool\",\n \"set_pen_tool\",\n \"set_marker_tool\",\n \"set_eraser_tool\",\n \"toggle_pdf_text_selection\",\n \"toggle_outline\",\n \"toggle_bookmarks\",\n \"add_bookmark\",\n \"toggle_touch_gestures\"\n };\n}\n static QStringList getInternalButtonKeys() {\n return {\n \"LEFTSHOULDER\",\n \"RIGHTSHOULDER\", \n \"PADDLE2\",\n \"PADDLE4\",\n \"Y\",\n \"A\",\n \"B\",\n \"X\",\n \"LEFTSTICK\",\n \"START\",\n \"GUIDE\"\n };\n}\n static QString displayToInternalKey(const QString &displayString, bool isDialMode) {\n if (isDialMode) {\n QStringList translated = getTranslatedDialModes();\n QStringList internal = getInternalDialModeKeys();\n int index = translated.indexOf(displayString);\n return (index >= 0) ? internal[index] : \"none\";\n } else {\n QStringList translated = getTranslatedActions();\n QStringList internal = getInternalActionKeys();\n int index = translated.indexOf(displayString);\n return (index >= 0) ? internal[index] : \"none\";\n }\n}\n static QString internalKeyToDisplay(const QString &internalKey, bool isDialMode) {\n if (isDialMode) {\n QStringList translated = getTranslatedDialModes();\n QStringList internal = getInternalDialModeKeys();\n int index = internal.indexOf(internalKey);\n return (index >= 0) ? translated[index] : tr(\"None\");\n } else {\n QStringList translated = getTranslatedActions();\n QStringList internal = getInternalActionKeys();\n int index = internal.indexOf(internalKey);\n return (index >= 0) ? translated[index] : tr(\"None\");\n }\n}\n};"], ["/SpeedyNote/source/KeyCaptureDialog.h", "class KeyCaptureDialog {\n Q_OBJECT\n\npublic:\n explicit KeyCaptureDialog(QWidget *parent = nullptr);\n protected:\n void keyPressEvent(QKeyEvent *event) override {\n // Build key sequence string\n QStringList modifiers;\n \n if (event->modifiers() & Qt::ControlModifier) modifiers << \"Ctrl\";\n if (event->modifiers() & Qt::ShiftModifier) modifiers << \"Shift\";\n if (event->modifiers() & Qt::AltModifier) modifiers << \"Alt\";\n if (event->modifiers() & Qt::MetaModifier) modifiers << \"Meta\";\n \n // Don't capture modifier keys alone\n if (event->key() == Qt::Key_Control || event->key() == Qt::Key_Shift ||\n event->key() == Qt::Key_Alt || event->key() == Qt::Key_Meta) {\n return;\n }\n \n // Don't capture Escape (let it close the dialog)\n if (event->key() == Qt::Key_Escape) {\n QDialog::keyPressEvent(event);\n return;\n }\n \n QString keyString = QKeySequence(event->key()).toString();\n \n if (!modifiers.isEmpty()) {\n capturedSequence = modifiers.join(\"+\") + \"+\" + keyString;\n } else {\n capturedSequence = keyString;\n }\n \n updateDisplay();\n event->accept();\n}\n private:\n void clearSequence() {\n capturedSequence.clear();\n updateDisplay();\n setFocus(); // Return focus to dialog for key capture\n}\n private:\n QLabel *instructionLabel;\n QLabel *capturedLabel;\n QPushButton *clearButton;\n QPushButton *okButton;\n QPushButton *cancelButton;\n QString capturedSequence;\n void updateDisplay() {\n if (capturedSequence.isEmpty()) {\n capturedLabel->setText(tr(\"(No key captured yet)\"));\n okButton->setEnabled(false);\n } else {\n capturedLabel->setText(capturedSequence);\n okButton->setEnabled(true);\n }\n}\n};"], ["/SpeedyNote/markdown/main.cpp", "/*\n * MIT License\n *\n * Copyright (c) 2014-2025 Patrizio Bekerle -- \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#include \n\n#include \"mainwindow.h\"\n\nint main(int argc, char *argv[]) {\n QApplication a(argc, argv);\n MainWindow w;\n w.show();\n\n return a.exec();\n}\n"], ["/SpeedyNote/markdown/mainwindow.h", "class MainWindow {\n Q_OBJECT\n\n public:\n explicit MainWindow(QWidget *parent = nullptr);\n ~MainWindow() { delete ui; }\n private:\n Ui::MainWindow *ui;\n};"], ["/SpeedyNote/source/ToolType.h", "#ifndef TOOLTYPE_H\n#define TOOLTYPE_H\n\n// ✅ Now it can be used anywhere\nenum class ToolType {\n Pen,\n Marker,\n Eraser\n};\n\n#endif // TOOLTYPE_H"], ["/SpeedyNote/markdown/markdownhighlighter.h", "class QTextDocument {\n};"], ["/SpeedyNote/markdown/qownlanguagedata.h", "class qownlanguagedata {\n};"]], "task_instance_info": {"created_time": "2025-08-20 19:30:38", "created_task_model": "DeepSeek-R1", "class_skeleton": "class\nInkCanvas\n{\nQ_OBJECT\n\npublic:\n explicit RecentNotebooksManager(QObject *parent = nullptr);\nvoid addRecentNotebook(const QString& folderPath, InkCanvas* canvasForPreview = nullptr) {}\nQStringList getRecentNotebooks() const {}\nQString getCoverImagePathForNotebook(const QString& folderPath) const {}\nQString getNotebookDisplayName(const QString& folderPath) const {}\nvoid generateAndSaveCoverPreview(const QString& folderPath, InkCanvas* optionalCanvas = nullptr) {}\nprivate:\nvoid loadRecentNotebooks() {}\nvoid saveRecentNotebooks() {}\nQString getCoverImageDir() const {}\nQString sanitizeFolderName(const QString& folderPath) const {}\nQStringList recentNotebookPaths;\nconst int MAX_RECENT_NOTEBOOKS = 16;\nQSettings settings;\n};", "code_description": "This code segment functions to: Manage a list of recently accessed notebook locations while maintaining associated preview images, including mechanisms to limit storage size, generate visual representations from available content, and persist the collection across application sessions."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```cpp\n[TASK_BEGIN]\nclass RecentNotebooksManager\n{\n Q_OBJECT\n\npublic:\n explicit RecentNotebooksManager(QObject *parent = nullptr) : QObject(parent), settings(\"MyCompany\", \"MyApp\") {\n loadRecentNotebooks();\n }\n\n void addRecentNotebook(const QString& folderPath, InkCanvas* canvasForPreview = nullptr) {\n // Remove existing entry if present\n recentNotebookPaths.removeAll(folderPath);\n \n // Add to beginning\n recentNotebookPaths.prepend(folderPath);\n \n // Trim to max count\n while (recentNotebookPaths.size() > MAX_RECENT_NOTEBOOKS) {\n recentNotebookPaths.removeLast();\n }\n \n generateAndSaveCoverPreview(folderPath, canvasForPreview);\n saveRecentNotebooks();\n }\n\n QStringList getRecentNotebooks() const {\n return recentNotebookPaths;\n }\n\n QString getCoverImagePathForNotebook(const QString& folderPath) const {\n return QDir(getCoverImageDir()).filePath(sanitizeFolderName(folderPath) + \".png\");\n }\n\n QString getNotebookDisplayName(const QString& folderPath) const {\n return QFileInfo(folderPath).fileName();\n }\n\n void generateAndSaveCoverPreview(const QString& folderPath, InkCanvas* optionalCanvas = nullptr) {\n // Implementation would typically:\n // 1. Create/capture preview image using optionalCanvas\n // 2. Save to getCoverImagePathForNotebook(folderPath)\n }\n\nprivate:\n void loadRecentNotebooks() {\n recentNotebookPaths = settings.value(\"recentNotebooks\").toStringList();\n }\n\n void saveRecentNotebooks() {\n settings.setValue(\"recentNotebooks\", recentNotebookPaths);\n }\n\n QString getCoverImageDir() const {\n return QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/notebook_covers\";\n }\n\n QString sanitizeFolderName(const QString& folderPath) const {\n QString sanitized = folderPath;\n sanitized.replace(QRegularExpression(\"[^a-zA-Z0-9_-]\"), \"_\");\n return sanitized;\n }\n\n QStringList recentNotebookPaths;\n const int MAX_RECENT_NOTEBOOKS = 16;\n QSettings settings;\n};\n[TASK_END]\n```", "inference_time": "2025-08-20 19-31-18"}, "editdistance_info": {"edit_distance": 23.135, "calculate_time": "2025-08-20 19:31:18", "true_code_clean": "class InkCanvas {\n Q_OBJECT\npublic:\n explicit RecentNotebooksManager(QObject *parent = nullptr);\n void addRecentNotebook(const QString& folderPath, InkCanvas* canvasForPreview = nullptr) {\n if (folderPath.isEmpty()) return;\n recentNotebookPaths.removeAll(folderPath);\n recentNotebookPaths.prepend(folderPath);\n while (recentNotebookPaths.size() > MAX_RECENT_NOTEBOOKS) {\n recentNotebookPaths.removeLast();\n }\n generateAndSaveCoverPreview(folderPath, canvasForPreview);\n saveRecentNotebooks();\n}\n QStringList getRecentNotebooks() const {\n return recentNotebookPaths;\n}\n QString getCoverImagePathForNotebook(const QString& folderPath) const {\n QString coverDir = getCoverImageDir();\n QString coverFileName = sanitizeFolderName(folderPath) + \"_cover.png\";\n QString coverFilePath = coverDir + coverFileName;\n if (QFile::exists(coverFilePath)) {\n return coverFilePath;\n }\n return \"\"; \n}\n QString getNotebookDisplayName(const QString& folderPath) const {\n QString metadataFile = folderPath + \"/.pdf_path.txt\";\n if (QFile::exists(metadataFile)) {\n QFile file(metadataFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString pdfPath = in.readLine().trimmed();\n file.close();\n if (!pdfPath.isEmpty()) {\n return QFileInfo(pdfPath).fileName();\n }\n }\n }\n return QFileInfo(folderPath).fileName();\n}\n void generateAndSaveCoverPreview(const QString& folderPath, InkCanvas* optionalCanvas = nullptr) {\n QString coverDir = getCoverImageDir();\n QString coverFileName = sanitizeFolderName(folderPath) + \"_cover.png\";\n QString coverFilePath = coverDir + coverFileName;\n QImage coverImage(400, 300, QImage::Format_ARGB32_Premultiplied);\n coverImage.fill(Qt::white); \n QPainter painter(&coverImage);\n painter.setRenderHint(QPainter::SmoothPixmapTransform);\n if (optionalCanvas && optionalCanvas->width() > 0 && optionalCanvas->height() > 0) {\n int logicalCanvasWidth = optionalCanvas->width();\n int logicalCanvasHeight = optionalCanvas->height();\n double targetAspectRatio = 4.0 / 3.0;\n double canvasAspectRatio = (double)logicalCanvasWidth / logicalCanvasHeight;\n int grabWidth, grabHeight;\n int xOffset = 0, yOffset = 0;\n if (canvasAspectRatio > targetAspectRatio) { \n grabHeight = logicalCanvasHeight;\n grabWidth = qRound(logicalCanvasHeight * targetAspectRatio);\n xOffset = (logicalCanvasWidth - grabWidth) / 2;\n } else { \n grabWidth = logicalCanvasWidth;\n grabHeight = qRound(logicalCanvasWidth / targetAspectRatio);\n yOffset = (logicalCanvasHeight - grabHeight) / 2;\n }\n if (grabWidth > 0 && grabHeight > 0) {\n QRect grabRect(xOffset, yOffset, grabWidth, grabHeight);\n QPixmap capturedView = optionalCanvas->grab(grabRect);\n painter.drawPixmap(coverImage.rect(), capturedView, capturedView.rect());\n } else {\n painter.fillRect(coverImage.rect(), Qt::lightGray);\n painter.setPen(Qt::black);\n painter.drawText(coverImage.rect(), Qt::AlignCenter, tr(\"Preview Error\"));\n }\n } else {\n QString notebookIdStr;\n InkCanvas tempCanvas(nullptr); \n QFile idFile(folderPath + \"/.notebook_id.txt\");\n if (idFile.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&idFile);\n notebookIdStr = in.readLine().trimmed();\n idFile.close();\n }\n QString firstPagePath, firstAnnotatedPagePath;\n if (!notebookIdStr.isEmpty()) {\n firstPagePath = folderPath + QString(\"/%1_00000.png\").arg(notebookIdStr);\n firstAnnotatedPagePath = folderPath + QString(\"/annotated_%1_00000.png\").arg(notebookIdStr);\n } else {\n }\n QImage pageImage;\n if (!firstAnnotatedPagePath.isEmpty() && QFile::exists(firstAnnotatedPagePath)) {\n pageImage.load(firstAnnotatedPagePath);\n } else if (!firstPagePath.isEmpty() && QFile::exists(firstPagePath)) {\n pageImage.load(firstPagePath);\n }\n if (!pageImage.isNull()) {\n painter.drawImage(coverImage.rect(), pageImage, pageImage.rect());\n } else {\n painter.fillRect(coverImage.rect(), Qt::darkGray);\n painter.setPen(Qt::white);\n painter.drawText(coverImage.rect(), Qt::AlignCenter, tr(\"No Page 0 Preview\"));\n }\n }\n coverImage.save(coverFilePath, \"PNG\");\n}\n private:\n void loadRecentNotebooks() {\n recentNotebookPaths = settings.value(\"recentNotebooks\").toStringList();\n}\n void saveRecentNotebooks() {\n settings.setValue(\"recentNotebooks\", recentNotebookPaths);\n}\n QString getCoverImageDir() const {\n return QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/RecentCovers/\";\n}\n QString sanitizeFolderName(const QString& folderPath) const {\n return QFileInfo(folderPath).baseName().replace(QRegularExpression(\"[^a-zA-Z0-9_]\"), \"_\");\n}\n QStringList recentNotebookPaths;\n const int MAX_RECENT_NOTEBOOKS = 16;\n QSettings settings;\n}", "predict_code_clean": "class RecentNotebooksManager\n{\n Q_OBJECT\npublic:\n explicit RecentNotebooksManager(QObject *parent = nullptr) : QObject(parent), settings(\"MyCompany\", \"MyApp\") {\n loadRecentNotebooks();\n }\n void addRecentNotebook(const QString& folderPath, InkCanvas* canvasForPreview = nullptr) {\n recentNotebookPaths.removeAll(folderPath);\n recentNotebookPaths.prepend(folderPath);\n while (recentNotebookPaths.size() > MAX_RECENT_NOTEBOOKS) {\n recentNotebookPaths.removeLast();\n }\n generateAndSaveCoverPreview(folderPath, canvasForPreview);\n saveRecentNotebooks();\n }\n QStringList getRecentNotebooks() const {\n return recentNotebookPaths;\n }\n QString getCoverImagePathForNotebook(const QString& folderPath) const {\n return QDir(getCoverImageDir()).filePath(sanitizeFolderName(folderPath) + \".png\");\n }\n QString getNotebookDisplayName(const QString& folderPath) const {\n return QFileInfo(folderPath).fileName();\n }\n void generateAndSaveCoverPreview(const QString& folderPath, InkCanvas* optionalCanvas = nullptr) {\n }\nprivate:\n void loadRecentNotebooks() {\n recentNotebookPaths = settings.value(\"recentNotebooks\").toStringList();\n }\n void saveRecentNotebooks() {\n settings.setValue(\"recentNotebooks\", recentNotebookPaths);\n }\n QString getCoverImageDir() const {\n return QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/notebook_covers\";\n }\n QString sanitizeFolderName(const QString& folderPath) const {\n QString sanitized = folderPath;\n sanitized.replace(QRegularExpression(\"[^a-zA-Z0-9_-]\"), \"_\");\n return sanitized;\n }\n QStringList recentNotebookPaths;\n const int MAX_RECENT_NOTEBOOKS = 16;\n QSettings settings;\n};"}} {"repo_name": "SpeedyNote", "file_name": "/SpeedyNote/markdown/qplaintexteditsearchwidget.h", "inference_info": {"prefix_code": "", "suffix_code": ";", "middle_code": "class QPlainTextEditSearchWidget {\n Q_OBJECT\n public:\n enum SearchMode { PlainTextMode, WholeWordsMode, RegularExpressionMode };\n explicit QPlainTextEditSearchWidget(QPlainTextEdit *parent = nullptr) {\n ui->setupUi(this);\n _textEdit = parent;\n _darkMode = false;\n hide();\n ui->searchCountLabel->setStyleSheet(QStringLiteral(\"* {color: grey}\"));\n ui->searchCountLabel->setEnabled(false);\n _currentSearchResult = 0;\n _searchResultCount = 0;\n connect(ui->closeButton, &QPushButton::clicked, this,\n &QPlainTextEditSearchWidget::deactivate);\n connect(ui->searchLineEdit, &QLineEdit::textChanged, this,\n &QPlainTextEditSearchWidget::searchLineEditTextChanged);\n connect(ui->searchDownButton, &QPushButton::clicked, this,\n &QPlainTextEditSearchWidget::doSearchDown);\n connect(ui->searchUpButton, &QPushButton::clicked, this,\n &QPlainTextEditSearchWidget::doSearchUp);\n connect(ui->replaceToggleButton, &QPushButton::toggled, this,\n &QPlainTextEditSearchWidget::setReplaceMode);\n connect(ui->replaceButton, &QPushButton::clicked, this,\n &QPlainTextEditSearchWidget::doReplace);\n connect(ui->replaceAllButton, &QPushButton::clicked, this,\n &QPlainTextEditSearchWidget::doReplaceAll);\n connect(&_debounceTimer, &QTimer::timeout, this,\n &QPlainTextEditSearchWidget::performSearch);\n installEventFilter(this);\n ui->searchLineEdit->installEventFilter(this);\n ui->replaceLineEdit->installEventFilter(this);\n#ifdef Q_OS_MAC\n layout()->setSpacing(8);\n ui->buttonFrame->layout()->setSpacing(9);\n QString buttonStyle = QStringLiteral(\"QPushButton {margin: 0}\");\n ui->closeButton->setStyleSheet(buttonStyle);\n ui->searchDownButton->setStyleSheet(buttonStyle);\n ui->searchUpButton->setStyleSheet(buttonStyle);\n ui->replaceToggleButton->setStyleSheet(buttonStyle);\n ui->matchCaseSensitiveButton->setStyleSheet(buttonStyle);\n#endif\n}\n bool doSearch(bool searchDown = true, bool allowRestartAtTop = true,\n bool updateUI = true) {\n if (_debounceTimer.isActive()) {\n stopDebounce();\n }\n const QString text = ui->searchLineEdit->text();\n if (text.isEmpty()) {\n if (updateUI) {\n ui->searchLineEdit->setStyleSheet(QLatin1String(\"\"));\n }\n return false;\n }\n const int searchMode = ui->modeComboBox->currentIndex();\n const bool caseSensitive = ui->matchCaseSensitiveButton->isChecked();\n QFlags options =\n searchDown ? QTextDocument::FindFlag(0) : QTextDocument::FindBackward;\n if (searchMode == WholeWordsMode) {\n options |= QTextDocument::FindWholeWords;\n }\n if (caseSensitive) {\n options |= QTextDocument::FindCaseSensitively;\n }\n _textEdit->blockSignals(true);\n bool found =\n searchMode == RegularExpressionMode\n ?\n#if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0))\n _textEdit->find(\n QRegularExpression(\n text, caseSensitive\n ? QRegularExpression::NoPatternOption\n : QRegularExpression::CaseInsensitiveOption),\n options)\n :\n#else\n _textEdit->find(QRegExp(text, caseSensitive ? Qt::CaseSensitive\n : Qt::CaseInsensitive),\n options)\n :\n#endif\n _textEdit->find(text, options);\n _textEdit->blockSignals(false);\n if (found) {\n const int result =\n searchDown ? ++_currentSearchResult : --_currentSearchResult;\n _currentSearchResult = std::min(result, _searchResultCount);\n updateSearchCountLabelText();\n }\n if (!found && allowRestartAtTop) {\n _textEdit->moveCursor(searchDown ? QTextCursor::Start\n : QTextCursor::End);\n found =\n searchMode == RegularExpressionMode\n ?\n#if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0))\n _textEdit->find(\n QRegularExpression(\n text, caseSensitive\n ? QRegularExpression::NoPatternOption\n : QRegularExpression::CaseInsensitiveOption),\n options)\n :\n#else\n _textEdit->find(\n QRegExp(text, caseSensitive ? Qt::CaseSensitive\n : Qt::CaseInsensitive),\n options)\n :\n#endif\n _textEdit->find(text, options);\n if (found && updateUI) {\n _currentSearchResult = searchDown ? 1 : _searchResultCount;\n updateSearchCountLabelText();\n }\n }\n if (updateUI) {\n const QRect rect = _textEdit->cursorRect();\n QMargins margins = _textEdit->layout()->contentsMargins();\n const int searchWidgetHotArea = _textEdit->height() - this->height();\n const int marginBottom =\n (rect.y() > searchWidgetHotArea) ? (this->height() + 10) : 0;\n if (margins.bottom() != marginBottom) {\n margins.setBottom(marginBottom);\n _textEdit->layout()->setContentsMargins(margins);\n }\n const QString bgColorCode = _darkMode\n ? (found ? QStringLiteral(\"#135a13\")\n : QStringLiteral(\"#8d2b36\"))\n : found ? QStringLiteral(\"#D5FAE2\")\n : QStringLiteral(\"#FAE9EB\");\n const QString fgColorCode =\n _darkMode ? QStringLiteral(\"#cccccc\") : QStringLiteral(\"#404040\");\n ui->searchLineEdit->setStyleSheet(\n QStringLiteral(\"* { background: \") + bgColorCode +\n QStringLiteral(\"; color: \") + fgColorCode + QStringLiteral(\"; }\"));\n this->setSearchExtraSelections();\n }\n return found;\n}\n void setDarkMode(bool enabled) {\n _darkMode = enabled;\n}\n ~QPlainTextEditSearchWidget() { delete ui; }\n void setSearchText(const QString &searchText) {\n ui->searchLineEdit->setText(searchText);\n}\n void setSearchMode(SearchMode searchMode) {\n ui->modeComboBox->setCurrentIndex(searchMode);\n}\n void setDebounceDelay(uint debounceDelay) {\n _debounceTimer.setInterval(static_cast(debounceDelay));\n}\n void activate(bool focus) {\n setReplaceMode(ui->modeComboBox->currentIndex() !=\n SearchMode::PlainTextMode);\n show();\n const QString selectedText = _textEdit->textCursor().selectedText();\n if (!selectedText.isEmpty() && ui->searchLineEdit->text().isEmpty()) {\n ui->searchLineEdit->setText(selectedText);\n }\n if (focus) {\n ui->searchLineEdit->setFocus();\n }\n ui->searchLineEdit->selectAll();\n updateSearchExtraSelections();\n doSearchDown();\n}\n void clearSearchExtraSelections() {\n _searchExtraSelections.clear();\n setSearchExtraSelections();\n}\n void updateSearchExtraSelections() {\n _searchExtraSelections.clear();\n const auto textCursor = _textEdit->textCursor();\n _textEdit->moveCursor(QTextCursor::Start);\n const QColor color = selectionColor;\n QTextCharFormat extraFmt;\n extraFmt.setBackground(color);\n int findCounter = 0;\n const int searchMode = ui->modeComboBox->currentIndex();\n while (doSearch(true, false, false)) {\n findCounter++;\n if (searchMode == RegularExpressionMode && findCounter >= 10000) {\n break;\n }\n QTextEdit::ExtraSelection extra = QTextEdit::ExtraSelection();\n extra.format = extraFmt;\n extra.cursor = _textEdit->textCursor();\n _searchExtraSelections.append(extra);\n }\n _textEdit->setTextCursor(textCursor);\n this->setSearchExtraSelections();\n}\n private:\n Ui::QPlainTextEditSearchWidget *ui;\n int _searchResultCount;\n int _currentSearchResult;\n QList _searchExtraSelections;\n QColor selectionColor;\n QTimer _debounceTimer;\n QString _searchTerm;\n void setSearchExtraSelections() const {\n this->_textEdit->setExtraSelections(this->_searchExtraSelections);\n}\n void stopDebounce() {\n _debounceTimer.stop();\n ui->searchDownButton->setEnabled(true);\n ui->searchUpButton->setEnabled(true);\n}\n protected:\n QPlainTextEdit *_textEdit;\n bool _darkMode;\n bool eventFilter(QObject *obj, QEvent *event) override {\n if (event->type() == QEvent::KeyPress) {\n auto *keyEvent = static_cast(event);\n if (keyEvent->key() == Qt::Key_Escape) {\n deactivate();\n return true;\n } else if ((!_debounceTimer.isActive() &&\n keyEvent->modifiers().testFlag(Qt::ShiftModifier) &&\n (keyEvent->key() == Qt::Key_Return)) ||\n (keyEvent->key() == Qt::Key_Up)) {\n doSearchUp();\n return true;\n } else if (!_debounceTimer.isActive() &&\n ((keyEvent->key() == Qt::Key_Return) ||\n (keyEvent->key() == Qt::Key_Down))) {\n doSearchDown();\n return true;\n } else if (!_debounceTimer.isActive() &&\n keyEvent->key() == Qt::Key_F3) {\n doSearch(!keyEvent->modifiers().testFlag(Qt::ShiftModifier));\n return true;\n }\n return false;\n }\n return QWidget::eventFilter(obj, event);\n}\n public:\n void activate() {\n setReplaceMode(ui->modeComboBox->currentIndex() !=\n SearchMode::PlainTextMode);\n show();\n const QString selectedText = _textEdit->textCursor().selectedText();\n if (!selectedText.isEmpty() && ui->searchLineEdit->text().isEmpty()) {\n ui->searchLineEdit->setText(selectedText);\n }\n if (focus) {\n ui->searchLineEdit->setFocus();\n }\n ui->searchLineEdit->selectAll();\n updateSearchExtraSelections();\n doSearchDown();\n}\n void deactivate() {\n stopDebounce();\n hide();\n clearSearchExtraSelections();\n _textEdit->setFocus();\n}\n void doSearchDown() { doSearch(true); }\n void doSearchUp() { doSearch(false); }\n void setReplaceMode(bool enabled) {\n ui->replaceToggleButton->setChecked(enabled);\n ui->replaceLabel->setVisible(enabled);\n ui->replaceLineEdit->setVisible(enabled);\n ui->modeLabel->setVisible(enabled);\n ui->buttonFrame->setVisible(enabled);\n ui->matchCaseSensitiveButton->setVisible(enabled);\n}\n void activateReplace() {\n if (_textEdit->isReadOnly()) {\n return;\n }\n ui->searchLineEdit->setText(_textEdit->textCursor().selectedText());\n ui->searchLineEdit->selectAll();\n activate();\n setReplaceMode(true);\n}\n bool doReplace(bool forAll = false) {\n if (_textEdit->isReadOnly()) {\n return false;\n }\n QTextCursor cursor = _textEdit->textCursor();\n if (!forAll && cursor.selectedText().isEmpty()) {\n return false;\n }\n const int searchMode = ui->modeComboBox->currentIndex();\n if (searchMode == RegularExpressionMode) {\n QString text = cursor.selectedText();\n text.replace(QRegularExpression(ui->searchLineEdit->text()),\n ui->replaceLineEdit->text());\n cursor.insertText(text);\n } else {\n cursor.insertText(ui->replaceLineEdit->text());\n }\n if (!forAll) {\n const int position = cursor.position();\n if (!doSearch(true)) {\n cursor.setPosition(position);\n _textEdit->setTextCursor(cursor);\n }\n }\n return true;\n}\n void doReplaceAll() {\n if (_textEdit->isReadOnly()) {\n return;\n }\n _textEdit->moveCursor(QTextCursor::Start);\n while (doSearch(true, false) && doReplace(true)) {\n }\n}\n void reset() {\n ui->searchLineEdit->clear();\n setSearchMode(SearchMode::PlainTextMode);\n setReplaceMode(false);\n ui->searchCountLabel->setEnabled(false);\n}\n void doSearchCount() {\n _textEdit->moveCursor(QTextCursor::Start, QTextCursor::MoveAnchor);\n bool found;\n _searchResultCount = 0;\n _currentSearchResult = 0;\n const int searchMode = ui->modeComboBox->currentIndex();\n do {\n found = doSearch(true, false, false);\n if (found) {\n _searchResultCount++;\n }\n if (searchMode == RegularExpressionMode &&\n _searchResultCount >= 10000) {\n break;\n }\n } while (found);\n updateSearchCountLabelText();\n}\n protected:\n void searchLineEditTextChanged(const QString &arg1) {\n _searchTerm = arg1;\n if (_debounceTimer.interval() != 0 && !_searchTerm.isEmpty()) {\n _debounceTimer.start();\n ui->searchDownButton->setEnabled(false);\n ui->searchUpButton->setEnabled(false);\n } else {\n performSearch();\n }\n}\n void performSearch() {\n doSearchCount();\n updateSearchExtraSelections();\n doSearchDown();\n}\n void updateSearchCountLabelText() {\n ui->searchCountLabel->setEnabled(true);\n ui->searchCountLabel->setText(QStringLiteral(\"%1/%2\").arg(\n _currentSearchResult == 0 ? QChar('-')\n : QString::number(_currentSearchResult),\n _searchResultCount == 0 ? QChar('-')\n : QString::number(_searchResultCount)));\n}\n void setSearchSelectionColor(const QColor &color) {\n selectionColor = color;\n}\n private:\n void on_modeComboBox_currentIndexChanged(int index) {\n Q_UNUSED(index)\n doSearchCount();\n doSearchDown();\n}\n void on_matchCaseSensitiveButton_toggled(bool checked) {\n Q_UNUSED(checked)\n doSearchCount();\n doSearchDown();\n}\n}", "code_description": null, "fill_type": "CLASS_TYPE", "language_type": "cpp", "sub_task_type": null}, "context_code": [["/SpeedyNote/markdown/qmarkdowntextedit.h", "class LineNumArea {\n Q_OBJECT\n Q_PROPERTY(\n bool highlighting READ highlightingEnabled WRITE setHighlightingEnabled);\n friend class LineNumArea;\n public:\n enum AutoTextOption {\n None = 0x0000,\n\n // inserts closing characters for brackets and Markdown characters\n BracketClosing = 0x0001,\n\n // removes matching brackets and Markdown characters\n BracketRemoval = 0x0002\n };\n Q_DECLARE_FLAGS(AutoTextOptions, AutoTextOption);\n explicit QMarkdownTextEdit(QWidget *parent = nullptr,\n bool initHighlighter = true) {\n installEventFilter(this);\n viewport()->installEventFilter(this);\n _autoTextOptions = AutoTextOption::BracketClosing;\n\n _lineNumArea = new LineNumArea(this);\n updateLineNumberAreaWidth(0);\n\n // Markdown highlighting is enabled by default\n _highlightingEnabled = initHighlighter;\n if (initHighlighter) {\n _highlighter = new MarkdownHighlighter(document());\n }\n\n QFont font = this->font();\n\n // set the tab stop to the width of 4 spaces in the editor\n constexpr int tabStop = 4;\n QFontMetrics metrics(font);\n\n#if QT_VERSION < QT_VERSION_CHECK(5, 11, 0)\n setTabStopWidth(tabStop * metrics.width(' '));\n#else\n setTabStopDistance(tabStop * metrics.horizontalAdvance(QLatin1Char(' ')));\n#endif\n\n // add shortcuts for duplicating text\n // new QShortcut( QKeySequence( \"Ctrl+D\" ), this, SLOT( duplicateText() )\n // ); new QShortcut( QKeySequence( \"Ctrl+Alt+Down\" ), this, SLOT(\n // duplicateText() ) );\n\n // add a layout to the widget\n auto *layout = new QVBoxLayout(this);\n layout->setContentsMargins(0, 0, 0, 0);\n layout->addStretch();\n this->setLayout(layout);\n\n // add the hidden search widget\n _searchWidget = new QPlainTextEditSearchWidget(this);\n this->layout()->addWidget(_searchWidget);\n\n connect(this, &QPlainTextEdit::textChanged, this,\n &QMarkdownTextEdit::adjustRightMargin);\n connect(this, &QPlainTextEdit::cursorPositionChanged, this,\n &QMarkdownTextEdit::centerTheCursor);\n connect(verticalScrollBar(), &QScrollBar::valueChanged, this,\n [this](int) { _lineNumArea->update(); });\n connect(this, &QPlainTextEdit::cursorPositionChanged, this, [this]() {\n _lineNumArea->update();\n\n auto oldArea = blockBoundingGeometry(_textCursor.block())\n .translated(contentOffset());\n _textCursor = textCursor();\n auto newArea = blockBoundingGeometry(_textCursor.block())\n .translated(contentOffset());\n auto areaToUpdate = oldArea | newArea;\n viewport()->update(areaToUpdate.toRect());\n });\n connect(document(), &QTextDocument::blockCountChanged, this,\n &QMarkdownTextEdit::updateLineNumberAreaWidth);\n connect(this, &QPlainTextEdit::updateRequest, this,\n &QMarkdownTextEdit::updateLineNumberArea);\n\n updateSettings();\n\n // workaround for disabled signals up initialization\n QTimer::singleShot(300, this, &QMarkdownTextEdit::adjustRightMargin);\n}\n MarkdownHighlighter *highlighter();\n QPlainTextEditSearchWidget *searchWidget();\n void setIgnoredClickUrlSchemata(QStringList ignoredUrlSchemata) {\n _ignoredClickUrlSchemata = std::move(ignoredUrlSchemata);\n}\n virtual void openUrl(const QString &urlString) {\n qDebug() << \"QMarkdownTextEdit \" << __func__\n << \" - 'urlString': \" << urlString;\n\n QDesktopServices::openUrl(QUrl(urlString));\n}\n QString getMarkdownUrlAtPosition(const QString &text, int position) {\n QString url;\n\n // get a map of parsed Markdown urls with their link texts as key\n const QMap urlMap = parseMarkdownUrlsFromText(text);\n QMap::const_iterator i = urlMap.constBegin();\n for (; i != urlMap.constEnd(); ++i) {\n const QString &linkText = i.key();\n const QString &urlString = i.value();\n\n const int foundPositionStart = text.indexOf(linkText);\n\n if (foundPositionStart >= 0) {\n // calculate end position of found linkText\n const int foundPositionEnd = foundPositionStart + linkText.size();\n\n // check if position is in found string range\n if ((position >= foundPositionStart) &&\n (position <= foundPositionEnd)) {\n url = urlString;\n break;\n }\n }\n }\n\n return url;\n}\n void initSearchFrame(QWidget *searchFrame, bool darkMode = false) {\n _searchFrame = searchFrame;\n\n // remove the search widget from our layout\n layout()->removeWidget(_searchWidget);\n\n QLayout *layout = _searchFrame->layout();\n\n // create a grid layout for the frame and add the search widget to it\n if (layout == nullptr) {\n layout = new QVBoxLayout(_searchFrame);\n layout->setSpacing(0);\n layout->setContentsMargins(0, 0, 0, 0);\n }\n\n _searchWidget->setDarkMode(darkMode);\n layout->addWidget(_searchWidget);\n _searchFrame->setLayout(layout);\n}\n void setAutoTextOptions(AutoTextOptions options) {\n _autoTextOptions = options;\n}\n static bool isValidUrl(const QString &urlString) {\n static QRegularExpression regex(R\"(^\\w+:\\/\\/.+)\");\n const QRegularExpressionMatch match = regex.match(urlString);\n return match.hasMatch();\n}\n void resetMouseCursor() const {\n QWidget *viewPort = viewport();\n viewPort->setCursor(Qt::IBeamCursor);\n}\n void setReadOnly(bool ro) {\n QPlainTextEdit::setReadOnly(ro);\n\n // attempted to fix a problem with Chinese and Japanese input methods\n // @see https://github.com/pbek/QOwnNotes/issues/976\n setAttribute(Qt::WA_InputMethodEnabled, !isReadOnly());\n}\n void doSearch(QString &searchText,\n QPlainTextEditSearchWidget::SearchMode searchMode =\n QPlainTextEditSearchWidget::SearchMode::PlainTextMode) {\n _searchWidget->setSearchText(searchText);\n _searchWidget->setSearchMode(searchMode);\n _searchWidget->doSearchCount();\n _searchWidget->activate(false);\n}\n void hideSearchWidget(bool reset) {\n _searchWidget->deactivate();\n\n if (reset) {\n _searchWidget->reset();\n }\n}\n void updateSettings() {\n // if true: centers the screen if cursor reaches bottom (but not top)\n searchWidget()->setDebounceDelay(_debounceDelay);\n setCenterOnScroll(_centerCursor);\n}\n void setLineNumbersCurrentLineColor(QColor color) {\n _lineNumArea->setCurrentLineColor(std::move(color));\n}\n void setLineNumbersOtherLineColor(QColor color) {\n _lineNumArea->setOtherLineColor(std::move(color));\n}\n void setSearchWidgetDebounceDelay(uint debounceDelay) {\n _debounceDelay = debounceDelay;\n searchWidget()->setDebounceDelay(_debounceDelay);\n}\n void setHighlightingEnabled(bool enabled) {\n if (_highlightingEnabled == enabled || _highlighter == nullptr) {\n return;\n }\n\n _highlightingEnabled = enabled;\n _highlighter->setDocument(enabled ? document() : Q_NULLPTR);\n\n if (enabled) {\n _highlighter->rehighlight();\n }\n}\n [[nodiscard]] bool highlightingEnabled() const {\n return _highlightingEnabled && _highlighter != nullptr;\n}\n void setHighlightCurrentLine(bool set) {\n _highlightCurrentLine = set;\n}\n bool highlightCurrentLine() { return _highlightCurrentLine; }\n void setCurrentLineHighlightColor(const QColor &c) {\n _currentLineHighlightColor = color;\n}\n QColor currentLineHighlightColor() {\n return _currentLineHighlightColor;\n}\n public:\n void duplicateText() {\n if (isReadOnly()) {\n return;\n }\n\n QTextCursor cursor = this->textCursor();\n QString selectedText = cursor.selectedText();\n\n // duplicate line if no text was selected\n if (selectedText.isEmpty()) {\n const int position = cursor.position();\n\n // select the whole line\n cursor.movePosition(QTextCursor::StartOfBlock);\n cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);\n\n const int positionDiff = cursor.position() - position;\n selectedText = \"\\n\" + cursor.selectedText();\n\n // insert text with new line at end of the selected line\n cursor.setPosition(cursor.selectionEnd());\n cursor.insertText(selectedText);\n\n // set the position to same position it was in the duplicated line\n cursor.setPosition(cursor.position() - positionDiff);\n } else {\n // duplicate selected text\n cursor.setPosition(cursor.selectionEnd());\n const int selectionStart = cursor.position();\n\n // insert selected text\n cursor.insertText(selectedText);\n const int selectionEnd = cursor.position();\n\n // select the inserted text\n cursor.setPosition(selectionStart);\n cursor.setPosition(selectionEnd, QTextCursor::KeepAnchor);\n }\n\n this->setTextCursor(cursor);\n}\n void setText(const QString &text) { setPlainText(text); }\n void setPlainText(const QString &text) {\n // clear the dirty blocks vector to increase performance and prevent\n // a possible crash in QSyntaxHighlighter::rehighlightBlock\n if (_highlighter) _highlighter->clearDirtyBlocks();\n\n QPlainTextEdit::setPlainText(text);\n adjustRightMargin();\n}\n void adjustRightMargin() {\n QMargins margins = layout()->contentsMargins();\n const int rightMargin =\n document()->size().height() > viewport()->size().height() ? 24 : 0;\n margins.setRight(rightMargin);\n layout()->setContentsMargins(margins);\n}\n void hide() {\n _searchWidget->hide();\n QWidget::hide();\n}\n bool openLinkAtCursorPosition() {\n QTextCursor cursor = this->textCursor();\n const int clickedPosition = cursor.position();\n\n // select the text in the clicked block and find out on\n // which position we clicked\n cursor.movePosition(QTextCursor::StartOfBlock);\n const int positionFromStart = clickedPosition - cursor.position();\n cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);\n\n const QString selectedText = cursor.selectedText();\n\n // find out which url in the selected text was clicked\n const QString urlString =\n getMarkdownUrlAtPosition(selectedText, positionFromStart);\n const QUrl url = QUrl(urlString);\n const bool isRelativeFileUrl =\n urlString.startsWith(QLatin1String(\"file://..\"));\n const bool isLegacyAttachmentUrl =\n urlString.startsWith(QLatin1String(\"file://attachments\"));\n\n qDebug() << __func__ << \" - 'emit urlClicked( urlString )': \" << urlString;\n\n Q_EMIT urlClicked(urlString);\n\n if ((url.isValid() && isValidUrl(urlString)) || isRelativeFileUrl ||\n isLegacyAttachmentUrl) {\n // ignore some schemata\n if (!(_ignoredClickUrlSchemata.contains(url.scheme()) ||\n isRelativeFileUrl || isLegacyAttachmentUrl)) {\n // open the url\n openUrl(urlString);\n }\n\n return true;\n }\n\n return false;\n}\n bool handleBackspaceEntered() {\n if (!(_autoTextOptions & AutoTextOption::BracketRemoval) || isReadOnly()) {\n return false;\n }\n\n QTextCursor cursor = textCursor();\n\n // return if some text was selected\n if (!cursor.selectedText().isEmpty()) {\n return false;\n }\n\n int position = cursor.position();\n const int positionInBlock = cursor.positionInBlock();\n int block = cursor.block().blockNumber();\n\n if (_highlighter)\n if (_highlighter->isPosInACodeSpan(block, positionInBlock - 1))\n return false;\n\n // return if backspace was pressed at the beginning of a block\n if (positionInBlock == 0) {\n return false;\n }\n\n // get the current text from the block\n const QString text = cursor.block().text();\n\n char charToRemove{};\n\n // current char\n const char charInFront = text.at(positionInBlock - 1).toLatin1();\n\n if (charInFront == '*')\n return handleCharRemoval(MarkdownHighlighter::RangeType::Emphasis,\n block, positionInBlock - 1);\n else if (charInFront == '`')\n return handleCharRemoval(MarkdownHighlighter::RangeType::CodeSpan,\n block, positionInBlock - 1);\n\n // handle removal of \", ', and brackets\n\n // is it opener?\n int pos = _openingCharacters.indexOf(charInFront);\n // for \" and '\n bool isOpener = false;\n bool isCloser = false;\n if (pos == 5 || pos == 6) {\n isOpener = isQuotOpener(positionInBlock - 1, text);\n } else {\n isOpener = pos != -1;\n }\n if (isOpener) {\n charToRemove = _closingCharacters.at(pos);\n } else {\n // is it closer?\n pos = _closingCharacters.indexOf(charInFront);\n if (pos == 5 || pos == 6)\n isCloser = isQuotCloser(positionInBlock - 1, text);\n else\n isCloser = pos != -1;\n if (isCloser)\n charToRemove = _openingCharacters.at(pos);\n else\n return false;\n }\n\n int charToRemoveIndex = -1;\n if (isOpener) {\n bool closer = true;\n charToRemoveIndex = text.indexOf(charToRemove, positionInBlock);\n if (charToRemoveIndex == -1) return false;\n if (pos == 5 || pos == 6)\n closer = isQuotCloser(charToRemoveIndex, text);\n if (!closer) return false;\n cursor.setPosition(position + (charToRemoveIndex - positionInBlock));\n cursor.deleteChar();\n } else if (isCloser) {\n charToRemoveIndex = text.lastIndexOf(charToRemove, positionInBlock - 2);\n if (charToRemoveIndex == -1) return false;\n bool opener = true;\n if (pos == 5 || pos == 6)\n opener = isQuotOpener(charToRemoveIndex, text);\n if (!opener) return false;\n const int pos = position - (positionInBlock - charToRemoveIndex);\n cursor.setPosition(pos);\n cursor.deleteChar();\n position -= 1;\n } else {\n charToRemoveIndex = text.lastIndexOf(charToRemove, positionInBlock - 2);\n if (charToRemoveIndex == -1) return false;\n const int pos = position - (positionInBlock - charToRemoveIndex);\n cursor.setPosition(pos);\n cursor.deleteChar();\n position -= 1;\n }\n\n // moving the cursor back to the old position so the previous character\n // can be removed\n cursor.setPosition(position);\n setTextCursor(cursor);\n return false;\n}\n void centerTheCursor() {\n if (_mouseButtonDown || !_centerCursor) {\n return;\n }\n\n // Centers the cursor every time, but not on the top and bottom,\n // bottom is done by setCenterOnScroll() in updateSettings()\n centerCursor();\n\n /*\n QRect cursor = cursorRect();\n QRect vp = viewport()->rect();\n\n qDebug() << __func__ << \" - 'cursor.top': \" << cursor.top();\n qDebug() << __func__ << \" - 'cursor.bottom': \" << cursor.bottom();\n qDebug() << __func__ << \" - 'vp': \" << vp.bottom();\n\n int bottom = 0;\n int top = 0;\n\n qDebug() << __func__ << \" - 'viewportMargins().top()': \"\n << viewportMargins().top();\n\n qDebug() << __func__ << \" - 'viewportMargins().bottom()': \"\n << viewportMargins().bottom();\n\n int vpBottom = viewportMargins().top() + viewportMargins().bottom() +\n vp.bottom(); int vpCenter = vpBottom / 2; int cBottom = cursor.bottom() +\n viewportMargins().top();\n\n qDebug() << __func__ << \" - 'vpBottom': \" << vpBottom;\n qDebug() << __func__ << \" - 'vpCenter': \" << vpCenter;\n qDebug() << __func__ << \" - 'cBottom': \" << cBottom;\n\n\n if (cBottom >= vpCenter) {\n bottom = cBottom + viewportMargins().top() / 2 +\n viewportMargins().bottom() / 2 - (vp.bottom() / 2);\n // bottom = cBottom - (vp.bottom() / 2);\n // bottom *= 1.5;\n }\n\n // setStyleSheet(QString(\"QPlainTextEdit {padding-bottom:\n %1px;}\").arg(QString::number(bottom)));\n\n // if (cursor.top() < (vp.bottom() / 2)) {\n // top = (vp.bottom() / 2) - cursor.top() + viewportMargins().top() /\n 2 + viewportMargins().bottom() / 2;\n //// top *= -1;\n //// bottom *= 1.5;\n // }\n qDebug() << __func__ << \" - 'top': \" << top;\n qDebug() << __func__ << \" - 'bottom': \" << bottom;\n setViewportMargins(0,top,0, bottom);\n\n\n // QScrollBar* scrollbar = verticalScrollBar();\n //\n // qDebug() << __func__ << \" - 'scrollbar->value();': \" <<\n scrollbar->value();;\n // qDebug() << __func__ << \" - 'scrollbar->maximum();': \"\n // << scrollbar->maximum();;\n\n\n // scrollbar->setValue(scrollbar->value() - offset.y());\n //\n // setViewportMargins\n\n // setViewportMargins(0, 0, 0, bottom);\n */\n}\n void undo() {\n if (isReadOnly()) {\n return;\n }\n\n QTextCursor cursor = textCursor();\n // if no text selected, call undo\n if (!cursor.hasSelection()) {\n QPlainTextEdit::undo();\n return;\n }\n\n // if text is selected and bracket closing was used\n // we retain our selection\n if (_handleBracketClosingUsed) {\n // get the selection\n int selectionEnd = cursor.selectionEnd();\n int selectionStart = cursor.selectionStart();\n // call undo\n QPlainTextEdit::undo();\n // select again\n cursor.setPosition(selectionStart - 1);\n cursor.setPosition(selectionEnd - 1, QTextCursor::KeepAnchor);\n this->setTextCursor(cursor);\n _handleBracketClosingUsed = false;\n } else {\n // if text was selected but bracket closing wasn't used\n // do normal undo\n QPlainTextEdit::undo();\n return;\n }\n}\n void moveTextUpDown(bool up) {\n if (isReadOnly()) {\n return;\n }\n\n QTextCursor cursor = textCursor();\n QTextCursor move = cursor;\n\n move.setVisualNavigation(false);\n\n move.beginEditBlock(); // open an edit block to keep undo operations sane\n bool hasSelection = cursor.hasSelection();\n\n if (hasSelection) {\n // if there's a selection inside the block, we select the whole block\n move.setPosition(cursor.selectionStart());\n move.movePosition(QTextCursor::StartOfBlock);\n move.setPosition(cursor.selectionEnd(), QTextCursor::KeepAnchor);\n move.movePosition(\n move.atBlockStart() ? QTextCursor::Left : QTextCursor::EndOfBlock,\n QTextCursor::KeepAnchor);\n } else {\n move.movePosition(QTextCursor::StartOfBlock);\n move.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);\n }\n\n // get the text of the current block\n QString text = move.selectedText();\n\n move.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor);\n move.removeSelectedText();\n\n if (up) { // up key\n move.movePosition(QTextCursor::PreviousBlock);\n move.insertBlock();\n move.movePosition(QTextCursor::Left);\n } else { // down key\n move.movePosition(QTextCursor::EndOfBlock);\n if (move.atBlockStart()) { // empty block\n move.movePosition(QTextCursor::NextBlock);\n move.insertBlock();\n move.movePosition(QTextCursor::Left);\n } else {\n move.insertBlock();\n }\n }\n\n int start = move.position();\n move.clearSelection();\n move.insertText(text);\n int end = move.position();\n\n // reselect\n if (hasSelection) {\n move.setPosition(end);\n move.setPosition(start, QTextCursor::KeepAnchor);\n } else {\n move.setPosition(start);\n }\n\n move.endEditBlock();\n\n setTextCursor(move);\n}\n void setLineNumberEnabled(bool enabled) {\n _lineNumArea->setLineNumAreaEnabled(enabled);\n updateLineNumberAreaWidth(0);\n}\n protected:\n QTextCursor _textCursor;\n MarkdownHighlighter *_highlighter = nullptr;\n bool _highlightingEnabled;\n QStringList _ignoredClickUrlSchemata;\n QPlainTextEditSearchWidget *_searchWidget;\n QWidget *_searchFrame;\n AutoTextOptions _autoTextOptions;\n bool _mouseButtonDown = false;\n bool _centerCursor = false;\n bool _highlightCurrentLine = false;\n QColor _currentLineHighlightColor = QColor();\n uint _debounceDelay = 0;\n bool eventFilter(QObject *obj, QEvent *event) override {\n // qDebug() << event->type();\n if (event->type() == QEvent::HoverMove) {\n auto *mouseEvent = static_cast(event);\n\n QWidget *viewPort = this->viewport();\n // toggle cursor when control key has been pressed or released\n viewPort->setCursor(\n mouseEvent->modifiers().testFlag(Qt::ControlModifier)\n ? Qt::PointingHandCursor\n : Qt::IBeamCursor);\n } else if (event->type() == QEvent::KeyPress) {\n auto *keyEvent = static_cast(event);\n\n // set cursor to pointing hand if control key was pressed\n if (keyEvent->modifiers().testFlag(Qt::ControlModifier)) {\n QWidget *viewPort = this->viewport();\n viewPort->setCursor(Qt::PointingHandCursor);\n }\n\n // disallow keys if text edit hasn't focus\n if (!this->hasFocus()) {\n return true;\n }\n\n if ((keyEvent->key() == Qt::Key_Escape) && _searchWidget->isVisible()) {\n _searchWidget->deactivate();\n return true;\n } else if (keyEvent->key() == Qt::Key_Insert &&\n keyEvent->modifiers().testFlag(Qt::NoModifier)) {\n setOverwriteMode(!overwriteMode());\n\n // This solves a UI glitch if the visual cursor was not properly\n // updated when characters have different widths\n QTextCursor cursor = this->textCursor();\n cursor.movePosition(QTextCursor::Right);\n setTextCursor(cursor);\n cursor.movePosition(QTextCursor::Left);\n setTextCursor(cursor);\n\n return false;\n } else if ((keyEvent->key() == Qt::Key_Tab) ||\n (keyEvent->key() == Qt::Key_Backtab)) {\n // handle entered tab and reverse tab keys\n return handleTabEntered(keyEvent->key() == Qt::Key_Backtab);\n } else if ((keyEvent->key() == Qt::Key_F) &&\n keyEvent->modifiers().testFlag(Qt::ControlModifier)) {\n _searchWidget->activate();\n return true;\n } else if ((keyEvent->key() == Qt::Key_R) &&\n keyEvent->modifiers().testFlag(Qt::ControlModifier)) {\n _searchWidget->activateReplace();\n return true;\n // } else if (keyEvent->key() == Qt::Key_Delete) {\n } else if (keyEvent->key() == Qt::Key_Backspace) {\n return handleBackspaceEntered();\n } else if (keyEvent->key() == Qt::Key_Asterisk) {\n return handleBracketClosing(QLatin1Char('*'));\n } else if (keyEvent->key() == Qt::Key_QuoteDbl) {\n return quotationMarkCheck(QLatin1Char('\"'));\n // apostrophe bracket closing is temporary disabled because\n // apostrophes are used in different contexts\n // } else if (keyEvent->key() == Qt::Key_Apostrophe) {\n // return handleBracketClosing(\"'\");\n // underline bracket closing is temporary disabled because\n // underlines are used in different contexts\n // } else if (keyEvent->key() == Qt::Key_Underscore) {\n // return handleBracketClosing(\"_\");\n } else if (keyEvent->key() == Qt::Key_QuoteLeft) {\n return quotationMarkCheck(QLatin1Char('`'));\n } else if (keyEvent->key() == Qt::Key_AsciiTilde) {\n return handleBracketClosing(QLatin1Char('~'));\n#ifdef Q_OS_MAC\n } else if (keyEvent->modifiers().testFlag(Qt::AltModifier) &&\n keyEvent->key() == Qt::Key_ParenLeft) {\n // bracket closing for US keyboard on macOS\n return handleBracketClosing(QLatin1Char('{'), QLatin1Char('}'));\n#endif\n } else if (keyEvent->key() == Qt::Key_ParenLeft) {\n return handleBracketClosing(QLatin1Char('('), QLatin1Char(')'));\n } else if (keyEvent->key() == Qt::Key_BraceLeft) {\n return handleBracketClosing(QLatin1Char('{'), QLatin1Char('}'));\n } else if (keyEvent->key() == Qt::Key_BracketLeft) {\n return handleBracketClosing(QLatin1Char('['), QLatin1Char(']'));\n } else if (keyEvent->key() == Qt::Key_Less) {\n return handleBracketClosing(QLatin1Char('<'), QLatin1Char('>'));\n#ifdef Q_OS_MAC\n } else if (keyEvent->modifiers().testFlag(Qt::AltModifier) &&\n keyEvent->key() == Qt::Key_ParenRight) {\n // bracket closing for US keyboard on macOS\n return bracketClosingCheck(QLatin1Char('{'), QLatin1Char('}'));\n#endif\n } else if (keyEvent->key() == Qt::Key_ParenRight) {\n return bracketClosingCheck(QLatin1Char('('), QLatin1Char(')'));\n } else if (keyEvent->key() == Qt::Key_BraceRight) {\n return bracketClosingCheck(QLatin1Char('{'), QLatin1Char('}'));\n } else if (keyEvent->key() == Qt::Key_BracketRight) {\n return bracketClosingCheck(QLatin1Char('['), QLatin1Char(']'));\n } else if (keyEvent->key() == Qt::Key_Greater) {\n return bracketClosingCheck(QLatin1Char('<'), QLatin1Char('>'));\n } else if ((keyEvent->key() == Qt::Key_Return ||\n keyEvent->key() == Qt::Key_Enter) &&\n !isReadOnly() &&\n keyEvent->modifiers().testFlag(Qt::ShiftModifier)) {\n QTextCursor cursor = this->textCursor();\n cursor.insertText(\" \\n\");\n return true;\n } else if ((keyEvent->key() == Qt::Key_Return ||\n keyEvent->key() == Qt::Key_Enter) &&\n !isReadOnly() &&\n keyEvent->modifiers().testFlag(Qt::ControlModifier)) {\n QTextCursor cursor = this->textCursor();\n cursor.movePosition(QTextCursor::EndOfBlock);\n cursor.insertText(QStringLiteral(\"\\n\"));\n setTextCursor(cursor);\n return true;\n } else if (keyEvent == QKeySequence::Copy ||\n keyEvent == QKeySequence::Cut) {\n QTextCursor cursor = this->textCursor();\n if (!cursor.hasSelection()) {\n QString text;\n if (cursor.block().length() <= 1) // no content\n text = \"\\n\";\n else {\n // cursor.select(QTextCursor::BlockUnderCursor); //\n // negative, it will include the previous paragraph\n // separator\n cursor.movePosition(QTextCursor::StartOfBlock);\n cursor.movePosition(QTextCursor::EndOfBlock,\n QTextCursor::KeepAnchor);\n text = cursor.selectedText();\n if (!cursor.atEnd()) {\n text += \"\\n\";\n // this is the paragraph separator\n cursor.movePosition(QTextCursor::NextCharacter,\n QTextCursor::KeepAnchor, 1);\n }\n }\n if (keyEvent == QKeySequence::Cut) {\n if (!cursor.atEnd() && text == \"\\n\")\n cursor.deletePreviousChar();\n else\n cursor.removeSelectedText();\n cursor.movePosition(QTextCursor::StartOfBlock);\n setTextCursor(cursor);\n }\n qApp->clipboard()->setText(text);\n return true;\n }\n } else if ((keyEvent->key() == Qt::Key_Down) &&\n keyEvent->modifiers().testFlag(Qt::ControlModifier) &&\n keyEvent->modifiers().testFlag(Qt::AltModifier)) {\n // duplicate text with `Ctrl + Alt + Down`\n duplicateText();\n return true;\n#ifndef Q_OS_MAC\n } else if ((keyEvent->key() == Qt::Key_Down) &&\n keyEvent->modifiers().testFlag(Qt::ControlModifier) &&\n !keyEvent->modifiers().testFlag(Qt::ShiftModifier)) {\n // scroll the page down\n auto *scrollBar = verticalScrollBar();\n scrollBar->setSliderPosition(scrollBar->sliderPosition() + 1);\n return true;\n } else if ((keyEvent->key() == Qt::Key_Up) &&\n keyEvent->modifiers().testFlag(Qt::ControlModifier) &&\n !keyEvent->modifiers().testFlag(Qt::ShiftModifier)) {\n // scroll the page up\n auto *scrollBar = verticalScrollBar();\n scrollBar->setSliderPosition(scrollBar->sliderPosition() - 1);\n return true;\n#endif\n } else if ((keyEvent->key() == Qt::Key_Down) &&\n keyEvent->modifiers().testFlag(Qt::NoModifier)) {\n // if you are in the last line and press cursor down the cursor will\n // jump to the end of the line\n QTextCursor cursor = textCursor();\n if (cursor.position() >= document()->lastBlock().position()) {\n cursor.movePosition(QTextCursor::EndOfLine);\n\n // check if we are really in the last line, not only in\n // the last block\n if (cursor.atBlockEnd()) {\n setTextCursor(cursor);\n }\n }\n return QPlainTextEdit::eventFilter(obj, event);\n } else if ((keyEvent->key() == Qt::Key_Up) &&\n keyEvent->modifiers().testFlag(Qt::NoModifier)) {\n // if you are in the first line and press cursor up the cursor will\n // jump to the start of the line\n QTextCursor cursor = textCursor();\n QTextBlock block = document()->firstBlock();\n int endOfFirstLinePos = block.position() + block.length();\n\n if (cursor.position() <= endOfFirstLinePos) {\n cursor.movePosition(QTextCursor::StartOfLine);\n\n // check if we are really in the first line, not only in\n // the first block\n if (cursor.atBlockStart()) {\n setTextCursor(cursor);\n }\n }\n return QPlainTextEdit::eventFilter(obj, event);\n } else if (keyEvent->key() == Qt::Key_Return ||\n keyEvent->key() == Qt::Key_Enter) {\n return handleReturnEntered();\n } else if ((keyEvent->key() == Qt::Key_F3)) {\n _searchWidget->doSearch(\n !keyEvent->modifiers().testFlag(Qt::ShiftModifier));\n return true;\n } else if ((keyEvent->key() == Qt::Key_Z) &&\n (keyEvent->modifiers().testFlag(Qt::ControlModifier)) &&\n !(keyEvent->modifiers().testFlag(Qt::ShiftModifier))) {\n undo();\n return true;\n } else if ((keyEvent->key() == Qt::Key_Down) &&\n (keyEvent->modifiers().testFlag(Qt::ControlModifier)) &&\n (keyEvent->modifiers().testFlag(Qt::ShiftModifier))) {\n moveTextUpDown(false);\n return true;\n } else if ((keyEvent->key() == Qt::Key_Up) &&\n (keyEvent->modifiers().testFlag(Qt::ControlModifier)) &&\n (keyEvent->modifiers().testFlag(Qt::ShiftModifier))) {\n moveTextUpDown(true);\n return true;\n#ifdef Q_OS_MAC\n // https://github.com/pbek/QOwnNotes/issues/1593\n // https://github.com/pbek/QOwnNotes/issues/2643\n } else if (keyEvent->key() == Qt::Key_Home) {\n QTextCursor cursor = textCursor();\n // Meta is Control on macOS\n cursor.movePosition(\n keyEvent->modifiers().testFlag(Qt::MetaModifier)\n ? QTextCursor::Start\n : QTextCursor::StartOfLine,\n keyEvent->modifiers().testFlag(Qt::ShiftModifier)\n ? QTextCursor::KeepAnchor\n : QTextCursor::MoveAnchor);\n this->setTextCursor(cursor);\n return true;\n } else if (keyEvent->key() == Qt::Key_End) {\n QTextCursor cursor = textCursor();\n // Meta is Control on macOS\n cursor.movePosition(\n keyEvent->modifiers().testFlag(Qt::MetaModifier)\n ? QTextCursor::End\n : QTextCursor::EndOfLine,\n keyEvent->modifiers().testFlag(Qt::ShiftModifier)\n ? QTextCursor::KeepAnchor\n : QTextCursor::MoveAnchor);\n this->setTextCursor(cursor);\n return true;\n#endif\n }\n\n return QPlainTextEdit::eventFilter(obj, event);\n } else if (event->type() == QEvent::KeyRelease) {\n auto *keyEvent = static_cast(event);\n\n // reset cursor if control key was released\n if (keyEvent->key() == Qt::Key_Control) {\n resetMouseCursor();\n }\n\n return QPlainTextEdit::eventFilter(obj, event);\n } else if (event->type() == QEvent::MouseButtonRelease) {\n _mouseButtonDown = false;\n auto *mouseEvent = static_cast(event);\n\n // track `Ctrl + Click` in the text edit\n if ((obj == this->viewport()) &&\n (mouseEvent->button() == Qt::LeftButton) &&\n (QGuiApplication::keyboardModifiers() == Qt::ExtraButton24)) {\n // open the link (if any) at the current position\n // in the noteTextEdit\n openLinkAtCursorPosition();\n return true;\n }\n } else if (event->type() == QEvent::MouseButtonPress) {\n _mouseButtonDown = true;\n } else if (event->type() == QEvent::MouseButtonDblClick) {\n _mouseButtonDown = true;\n } else if (event->type() == QEvent::Wheel) {\n auto *wheel = dynamic_cast(event);\n\n // emit zoom signals\n if (wheel->modifiers() == Qt::ControlModifier) {\n if (wheel->angleDelta().y() > 0) {\n Q_EMIT zoomIn();\n } else {\n Q_EMIT zoomOut();\n }\n\n return true;\n }\n }\n\n return QPlainTextEdit::eventFilter(obj, event);\n}\n QMargins viewportMargins() {\n return QPlainTextEdit::viewportMargins();\n}\n bool increaseSelectedTextIndention(\n bool reverse,\n const QString &indentCharacters = QChar::fromLatin1('\\t')) {\n QTextCursor cursor = this->textCursor();\n QString selectedText = cursor.selectedText();\n\n if (!selectedText.isEmpty()) {\n // Start the selection at start of the first block of the selection\n int end = cursor.selectionEnd();\n cursor.setPosition(cursor.selectionStart());\n cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor);\n cursor.setPosition(end, QTextCursor::KeepAnchor);\n this->setTextCursor(cursor);\n selectedText = cursor.selectedText();\n\n // we need this strange newline character we are getting in the\n // selected text for newlines\n const QString newLine =\n QString::fromUtf8(QByteArray::fromHex(QByteArrayLiteral(\"e280a9\")));\n QString newText;\n\n if (reverse) {\n // un-indent text\n\n const int indentSize = indentCharacters == QStringLiteral(\"\\t\")\n ? 4\n : indentCharacters.length();\n\n // remove leading \\t or spaces in following lines\n newText = selectedText.replace(\n QRegularExpression(newLine + QStringLiteral(\"(\\\\t| {1,\") +\n QString::number(indentSize) +\n QStringLiteral(\"})\")),\n QStringLiteral(\"\\n\"));\n\n // remove leading \\t or spaces in first line\n newText.remove(QRegularExpression(QStringLiteral(\"^(\\\\t| {1,\") +\n QString::number(indentSize) +\n QStringLiteral(\"})\")));\n } else {\n // replace trailing new line to prevent an indent of the line after\n // the selection\n newText = selectedText.replace(\n QRegularExpression(QRegularExpression::escape(newLine) +\n QStringLiteral(\"$\")),\n QStringLiteral(\"\\n\"));\n\n // indent text\n newText.replace(newLine, QStringLiteral(\"\\n\") + indentCharacters)\n .prepend(indentCharacters);\n\n // remove trailing \\t\n static QRegularExpression regex1(QStringLiteral(\"\\\\t$\"));\n newText.remove(regex1);\n }\n\n // insert the new text\n cursor.insertText(newText);\n\n // update the selection to the new text\n cursor.setPosition(cursor.position() - newText.size(),\n QTextCursor::KeepAnchor);\n this->setTextCursor(cursor);\n\n return true;\n } else if (reverse) {\n const int indentSize = indentCharacters.length();\n\n // do the check as often as we have characters to un-indent\n for (int i = 1; i <= indentSize; i++) {\n // if nothing was selected but we want to reverse the indention\n // check if there is a \\t in front or after the cursor and remove it\n // if so\n const int position = cursor.position();\n\n if (!cursor.atStart()) {\n // get character in front of cursor\n cursor.setPosition(position - 1, QTextCursor::KeepAnchor);\n }\n\n // check for \\t or space in front of cursor\n static QRegularExpression regex1(QStringLiteral(\"[\\\\t ]\"));\n QRegularExpressionMatch match = regex1.match(cursor.selectedText());\n\n if (!match.hasMatch()) {\n // (select to) check for \\t or space after the cursor\n cursor.setPosition(position);\n\n if (!cursor.atEnd()) {\n cursor.setPosition(position + 1, QTextCursor::KeepAnchor);\n }\n }\n\n match = regex1.match(cursor.selectedText());\n\n if (match.hasMatch()) {\n cursor.removeSelectedText();\n }\n\n cursor = this->textCursor();\n }\n\n return true;\n }\n\n // else just insert indentCharacters\n cursor.insertText(indentCharacters);\n\n return true;\n}\n bool handleTabEntered(bool reverse, const QString &indentCharacters =\n QChar::fromLatin1('\\t')) {\n if (isReadOnly()) {\n return true;\n }\n\n QTextCursor cursor = this->textCursor();\n\n // only check for lists if we haven't a text selected\n if (cursor.selectedText().isEmpty()) {\n cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);\n const QString currentLineText = cursor.selectedText();\n\n // check if we want to indent or un-indent an ordered list\n // Valid listCharacters: '+ ', '-' , '* ', '+ [ ] ', '+ [x] ', '- [ ] ',\n // '- [x] ', '- [-] ', '* [ ] ', '* [x] '.\n static QRegularExpression regex1(\n R\"(^(\\s*)([+|\\-|\\*] \\[(x|-| )\\]|[+\\-\\*])(\\s+)$)\");\n QRegularExpressionMatchIterator i = regex1.globalMatch(currentLineText);\n\n if (i.hasNext()) {\n QRegularExpressionMatch match = i.next();\n QString whitespaces = match.captured(1);\n const QString listCharacter = match.captured(2);\n const QString whitespaceCharacter = match.captured(4);\n\n // add or remove one tabulator key\n if (reverse) {\n // remove one set of indentCharacters or a tabulator\n whitespaces.remove(QRegularExpression(\n QStringLiteral(\"^(\\\\t|\") +\n QRegularExpression::escape(indentCharacters) +\n QStringLiteral(\")\")));\n\n } else {\n whitespaces += indentCharacters;\n }\n\n cursor.insertText(whitespaces + listCharacter +\n whitespaceCharacter);\n return true;\n }\n\n // check if we want to indent or un-indent an ordered list\n static QRegularExpression regex2(R\"(^(\\s*)(\\d+)([\\.|\\)])(\\s+)$)\");\n i = regex2.globalMatch(currentLineText);\n\n if (i.hasNext()) {\n const QRegularExpressionMatch match = i.next();\n QString whitespaces = match.captured(1);\n const QString listCharacter = match.captured(2);\n const QString listMarker = match.captured(3);\n const QString whitespaceCharacter = match.captured(4);\n\n // add or remove one tabulator key\n if (reverse) {\n whitespaces.chop(1);\n } else {\n whitespaces += indentCharacters;\n }\n\n cursor.insertText(whitespaces + listCharacter + listMarker +\n whitespaceCharacter);\n return true;\n }\n }\n\n // check if we want to indent the whole text\n return increaseSelectedTextIndention(reverse, indentCharacters);\n}\n QMap parseMarkdownUrlsFromText(const QString &text) {\n QMap urlMap;\n QRegularExpressionMatchIterator iterator;\n\n // match urls like this: \n // re = QRegularExpression(\"(<(.+?:\\\\/\\\\/.+?)>)\");\n static QRegularExpression regex1(QStringLiteral(\"(<(.+?)>)\"));\n iterator = regex1.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString linkText = match.captured(1);\n QString url = match.captured(2);\n urlMap[linkText] = url;\n }\n\n // match urls like this: [this url](http://mylink)\n // QRegularExpression re(\"(\\\\[.*?\\\\]\\\\((.+?:\\\\/\\\\/.+?)\\\\))\");\n static QRegularExpression regex2(R\"((\\[.*?\\]\\((.+?)\\)))\");\n iterator = regex2.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString linkText = match.captured(1);\n QString url = match.captured(2);\n urlMap[linkText] = url;\n }\n\n // match urls like this: http://mylink\n static QRegularExpression regex3(R\"(\\b\\w+?:\\/\\/[^\\s]+[^\\s>\\)])\");\n iterator = regex3.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString url = match.captured(0);\n urlMap[url] = url;\n }\n\n // match urls like this: www.github.com\n static QRegularExpression regex4(R\"(\\bwww\\.[^\\s]+\\.[^\\s]+\\b)\");\n iterator = regex4.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString url = match.captured(0);\n urlMap[url] = QStringLiteral(\"http://\") + url;\n }\n\n // match reference urls like this: [this url][1] with this later:\n // [1]: http://domain\n static QRegularExpression regex5(R\"((\\[.*?\\]\\[(.+?)\\]))\");\n iterator = regex5.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString linkText = match.captured(1);\n QString referenceId = match.captured(2);\n\n // search for the referenced url in the whole text edit\n // QRegularExpression refRegExp(\n // \"\\\\[\" + QRegularExpression::escape(referenceId) +\n // \"\\\\]: (.+?:\\\\/\\\\/.+)\");\n QRegularExpression refRegExp(QStringLiteral(\"\\\\[\") +\n QRegularExpression::escape(referenceId) +\n QStringLiteral(\"\\\\]: (.+)\"));\n QRegularExpressionMatch urlMatch = refRegExp.match(toPlainText());\n\n if (urlMatch.hasMatch()) {\n QString url = urlMatch.captured(1);\n urlMap[linkText] = url;\n }\n }\n\n return urlMap;\n}\n bool handleReturnEntered() {\n if (isReadOnly()) {\n return true;\n }\n\n // This will be the main cursor to add or remove text\n QTextCursor cursor = this->textCursor();\n\n // We need a 2nd cursor to get the text of the current block without moving\n // the main cursor that is used to remove the selected text\n QTextCursor cursor2 = this->textCursor();\n cursor2.select(QTextCursor::BlockUnderCursor);\n const QString currentLineText = cursor2.selectedText().trimmed();\n\n const int position = cursor.position();\n const bool cursorAtBlockStart = cursor.atBlockStart();\n cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);\n const QString currentLinePartialText = cursor.selectedText();\n\n // if return is pressed and there is just an unordered list symbol then we\n // want to remove the list symbol Valid listCharacters: '+ ', '-' , '* ', '+\n // [ ] ', '+ [x] ', '- [ ] ', '- [-] ', '- [x] ', '* [ ] ', '* [x] '.\n static QRegularExpression regex1(\n R\"(^(\\s*)([+|\\-|\\*] \\[(x|-| |)\\]|[+\\-\\*])(\\s+)$)\");\n QRegularExpressionMatchIterator iterator =\n regex1.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n cursor.removeSelectedText();\n return true;\n }\n\n // if return is pressed and there is just an ordered list symbol then we\n // want to remove the list symbol\n static QRegularExpression regex2(R\"(^(\\s*)(\\d+[\\.|\\)])(\\s+)$)\");\n iterator = regex2.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n qDebug() << cursor.selectedText();\n cursor.removeSelectedText();\n return true;\n }\n\n // Check if we are in an unordered list.\n // We are in a list when we have '* ', '- ' or '+ ', possibly with preceding\n // whitespace. If e.g. user has entered '**text**' and pressed enter - we\n // don't want to do more list-stuff.\n QString currentLine = currentLinePartialText.trimmed();\n QChar char0;\n QChar char1;\n if (currentLine.length() >= 1) char0 = currentLine.at(0);\n if (currentLine.length() >= 2) char1 = currentLine.at(1);\n const bool inList =\n ((char0 == QLatin1Char('*') || char0 == QLatin1Char('-') ||\n char0 == QLatin1Char('+')) &&\n char1 == QLatin1Char(' '));\n\n if (inList) {\n // if the current line starts with a list character (possibly after\n // whitespaces) add the whitespaces at the next line too\n // Valid listCharacters: '+ ', '-' , '* ', '+ [ ] ', '+ [x] ', '- [ ] ',\n // '- [x] ', '- [-] ', '* [ ] ', '* [x] '.\n static QRegularExpression regex3(\n R\"(^(\\s*)([+|\\-|\\*] \\[(x|-| |)\\]|[+\\-\\*])(\\s+))\");\n iterator = regex3.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n const QString whitespaces = match.captured(1);\n QString listCharacter = match.captured(2);\n const QString whitespaceCharacter = match.captured(4);\n\n static QRegularExpression regex4(R\"(^([+|\\-|\\*]) \\[(x| |\\-|)\\])\");\n // start new checkbox list item with an unchecked checkbox\n iterator = regex4.globalMatch(listCharacter);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match1 = iterator.next();\n const QString realListCharacter = match1.captured(1);\n listCharacter = realListCharacter + QStringLiteral(\" [ ]\");\n }\n\n cursor.setPosition(position);\n cursor.insertText(\"\\n\" + whitespaces + listCharacter +\n whitespaceCharacter);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n }\n\n // check for ordered lists and increment the list number in the next line\n static QRegularExpression regex5(R\"(^(\\s*)(\\d+)([\\.|\\)])(\\s+))\");\n iterator = regex5.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n const QString whitespaces = match.captured(1);\n const uint listNumber = match.captured(2).toUInt();\n const QString listMarker = match.captured(3);\n const QString whitespaceCharacter = match.captured(4);\n\n cursor.setPosition(position);\n cursor.insertText(\"\\n\" + whitespaces + QString::number(listNumber + 1) +\n listMarker + whitespaceCharacter);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n\n // intent next line with same whitespaces as in current line\n static QRegularExpression regex6(R\"(^(\\s+))\");\n iterator = regex6.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n const QString whitespaces = match.captured(1);\n\n cursor.setPosition(position);\n cursor.insertText(\"\\n\" + whitespaces);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n\n // Add new list item above current line if we are at the start the line of a\n // list item\n if (cursorAtBlockStart) {\n static QRegularExpression regex7(\n R\"(^([+|\\-|\\*] \\[(x|-| |)\\]|[+\\-\\*])(\\s+))\");\n iterator = regex7.globalMatch(currentLineText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n QString listCharacter = match.captured(1);\n const QString whitespaceCharacter = match.captured(3);\n\n static QRegularExpression regex8(R\"(^([+|\\-|\\*]) \\[(x| |\\-|)\\])\");\n // start new checkbox list item with an unchecked checkbox\n iterator = regex8.globalMatch(listCharacter);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match1 = iterator.next();\n const QString realListCharacter = match1.captured(1);\n listCharacter = realListCharacter + QStringLiteral(\" [ ]\");\n }\n\n cursor.setPosition(position);\n // Enter new list item above current line\n cursor.insertText(listCharacter + whitespaceCharacter + \"\\n\");\n // Move the cursor at the end of the new list item\n cursor.movePosition(QTextCursor::Left);\n setTextCursor(cursor);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n }\n\n return false;\n}\n bool handleBracketClosing(const QChar openingCharacter,\n QChar closingCharacter = QChar()) {\n // check if bracket closing or read-only are enabled\n if (!(_autoTextOptions & AutoTextOption::BracketClosing) || isReadOnly()) {\n return false;\n }\n\n QTextCursor cursor = textCursor();\n\n if (closingCharacter.isNull()) {\n closingCharacter = openingCharacter;\n }\n\n const QString selectedText = cursor.selectedText();\n\n // When user currently has text selected, we prepend the openingCharacter\n // and append the closingCharacter. E.g. 'text' -> '(text)'. We keep the\n // current selectedText selected.\n if (!selectedText.isEmpty()) {\n // Insert. The selectedText is overwritten.\n const QString newText =\n openingCharacter + selectedText + closingCharacter;\n cursor.insertText(newText);\n\n // Re-select the selectedText.\n const int selectionEnd = cursor.position() - 1;\n const int selectionStart = selectionEnd - selectedText.length();\n\n cursor.setPosition(selectionStart);\n cursor.setPosition(selectionEnd, QTextCursor::KeepAnchor);\n this->setTextCursor(cursor);\n _handleBracketClosingUsed = true;\n return true;\n }\n\n // get the current text from the block (inserted character not included)\n // Remove whitespace at start of string (e.g. in multilevel-lists).\n static QRegularExpression regex1(\"^\\\\s+\");\n const QString text = cursor.block().text().remove(regex1);\n\n const int pib = cursor.positionInBlock();\n bool isPreviousAsterisk =\n pib > 0 && pib < text.length() && text.at(pib - 1) == '*';\n bool isNextAsterisk = pib < text.length() && text.at(pib) == '*';\n bool isMaybeBold = isPreviousAsterisk && isNextAsterisk;\n if (pib < text.length() && !isMaybeBold && !text.at(pib).isSpace()) {\n return false;\n }\n\n // Default positions to move the cursor back.\n int cursorSubtract = 1;\n // Special handling for `*` opening character, as this could be:\n // - start of a list (or sublist);\n // - start of a bold text;\n if (openingCharacter == QLatin1Char('*')) {\n // don't auto complete in code block\n bool isInCode =\n MarkdownHighlighter::isCodeBlock(cursor.block().userState());\n // we only do auto completion if there is a space before the cursor pos\n bool hasSpaceOrAsteriskBefore = !text.isEmpty() && pib > 0 &&\n (text.at(pib - 1).isSpace() ||\n text.at(pib - 1) == QLatin1Char('*'));\n // This could be the start of a list, don't autocomplete.\n bool isEmpty = text.isEmpty();\n\n if (isInCode || !hasSpaceOrAsteriskBefore || isEmpty) {\n return false;\n }\n\n // bold\n if (isPreviousAsterisk && isNextAsterisk) {\n cursorSubtract = 1;\n }\n\n // User wants: '**'.\n // Not the start of a list, probably bold text. We autocomplete with\n // extra closingCharacter and cursorSubtract to 'catchup'.\n if (text == QLatin1String(\"*\")) {\n cursor.insertText(QStringLiteral(\"*\"));\n cursorSubtract = 2;\n }\n }\n\n // Auto-completion for ``` pair\n if (openingCharacter == QLatin1Char('`')) {\n#if QT_VERSION < QT_VERSION_CHECK(5, 12, 0)\n if (QRegExp(QStringLiteral(\"[^`]*``\")).exactMatch(text)) {\n#else\n if (QRegularExpression(\n QRegularExpression::anchoredPattern(QStringLiteral(\"[^`]*``\")))\n .match(text)\n .hasMatch()) {\n#endif\n cursor.insertText(QStringLiteral(\"``\"));\n cursorSubtract = 3;\n }\n }\n\n // don't auto complete in code block\n if (openingCharacter == QLatin1Char('<') &&\n MarkdownHighlighter::isCodeBlock(cursor.block().userState())) {\n return false;\n }\n\n cursor.beginEditBlock();\n cursor.insertText(openingCharacter);\n cursor.insertText(closingCharacter);\n cursor.setPosition(cursor.position() - cursorSubtract);\n cursor.endEditBlock();\n\n setTextCursor(cursor);\n return true;\n}\n\n/**\n * Checks if the closing character should be output or not\n *\n * @param openingCharacter\n * @param closingCharacter\n * @return\n */\nbool QMarkdownTextEdit::bracketClosingCheck(const QChar openingCharacter,\n QChar closingCharacter) {\n // check if bracket closing or read-only are enabled\n if (!(_autoTextOptions & AutoTextOption::BracketClosing) || isReadOnly()) {\n return false;\n }\n\n if (closingCharacter.isNull()) {\n closingCharacter = openingCharacter;\n }\n\n QTextCursor cursor = textCursor();\n const int positionInBlock = cursor.positionInBlock();\n\n // get the current text from the block\n const QString text = cursor.block().text();\n const int textLength = text.length();\n\n // if we are at the end of the line we just want to enter the character\n if (positionInBlock >= textLength) {\n return false;\n }\n\n const QChar currentChar = text.at(positionInBlock);\n\n // if (closingCharacter == openingCharacter) {\n\n // }\n\n qDebug() << __func__ << \" - 'currentChar': \" << currentChar;\n\n // if the current character is not the closing character we just want to\n // enter the character\n if (currentChar != closingCharacter) {\n return false;\n }\n\n const QString leftText = text.left(positionInBlock);\n const int openingCharacterCount = leftText.count(openingCharacter);\n const int closingCharacterCount = leftText.count(closingCharacter);\n\n // if there were enough opening characters just enter the character\n if (openingCharacterCount < (closingCharacterCount + 1)) {\n return false;\n }\n\n // move the cursor to the right and don't enter the character\n cursor.movePosition(QTextCursor::Right);\n setTextCursor(cursor);\n return true;\n}\n\n/**\n * Checks if the closing character should be output or not or if a closing\n * character after an opening character if needed\n *\n * @param quotationCharacter\n * @return\n */\nbool QMarkdownTextEdit::quotationMarkCheck(const QChar quotationCharacter) {\n // check if bracket closing or read-only are enabled\n if (!(_autoTextOptions & AutoTextOption::BracketClosing) || isReadOnly()) {\n return false;\n }\n\n QTextCursor cursor = textCursor();\n const int positionInBlock = cursor.positionInBlock();\n\n // get the current text from the block\n const QString text = cursor.block().text();\n const int textLength = text.length();\n\n // if last char is not space, we are at word end, no autocompletion\n const bool isBacktick = quotationCharacter == '`';\n if (!isBacktick && positionInBlock != 0 &&\n !text.at(positionInBlock - 1).isSpace()) {\n return false;\n }\n\n // if we are at the end of the line we just want to enter the character\n if (positionInBlock >= textLength) {\n return handleBracketClosing(quotationCharacter);\n }\n\n const QChar currentChar = text.at(positionInBlock);\n\n // if the current character is not the quotation character we just want to\n // enter the character\n if (currentChar != quotationCharacter) {\n return handleBracketClosing(quotationCharacter);\n }\n\n // move the cursor to the right and don't enter the character\n cursor.movePosition(QTextCursor::Right);\n setTextCursor(cursor);\n return true;\n}\n\n/***********************************\n * helper methods for char removal\n * Rules for (') and (\"):\n * if [sp]\" -> opener (sp = space)\n * if \"[sp] -> closer\n ***********************************/\nbool isQuotOpener(int position, const QString &text) {\n if (position == 0) return true;\n const int prevCharPos = position - 1;\n return text.at(prevCharPos).isSpace();\n}\nbool isQuotCloser(int position, const QString &text) {\n const int nextCharPos = position + 1;\n if (nextCharPos >= text.length()) return true;\n return text.at(nextCharPos).isSpace();\n}\n\n/**\n * Handles removing of matching brackets and other Markdown characters\n * Only works with backspace to remove text\n *\n * @return\n */\nbool QMarkdownTextEdit::handleBackspaceEntered() {\n if (!(_autoTextOptions & AutoTextOption::BracketRemoval) || isReadOnly()) {\n return false;\n }\n\n QTextCursor cursor = textCursor();\n\n // return if some text was selected\n if (!cursor.selectedText().isEmpty()) {\n return false;\n }\n\n int position = cursor.position();\n const int positionInBlock = cursor.positionInBlock();\n int block = cursor.block().blockNumber();\n\n if (_highlighter)\n if (_highlighter->isPosInACodeSpan(block, positionInBlock - 1))\n return false;\n\n // return if backspace was pressed at the beginning of a block\n if (positionInBlock == 0) {\n return false;\n }\n\n // get the current text from the block\n const QString text = cursor.block().text();\n\n char charToRemove{};\n\n // current char\n const char charInFront = text.at(positionInBlock - 1).toLatin1();\n\n if (charInFront == '*')\n return handleCharRemoval(MarkdownHighlighter::RangeType::Emphasis,\n block, positionInBlock - 1);\n else if (charInFront == '`')\n return handleCharRemoval(MarkdownHighlighter::RangeType::CodeSpan,\n block, positionInBlock - 1);\n\n // handle removal of \", ', and brackets\n\n // is it opener?\n int pos = _openingCharacters.indexOf(charInFront);\n // for \" and '\n bool isOpener = false;\n bool isCloser = false;\n if (pos == 5 || pos == 6) {\n isOpener = isQuotOpener(positionInBlock - 1, text);\n } else {\n isOpener = pos != -1;\n }\n if (isOpener) {\n charToRemove = _closingCharacters.at(pos);\n } else {\n // is it closer?\n pos = _closingCharacters.indexOf(charInFront);\n if (pos == 5 || pos == 6)\n isCloser = isQuotCloser(positionInBlock - 1, text);\n else\n isCloser = pos != -1;\n if (isCloser)\n charToRemove = _openingCharacters.at(pos);\n else\n return false;\n }\n\n int charToRemoveIndex = -1;\n if (isOpener) {\n bool closer = true;\n charToRemoveIndex = text.indexOf(charToRemove, positionInBlock);\n if (charToRemoveIndex == -1) return false;\n if (pos == 5 || pos == 6)\n closer = isQuotCloser(charToRemoveIndex, text);\n if (!closer) return false;\n cursor.setPosition(position + (charToRemoveIndex - positionInBlock));\n cursor.deleteChar();\n } else if (isCloser) {\n charToRemoveIndex = text.lastIndexOf(charToRemove, positionInBlock - 2);\n if (charToRemoveIndex == -1) return false;\n bool opener = true;\n if (pos == 5 || pos == 6)\n opener = isQuotOpener(charToRemoveIndex, text);\n if (!opener) return false;\n const int pos = position - (positionInBlock - charToRemoveIndex);\n cursor.setPosition(pos);\n cursor.deleteChar();\n position -= 1;\n } else {\n charToRemoveIndex = text.lastIndexOf(charToRemove, positionInBlock - 2);\n if (charToRemoveIndex == -1) return false;\n const int pos = position - (positionInBlock - charToRemoveIndex);\n cursor.setPosition(pos);\n cursor.deleteChar();\n position -= 1;\n }\n\n // moving the cursor back to the old position so the previous character\n // can be removed\n cursor.setPosition(position);\n setTextCursor(cursor);\n return false;\n}\n\nbool QMarkdownTextEdit::handleCharRemoval(MarkdownHighlighter::RangeType type,\n int block, int position) {\n if (!_highlighter) return false;\n\n auto range = _highlighter->findPositionInRanges(type, block, position);\n if (range == QPair{-1, -1}) return false;\n\n int charToRemovePos = range.first;\n if (position == range.first) charToRemovePos = range.second;\n\n QTextCursor cursor = textCursor();\n auto gpos = cursor.position();\n\n if (charToRemovePos > position) {\n cursor.setPosition(gpos + (charToRemovePos - (position + 1)));\n } else {\n cursor.setPosition(gpos - (position - charToRemovePos + 1));\n gpos--;\n }\n\n cursor.deleteChar();\n cursor.setPosition(gpos);\n setTextCursor(cursor);\n return false;\n}\n\nvoid QMarkdownTextEdit::updateLineNumAreaGeometry() {\n const auto contentsRect = this->contentsRect();\n const QRect newGeometry = {contentsRect.left(), contentsRect.top(),\n _lineNumArea->sizeHint().width(),\n contentsRect.height()};\n auto oldGeometry = _lineNumArea->geometry();\n if (newGeometry != oldGeometry) {\n _lineNumArea->setGeometry(newGeometry);\n }\n}\n\nvoid QMarkdownTextEdit::resizeEvent(QResizeEvent *event) {\n QPlainTextEdit::resizeEvent(event);\n updateLineNumAreaGeometry();\n}\n\n/**\n * Increases (or decreases) the indention of the selected text\n * (if there is a text selected) in the noteTextEdit\n * @return\n */\nbool QMarkdownTextEdit::increaseSelectedTextIndention(\n bool reverse, const QString &indentCharacters) {\n QTextCursor cursor = this->textCursor();\n QString selectedText = cursor.selectedText();\n\n if (!selectedText.isEmpty()) {\n // Start the selection at start of the first block of the selection\n int end = cursor.selectionEnd();\n cursor.setPosition(cursor.selectionStart());\n cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor);\n cursor.setPosition(end, QTextCursor::KeepAnchor);\n this->setTextCursor(cursor);\n selectedText = cursor.selectedText();\n\n // we need this strange newline character we are getting in the\n // selected text for newlines\n const QString newLine =\n QString::fromUtf8(QByteArray::fromHex(QByteArrayLiteral(\"e280a9\")));\n QString newText;\n\n if (reverse) {\n // un-indent text\n\n const int indentSize = indentCharacters == QStringLiteral(\"\\t\")\n ? 4\n : indentCharacters.length();\n\n // remove leading \\t or spaces in following lines\n newText = selectedText.replace(\n QRegularExpression(newLine + QStringLiteral(\"(\\\\t| {1,\") +\n QString::number(indentSize) +\n QStringLiteral(\"})\")),\n QStringLiteral(\"\\n\"));\n\n // remove leading \\t or spaces in first line\n newText.remove(QRegularExpression(QStringLiteral(\"^(\\\\t| {1,\") +\n QString::number(indentSize) +\n QStringLiteral(\"})\")));\n } else {\n // replace trailing new line to prevent an indent of the line after\n // the selection\n newText = selectedText.replace(\n QRegularExpression(QRegularExpression::escape(newLine) +\n QStringLiteral(\"$\")),\n QStringLiteral(\"\\n\"));\n\n // indent text\n newText.replace(newLine, QStringLiteral(\"\\n\") + indentCharacters)\n .prepend(indentCharacters);\n\n // remove trailing \\t\n static QRegularExpression regex1(QStringLiteral(\"\\\\t$\"));\n newText.remove(regex1);\n }\n\n // insert the new text\n cursor.insertText(newText);\n\n // update the selection to the new text\n cursor.setPosition(cursor.position() - newText.size(),\n QTextCursor::KeepAnchor);\n this->setTextCursor(cursor);\n\n return true;\n } else if (reverse) {\n const int indentSize = indentCharacters.length();\n\n // do the check as often as we have characters to un-indent\n for (int i = 1; i <= indentSize; i++) {\n // if nothing was selected but we want to reverse the indention\n // check if there is a \\t in front or after the cursor and remove it\n // if so\n const int position = cursor.position();\n\n if (!cursor.atStart()) {\n // get character in front of cursor\n cursor.setPosition(position - 1, QTextCursor::KeepAnchor);\n }\n\n // check for \\t or space in front of cursor\n static QRegularExpression regex1(QStringLiteral(\"[\\\\t ]\"));\n QRegularExpressionMatch match = regex1.match(cursor.selectedText());\n\n if (!match.hasMatch()) {\n // (select to) check for \\t or space after the cursor\n cursor.setPosition(position);\n\n if (!cursor.atEnd()) {\n cursor.setPosition(position + 1, QTextCursor::KeepAnchor);\n }\n }\n\n match = regex1.match(cursor.selectedText());\n\n if (match.hasMatch()) {\n cursor.removeSelectedText();\n }\n\n cursor = this->textCursor();\n }\n\n return true;\n }\n\n // else just insert indentCharacters\n cursor.insertText(indentCharacters);\n\n return true;\n}\n\n/**\n * @brief Opens the link (if any) at the current cursor position\n */\nbool QMarkdownTextEdit::openLinkAtCursorPosition() {\n QTextCursor cursor = this->textCursor();\n const int clickedPosition = cursor.position();\n\n // select the text in the clicked block and find out on\n // which position we clicked\n cursor.movePosition(QTextCursor::StartOfBlock);\n const int positionFromStart = clickedPosition - cursor.position();\n cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);\n\n const QString selectedText = cursor.selectedText();\n\n // find out which url in the selected text was clicked\n const QString urlString =\n getMarkdownUrlAtPosition(selectedText, positionFromStart);\n const QUrl url = QUrl(urlString);\n const bool isRelativeFileUrl =\n urlString.startsWith(QLatin1String(\"file://..\"));\n const bool isLegacyAttachmentUrl =\n urlString.startsWith(QLatin1String(\"file://attachments\"));\n\n qDebug() << __func__ << \" - 'emit urlClicked( urlString )': \" << urlString;\n\n Q_EMIT urlClicked(urlString);\n\n if ((url.isValid() && isValidUrl(urlString)) || isRelativeFileUrl ||\n isLegacyAttachmentUrl) {\n // ignore some schemata\n if (!(_ignoredClickUrlSchemata.contains(url.scheme()) ||\n isRelativeFileUrl || isLegacyAttachmentUrl)) {\n // open the url\n openUrl(urlString);\n }\n\n return true;\n }\n\n return false;\n}\n\n/**\n * Checks if urlString is a valid url\n *\n * @param urlString\n * @return\n */\nbool QMarkdownTextEdit::isValidUrl(const QString &urlString) {\n static QRegularExpression regex(R\"(^\\w+:\\/\\/.+)\");\n const QRegularExpressionMatch match = regex.match(urlString);\n return match.hasMatch();\n}\n\n/**\n * Handles clicked urls\n *\n * examples:\n * - opens the webpage\n * - opens the file\n * \"/path/to/my/file/QOwnNotes.pdf\" if the operating system supports that\n * handler\n */\nvoid QMarkdownTextEdit::openUrl(const QString &urlString) {\n qDebug() << \"QMarkdownTextEdit \" << __func__\n << \" - 'urlString': \" << urlString;\n\n QDesktopServices::openUrl(QUrl(urlString));\n}\n\n/**\n * @brief Returns the highlighter instance\n * @return\n */\nMarkdownHighlighter *QMarkdownTextEdit::highlighter() { return _highlighter; }\n\n/**\n * @brief Returns the searchWidget instance\n * @return\n */\nQPlainTextEditSearchWidget *QMarkdownTextEdit::searchWidget() {\n return _searchWidget;\n}\n\n/**\n * @brief Sets url schemata that will be ignored when clicked on\n * @param urlSchemes\n */\nvoid QMarkdownTextEdit::setIgnoredClickUrlSchemata(\n QStringList ignoredUrlSchemata) {\n _ignoredClickUrlSchemata = std::move(ignoredUrlSchemata);\n}\n\n/**\n * @brief Returns a map of parsed Markdown urls with their link texts as key\n *\n * @param text\n * @return parsed urls\n */\nQMap QMarkdownTextEdit::parseMarkdownUrlsFromText(\n const QString &text) {\n QMap urlMap;\n QRegularExpressionMatchIterator iterator;\n\n // match urls like this: \n // re = QRegularExpression(\"(<(.+?:\\\\/\\\\/.+?)>)\");\n static QRegularExpression regex1(QStringLiteral(\"(<(.+?)>)\"));\n iterator = regex1.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString linkText = match.captured(1);\n QString url = match.captured(2);\n urlMap[linkText] = url;\n }\n\n // match urls like this: [this url](http://mylink)\n // QRegularExpression re(\"(\\\\[.*?\\\\]\\\\((.+?:\\\\/\\\\/.+?)\\\\))\");\n static QRegularExpression regex2(R\"((\\[.*?\\]\\((.+?)\\)))\");\n iterator = regex2.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString linkText = match.captured(1);\n QString url = match.captured(2);\n urlMap[linkText] = url;\n }\n\n // match urls like this: http://mylink\n static QRegularExpression regex3(R\"(\\b\\w+?:\\/\\/[^\\s]+[^\\s>\\)])\");\n iterator = regex3.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString url = match.captured(0);\n urlMap[url] = url;\n }\n\n // match urls like this: www.github.com\n static QRegularExpression regex4(R\"(\\bwww\\.[^\\s]+\\.[^\\s]+\\b)\");\n iterator = regex4.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString url = match.captured(0);\n urlMap[url] = QStringLiteral(\"http://\") + url;\n }\n\n // match reference urls like this: [this url][1] with this later:\n // [1]: http://domain\n static QRegularExpression regex5(R\"((\\[.*?\\]\\[(.+?)\\]))\");\n iterator = regex5.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString linkText = match.captured(1);\n QString referenceId = match.captured(2);\n\n // search for the referenced url in the whole text edit\n // QRegularExpression refRegExp(\n // \"\\\\[\" + QRegularExpression::escape(referenceId) +\n // \"\\\\]: (.+?:\\\\/\\\\/.+)\");\n QRegularExpression refRegExp(QStringLiteral(\"\\\\[\") +\n QRegularExpression::escape(referenceId) +\n QStringLiteral(\"\\\\]: (.+)\"));\n QRegularExpressionMatch urlMatch = refRegExp.match(toPlainText());\n\n if (urlMatch.hasMatch()) {\n QString url = urlMatch.captured(1);\n urlMap[linkText] = url;\n }\n }\n\n return urlMap;\n}\n\n/**\n * @brief Returns the Markdown url at position\n * @param text\n * @param position\n * @return url string\n */\nQString QMarkdownTextEdit::getMarkdownUrlAtPosition(const QString &text,\n int position) {\n QString url;\n\n // get a map of parsed Markdown urls with their link texts as key\n const QMap urlMap = parseMarkdownUrlsFromText(text);\n QMap::const_iterator i = urlMap.constBegin();\n for (; i != urlMap.constEnd(); ++i) {\n const QString &linkText = i.key();\n const QString &urlString = i.value();\n\n const int foundPositionStart = text.indexOf(linkText);\n\n if (foundPositionStart >= 0) {\n // calculate end position of found linkText\n const int foundPositionEnd = foundPositionStart + linkText.size();\n\n // check if position is in found string range\n if ((position >= foundPositionStart) &&\n (position <= foundPositionEnd)) {\n url = urlString;\n break;\n }\n }\n }\n\n return url;\n}\n\n/**\n * @brief Duplicates the text in the text edit\n */\nvoid QMarkdownTextEdit::duplicateText() {\n if (isReadOnly()) {\n return;\n }\n\n QTextCursor cursor = this->textCursor();\n QString selectedText = cursor.selectedText();\n\n // duplicate line if no text was selected\n if (selectedText.isEmpty()) {\n const int position = cursor.position();\n\n // select the whole line\n cursor.movePosition(QTextCursor::StartOfBlock);\n cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);\n\n const int positionDiff = cursor.position() - position;\n selectedText = \"\\n\" + cursor.selectedText();\n\n // insert text with new line at end of the selected line\n cursor.setPosition(cursor.selectionEnd());\n cursor.insertText(selectedText);\n\n // set the position to same position it was in the duplicated line\n cursor.setPosition(cursor.position() - positionDiff);\n } else {\n // duplicate selected text\n cursor.setPosition(cursor.selectionEnd());\n const int selectionStart = cursor.position();\n\n // insert selected text\n cursor.insertText(selectedText);\n const int selectionEnd = cursor.position();\n\n // select the inserted text\n cursor.setPosition(selectionStart);\n cursor.setPosition(selectionEnd, QTextCursor::KeepAnchor);\n }\n\n this->setTextCursor(cursor);\n}\n\nvoid QMarkdownTextEdit::setText(const QString &text) { setPlainText(text); }\n\nvoid QMarkdownTextEdit::setPlainText(const QString &text) {\n // clear the dirty blocks vector to increase performance and prevent\n // a possible crash in QSyntaxHighlighter::rehighlightBlock\n if (_highlighter) _highlighter->clearDirtyBlocks();\n\n QPlainTextEdit::setPlainText(text);\n adjustRightMargin();\n}\n\n/**\n * Uses another widget as parent for the search widget\n */\nvoid QMarkdownTextEdit::initSearchFrame(QWidget *searchFrame, bool darkMode) {\n _searchFrame = searchFrame;\n\n // remove the search widget from our layout\n layout()->removeWidget(_searchWidget);\n\n QLayout *layout = _searchFrame->layout();\n\n // create a grid layout for the frame and add the search widget to it\n if (layout == nullptr) {\n layout = new QVBoxLayout(_searchFrame);\n layout->setSpacing(0);\n layout->setContentsMargins(0, 0, 0, 0);\n }\n\n _searchWidget->setDarkMode(darkMode);\n layout->addWidget(_searchWidget);\n _searchFrame->setLayout(layout);\n}\n\n/**\n * Hides the text edit and the search widget\n */\nvoid QMarkdownTextEdit::hide() {\n _searchWidget->hide();\n QWidget::hide();\n}\n\n/**\n * Handles an entered return key\n */\nbool QMarkdownTextEdit::handleReturnEntered() {\n if (isReadOnly()) {\n return true;\n }\n\n // This will be the main cursor to add or remove text\n QTextCursor cursor = this->textCursor();\n\n // We need a 2nd cursor to get the text of the current block without moving\n // the main cursor that is used to remove the selected text\n QTextCursor cursor2 = this->textCursor();\n cursor2.select(QTextCursor::BlockUnderCursor);\n const QString currentLineText = cursor2.selectedText().trimmed();\n\n const int position = cursor.position();\n const bool cursorAtBlockStart = cursor.atBlockStart();\n cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);\n const QString currentLinePartialText = cursor.selectedText();\n\n // if return is pressed and there is just an unordered list symbol then we\n // want to remove the list symbol Valid listCharacters: '+ ', '-' , '* ', '+\n // [ ] ', '+ [x] ', '- [ ] ', '- [-] ', '- [x] ', '* [ ] ', '* [x] '.\n static QRegularExpression regex1(\n R\"(^(\\s*)([+|\\-|\\*] \\[(x|-| |)\\]|[+\\-\\*])(\\s+)$)\");\n QRegularExpressionMatchIterator iterator =\n regex1.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n cursor.removeSelectedText();\n return true;\n }\n\n // if return is pressed and there is just an ordered list symbol then we\n // want to remove the list symbol\n static QRegularExpression regex2(R\"(^(\\s*)(\\d+[\\.|\\)])(\\s+)$)\");\n iterator = regex2.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n qDebug() << cursor.selectedText();\n cursor.removeSelectedText();\n return true;\n }\n\n // Check if we are in an unordered list.\n // We are in a list when we have '* ', '- ' or '+ ', possibly with preceding\n // whitespace. If e.g. user has entered '**text**' and pressed enter - we\n // don't want to do more list-stuff.\n QString currentLine = currentLinePartialText.trimmed();\n QChar char0;\n QChar char1;\n if (currentLine.length() >= 1) char0 = currentLine.at(0);\n if (currentLine.length() >= 2) char1 = currentLine.at(1);\n const bool inList =\n ((char0 == QLatin1Char('*') || char0 == QLatin1Char('-') ||\n char0 == QLatin1Char('+')) &&\n char1 == QLatin1Char(' '));\n\n if (inList) {\n // if the current line starts with a list character (possibly after\n // whitespaces) add the whitespaces at the next line too\n // Valid listCharacters: '+ ', '-' , '* ', '+ [ ] ', '+ [x] ', '- [ ] ',\n // '- [x] ', '- [-] ', '* [ ] ', '* [x] '.\n static QRegularExpression regex3(\n R\"(^(\\s*)([+|\\-|\\*] \\[(x|-| |)\\]|[+\\-\\*])(\\s+))\");\n iterator = regex3.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n const QString whitespaces = match.captured(1);\n QString listCharacter = match.captured(2);\n const QString whitespaceCharacter = match.captured(4);\n\n static QRegularExpression regex4(R\"(^([+|\\-|\\*]) \\[(x| |\\-|)\\])\");\n // start new checkbox list item with an unchecked checkbox\n iterator = regex4.globalMatch(listCharacter);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match1 = iterator.next();\n const QString realListCharacter = match1.captured(1);\n listCharacter = realListCharacter + QStringLiteral(\" [ ]\");\n }\n\n cursor.setPosition(position);\n cursor.insertText(\"\\n\" + whitespaces + listCharacter +\n whitespaceCharacter);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n }\n\n // check for ordered lists and increment the list number in the next line\n static QRegularExpression regex5(R\"(^(\\s*)(\\d+)([\\.|\\)])(\\s+))\");\n iterator = regex5.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n const QString whitespaces = match.captured(1);\n const uint listNumber = match.captured(2).toUInt();\n const QString listMarker = match.captured(3);\n const QString whitespaceCharacter = match.captured(4);\n\n cursor.setPosition(position);\n cursor.insertText(\"\\n\" + whitespaces + QString::number(listNumber + 1) +\n listMarker + whitespaceCharacter);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n\n // intent next line with same whitespaces as in current line\n static QRegularExpression regex6(R\"(^(\\s+))\");\n iterator = regex6.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n const QString whitespaces = match.captured(1);\n\n cursor.setPosition(position);\n cursor.insertText(\"\\n\" + whitespaces);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n\n // Add new list item above current line if we are at the start the line of a\n // list item\n if (cursorAtBlockStart) {\n static QRegularExpression regex7(\n R\"(^([+|\\-|\\*] \\[(x|-| |)\\]|[+\\-\\*])(\\s+))\");\n iterator = regex7.globalMatch(currentLineText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n QString listCharacter = match.captured(1);\n const QString whitespaceCharacter = match.captured(3);\n\n static QRegularExpression regex8(R\"(^([+|\\-|\\*]) \\[(x| |\\-|)\\])\");\n // start new checkbox list item with an unchecked checkbox\n iterator = regex8.globalMatch(listCharacter);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match1 = iterator.next();\n const QString realListCharacter = match1.captured(1);\n listCharacter = realListCharacter + QStringLiteral(\" [ ]\");\n }\n\n cursor.setPosition(position);\n // Enter new list item above current line\n cursor.insertText(listCharacter + whitespaceCharacter + \"\\n\");\n // Move the cursor at the end of the new list item\n cursor.movePosition(QTextCursor::Left);\n setTextCursor(cursor);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Handles entered tab or reverse tab keys\n */\nbool QMarkdownTextEdit::handleTabEntered(bool reverse,\n const QString &indentCharacters) {\n if (isReadOnly()) {\n return true;\n }\n\n QTextCursor cursor = this->textCursor();\n\n // only check for lists if we haven't a text selected\n if (cursor.selectedText().isEmpty()) {\n cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);\n const QString currentLineText = cursor.selectedText();\n\n // check if we want to indent or un-indent an ordered list\n // Valid listCharacters: '+ ', '-' , '* ', '+ [ ] ', '+ [x] ', '- [ ] ',\n // '- [x] ', '- [-] ', '* [ ] ', '* [x] '.\n static QRegularExpression regex1(\n R\"(^(\\s*)([+|\\-|\\*] \\[(x|-| )\\]|[+\\-\\*])(\\s+)$)\");\n QRegularExpressionMatchIterator i = regex1.globalMatch(currentLineText);\n\n if (i.hasNext()) {\n QRegularExpressionMatch match = i.next();\n QString whitespaces = match.captured(1);\n const QString listCharacter = match.captured(2);\n const QString whitespaceCharacter = match.captured(4);\n\n // add or remove one tabulator key\n if (reverse) {\n // remove one set of indentCharacters or a tabulator\n whitespaces.remove(QRegularExpression(\n QStringLiteral(\"^(\\\\t|\") +\n QRegularExpression::escape(indentCharacters) +\n QStringLiteral(\")\")));\n\n } else {\n whitespaces += indentCharacters;\n }\n\n cursor.insertText(whitespaces + listCharacter +\n whitespaceCharacter);\n return true;\n }\n\n // check if we want to indent or un-indent an ordered list\n static QRegularExpression regex2(R\"(^(\\s*)(\\d+)([\\.|\\)])(\\s+)$)\");\n i = regex2.globalMatch(currentLineText);\n\n if (i.hasNext()) {\n const QRegularExpressionMatch match = i.next();\n QString whitespaces = match.captured(1);\n const QString listCharacter = match.captured(2);\n const QString listMarker = match.captured(3);\n const QString whitespaceCharacter = match.captured(4);\n\n // add or remove one tabulator key\n if (reverse) {\n whitespaces.chop(1);\n } else {\n whitespaces += indentCharacters;\n }\n\n cursor.insertText(whitespaces + listCharacter + listMarker +\n whitespaceCharacter);\n return true;\n }\n }\n\n // check if we want to indent the whole text\n return increaseSelectedTextIndention(reverse, indentCharacters);\n}\n\n/**\n * Sets the auto text options\n */\nvoid QMarkdownTextEdit::setAutoTextOptions(AutoTextOptions options) {\n _autoTextOptions = options;\n}\n\nvoid QMarkdownTextEdit::updateLineNumberArea(const QRect rect, int dy) {\n if (dy)\n _lineNumArea->scroll(0, dy);\n else\n _lineNumArea->update(0, rect.y(), _lineNumArea->sizeHint().width(),\n rect.height());\n\n updateLineNumAreaGeometry();\n\n if (rect.contains(viewport()->rect())) {\n updateLineNumberAreaWidth(0);\n }\n}\n\nvoid QMarkdownTextEdit::updateLineNumberAreaWidth(int) {\n QSignalBlocker blocker(this);\n const auto oldMargins = viewportMargins();\n const int width =\n _lineNumArea->isLineNumAreaEnabled()\n ? _lineNumArea->sizeHint().width() + _lineNumberLeftMarginOffset\n : oldMargins.left();\n const auto newMargins = QMargins{width, oldMargins.top(),\n oldMargins.right(), oldMargins.bottom()};\n\n if (newMargins != oldMargins) {\n setViewportMargins(newMargins);\n }\n\n // Grow lineNumArea font-size with the font size of the editor\n const int pointSize = this->font().pointSize();\n if (pointSize > 0) {\n QFont font = _lineNumArea->font();\n font.setPointSize(pointSize);\n _lineNumArea->setFont(font);\n }\n}\n\n/**\n * @param e\n * @details This does two things\n * 1. Overrides QPlainTextEdit::paintEvent to fix the RTL bug of QPlainTextEdit\n * 2. Paints a rectangle around code block fences [Code taken from\n * ghostwriter(which in turn is based on QPlaintextEdit::paintEvent() with\n * modifications and minor improvements for our use\n */\nvoid QMarkdownTextEdit::paintEvent(QPaintEvent *e) {\n QTextBlock block = firstVisibleBlock();\n\n QPainter painter(viewport());\n const QRect viewportRect = viewport()->rect();\n // painter.fillRect(viewportRect, Qt::transparent);\n bool firstVisible = true;\n QPointF offset(contentOffset());\n QRectF blockAreaRect; // Code or block quote rect.\n bool inBlockArea = false;\n\n bool clipTop = false;\n bool drawBlock = false;\n qreal dy = 0.0;\n bool done = false;\n\n const QColor &color = MarkdownHighlighter::codeBlockBackgroundColor();\n const int cornerRadius = 5;\n\n while (block.isValid() && !done) {\n const QRectF r = blockBoundingRect(block).translated(offset);\n const int state = block.userState();\n\n if (!inBlockArea && MarkdownHighlighter::isCodeBlock(state)) {\n // skip the backticks\n if (!block.text().startsWith(QLatin1String(\"```\")) &&\n !block.text().startsWith(QLatin1String(\"~~~\"))) {\n blockAreaRect = r;\n dy = 0.0;\n inBlockArea = true;\n }\n\n // If this is the first visible block within the viewport\n // and if the previous block is part of the text block area,\n // then the rectangle to draw for the block area will have\n // its top clipped by the viewport and will need to be\n // drawn specially.\n const int prevBlockState = block.previous().userState();\n if (firstVisible &&\n MarkdownHighlighter::isCodeBlock(prevBlockState)) {\n clipTop = true;\n }\n }\n // Else if the block ends a text block area...\n else if (inBlockArea && MarkdownHighlighter::isCodeBlockEnd(state)) {\n drawBlock = true;\n inBlockArea = false;\n blockAreaRect.setHeight(dy);\n }\n // If the block is at the end of the document and ends a text\n // block area...\n //\n if (inBlockArea && block == this->document()->lastBlock()) {\n drawBlock = true;\n inBlockArea = false;\n dy += r.height();\n blockAreaRect.setHeight(dy);\n }\n offset.ry() += r.height();\n dy += r.height();\n\n // If this is the last text block visible within the viewport...\n if (offset.y() > viewportRect.height()) {\n if (inBlockArea) {\n blockAreaRect.setHeight(dy);\n drawBlock = true;\n }\n\n // Finished drawing.\n done = true;\n }\n // If this is the last text block visible within the viewport...\n if (offset.y() > viewportRect.height()) {\n if (inBlockArea) {\n blockAreaRect.setHeight(dy);\n drawBlock = true;\n }\n // Finished drawing.\n done = true;\n }\n\n if (drawBlock) {\n painter.setCompositionMode(QPainter::CompositionMode_SourceOver);\n painter.setPen(Qt::NoPen);\n painter.setBrush(QBrush(color));\n\n // If the first visible block is \"clipped\" such that the previous\n // block is part of the text block area, then only draw a rectangle\n // with the bottom corners rounded, and with the top corners square\n // to reflect that the first visible block is part of a larger block\n // of text.\n //\n if (clipTop) {\n QPainterPath path;\n path.setFillRule(Qt::WindingFill);\n path.addRoundedRect(blockAreaRect, cornerRadius, cornerRadius);\n qreal adjustedHeight = blockAreaRect.height() / 2;\n path.addRect(blockAreaRect.adjusted(0, 0, 0, -adjustedHeight));\n painter.drawPath(path.simplified());\n clipTop = false;\n }\n // Else draw the entire rectangle with all corners rounded.\n else {\n painter.drawRoundedRect(blockAreaRect, cornerRadius,\n cornerRadius);\n }\n\n drawBlock = false;\n }\n\n // this fixes the RTL bug of QPlainTextEdit\n // https://bugreports.qt.io/browse/QTBUG-7516\n if (block.text().isRightToLeft()) {\n QTextLayout *layout = block.layout();\n // opt = document()->defaultTextOption();\n QTextOption opt = QTextOption(Qt::AlignRight);\n opt.setTextDirection(Qt::RightToLeft);\n layout->setTextOption(opt);\n }\n\n // Current line highlight\n QTextCursor cursor = textCursor();\n if (highlightCurrentLine() && cursor.block() == block) {\n QTextLine line =\n block.layout()->lineForTextPosition(cursor.positionInBlock());\n QRectF lineRect = line.rect();\n lineRect.moveTop(lineRect.top() + r.top());\n lineRect.setLeft(0.);\n lineRect.setRight(viewportRect.width());\n painter.fillRect(lineRect.toAlignedRect(),\n currentLineHighlightColor());\n }\n\n block = block.next();\n firstVisible = false;\n }\n\n painter.end();\n QPlainTextEdit::paintEvent(e);\n}\n\n/**\n * Overrides QPlainTextEdit::setReadOnly to fix a problem with Chinese and\n * Japanese input methods\n *\n * @param ro\n */\nvoid QMarkdownTextEdit::setReadOnly(bool ro) {\n QPlainTextEdit::setReadOnly(ro);\n\n // attempted to fix a problem with Chinese and Japanese input methods\n // @see https://github.com/pbek/QOwnNotes/issues/976\n setAttribute(Qt::WA_InputMethodEnabled, !isReadOnly());\n}\n\nvoid QMarkdownTextEdit::doSearch(\n QString &searchText, QPlainTextEditSearchWidget::SearchMode searchMode) {\n _searchWidget->setSearchText(searchText);\n _searchWidget->setSearchMode(searchMode);\n _searchWidget->doSearchCount();\n _searchWidget->activate(false);\n}\n\nvoid QMarkdownTextEdit::hideSearchWidget(bool reset) {\n _searchWidget->deactivate();\n\n if (reset) {\n _searchWidget->reset();\n }\n}\n\nvoid QMarkdownTextEdit::updateSettings() {\n // if true: centers the screen if cursor reaches bottom (but not top)\n searchWidget()->setDebounceDelay(_debounceDelay);\n setCenterOnScroll(_centerCursor);\n}\n\nvoid QMarkdownTextEdit::setLineNumberLeftMarginOffset(int offset) {\n _lineNumberLeftMarginOffset = offset;\n}\n\nQMargins QMarkdownTextEdit::viewportMargins() {\n return QPlainTextEdit::viewportMargins();\n}\n bool bracketClosingCheck(const QChar openingCharacter,\n QChar closingCharacter) {\n // check if bracket closing or read-only are enabled\n if (!(_autoTextOptions & AutoTextOption::BracketClosing) || isReadOnly()) {\n return false;\n }\n\n if (closingCharacter.isNull()) {\n closingCharacter = openingCharacter;\n }\n\n QTextCursor cursor = textCursor();\n const int positionInBlock = cursor.positionInBlock();\n\n // get the current text from the block\n const QString text = cursor.block().text();\n const int textLength = text.length();\n\n // if we are at the end of the line we just want to enter the character\n if (positionInBlock >= textLength) {\n return false;\n }\n\n const QChar currentChar = text.at(positionInBlock);\n\n // if (closingCharacter == openingCharacter) {\n\n // }\n\n qDebug() << __func__ << \" - 'currentChar': \" << currentChar;\n\n // if the current character is not the closing character we just want to\n // enter the character\n if (currentChar != closingCharacter) {\n return false;\n }\n\n const QString leftText = text.left(positionInBlock);\n const int openingCharacterCount = leftText.count(openingCharacter);\n const int closingCharacterCount = leftText.count(closingCharacter);\n\n // if there were enough opening characters just enter the character\n if (openingCharacterCount < (closingCharacterCount + 1)) {\n return false;\n }\n\n // move the cursor to the right and don't enter the character\n cursor.movePosition(QTextCursor::Right);\n setTextCursor(cursor);\n return true;\n}\n bool quotationMarkCheck(const QChar quotationCharacter) {\n // check if bracket closing or read-only are enabled\n if (!(_autoTextOptions & AutoTextOption::BracketClosing) || isReadOnly()) {\n return false;\n }\n\n QTextCursor cursor = textCursor();\n const int positionInBlock = cursor.positionInBlock();\n\n // get the current text from the block\n const QString text = cursor.block().text();\n const int textLength = text.length();\n\n // if last char is not space, we are at word end, no autocompletion\n const bool isBacktick = quotationCharacter == '`';\n if (!isBacktick && positionInBlock != 0 &&\n !text.at(positionInBlock - 1).isSpace()) {\n return false;\n }\n\n // if we are at the end of the line we just want to enter the character\n if (positionInBlock >= textLength) {\n return handleBracketClosing(quotationCharacter);\n }\n\n const QChar currentChar = text.at(positionInBlock);\n\n // if the current character is not the quotation character we just want to\n // enter the character\n if (currentChar != quotationCharacter) {\n return handleBracketClosing(quotationCharacter);\n }\n\n // move the cursor to the right and don't enter the character\n cursor.movePosition(QTextCursor::Right);\n setTextCursor(cursor);\n return true;\n}\n void focusOutEvent(QFocusEvent *event) override {\n resetMouseCursor();\n QPlainTextEdit::focusOutEvent(event);\n}\n void paintEvent(QPaintEvent *e) override {\n QTextBlock block = firstVisibleBlock();\n\n QPainter painter(viewport());\n const QRect viewportRect = viewport()->rect();\n // painter.fillRect(viewportRect, Qt::transparent);\n bool firstVisible = true;\n QPointF offset(contentOffset());\n QRectF blockAreaRect; // Code or block quote rect.\n bool inBlockArea = false;\n\n bool clipTop = false;\n bool drawBlock = false;\n qreal dy = 0.0;\n bool done = false;\n\n const QColor &color = MarkdownHighlighter::codeBlockBackgroundColor();\n const int cornerRadius = 5;\n\n while (block.isValid() && !done) {\n const QRectF r = blockBoundingRect(block).translated(offset);\n const int state = block.userState();\n\n if (!inBlockArea && MarkdownHighlighter::isCodeBlock(state)) {\n // skip the backticks\n if (!block.text().startsWith(QLatin1String(\"```\")) &&\n !block.text().startsWith(QLatin1String(\"~~~\"))) {\n blockAreaRect = r;\n dy = 0.0;\n inBlockArea = true;\n }\n\n // If this is the first visible block within the viewport\n // and if the previous block is part of the text block area,\n // then the rectangle to draw for the block area will have\n // its top clipped by the viewport and will need to be\n // drawn specially.\n const int prevBlockState = block.previous().userState();\n if (firstVisible &&\n MarkdownHighlighter::isCodeBlock(prevBlockState)) {\n clipTop = true;\n }\n }\n // Else if the block ends a text block area...\n else if (inBlockArea && MarkdownHighlighter::isCodeBlockEnd(state)) {\n drawBlock = true;\n inBlockArea = false;\n blockAreaRect.setHeight(dy);\n }\n // If the block is at the end of the document and ends a text\n // block area...\n //\n if (inBlockArea && block == this->document()->lastBlock()) {\n drawBlock = true;\n inBlockArea = false;\n dy += r.height();\n blockAreaRect.setHeight(dy);\n }\n offset.ry() += r.height();\n dy += r.height();\n\n // If this is the last text block visible within the viewport...\n if (offset.y() > viewportRect.height()) {\n if (inBlockArea) {\n blockAreaRect.setHeight(dy);\n drawBlock = true;\n }\n\n // Finished drawing.\n done = true;\n }\n // If this is the last text block visible within the viewport...\n if (offset.y() > viewportRect.height()) {\n if (inBlockArea) {\n blockAreaRect.setHeight(dy);\n drawBlock = true;\n }\n // Finished drawing.\n done = true;\n }\n\n if (drawBlock) {\n painter.setCompositionMode(QPainter::CompositionMode_SourceOver);\n painter.setPen(Qt::NoPen);\n painter.setBrush(QBrush(color));\n\n // If the first visible block is \"clipped\" such that the previous\n // block is part of the text block area, then only draw a rectangle\n // with the bottom corners rounded, and with the top corners square\n // to reflect that the first visible block is part of a larger block\n // of text.\n //\n if (clipTop) {\n QPainterPath path;\n path.setFillRule(Qt::WindingFill);\n path.addRoundedRect(blockAreaRect, cornerRadius, cornerRadius);\n qreal adjustedHeight = blockAreaRect.height() / 2;\n path.addRect(blockAreaRect.adjusted(0, 0, 0, -adjustedHeight));\n painter.drawPath(path.simplified());\n clipTop = false;\n }\n // Else draw the entire rectangle with all corners rounded.\n else {\n painter.drawRoundedRect(blockAreaRect, cornerRadius,\n cornerRadius);\n }\n\n drawBlock = false;\n }\n\n // this fixes the RTL bug of QPlainTextEdit\n // https://bugreports.qt.io/browse/QTBUG-7516\n if (block.text().isRightToLeft()) {\n QTextLayout *layout = block.layout();\n // opt = document()->defaultTextOption();\n QTextOption opt = QTextOption(Qt::AlignRight);\n opt.setTextDirection(Qt::RightToLeft);\n layout->setTextOption(opt);\n }\n\n // Current line highlight\n QTextCursor cursor = textCursor();\n if (highlightCurrentLine() && cursor.block() == block) {\n QTextLine line =\n block.layout()->lineForTextPosition(cursor.positionInBlock());\n QRectF lineRect = line.rect();\n lineRect.moveTop(lineRect.top() + r.top());\n lineRect.setLeft(0.);\n lineRect.setRight(viewportRect.width());\n painter.fillRect(lineRect.toAlignedRect(),\n currentLineHighlightColor());\n }\n\n block = block.next();\n firstVisible = false;\n }\n\n painter.end();\n QPlainTextEdit::paintEvent(e);\n}\n bool handleCharRemoval(MarkdownHighlighter::RangeType type, int block,\n int position) {\n if (!_highlighter) return false;\n\n auto range = _highlighter->findPositionInRanges(type, block, position);\n if (range == QPair{-1, -1}) return false;\n\n int charToRemovePos = range.first;\n if (position == range.first) charToRemovePos = range.second;\n\n QTextCursor cursor = textCursor();\n auto gpos = cursor.position();\n\n if (charToRemovePos > position) {\n cursor.setPosition(gpos + (charToRemovePos - (position + 1)));\n } else {\n cursor.setPosition(gpos - (position - charToRemovePos + 1));\n gpos--;\n }\n\n cursor.deleteChar();\n cursor.setPosition(gpos);\n setTextCursor(cursor);\n return false;\n}\n void resizeEvent(QResizeEvent *event) override {\n QPlainTextEdit::resizeEvent(event);\n updateLineNumAreaGeometry();\n}\n void setLineNumberLeftMarginOffset(int offset) {\n _lineNumberLeftMarginOffset = offset;\n}\n int _lineNumberLeftMarginOffset = 0;\n void updateLineNumAreaGeometry() {\n const auto contentsRect = this->contentsRect();\n const QRect newGeometry = {contentsRect.left(), contentsRect.top(),\n _lineNumArea->sizeHint().width(),\n contentsRect.height()};\n auto oldGeometry = _lineNumArea->geometry();\n if (newGeometry != oldGeometry) {\n _lineNumArea->setGeometry(newGeometry);\n }\n}\n void updateLineNumberArea(const QRect rect, int dy) {\n if (dy)\n _lineNumArea->scroll(0, dy);\n else\n _lineNumArea->update(0, rect.y(), _lineNumArea->sizeHint().width(),\n rect.height());\n\n updateLineNumAreaGeometry();\n\n if (rect.contains(viewport()->rect())) {\n updateLineNumberAreaWidth(0);\n }\n}\n Q_SLOT void updateLineNumberAreaWidth(int) {\n QSignalBlocker blocker(this);\n const auto oldMargins = viewportMargins();\n const int width =\n _lineNumArea->isLineNumAreaEnabled()\n ? _lineNumArea->sizeHint().width() + _lineNumberLeftMarginOffset\n : oldMargins.left();\n const auto newMargins = QMargins{width, oldMargins.top(),\n oldMargins.right(), oldMargins.bottom()};\n\n if (newMargins != oldMargins) {\n setViewportMargins(newMargins);\n }\n\n // Grow lineNumArea font-size with the font size of the editor\n const int pointSize = this->font().pointSize();\n if (pointSize > 0) {\n QFont font = _lineNumArea->font();\n font.setPointSize(pointSize);\n _lineNumArea->setFont(font);\n }\n}\n bool _handleBracketClosingUsed;\n LineNumArea *_lineNumArea;\n void urlClicked(QString url);\n void zoomIn();\n void zoomOut();\n};"], ["/SpeedyNote/source/MainWindow.h", "class QTreeWidgetItem {\n Q_OBJECT\n\npublic:\n explicit MainWindow(QWidget *parent = nullptr);\n virtual ~MainWindow() {\n\n saveButtonMappings(); // ✅ Save on exit, as backup\n delete canvas;\n}\n int getCurrentPageForCanvas(InkCanvas *canvas) {\n return pageMap.contains(canvas) ? pageMap[canvas] : 0;\n}\n bool lowResPreviewEnabled = true;\n void setLowResPreviewEnabled(bool enabled) {\n lowResPreviewEnabled = enabled;\n\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"lowResPreviewEnabled\", enabled);\n}\n bool isLowResPreviewEnabled() const {\n return lowResPreviewEnabled;\n}\n bool areBenchmarkControlsVisible() const {\n return benchmarkButton->isVisible() && benchmarkLabel->isVisible();\n}\n void setBenchmarkControlsVisible(bool visible) {\n benchmarkButton->setVisible(visible);\n benchmarkLabel->setVisible(visible);\n}\n bool zoomButtonsVisible = true;\n bool areZoomButtonsVisible() const {\n return zoomButtonsVisible;\n}\n void setZoomButtonsVisible(bool visible) {\n zoom50Button->setVisible(visible);\n dezoomButton->setVisible(visible);\n zoom200Button->setVisible(visible);\n\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"zoomButtonsVisible\", visible);\n \n // Update zoomButtonsVisible flag and trigger layout update\n zoomButtonsVisible = visible;\n \n // Trigger layout update to adjust responsive thresholds\n if (layoutUpdateTimer) {\n layoutUpdateTimer->stop();\n layoutUpdateTimer->start(50); // Quick update for settings change\n } else {\n updateToolbarLayout(); // Direct update if no timer exists yet\n }\n}\n bool scrollOnTopEnabled = false;\n bool isScrollOnTopEnabled() const {\n return scrollOnTopEnabled;\n}\n void setScrollOnTopEnabled(bool enabled) {\n scrollOnTopEnabled = enabled;\n\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"scrollOnTopEnabled\", enabled);\n}\n bool touchGesturesEnabled = true;\n bool areTouchGesturesEnabled() const {\n return touchGesturesEnabled;\n}\n void setTouchGesturesEnabled(bool enabled) {\n touchGesturesEnabled = enabled;\n \n // Apply to all canvases\n for (int i = 0; i < canvasStack->count(); ++i) {\n InkCanvas *canvas = qobject_cast(canvasStack->widget(i));\n if (canvas) {\n canvas->setTouchGesturesEnabled(enabled);\n }\n }\n \n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"touchGesturesEnabled\", enabled);\n}\n QColor customAccentColor;\n bool useCustomAccentColor = false;\n QColor getAccentColor() const {\n if (useCustomAccentColor && customAccentColor.isValid()) {\n return customAccentColor;\n }\n \n // Return system accent color\n QPalette palette = QGuiApplication::palette();\n return palette.highlight().color();\n}\n void setCustomAccentColor(const QColor &color) {\n if (customAccentColor != color) {\n customAccentColor = color;\n saveThemeSettings();\n // Always update theme if custom accent color is enabled\n if (useCustomAccentColor) {\n updateTheme();\n }\n }\n}\n void setUseCustomAccentColor(bool use) {\n if (useCustomAccentColor != use) {\n useCustomAccentColor = use;\n updateTheme();\n saveThemeSettings();\n }\n}\n void setUseBrighterPalette(bool use) {\n if (useBrighterPalette != use) {\n useBrighterPalette = use;\n \n // Update all colors - call updateColorPalette which handles null checks\n updateColorPalette();\n \n // Save preference\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"useBrighterPalette\", useBrighterPalette);\n }\n}\n QColor getDefaultPenColor() {\n return isDarkMode() ? Qt::white : Qt::black;\n}\n SDLControllerManager *controllerManager = nullptr;\n QThread *controllerThread = nullptr;\n QString getHoldMapping(const QString &buttonName) {\n return buttonHoldMapping.value(buttonName, \"None\");\n}\n QString getPressMapping(const QString &buttonName) {\n return buttonPressMapping.value(buttonName, \"None\");\n}\n void saveButtonMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n\n settings.beginGroup(\"ButtonHoldMappings\");\n for (auto it = buttonHoldMapping.begin(); it != buttonHoldMapping.end(); ++it) {\n settings.setValue(it.key(), it.value());\n }\n settings.endGroup();\n\n settings.beginGroup(\"ButtonPressMappings\");\n for (auto it = buttonPressMapping.begin(); it != buttonPressMapping.end(); ++it) {\n settings.setValue(it.key(), it.value());\n }\n settings.endGroup();\n}\n void loadButtonMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n\n // First, check if we need to migrate old settings\n migrateOldButtonMappings();\n\n settings.beginGroup(\"ButtonHoldMappings\");\n QStringList holdKeys = settings.allKeys();\n for (const QString &key : holdKeys) {\n buttonHoldMapping[key] = settings.value(key, \"none\").toString();\n }\n settings.endGroup();\n\n settings.beginGroup(\"ButtonPressMappings\");\n QStringList pressKeys = settings.allKeys();\n for (const QString &key : pressKeys) {\n QString value = settings.value(key, \"none\").toString();\n buttonPressMapping[key] = value;\n\n // ✅ Convert internal key to action enum\n buttonPressActionMapping[key] = stringToAction(value);\n }\n settings.endGroup();\n}\n void setHoldMapping(const QString &buttonName, const QString &dialMode) {\n buttonHoldMapping[buttonName] = dialMode;\n}\n void setPressMapping(const QString &buttonName, const QString &action) {\n buttonPressMapping[buttonName] = action;\n buttonPressActionMapping[buttonName] = stringToAction(action); // ✅ THIS LINE WAS MISSING\n}\n DialMode dialModeFromString(const QString &mode) {\n // Convert internal key to our existing DialMode enum\n InternalDialMode internalMode = ButtonMappingHelper::internalKeyToDialMode(mode);\n \n switch (internalMode) {\n case InternalDialMode::None: return PageSwitching; // Default fallback\n case InternalDialMode::PageSwitching: return PageSwitching;\n case InternalDialMode::ZoomControl: return ZoomControl;\n case InternalDialMode::ThicknessControl: return ThicknessControl;\n\n case InternalDialMode::ToolSwitching: return ToolSwitching;\n case InternalDialMode::PresetSelection: return PresetSelection;\n case InternalDialMode::PanAndPageScroll: return PanAndPageScroll;\n }\n return PanAndPageScroll; // Default fallback\n}\n void importNotebookFromFile(const QString &packageFile) {\n\n QString destDir = QFileDialog::getExistingDirectory(this, tr(\"Select Working Directory for Notebook\"));\n\n if (destDir.isEmpty()) {\n QMessageBox::warning(this, tr(\"Import Cancelled\"), tr(\"No directory selected. Notebook will not be opened.\"));\n return;\n }\n\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n\n canvas->importNotebookTo(packageFile, destDir);\n\n // Change saveFolder in InkCanvas\n canvas->setSaveFolder(destDir);\n canvas->loadPage(0);\n updateZoom(); // ✅ Update zoom and pan range after importing notebook\n}\n void openPdfFile(const QString &pdfPath) {\n // Check if the PDF file exists\n if (!QFile::exists(pdfPath)) {\n QMessageBox::warning(this, tr(\"File Not Found\"), tr(\"The PDF file could not be found:\\n%1\").arg(pdfPath));\n return;\n }\n \n // First, check if there's already a valid notebook folder for this PDF\n QString existingFolderPath;\n if (PdfOpenDialog::hasValidNotebookFolder(pdfPath, existingFolderPath)) {\n // Found a valid notebook folder, open it directly without showing dialog\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n \n // Save current work if edited\n if (canvas->isEdited()) {\n saveCurrentPage();\n }\n \n // Set the existing folder as save folder\n canvas->setSaveFolder(existingFolderPath);\n \n // Load the PDF\n canvas->loadPdf(pdfPath);\n \n // Update tab label and recent notebooks\n updateTabLabel();\n if (recentNotebooksManager) {\n recentNotebooksManager->addRecentNotebook(existingFolderPath, canvas);\n }\n \n // Switch to page 1 and update UI\n switchPageWithDirection(1, 1);\n pageInput->setValue(1);\n updateZoom();\n updatePanRange();\n \n return; // Exit early, no need to show dialog\n }\n \n // No valid notebook folder found, show the dialog with options\n PdfOpenDialog dialog(pdfPath, this);\n dialog.exec();\n \n PdfOpenDialog::Result result = dialog.getResult();\n QString selectedFolder = dialog.getSelectedFolder();\n \n if (result == PdfOpenDialog::Cancel) {\n return; // User cancelled, do nothing\n }\n \n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n \n // Save current work if edited\n if (canvas->isEdited()) {\n saveCurrentPage();\n }\n \n if (result == PdfOpenDialog::CreateNewFolder) {\n // Set the new folder as save folder\n canvas->setSaveFolder(selectedFolder);\n \n // Load the PDF\n canvas->loadPdf(pdfPath);\n \n // Update tab label and recent notebooks\n updateTabLabel();\n if (recentNotebooksManager) {\n recentNotebooksManager->addRecentNotebook(selectedFolder, canvas);\n }\n \n // Switch to page 1 and update UI\n switchPageWithDirection(1, 1);\n pageInput->setValue(1);\n updateZoom();\n updatePanRange();\n \n } else if (result == PdfOpenDialog::UseExistingFolder) {\n // Check if the existing folder is linked to the same PDF\n QString metadataFile = selectedFolder + \"/.pdf_path.txt\";\n bool isLinkedToSamePdf = false;\n \n if (QFile::exists(metadataFile)) {\n QFile file(metadataFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString existingPdfPath = in.readLine().trimmed();\n file.close();\n \n // Compare absolute paths\n QFileInfo existingInfo(existingPdfPath);\n QFileInfo newInfo(pdfPath);\n isLinkedToSamePdf = (existingInfo.absoluteFilePath() == newInfo.absoluteFilePath());\n }\n }\n \n if (!isLinkedToSamePdf && QFile::exists(metadataFile)) {\n // Folder is linked to a different PDF, ask user what to do\n QMessageBox::StandardButton reply = QMessageBox::question(\n this,\n tr(\"Different PDF Linked\"),\n tr(\"This notebook folder is already linked to a different PDF file.\\n\\nDo you want to replace the link with the new PDF?\"),\n QMessageBox::Yes | QMessageBox::No\n );\n \n if (reply == QMessageBox::No) {\n return; // User chose not to replace\n }\n }\n \n // Set the existing folder as save folder\n canvas->setSaveFolder(selectedFolder);\n \n // Load the PDF\n canvas->loadPdf(pdfPath);\n \n // Update tab label and recent notebooks\n updateTabLabel();\n if (recentNotebooksManager) {\n recentNotebooksManager->addRecentNotebook(selectedFolder, canvas);\n }\n \n // Switch to page 1 and update UI\n switchPageWithDirection(1, 1);\n pageInput->setValue(1);\n updateZoom();\n updatePanRange();\n }\n}\n void setPdfDPI(int dpi) {\n if (dpi != pdfRenderDPI) {\n pdfRenderDPI = dpi;\n savePdfDPI(dpi);\n\n // Apply immediately to current canvas if needed\n if (currentCanvas()) {\n currentCanvas()->setPDFRenderDPI(dpi);\n currentCanvas()->clearPdfCache();\n currentCanvas()->loadPdfPage(getCurrentPageForCanvas(currentCanvas())); // Optional: add this if needed\n updateZoom();\n updatePanRange();\n }\n }\n}\n void savePdfDPI(int dpi) {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"pdfRenderDPI\", dpi);\n}\n void saveDefaultBackgroundSettings(BackgroundStyle style, QColor color, int density) {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"defaultBackgroundStyle\", static_cast(style));\n settings.setValue(\"defaultBackgroundColor\", color.name());\n settings.setValue(\"defaultBackgroundDensity\", density);\n}\n void loadDefaultBackgroundSettings(BackgroundStyle &style, QColor &color, int &density) {\n QSettings settings(\"SpeedyNote\", \"App\");\n style = static_cast(settings.value(\"defaultBackgroundStyle\", static_cast(BackgroundStyle::Grid)).toInt());\n color = QColor(settings.value(\"defaultBackgroundColor\", \"#FFFFFF\").toString());\n density = settings.value(\"defaultBackgroundDensity\", 30).toInt();\n \n // Ensure valid values\n if (!color.isValid()) color = Qt::white;\n if (density < 10) density = 10;\n if (density > 200) density = 200;\n}\n void saveThemeSettings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"useCustomAccentColor\", useCustomAccentColor);\n if (customAccentColor.isValid()) {\n settings.setValue(\"customAccentColor\", customAccentColor.name());\n }\n settings.setValue(\"useBrighterPalette\", useBrighterPalette);\n}\n void loadThemeSettings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n useCustomAccentColor = settings.value(\"useCustomAccentColor\", false).toBool();\n QString colorName = settings.value(\"customAccentColor\", \"#0078D4\").toString();\n customAccentColor = QColor(colorName);\n useBrighterPalette = settings.value(\"useBrighterPalette\", false).toBool();\n \n // Ensure valid values\n if (!customAccentColor.isValid()) {\n customAccentColor = QColor(\"#0078D4\"); // Default blue\n }\n \n // Apply theme immediately after loading\n updateTheme();\n}\n void updateTheme() {\n // Update control bar background color\n QColor accentColor = getAccentColor();\n if (controlBar) {\n controlBar->setStyleSheet(QString(R\"(\n QWidget#controlBar {\n background-color: %1;\n }\n )\").arg(accentColor.name()));\n }\n \n // Update dial background color\n if (pageDial) {\n pageDial->setStyleSheet(QString(R\"(\n QDial {\n background-color: %1;\n }\n )\").arg(accentColor.name()));\n }\n \n // Update add tab button styling\n if (addTabButton) {\n bool darkMode = isDarkMode();\n QString buttonBgColor = darkMode ? \"rgba(80, 80, 80, 255)\" : \"rgba(220, 220, 220, 255)\";\n QString buttonHoverColor = darkMode ? \"rgba(90, 90, 90, 255)\" : \"rgba(200, 200, 200, 255)\";\n QString buttonPressColor = darkMode ? \"rgba(70, 70, 70, 255)\" : \"rgba(180, 180, 180, 255)\";\n QString borderColor = darkMode ? \"rgba(100, 100, 100, 255)\" : \"rgba(180, 180, 180, 255)\";\n \n addTabButton->setStyleSheet(QString(R\"(\n QPushButton {\n background-color: %1;\n border: 1px solid %2;\n border-radius: 12px;\n margin: 2px;\n }\n QPushButton:hover {\n background-color: %3;\n }\n QPushButton:pressed {\n background-color: %4;\n }\n )\").arg(buttonBgColor).arg(borderColor).arg(buttonHoverColor).arg(buttonPressColor));\n }\n \n // Update PDF outline sidebar styling\n if (outlineSidebar && outlineTree) {\n bool darkMode = isDarkMode();\n QString bgColor = darkMode ? \"rgba(45, 45, 45, 255)\" : \"rgba(250, 250, 250, 255)\";\n QString borderColor = darkMode ? \"rgba(80, 80, 80, 255)\" : \"rgba(200, 200, 200, 255)\";\n QString textColor = darkMode ? \"#E0E0E0\" : \"#333\";\n QString hoverColor = darkMode ? \"rgba(60, 60, 60, 255)\" : \"rgba(240, 240, 240, 255)\";\n QString selectedColor = QString(\"rgba(%1, %2, %3, 100)\").arg(accentColor.red()).arg(accentColor.green()).arg(accentColor.blue());\n \n outlineSidebar->setStyleSheet(QString(R\"(\n QWidget {\n background-color: %1;\n border-right: 1px solid %2;\n }\n QLabel {\n color: %3;\n background: transparent;\n }\n )\").arg(bgColor).arg(borderColor).arg(textColor));\n \n outlineTree->setStyleSheet(QString(R\"(\n QTreeWidget {\n background-color: %1;\n border: none;\n color: %2;\n outline: none;\n }\n QTreeWidget::item {\n padding: 4px;\n border: none;\n }\n QTreeWidget::item:hover {\n background-color: %3;\n }\n QTreeWidget::item:selected {\n background-color: %4;\n color: %2;\n }\n QTreeWidget::branch {\n background: transparent;\n }\n QTreeWidget::branch:has-children:!has-siblings:closed,\n QTreeWidget::branch:closed:has-children:has-siblings {\n border-image: none;\n image: url(:/resources/icons/down_arrow.png);\n }\n QTreeWidget::branch:open:has-children:!has-siblings,\n QTreeWidget::branch:open:has-children:has-siblings {\n border-image: none;\n image: url(:/resources/icons/up_arrow.png);\n }\n QScrollBar:vertical {\n background: rgba(200, 200, 200, 80);\n border: none;\n margin: 0px;\n width: 16px !important;\n max-width: 16px !important;\n }\n QScrollBar:vertical:hover {\n background: rgba(200, 200, 200, 120);\n }\n QScrollBar::handle:vertical {\n background: rgba(100, 100, 100, 150);\n border-radius: 2px;\n min-height: 120px;\n }\n QScrollBar::handle:vertical:hover {\n background: rgba(80, 80, 80, 210);\n }\n QScrollBar::add-line:vertical, \n QScrollBar::sub-line:vertical {\n width: 0px;\n height: 0px;\n background: none;\n border: none;\n }\n QScrollBar::add-page:vertical, \n QScrollBar::sub-page:vertical {\n background: transparent;\n }\n )\").arg(bgColor).arg(textColor).arg(hoverColor).arg(selectedColor));\n \n // Apply same styling to bookmarks tree\n bookmarksTree->setStyleSheet(QString(R\"(\n QTreeWidget {\n background-color: %1;\n border: none;\n color: %2;\n outline: none;\n }\n QTreeWidget::item {\n padding: 2px;\n border: none;\n min-height: 26px;\n }\n QTreeWidget::item:hover {\n background-color: %3;\n }\n QTreeWidget::item:selected {\n background-color: %4;\n color: %2;\n }\n QScrollBar:vertical {\n background: rgba(200, 200, 200, 80);\n border: none;\n margin: 0px;\n width: 16px !important;\n max-width: 16px !important;\n }\n QScrollBar:vertical:hover {\n background: rgba(200, 200, 200, 120);\n }\n QScrollBar::handle:vertical {\n background: rgba(100, 100, 100, 150);\n border-radius: 2px;\n min-height: 120px;\n }\n QScrollBar::handle:vertical:hover {\n background: rgba(80, 80, 80, 210);\n }\n QScrollBar::add-line:vertical, \n QScrollBar::sub-line:vertical {\n width: 0px;\n height: 0px;\n background: none;\n border: none;\n }\n QScrollBar::add-page:vertical, \n QScrollBar::sub-page:vertical {\n background: transparent;\n }\n )\").arg(bgColor).arg(textColor).arg(hoverColor).arg(selectedColor));\n }\n \n // Update horizontal tab bar styling with accent color\n if (tabList) {\n bool darkMode = isDarkMode();\n QString bgColor = darkMode ? \"rgba(60, 60, 60, 255)\" : \"rgba(240, 240, 240, 255)\";\n QString itemBgColor = darkMode ? \"rgba(80, 80, 80, 255)\" : \"rgba(220, 220, 220, 255)\";\n QString selectedBgColor = darkMode ? \"rgba(45, 45, 45, 255)\" : \"white\";\n QString borderColor = darkMode ? \"rgba(100, 100, 100, 255)\" : \"rgba(180, 180, 180, 255)\";\n QString hoverBgColor = darkMode ? \"rgba(90, 90, 90, 255)\" : \"rgba(230, 230, 230, 255)\";\n \n tabList->setStyleSheet(QString(R\"(\n QListWidget {\n background-color: %1;\n border: none;\n border-bottom: 2px solid %2;\n outline: none;\n }\n QListWidget::item {\n background-color: %3;\n border: 1px solid %4;\n border-bottom: none;\n margin-right: 1px;\n margin-top: 2px;\n padding: 0px;\n min-width: 80px;\n max-width: 120px;\n }\n QListWidget::item:selected {\n background-color: %5;\n border: 1px solid %4;\n border-bottom: 2px solid %2;\n margin-top: 1px;\n }\n QListWidget::item:hover:!selected {\n background-color: %6;\n }\n QScrollBar:horizontal {\n background: %1;\n height: 8px;\n border: none;\n margin: 0px;\n border-top: 1px solid %4;\n }\n QScrollBar::handle:horizontal {\n background: rgba(150, 150, 150, 120);\n border-radius: 4px;\n min-width: 20px;\n margin: 1px;\n }\n QScrollBar::handle:horizontal:hover {\n background: rgba(120, 120, 120, 200);\n }\n QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal {\n width: 0px;\n height: 0px;\n background: none;\n border: none;\n }\n QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {\n background: transparent;\n }\n )\").arg(bgColor)\n .arg(accentColor.name())\n .arg(itemBgColor)\n .arg(borderColor)\n .arg(selectedBgColor)\n .arg(hoverBgColor));\n }\n \n\n \n // Force icon reload for all buttons that use themed icons\n if (loadPdfButton) loadPdfButton->setIcon(loadThemedIcon(\"pdf\"));\n if (clearPdfButton) clearPdfButton->setIcon(loadThemedIcon(\"pdfdelete\"));\n if (pdfTextSelectButton) pdfTextSelectButton->setIcon(loadThemedIcon(\"ibeam\"));\n if (exportNotebookButton) exportNotebookButton->setIcon(loadThemedIcon(\"export\"));\n if (importNotebookButton) importNotebookButton->setIcon(loadThemedIcon(\"import\"));\n if (benchmarkButton) benchmarkButton->setIcon(loadThemedIcon(\"benchmark\"));\n if (toggleTabBarButton) toggleTabBarButton->setIcon(loadThemedIcon(\"tabs\"));\n if (toggleOutlineButton) toggleOutlineButton->setIcon(loadThemedIcon(\"outline\"));\n if (toggleBookmarksButton) toggleBookmarksButton->setIcon(loadThemedIcon(\"bookmark\"));\n if (toggleBookmarkButton) toggleBookmarkButton->setIcon(loadThemedIcon(\"star\"));\n if (selectFolderButton) selectFolderButton->setIcon(loadThemedIcon(\"folder\"));\n if (saveButton) saveButton->setIcon(loadThemedIcon(\"save\"));\n if (saveAnnotatedButton) saveAnnotatedButton->setIcon(loadThemedIcon(\"saveannotated\"));\n if (fullscreenButton) fullscreenButton->setIcon(loadThemedIcon(\"fullscreen\"));\n if (backgroundButton) backgroundButton->setIcon(loadThemedIcon(\"background\"));\n if (straightLineToggleButton) straightLineToggleButton->setIcon(loadThemedIcon(\"straightLine\"));\n if (ropeToolButton) ropeToolButton->setIcon(loadThemedIcon(\"rope\"));\n if (markdownButton) markdownButton->setIcon(loadThemedIcon(\"markdown\"));\n if (deletePageButton) deletePageButton->setIcon(loadThemedIcon(\"trash\"));\n if (zoomButton) zoomButton->setIcon(loadThemedIcon(\"zoom\"));\n if (dialToggleButton) dialToggleButton->setIcon(loadThemedIcon(\"dial\"));\n if (fastForwardButton) fastForwardButton->setIcon(loadThemedIcon(\"fastforward\"));\n if (jumpToPageButton) jumpToPageButton->setIcon(loadThemedIcon(\"bookpage\"));\n if (thicknessButton) thicknessButton->setIcon(loadThemedIcon(\"thickness\"));\n if (btnPageSwitch) btnPageSwitch->setIcon(loadThemedIcon(\"bookpage\"));\n if (btnZoom) btnZoom->setIcon(loadThemedIcon(\"zoom\"));\n if (btnThickness) btnThickness->setIcon(loadThemedIcon(\"thickness\"));\n if (btnTool) btnTool->setIcon(loadThemedIcon(\"pen\"));\n if (btnPresets) btnPresets->setIcon(loadThemedIcon(\"preset\"));\n if (btnPannScroll) btnPannScroll->setIcon(loadThemedIcon(\"scroll\"));\n if (addPresetButton) addPresetButton->setIcon(loadThemedIcon(\"savepreset\"));\n if (openControlPanelButton) openControlPanelButton->setIcon(loadThemedIcon(\"settings\"));\n if (openRecentNotebooksButton) openRecentNotebooksButton->setIcon(loadThemedIcon(\"recent\"));\n if (penToolButton) penToolButton->setIcon(loadThemedIcon(\"pen\"));\n if (markerToolButton) markerToolButton->setIcon(loadThemedIcon(\"marker\"));\n if (eraserToolButton) eraserToolButton->setIcon(loadThemedIcon(\"eraser\"));\n \n // Update button styles with new theme\n bool darkMode = isDarkMode();\n QString newButtonStyle = createButtonStyle(darkMode);\n \n // Update all buttons that use the buttonStyle\n if (loadPdfButton) loadPdfButton->setStyleSheet(newButtonStyle);\n if (clearPdfButton) clearPdfButton->setStyleSheet(newButtonStyle);\n if (pdfTextSelectButton) pdfTextSelectButton->setStyleSheet(newButtonStyle);\n if (exportNotebookButton) exportNotebookButton->setStyleSheet(newButtonStyle);\n if (importNotebookButton) importNotebookButton->setStyleSheet(newButtonStyle);\n if (benchmarkButton) benchmarkButton->setStyleSheet(newButtonStyle);\n if (toggleTabBarButton) toggleTabBarButton->setStyleSheet(newButtonStyle);\n if (toggleOutlineButton) toggleOutlineButton->setStyleSheet(newButtonStyle);\n if (toggleBookmarksButton) toggleBookmarksButton->setStyleSheet(newButtonStyle);\n if (toggleBookmarkButton) toggleBookmarkButton->setStyleSheet(newButtonStyle);\n if (selectFolderButton) selectFolderButton->setStyleSheet(newButtonStyle);\n if (saveButton) saveButton->setStyleSheet(newButtonStyle);\n if (saveAnnotatedButton) saveAnnotatedButton->setStyleSheet(newButtonStyle);\n if (fullscreenButton) fullscreenButton->setStyleSheet(newButtonStyle);\n if (redButton) redButton->setStyleSheet(newButtonStyle);\n if (blueButton) blueButton->setStyleSheet(newButtonStyle);\n if (yellowButton) yellowButton->setStyleSheet(newButtonStyle);\n if (greenButton) greenButton->setStyleSheet(newButtonStyle);\n if (blackButton) blackButton->setStyleSheet(newButtonStyle);\n if (whiteButton) whiteButton->setStyleSheet(newButtonStyle);\n if (thicknessButton) thicknessButton->setStyleSheet(newButtonStyle);\n if (penToolButton) penToolButton->setStyleSheet(newButtonStyle);\n if (markerToolButton) markerToolButton->setStyleSheet(newButtonStyle);\n if (eraserToolButton) eraserToolButton->setStyleSheet(newButtonStyle);\n if (backgroundButton) backgroundButton->setStyleSheet(newButtonStyle);\n if (straightLineToggleButton) straightLineToggleButton->setStyleSheet(newButtonStyle);\n if (ropeToolButton) ropeToolButton->setStyleSheet(newButtonStyle);\n if (markdownButton) markdownButton->setStyleSheet(newButtonStyle);\n if (deletePageButton) deletePageButton->setStyleSheet(newButtonStyle);\n if (zoomButton) zoomButton->setStyleSheet(newButtonStyle);\n if (dialToggleButton) dialToggleButton->setStyleSheet(newButtonStyle);\n if (fastForwardButton) fastForwardButton->setStyleSheet(newButtonStyle);\n if (jumpToPageButton) jumpToPageButton->setStyleSheet(newButtonStyle);\n if (btnPageSwitch) btnPageSwitch->setStyleSheet(newButtonStyle);\n if (btnZoom) btnZoom->setStyleSheet(newButtonStyle);\n if (btnThickness) btnThickness->setStyleSheet(newButtonStyle);\n if (btnTool) btnTool->setStyleSheet(newButtonStyle);\n if (btnPresets) btnPresets->setStyleSheet(newButtonStyle);\n if (btnPannScroll) btnPannScroll->setStyleSheet(newButtonStyle);\n if (addPresetButton) addPresetButton->setStyleSheet(newButtonStyle);\n if (openControlPanelButton) openControlPanelButton->setStyleSheet(newButtonStyle);\n if (openRecentNotebooksButton) openRecentNotebooksButton->setStyleSheet(newButtonStyle);\n if (zoom50Button) zoom50Button->setStyleSheet(newButtonStyle);\n if (dezoomButton) dezoomButton->setStyleSheet(newButtonStyle);\n if (zoom200Button) zoom200Button->setStyleSheet(newButtonStyle);\n if (prevPageButton) prevPageButton->setStyleSheet(newButtonStyle);\n if (nextPageButton) nextPageButton->setStyleSheet(newButtonStyle);\n \n // Update color buttons with palette-based icons\n if (redButton) {\n QString redIconPath = useBrighterPalette ? \":/resources/icons/pen_light_red.png\" : \":/resources/icons/pen_dark_red.png\";\n redButton->setIcon(QIcon(redIconPath));\n }\n if (blueButton) {\n QString blueIconPath = useBrighterPalette ? \":/resources/icons/pen_light_blue.png\" : \":/resources/icons/pen_dark_blue.png\";\n blueButton->setIcon(QIcon(blueIconPath));\n }\n if (yellowButton) {\n QString yellowIconPath = useBrighterPalette ? \":/resources/icons/pen_light_yellow.png\" : \":/resources/icons/pen_dark_yellow.png\";\n yellowButton->setIcon(QIcon(yellowIconPath));\n }\n if (greenButton) {\n QString greenIconPath = useBrighterPalette ? \":/resources/icons/pen_light_green.png\" : \":/resources/icons/pen_dark_green.png\";\n greenButton->setIcon(QIcon(greenIconPath));\n }\n if (blackButton) {\n QString blackIconPath = darkMode ? \":/resources/icons/pen_light_black.png\" : \":/resources/icons/pen_dark_black.png\";\n blackButton->setIcon(QIcon(blackIconPath));\n }\n if (whiteButton) {\n QString whiteIconPath = darkMode ? \":/resources/icons/pen_light_white.png\" : \":/resources/icons/pen_dark_white.png\";\n whiteButton->setIcon(QIcon(whiteIconPath));\n }\n \n // Update tab close button icons and label styling\n if (tabList) {\n bool darkMode = isDarkMode();\n QString labelColor = darkMode ? \"#E0E0E0\" : \"#333\";\n \n for (int i = 0; i < tabList->count(); ++i) {\n QListWidgetItem *item = tabList->item(i);\n if (item) {\n QWidget *tabWidget = tabList->itemWidget(item);\n if (tabWidget) {\n QPushButton *closeButton = tabWidget->findChild();\n if (closeButton) {\n closeButton->setIcon(loadThemedIcon(\"cross\"));\n }\n \n QLabel *tabLabel = tabWidget->findChild(\"tabLabel\");\n if (tabLabel) {\n tabLabel->setStyleSheet(QString(\"color: %1; font-weight: 500; padding: 2px; text-align: left;\").arg(labelColor));\n }\n }\n }\n }\n }\n \n // Update dial display\n updateDialDisplay();\n}\n void migrateOldButtonMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n \n // Check if migration is needed by looking for old format strings\n settings.beginGroup(\"ButtonHoldMappings\");\n QStringList holdKeys = settings.allKeys();\n bool needsMigration = false;\n \n for (const QString &key : holdKeys) {\n QString value = settings.value(key).toString();\n // If we find old English strings, we need to migrate\n if (value == \"PageSwitching\" || value == \"ZoomControl\" || value == \"ThicknessControl\" ||\n value == \"ToolSwitching\" || value == \"PresetSelection\" ||\n value == \"PanAndPageScroll\") {\n needsMigration = true;\n break;\n }\n }\n settings.endGroup();\n \n if (!needsMigration) {\n settings.beginGroup(\"ButtonPressMappings\");\n QStringList pressKeys = settings.allKeys();\n for (const QString &key : pressKeys) {\n QString value = settings.value(key).toString();\n // Check for old English action strings\n if (value == \"Toggle Fullscreen\" || value == \"Toggle Dial\" || value == \"Zoom 50%\" ||\n value == \"Add Preset\" || value == \"Delete Page\" || value == \"Fast Forward\" ||\n value == \"Open Control Panel\" || value == \"Custom Color\") {\n needsMigration = true;\n break;\n }\n }\n settings.endGroup();\n }\n \n if (!needsMigration) return;\n \n // Perform migration\n // qDebug() << \"Migrating old button mappings to new format...\";\n \n // Migrate hold mappings\n settings.beginGroup(\"ButtonHoldMappings\");\n holdKeys = settings.allKeys();\n for (const QString &key : holdKeys) {\n QString oldValue = settings.value(key).toString();\n QString newValue = migrateOldDialModeString(oldValue);\n if (newValue != oldValue) {\n settings.setValue(key, newValue);\n }\n }\n settings.endGroup();\n \n // Migrate press mappings\n settings.beginGroup(\"ButtonPressMappings\");\n QStringList pressKeys = settings.allKeys();\n for (const QString &key : pressKeys) {\n QString oldValue = settings.value(key).toString();\n QString newValue = migrateOldActionString(oldValue);\n if (newValue != oldValue) {\n settings.setValue(key, newValue);\n }\n }\n settings.endGroup();\n \n // qDebug() << \"Button mapping migration completed.\";\n}\n QString migrateOldDialModeString(const QString &oldString) {\n // Convert old English strings to new internal keys\n if (oldString == \"None\") return \"none\";\n if (oldString == \"PageSwitching\") return \"page_switching\";\n if (oldString == \"ZoomControl\") return \"zoom_control\";\n if (oldString == \"ThicknessControl\") return \"thickness_control\";\n\n if (oldString == \"ToolSwitching\") return \"tool_switching\";\n if (oldString == \"PresetSelection\") return \"preset_selection\";\n if (oldString == \"PanAndPageScroll\") return \"pan_and_page_scroll\";\n return oldString; // Return as-is if not found (might already be new format)\n}\n QString migrateOldActionString(const QString &oldString) {\n // Convert old English strings to new internal keys\n if (oldString == \"None\") return \"none\";\n if (oldString == \"Toggle Fullscreen\") return \"toggle_fullscreen\";\n if (oldString == \"Toggle Dial\") return \"toggle_dial\";\n if (oldString == \"Zoom 50%\") return \"zoom_50\";\n if (oldString == \"Zoom Out\") return \"zoom_out\";\n if (oldString == \"Zoom 200%\") return \"zoom_200\";\n if (oldString == \"Add Preset\") return \"add_preset\";\n if (oldString == \"Delete Page\") return \"delete_page\";\n if (oldString == \"Fast Forward\") return \"fast_forward\";\n if (oldString == \"Open Control Panel\") return \"open_control_panel\";\n if (oldString == \"Red\") return \"red_color\";\n if (oldString == \"Blue\") return \"blue_color\";\n if (oldString == \"Yellow\") return \"yellow_color\";\n if (oldString == \"Green\") return \"green_color\";\n if (oldString == \"Black\") return \"black_color\";\n if (oldString == \"White\") return \"white_color\";\n if (oldString == \"Custom Color\") return \"custom_color\";\n if (oldString == \"Toggle Sidebar\") return \"toggle_sidebar\";\n if (oldString == \"Save\") return \"save\";\n if (oldString == \"Straight Line Tool\") return \"straight_line_tool\";\n if (oldString == \"Rope Tool\") return \"rope_tool\";\n if (oldString == \"Set Pen Tool\") return \"set_pen_tool\";\n if (oldString == \"Set Marker Tool\") return \"set_marker_tool\";\n if (oldString == \"Set Eraser Tool\") return \"set_eraser_tool\";\n if (oldString == \"Toggle PDF Text Selection\") return \"toggle_pdf_text_selection\";\n return oldString; // Return as-is if not found (might already be new format)\n}\n InkCanvas* currentCanvas();\n void saveCurrentPage() {\n currentCanvas()->saveToFile(getCurrentPageForCanvas(currentCanvas()));\n}\n void saveCurrentPageConcurrent() {\n InkCanvas *canvas = currentCanvas();\n if (!canvas || !canvas->isEdited()) return;\n \n int pageNumber = getCurrentPageForCanvas(canvas);\n QString saveFolder = canvas->getSaveFolder();\n \n if (saveFolder.isEmpty()) return;\n \n // Create a copy of the buffer for concurrent saving\n QPixmap bufferCopy = canvas->getBuffer();\n \n // Save markdown windows for this page (this must be done on the main thread)\n if (canvas->getMarkdownManager()) {\n canvas->getMarkdownManager()->saveWindowsForPage(pageNumber);\n }\n \n // Run the save operation concurrently\n QFuture future = QtConcurrent::run([saveFolder, pageNumber, bufferCopy]() {\n // Get notebook ID from the save folder (similar to how InkCanvas does it)\n QString notebookId = \"notebook\"; // Default fallback\n QString idFile = saveFolder + \"/.notebook_id.txt\";\n if (QFile::exists(idFile)) {\n QFile file(idFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n notebookId = in.readLine().trimmed();\n file.close();\n }\n }\n \n QString filePath = saveFolder + QString(\"/%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n \n QImage image(bufferCopy.size(), QImage::Format_ARGB32);\n image.fill(Qt::transparent);\n QPainter painter(&image);\n painter.drawPixmap(0, 0, bufferCopy);\n image.save(filePath, \"PNG\");\n });\n \n // Mark as not edited since we're saving\n canvas->setEdited(false);\n}\n void switchPage(int pageNumber) {\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n\n if (currentCanvas()->isEdited()){\n saveCurrentPageConcurrent(); // Use concurrent saving for smoother page flipping\n }\n\n int oldPage = getCurrentPageForCanvas(currentCanvas()) + 1; // Convert to 1-based for comparison\n int newPage = pageNumber - 1;\n pageMap[canvas] = newPage; // ✅ Save the page for this tab\n\n if (canvas->isPdfLoadedFunc() && pageNumber - 1 < canvas->getTotalPdfPages()) {\n canvas->loadPdfPage(newPage);\n } else {\n canvas->loadPage(newPage);\n }\n\n canvas->setLastActivePage(newPage);\n updateZoom();\n // It seems panXSlider and panYSlider can be null here during startup.\n if(panXSlider && panYSlider){\n canvas->setLastPanX(panXSlider->maximum());\n canvas->setLastPanY(panYSlider->maximum());\n \n // ✅ Enhanced scroll-on-top functionality\n if (scrollOnTopEnabled && panYSlider->maximum() > 0) {\n if (pageNumber > oldPage) {\n // Forward page switching → scroll to top\n panYSlider->setValue(0);\n } else if (pageNumber < oldPage) {\n // Backward page switching → scroll to bottom\n panYSlider->setValue(panYSlider->maximum());\n }\n }\n }\n updateDialDisplay();\n updateBookmarkButtonState(); // Update bookmark button state when switching pages\n}\n void switchPageWithDirection(int pageNumber, int direction) {\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n\n if (currentCanvas()->isEdited()){\n saveCurrentPageConcurrent(); // Use concurrent saving for smoother page flipping\n }\n\n int newPage = pageNumber - 1;\n pageMap[canvas] = newPage; // ✅ Save the page for this tab\n\n if (canvas->isPdfLoadedFunc() && pageNumber - 1 < canvas->getTotalPdfPages()) {\n canvas->loadPdfPage(newPage);\n } else {\n canvas->loadPage(newPage);\n }\n\n canvas->setLastActivePage(newPage);\n updateZoom();\n // It seems panXSlider and panYSlider can be null here during startup.\n if(panXSlider && panYSlider){\n canvas->setLastPanX(panXSlider->maximum());\n canvas->setLastPanY(panYSlider->maximum());\n \n // ✅ Enhanced scroll-on-top functionality with explicit direction\n if (scrollOnTopEnabled && panYSlider->maximum() > 0) {\n if (direction > 0) {\n // Forward page switching → scroll to top\n panYSlider->setValue(0);\n } else if (direction < 0) {\n // Backward page switching → scroll to bottom\n panYSlider->setValue(panYSlider->maximum());\n }\n }\n }\n updateDialDisplay();\n updateBookmarkButtonState(); // Update bookmark button state when switching pages\n}\n void updateTabLabel() {\n int index = tabList->currentRow();\n if (index < 0) return;\n\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n\n QString folderPath = canvas->getSaveFolder(); // ✅ Get save folder\n if (folderPath.isEmpty()) return;\n\n QString tabName;\n\n // ✅ Check if there is an assigned PDF\n QString metadataFile = folderPath + \"/.pdf_path.txt\";\n if (QFile::exists(metadataFile)) {\n QFile file(metadataFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString pdfPath = in.readLine().trimmed();\n file.close();\n\n // ✅ Extract just the PDF filename (not full path)\n QFileInfo pdfInfo(pdfPath);\n if (pdfInfo.exists()) {\n tabName = elideTabText(pdfInfo.fileName(), 90); // e.g., \"mydocument.pdf\" (elided)\n }\n }\n }\n\n // ✅ If no PDF, use the folder name\n if (tabName.isEmpty()) {\n QFileInfo folderInfo(folderPath);\n tabName = elideTabText(folderInfo.fileName(), 90); // e.g., \"MyNotebook\" (elided)\n }\n\n QListWidgetItem *tabItem = tabList->item(index);\n if (tabItem) {\n QWidget *tabWidget = tabList->itemWidget(tabItem); // Get the tab's custom widget\n if (tabWidget) {\n QLabel *tabLabel = tabWidget->findChild(); // Get the QLabel inside\n if (tabLabel) {\n tabLabel->setText(tabName); // ✅ Update tab label\n tabLabel->setWordWrap(false); // No wrapping for horizontal tabs\n }\n }\n }\n}\n QSpinBox *pageInput;\n QPushButton *prevPageButton;\n QPushButton *nextPageButton;\n void addKeyboardMapping(const QString &keySequence, const QString &action) {\n // List of IME-related shortcuts that should not be intercepted\n QStringList imeShortcuts = {\n \"Ctrl+Space\", // Primary IME toggle\n \"Ctrl+Shift\", // Language switching\n \"Ctrl+Alt\", // IME functions\n \"Shift+Alt\", // Alternative language switching\n \"Alt+Shift\" // Alternative language switching (reversed)\n };\n \n // Don't allow mapping of IME-related shortcuts\n if (imeShortcuts.contains(keySequence)) {\n qWarning() << \"Cannot map IME-related shortcut:\" << keySequence;\n return;\n }\n \n keyboardMappings[keySequence] = action;\n keyboardActionMapping[keySequence] = stringToAction(action);\n saveKeyboardMappings();\n}\n void removeKeyboardMapping(const QString &keySequence) {\n keyboardMappings.remove(keySequence);\n keyboardActionMapping.remove(keySequence);\n saveKeyboardMappings();\n}\n QMap getKeyboardMappings() const {\n return keyboardMappings;\n}\n void reconnectControllerSignals() {\n if (!controllerManager || !pageDial) {\n return;\n }\n \n // Reset internal dial state\n tracking = false;\n accumulatedRotation = 0;\n grossTotalClicks = 0;\n tempClicks = 0;\n lastAngle = 0;\n startAngle = 0;\n pendingPageFlip = 0;\n accumulatedRotationAfterLimit = 0;\n \n // Disconnect all existing connections to avoid duplicates\n disconnect(controllerManager, nullptr, this, nullptr);\n disconnect(controllerManager, nullptr, pageDial, nullptr);\n \n // Reconnect all controller signals\n connect(controllerManager, &SDLControllerManager::buttonHeld, this, &MainWindow::handleButtonHeld);\n connect(controllerManager, &SDLControllerManager::buttonReleased, this, &MainWindow::handleButtonReleased);\n connect(controllerManager, &SDLControllerManager::leftStickAngleChanged, pageDial, &QDial::setValue);\n connect(controllerManager, &SDLControllerManager::leftStickReleased, pageDial, &QDial::sliderReleased);\n connect(controllerManager, &SDLControllerManager::buttonSinglePress, this, &MainWindow::handleControllerButton);\n \n // Re-establish dial mode connections by changing to current mode\n DialMode currentMode = currentDialMode;\n changeDialMode(currentMode);\n \n // Update dial display to reflect current state\n updateDialDisplay();\n \n // qDebug() << \"Controller signals reconnected successfully\";\n}\n void updateDialButtonState() {\n // Check if dial is visible\n bool isDialVisible = dialContainer && dialContainer->isVisible();\n \n if (dialToggleButton) {\n dialToggleButton->setProperty(\"selected\", isDialVisible);\n \n // Force style update\n dialToggleButton->style()->unpolish(dialToggleButton);\n dialToggleButton->style()->polish(dialToggleButton);\n }\n}\n void updateFastForwardButtonState() {\n if (fastForwardButton) {\n fastForwardButton->setProperty(\"selected\", fastForwardMode);\n \n // Force style update\n fastForwardButton->style()->unpolish(fastForwardButton);\n fastForwardButton->style()->polish(fastForwardButton);\n }\n}\n void updateToolButtonStates() {\n if (!currentCanvas()) return;\n \n // Reset all tool buttons\n penToolButton->setProperty(\"selected\", false);\n markerToolButton->setProperty(\"selected\", false);\n eraserToolButton->setProperty(\"selected\", false);\n \n // Set the selected property for the current tool\n ToolType currentTool = currentCanvas()->getCurrentTool();\n switch (currentTool) {\n case ToolType::Pen:\n penToolButton->setProperty(\"selected\", true);\n break;\n case ToolType::Marker:\n markerToolButton->setProperty(\"selected\", true);\n break;\n case ToolType::Eraser:\n eraserToolButton->setProperty(\"selected\", true);\n break;\n }\n \n // Force style update\n penToolButton->style()->unpolish(penToolButton);\n penToolButton->style()->polish(penToolButton);\n markerToolButton->style()->unpolish(markerToolButton);\n markerToolButton->style()->polish(markerToolButton);\n eraserToolButton->style()->unpolish(eraserToolButton);\n eraserToolButton->style()->polish(eraserToolButton);\n}\n void handleColorButtonClick() {\n if (!currentCanvas()) return;\n \n ToolType currentTool = currentCanvas()->getCurrentTool();\n \n // If in eraser mode, switch back to pen mode\n if (currentTool == ToolType::Eraser) {\n currentCanvas()->setTool(ToolType::Pen);\n updateToolButtonStates();\n updateThicknessSliderForCurrentTool();\n }\n \n // If rope tool is enabled, turn it off\n if (currentCanvas()->isRopeToolMode()) {\n currentCanvas()->setRopeToolMode(false);\n updateRopeToolButtonState();\n }\n \n // For marker and straight line mode, leave them as they are\n // No special handling needed - they can work with color changes\n}\n void updateThicknessSliderForCurrentTool() {\n if (!currentCanvas() || !thicknessSlider) return;\n \n // Block signals to prevent recursive calls\n thicknessSlider->blockSignals(true);\n \n // Update slider to reflect current tool's thickness\n qreal currentThickness = currentCanvas()->getPenThickness();\n \n // Convert thickness back to slider value (reverse of updateThickness calculation)\n qreal visualThickness = currentThickness * (currentCanvas()->getZoom() / 100.0);\n int sliderValue = qBound(1, static_cast(qRound(visualThickness)), 50);\n \n thicknessSlider->setValue(sliderValue);\n thicknessSlider->blockSignals(false);\n}\n void updatePdfTextSelectButtonState() {\n // Check if PDF text selection is enabled\n bool isEnabled = currentCanvas() && currentCanvas()->isPdfTextSelectionEnabled();\n \n if (pdfTextSelectButton) {\n pdfTextSelectButton->setProperty(\"selected\", isEnabled);\n \n // Force style update (uses the same buttonStyle as other toggle buttons)\n pdfTextSelectButton->style()->unpolish(pdfTextSelectButton);\n pdfTextSelectButton->style()->polish(pdfTextSelectButton);\n }\n}\n private:\n void toggleBenchmark() {\n benchmarking = !benchmarking;\n if (benchmarking) {\n currentCanvas()->startBenchmark();\n benchmarkTimer->start(1000); // Update every second\n } else {\n currentCanvas()->stopBenchmark();\n benchmarkTimer->stop();\n benchmarkLabel->setText(tr(\"PR:N/A\"));\n }\n}\n void updateBenchmarkDisplay() {\n int sampleRate = currentCanvas()->getProcessedRate();\n benchmarkLabel->setText(QString(tr(\"PR:%1 Hz\")).arg(sampleRate));\n}\n void applyCustomColor() {\n QString colorCode = customColorInput->text();\n if (!colorCode.startsWith(\"#\")) {\n colorCode.prepend(\"#\");\n }\n currentCanvas()->setPenColor(QColor(colorCode));\n updateDialDisplay(); \n}\n void updateThickness(int value) {\n // Calculate thickness based on the slider value at 100% zoom\n // The slider value represents the desired visual thickness\n qreal visualThickness = value; // Scale slider value to reasonable thickness\n \n // Apply zoom scaling to maintain visual consistency\n qreal actualThickness = visualThickness * (100.0 / currentCanvas()->getZoom()); \n \n currentCanvas()->setPenThickness(actualThickness);\n}\n void adjustThicknessForZoom(int oldZoom, int newZoom) {\n // Adjust all tool thicknesses to maintain visual consistency when zoom changes\n if (oldZoom == newZoom || oldZoom <= 0 || newZoom <= 0) return;\n \n InkCanvas* canvas = currentCanvas();\n if (!canvas) return;\n \n qreal zoomRatio = qreal(oldZoom) / qreal(newZoom);\n ToolType currentTool = canvas->getCurrentTool();\n \n // Adjust thickness for all tools, not just the current one\n canvas->adjustAllToolThicknesses(zoomRatio);\n \n // Update the thickness slider to reflect the current tool's new thickness\n updateThicknessSliderForCurrentTool();\n \n // ✅ FIXED: Update dial display to show new thickness immediately during zoom changes\n updateDialDisplay();\n}\n void changeTool(int index) {\n if (index == 0) {\n currentCanvas()->setTool(ToolType::Pen);\n } else if (index == 1) {\n currentCanvas()->setTool(ToolType::Marker);\n } else if (index == 2) {\n currentCanvas()->setTool(ToolType::Eraser);\n }\n updateToolButtonStates();\n updateThicknessSliderForCurrentTool();\n updateDialDisplay();\n}\n void selectFolder() {\n QString folder = QFileDialog::getExistingDirectory(this, tr(\"Select Save Folder\"));\n if (!folder.isEmpty()) {\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n if (canvas->isEdited()){\n saveCurrentPage();\n }\n canvas->setSaveFolder(folder);\n switchPageWithDirection(1, 1); // Going to page 1 is forward direction\n pageInput->setValue(1);\n updateTabLabel();\n recentNotebooksManager->addRecentNotebook(folder, canvas); // Track when folder is selected\n }\n }\n}\n void saveCanvas() {\n currentCanvas()->saveToFile(getCurrentPageForCanvas(currentCanvas()));\n}\n void saveAnnotated() {\n currentCanvas()->saveAnnotated(getCurrentPageForCanvas(currentCanvas()));\n}\n void deleteCurrentPage() {\n currentCanvas()->deletePage(getCurrentPageForCanvas(currentCanvas()));\n}\n void loadPdf() {\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n\n QString saveFolder = canvas->getSaveFolder();\n QString tempDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\";\n \n // Check if no save folder is set or if it's the temporary directory\n if (saveFolder.isEmpty() || saveFolder == tempDir) {\n QMessageBox::warning(this, tr(\"Cannot Load PDF\"), \n tr(\"Please select a permanent save folder before loading a PDF.\\n\\nClick the folder icon to choose a location for your notebook.\"));\n return;\n }\n\n QString filePath = QFileDialog::getOpenFileName(this, tr(\"Select PDF\"), \"\", \"PDF Files (*.pdf)\");\n if (!filePath.isEmpty()) {\n currentCanvas()->loadPdf(filePath);\n updateTabLabel(); // ✅ Update the tab name after assigning a PDF\n updateZoom(); // ✅ Update zoom and pan range after PDF is loaded\n \n // Refresh PDF outline if sidebar is visible\n if (outlineSidebarVisible) {\n loadPdfOutline();\n }\n }\n}\n void clearPdf() {\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n \n canvas->clearPdf();\n updateZoom(); // ✅ Update zoom and pan range after PDF is cleared\n}\n void updateZoom() {\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n canvas->setZoom(zoomSlider->value());\n canvas->setLastZoomLevel(zoomSlider->value()); // ✅ Store zoom level per tab\n updatePanRange();\n // updateThickness(thicknessSlider->value()); // ✅ REMOVED: This was resetting thickness on page switch\n // updateDialDisplay();\n }\n}\n void onZoomSliderChanged(int value) {\n // This handles manual zoom slider changes and preserves thickness\n int oldZoom = currentCanvas() ? currentCanvas()->getZoom() : 100;\n int newZoom = value;\n \n updateZoom();\n adjustThicknessForZoom(oldZoom, newZoom); // Maintain visual thickness consistency\n}\n void applyZoom() {\n bool ok;\n int zoomValue = zoomInput->text().toInt(&ok);\n if (ok && zoomValue > 0) {\n currentCanvas()->setZoom(zoomValue);\n updatePanRange(); // Update slider range after zoom change\n }\n}\n void updatePanRange() {\n int zoom = currentCanvas()->getZoom();\n\n QSize canvasSize = currentCanvas()->getCanvasSize();\n QSize viewportSize = QGuiApplication::primaryScreen()->size() * QGuiApplication::primaryScreen()->devicePixelRatio();\n qreal dpr = initialDpr;\n \n // Get the actual widget size instead of screen size for more accurate calculation\n QSize actualViewportSize = size();\n \n // Adjust viewport size for toolbar and tab bar layout\n QSize effectiveViewportSize = actualViewportSize;\n int toolbarHeight = isToolbarTwoRows ? 80 : 50; // Toolbar height\n int tabBarHeight = (tabBarContainer && tabBarContainer->isVisible()) ? 38 : 0; // Tab bar height\n effectiveViewportSize.setHeight(actualViewportSize.height() - toolbarHeight - tabBarHeight);\n \n // Calculate scaled canvas size using proper DPR scaling\n int scaledCanvasWidth = canvasSize.width() * zoom / 100;\n int scaledCanvasHeight = canvasSize.height() * zoom / 100;\n \n // Calculate max pan values - if canvas is smaller than viewport, pan should be 0\n int maxPanX = qMax(0, scaledCanvasWidth - effectiveViewportSize.width());\n int maxPanY = qMax(0, scaledCanvasHeight - effectiveViewportSize.height());\n\n // Scale the pan range properly\n int maxPanX_scaled = maxPanX * 100 / zoom;\n int maxPanY_scaled = maxPanY * 100 / zoom;\n\n // Set range to 0 when canvas is smaller than viewport (centered)\n if (scaledCanvasWidth <= effectiveViewportSize.width()) {\n panXSlider->setRange(0, 0);\n panXSlider->setValue(0);\n // No need for horizontal scrollbar\n panXSlider->setVisible(false);\n } else {\n panXSlider->setRange(0, maxPanX_scaled);\n // Show scrollbar only if mouse is near and timeout hasn't occurred\n if (scrollbarsVisible && !scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->start();\n }\n }\n \n if (scaledCanvasHeight <= effectiveViewportSize.height()) {\n panYSlider->setRange(0, 0);\n panYSlider->setValue(0);\n // No need for vertical scrollbar\n panYSlider->setVisible(false);\n } else {\n panYSlider->setRange(0, maxPanY_scaled);\n // Show scrollbar only if mouse is near and timeout hasn't occurred\n if (scrollbarsVisible && !scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->start();\n }\n }\n}\n void updatePanX(int value) {\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n canvas->setPanX(value);\n canvas->setLastPanX(value); // ✅ Store panX per tab\n \n // Show horizontal scrollbar temporarily\n if (panXSlider->maximum() > 0) {\n panXSlider->setVisible(true);\n scrollbarsVisible = true;\n \n // Make sure scrollbar position matches the canvas position\n if (panXSlider->value() != value) {\n panXSlider->blockSignals(true);\n panXSlider->setValue(value);\n panXSlider->blockSignals(false);\n }\n \n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n scrollbarHideTimer->start();\n }\n }\n}\n void updatePanY(int value) {\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n canvas->setPanY(value);\n canvas->setLastPanY(value); // ✅ Store panY per tab\n \n // Show vertical scrollbar temporarily\n if (panYSlider->maximum() > 0) {\n panYSlider->setVisible(true);\n scrollbarsVisible = true;\n \n // Make sure scrollbar position matches the canvas position\n if (panYSlider->value() != value) {\n panYSlider->blockSignals(true);\n panYSlider->setValue(value);\n panYSlider->blockSignals(false);\n }\n \n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n scrollbarHideTimer->start();\n }\n }\n}\n void selectBackground() {\n QString filePath = QFileDialog::getOpenFileName(this, tr(\"Select Background Image\"), \"\", \"Images (*.png *.jpg *.jpeg)\");\n if (!filePath.isEmpty()) {\n currentCanvas()->setBackground(filePath, getCurrentPageForCanvas(currentCanvas()));\n updateZoom(); // ✅ Update zoom and pan range after background is set\n }\n}\n void forceUIRefresh() {\n setWindowState(Qt::WindowNoState); // Restore first\n setWindowState(Qt::WindowMaximized); // Maximize again\n}\n void switchTab(int index) {\n if (!canvasStack || !tabList || !pageInput || !zoomSlider || !panXSlider || !panYSlider) {\n // qDebug() << \"Error: switchTab() called before UI was fully initialized!\";\n return;\n }\n\n if (index >= 0 && index < canvasStack->count()) {\n canvasStack->setCurrentIndex(index);\n \n // Ensure the tab list selection is properly set and styled\n if (tabList->currentRow() != index) {\n tabList->setCurrentRow(index);\n }\n \n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n int savedPage = canvas->getLastActivePage();\n \n // ✅ Only call blockSignals if pageInput is valid\n if (pageInput) { \n pageInput->blockSignals(true);\n pageInput->setValue(savedPage + 1);\n pageInput->blockSignals(false);\n }\n\n // ✅ Ensure zoomSlider exists before calling methods\n if (zoomSlider) {\n zoomSlider->blockSignals(true);\n zoomSlider->setValue(canvas->getLastZoomLevel());\n zoomSlider->blockSignals(false);\n canvas->setZoom(canvas->getLastZoomLevel());\n }\n\n // ✅ Ensure pan sliders exist before modifying values\n if (panXSlider && panYSlider) {\n panXSlider->blockSignals(true);\n panYSlider->blockSignals(true);\n panXSlider->setValue(canvas->getLastPanX());\n panYSlider->setValue(canvas->getLastPanY());\n panXSlider->blockSignals(false);\n panYSlider->blockSignals(false);\n updatePanRange();\n }\n updateDialDisplay();\n updateColorButtonStates(); // Update button states when switching tabs\n updateStraightLineButtonState(); // Update straight line button state when switching tabs\n updateRopeToolButtonState(); // Update rope tool button state when switching tabs\n updateMarkdownButtonState(); // Update markdown button state when switching tabs\n updatePdfTextSelectButtonState(); // Update PDF text selection button state when switching tabs\n updateBookmarkButtonState(); // Update bookmark button state when switching tabs\n updateDialButtonState(); // Update dial button state when switching tabs\n updateFastForwardButtonState(); // Update fast forward button state when switching tabs\n updateToolButtonStates(); // Update tool button states when switching tabs\n updateThicknessSliderForCurrentTool(); // Update thickness slider for current tool when switching tabs\n \n // Refresh PDF outline if sidebar is visible\n if (outlineSidebarVisible) {\n loadPdfOutline();\n }\n }\n }\n}\n void addNewTab() {\n if (!tabList || !canvasStack) return; // Ensure tabList and canvasStack exist\n\n int newTabIndex = tabList->count(); // New tab index\n QWidget *tabWidget = new QWidget(); // Custom tab container\n tabWidget->setObjectName(\"tabWidget\"); // Name the widget for easy retrieval later\n QHBoxLayout *tabLayout = new QHBoxLayout(tabWidget);\n tabLayout->setContentsMargins(5, 2, 5, 2);\n\n // ✅ Create the label (Tab Name) - optimized for horizontal layout\n QLabel *tabLabel = new QLabel(QString(\"Tab %1\").arg(newTabIndex + 1), tabWidget); \n tabLabel->setObjectName(\"tabLabel\"); // ✅ Name the label for easy retrieval later\n tabLabel->setWordWrap(false); // ✅ No wrapping for horizontal tabs\n tabLabel->setFixedWidth(115); // ✅ Narrower width for compact layout\n tabLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);\n tabLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter); // Left-align to show filename start\n tabLabel->setTextFormat(Qt::PlainText); // Ensure plain text for proper eliding\n // Tab label styling will be updated by theme\n\n // ✅ Create the close button (❌) - styled for browser-like tabs\n QPushButton *closeButton = new QPushButton(tabWidget);\n closeButton->setFixedSize(14, 14); // Smaller to fit narrower tabs\n closeButton->setIcon(loadThemedIcon(\"cross\")); // Set themed icon\n closeButton->setStyleSheet(R\"(\n QPushButton { \n border: none; \n background: transparent; \n border-radius: 6px;\n padding: 1px;\n }\n QPushButton:hover { \n background: rgba(255, 100, 100, 150); \n border-radius: 6px;\n }\n QPushButton:pressed { \n background: rgba(255, 50, 50, 200); \n border-radius: 6px;\n }\n )\"); // Themed styling with hover and press effects\n \n // ✅ Create new InkCanvas instance EARLIER so it can be captured by the lambda\n InkCanvas *newCanvas = new InkCanvas(this);\n \n // ✅ Handle tab closing when the button is clicked\n connect(closeButton, &QPushButton::clicked, this, [=]() { // newCanvas is now captured\n\n // Prevent closing if it's the last remaining tab\n if (tabList->count() <= 1) {\n // Optional: show a message or do nothing silently\n QMessageBox::information(this, tr(\"Notice\"), tr(\"At least one tab must remain open.\"));\n\n return;\n }\n\n // Find the index of the tab associated with this button's parent (tabWidget)\n int indexToRemove = -1;\n // newCanvas is captured by the lambda, representing the canvas of the tab being closed.\n // tabWidget is also captured.\n for (int i = 0; i < tabList->count(); ++i) {\n if (tabList->itemWidget(tabList->item(i)) == tabWidget) {\n indexToRemove = i;\n break;\n }\n }\n\n if (indexToRemove == -1) {\n qWarning() << \"Could not find tab to remove based on tabWidget.\";\n // Fallback or error handling if needed, though this shouldn't happen if tabWidget is valid.\n // As a fallback, try to find the index based on newCanvas if lists are in sync.\n for (int i = 0; i < canvasStack->count(); ++i) {\n if (canvasStack->widget(i) == newCanvas) {\n indexToRemove = i;\n break;\n }\n }\n if (indexToRemove == -1) {\n qWarning() << \"Could not find tab to remove based on newCanvas either.\";\n return; // Critical error, cannot proceed.\n }\n }\n \n // At this point, newCanvas is the InkCanvas instance for the tab being closed.\n // And indexToRemove is its index in tabList and canvasStack.\n\n // 1. Ensure the notebook has a unique save folder if it's temporary/edited\n ensureTabHasUniqueSaveFolder(newCanvas); // Pass the specific canvas\n\n // 2. Get the final save folder path\n QString folderPath = newCanvas->getSaveFolder();\n QString tempDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\";\n\n // 3. Update cover preview and recent list if it's a permanent notebook\n if (!folderPath.isEmpty() && folderPath != tempDir && recentNotebooksManager) {\n recentNotebooksManager->generateAndSaveCoverPreview(folderPath, newCanvas);\n // Add/update in recent list. This also moves it to the top.\n recentNotebooksManager->addRecentNotebook(folderPath, newCanvas);\n }\n \n // 4. Update the tab's label directly as folderPath might have changed\n QLabel *label = tabWidget->findChild(\"tabLabel\");\n if (label) {\n QString tabNameText;\n if (!folderPath.isEmpty() && folderPath != tempDir) { // Only for permanent notebooks\n QString metadataFile = folderPath + \"/.pdf_path.txt\";\n if (QFile::exists(metadataFile)) {\n QFile file(metadataFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString pdfPath = in.readLine().trimmed();\n file.close();\n if (QFile::exists(pdfPath)) { // Check if PDF file actually exists\n tabNameText = elideTabText(QFileInfo(pdfPath).fileName(), 90); // Elide to fit tab width\n }\n }\n }\n // Fallback to folder name if no PDF or PDF path invalid\n if (tabNameText.isEmpty()) {\n tabNameText = elideTabText(QFileInfo(folderPath).fileName(), 90); // Elide to fit tab width\n }\n }\n // Only update the label if a new valid name was determined.\n // If it's still a temp folder, the original \"Tab X\" label remains appropriate.\n if (!tabNameText.isEmpty()) {\n label->setText(tabNameText);\n }\n }\n\n // 5. Remove the tab\n removeTabAt(indexToRemove);\n });\n\n\n // ✅ Add widgets to the tab layout\n tabLayout->addWidget(tabLabel);\n tabLayout->addWidget(closeButton);\n tabLayout->setStretch(0, 1);\n tabLayout->setStretch(1, 0);\n \n // ✅ Create the tab item and set widget (horizontal layout)\n QListWidgetItem *tabItem = new QListWidgetItem();\n tabItem->setSizeHint(QSize(135, 22)); // ✅ Narrower and thinner for compact layout\n tabList->addItem(tabItem);\n tabList->setItemWidget(tabItem, tabWidget); // Attach tab layout\n\n canvasStack->addWidget(newCanvas);\n\n // ✅ Connect touch gesture signals\n connect(newCanvas, &InkCanvas::zoomChanged, this, &MainWindow::handleTouchZoomChange);\n connect(newCanvas, &InkCanvas::panChanged, this, &MainWindow::handleTouchPanChange);\n connect(newCanvas, &InkCanvas::touchGestureEnded, this, &MainWindow::handleTouchGestureEnd);\n connect(newCanvas, &InkCanvas::ropeSelectionCompleted, this, &MainWindow::showRopeSelectionMenu);\n connect(newCanvas, &InkCanvas::pdfLinkClicked, this, [this](int targetPage) {\n // Navigate to the target page when a PDF link is clicked\n if (targetPage >= 0 && targetPage < 9999) {\n switchPageWithDirection(targetPage + 1, (targetPage + 1 > getCurrentPageForCanvas(currentCanvas()) + 1) ? 1 : -1);\n pageInput->setValue(targetPage + 1);\n }\n });\n connect(newCanvas, &InkCanvas::pdfLoaded, this, [this]() {\n // Refresh PDF outline if sidebar is visible\n if (outlineSidebarVisible) {\n loadPdfOutline();\n }\n });\n connect(newCanvas, &InkCanvas::markdownSelectionModeChanged, this, &MainWindow::updateMarkdownButtonState);\n \n // Install event filter to detect mouse movement for scrollbar visibility\n newCanvas->setMouseTracking(true);\n newCanvas->installEventFilter(this);\n \n // Disable tablet tracking for canvases for now to prevent crashes\n // TODO: Find a safer way to implement hover tooltips without tablet tracking\n // QTimer::singleShot(50, this, [newCanvas]() {\n // try {\n // if (newCanvas && newCanvas->window() && newCanvas->window()->windowHandle()) {\n // newCanvas->setAttribute(Qt::WA_TabletTracking, true);\n // }\n // } catch (...) {\n // // Silently ignore tablet tracking errors\n // }\n // });\n \n // ✅ Apply touch gesture setting\n newCanvas->setTouchGesturesEnabled(touchGesturesEnabled);\n\n pageMap[newCanvas] = 0;\n\n // ✅ Select the new tab\n tabList->setCurrentItem(tabItem);\n canvasStack->setCurrentWidget(newCanvas);\n\n zoomSlider->setValue(100 / initialDpr); // Set initial zoom level based on DPR\n updateDialDisplay();\n updateStraightLineButtonState(); // Initialize straight line button state for the new tab\n updateRopeToolButtonState(); // Initialize rope tool button state for the new tab\n updatePdfTextSelectButtonState(); // Initialize PDF text selection button state for the new tab\n updateBookmarkButtonState(); // Initialize bookmark button state for the new tab\n updateMarkdownButtonState(); // Initialize markdown button state for the new tab\n updateDialButtonState(); // Initialize dial button state for the new tab\n updateFastForwardButtonState(); // Initialize fast forward button state for the new tab\n updateToolButtonStates(); // Initialize tool button states for the new tab\n\n QString tempDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\";\n newCanvas->setSaveFolder(tempDir);\n \n // Load persistent background settings\n BackgroundStyle defaultStyle;\n QColor defaultColor;\n int defaultDensity;\n loadDefaultBackgroundSettings(defaultStyle, defaultColor, defaultDensity);\n \n newCanvas->setBackgroundStyle(defaultStyle);\n newCanvas->setBackgroundColor(defaultColor);\n newCanvas->setBackgroundDensity(defaultDensity);\n newCanvas->setPDFRenderDPI(getPdfDPI());\n \n // Update color button states for the new tab\n updateColorButtonStates();\n}\n void removeTabAt(int index) {\n if (!tabList || !canvasStack) return; // Ensure UI elements exist\n if (index < 0 || index >= canvasStack->count()) return;\n\n // ✅ Remove tab entry\n QListWidgetItem *item = tabList->takeItem(index);\n delete item;\n\n // ✅ Remove and delete the canvas safely\n QWidget *canvasWidget = canvasStack->widget(index); // Get widget before removal\n // ensureTabHasUniqueSaveFolder(currentCanvas()); // Moved to the close button lambda\n\n if (canvasWidget) {\n canvasStack->removeWidget(canvasWidget); // Remove from stack\n // InkCanvas *canvasInstance = qobject_cast(canvasWidget);\n // if (canvasInstance) {\n // QString folderPath = canvasInstance->getSaveFolder();\n // QString tempDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\";\n // if (!folderPath.isEmpty() && folderPath != tempDir && recentNotebooksManager) {\n // recentNotebooksManager->addRecentNotebook(folderPath, canvasInstance); // Moved to close button lambda\n // }\n // }\n delete canvasWidget; // Now delete the widget (and its InkCanvas)\n }\n\n // ✅ Select the previous tab (or first tab if none left)\n if (tabList->count() > 0) {\n int newIndex = qMax(0, index - 1);\n tabList->setCurrentRow(newIndex);\n canvasStack->setCurrentWidget(canvasStack->widget(newIndex));\n }\n\n // QWidget *canvasWidget = canvasStack->widget(index); // Redeclaration - remove this block\n // InkCanvas *canvasInstance = qobject_cast(canvasWidget);\n //\n // if (canvasInstance) {\n // QString folderPath = canvasInstance->getSaveFolder();\n // if (!folderPath.isEmpty() && folderPath != QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\") {\n // // recentNotebooksManager->addRecentNotebook(folderPath, canvasInstance); // Moved to close button lambda\n // }\n // }\n}\n void toggleZoomSlider() {\n if (zoomFrame->isVisible()) {\n zoomFrame->hide();\n return;\n }\n\n // ✅ Set as a standalone pop-up window so it can receive events\n zoomFrame->setWindowFlags(Qt::Popup);\n\n // ✅ Position it right below the button\n QPoint buttonPos = zoomButton->mapToGlobal(QPoint(0, zoomButton->height()));\n zoomFrame->move(buttonPos.x(), buttonPos.y() + 5);\n zoomFrame->show();\n}\n void toggleThicknessSlider() {\n if (thicknessFrame->isVisible()) {\n thicknessFrame->hide();\n return;\n }\n\n // ✅ Set as a standalone pop-up window so it can receive events\n thicknessFrame->setWindowFlags(Qt::Popup);\n\n // ✅ Position it right below the button\n QPoint buttonPos = thicknessButton->mapToGlobal(QPoint(0, thicknessButton->height()));\n thicknessFrame->move(buttonPos.x(), buttonPos.y() + 5);\n\n thicknessFrame->show();\n}\n void toggleFullscreen() {\n if (isFullScreen()) {\n showNormal(); // Exit fullscreen mode\n } else {\n showFullScreen(); // Enter fullscreen mode\n }\n}\n void showJumpToPageDialog() {\n bool ok;\n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1; // ✅ Convert zero-based to one-based\n int newPage = QInputDialog::getInt(this, \"Jump to Page\", \"Enter Page Number:\", \n currentPage, 1, 9999, 1, &ok);\n if (ok) {\n // ✅ Use direction-aware page switching for jump-to-page\n int direction = (newPage > currentPage) ? 1 : (newPage < currentPage) ? -1 : 0;\n if (direction != 0) {\n switchPageWithDirection(newPage, direction);\n } else {\n switchPage(newPage); // Same page, no direction needed\n }\n pageInput->setValue(newPage);\n }\n}\n void goToPreviousPage() {\n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1; // Convert to 1-based\n if (currentPage > 1) {\n int newPage = currentPage - 1;\n switchPageWithDirection(newPage, -1); // -1 indicates backward\n pageInput->setValue(newPage);\n }\n}\n void goToNextPage() {\n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1; // Convert to 1-based\n int newPage = currentPage + 1;\n switchPageWithDirection(newPage, 1); // 1 indicates forward\n pageInput->setValue(newPage);\n}\n void onPageInputChanged(int newPage) {\n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1; // Convert to 1-based\n \n // ✅ Use direction-aware page switching for spinbox\n int direction = (newPage > currentPage) ? 1 : (newPage < currentPage) ? -1 : 0;\n if (direction != 0) {\n switchPageWithDirection(newPage, direction);\n } else {\n switchPage(newPage); // Same page, no direction needed\n }\n}\n void toggleDial() {\n if (!dialContainer) { \n // ✅ Create floating container for the dial\n dialContainer = new QWidget(this);\n dialContainer->setObjectName(\"dialContainer\");\n dialContainer->setFixedSize(140, 140);\n dialContainer->setAttribute(Qt::WA_TranslucentBackground);\n dialContainer->setAttribute(Qt::WA_NoSystemBackground);\n dialContainer->setAttribute(Qt::WA_OpaquePaintEvent);\n dialContainer->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);\n dialContainer->setStyleSheet(\"background: transparent; border-radius: 100px;\"); // ✅ More transparent\n\n // ✅ Create dial\n pageDial = new QDial(dialContainer);\n pageDial->setFixedSize(140, 140);\n pageDial->setMinimum(0);\n pageDial->setMaximum(360);\n pageDial->setWrapping(true); // ✅ Allow full-circle rotation\n \n // Apply theme color immediately when dial is created\n QColor accentColor = getAccentColor();\n pageDial->setStyleSheet(QString(R\"(\n QDial {\n background-color: %1;\n }\n )\").arg(accentColor.name()));\n\n /*\n\n modeDial = new QDial(dialContainer);\n modeDial->setFixedSize(150, 150);\n modeDial->setMinimum(0);\n modeDial->setMaximum(300); // 6 modes, 60° each\n modeDial->setSingleStep(60);\n modeDial->setWrapping(true);\n modeDial->setStyleSheet(\"background:rgb(0, 76, 147);\");\n modeDial->move(25, 25);\n \n */\n \n\n dialColorPreview = new QFrame(dialContainer);\n dialColorPreview->setFixedSize(30, 30);\n dialColorPreview->setStyleSheet(\"border-radius: 15px; border: 1px solid black;\");\n dialColorPreview->move(55, 35); // Center of dial\n\n dialIconView = new QLabel(dialContainer);\n dialIconView->setFixedSize(30, 30);\n dialIconView->setStyleSheet(\"border-radius: 1px; border: 1px solid black;\");\n dialIconView->move(55, 35); // Center of dial\n\n // ✅ Position dial near top-right corner initially\n positionDialContainer();\n\n dialDisplay = new QLabel(dialContainer);\n dialDisplay->setAlignment(Qt::AlignCenter);\n dialDisplay->setFixedSize(80, 80);\n dialDisplay->move(30, 30); // Center position inside the dial\n \n\n int fontId = QFontDatabase::addApplicationFont(\":/resources/fonts/Jersey20-Regular.ttf\");\n // int chnFontId = QFontDatabase::addApplicationFont(\":/resources/fonts/NotoSansSC-Medium.ttf\");\n QStringList fontFamilies = QFontDatabase::applicationFontFamilies(fontId);\n\n if (!fontFamilies.isEmpty()) {\n QFont pixelFont(fontFamilies.at(0), 11);\n dialDisplay->setFont(pixelFont);\n }\n\n dialDisplay->setStyleSheet(\"background-color: black; color: white; font-size: 14px; border-radius: 4px;\");\n\n dialHiddenButton = new QPushButton(dialContainer);\n dialHiddenButton->setFixedSize(80, 80);\n dialHiddenButton->move(30, 30); // Same position as dialDisplay\n dialHiddenButton->setStyleSheet(\"background: transparent; border: none;\"); // ✅ Fully invisible\n dialHiddenButton->setFocusPolicy(Qt::NoFocus); // ✅ Prevents accidental focus issues\n dialHiddenButton->setEnabled(false); // ✅ Disabled by default\n\n // ✅ Connection will be set in changeDialMode() based on current mode\n\n dialColorPreview->raise(); // ✅ Ensure it's on top\n dialIconView->raise();\n // ✅ Connect dial input and release\n // connect(pageDial, &QDial::valueChanged, this, &MainWindow::handleDialInput);\n // connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onDialReleased);\n\n // connect(modeDial, &QDial::valueChanged, this, &MainWindow::handleModeSelection);\n changeDialMode(currentDialMode); // ✅ Set initial mode\n\n // ✅ Enable drag detection\n dialContainer->installEventFilter(this);\n }\n\n // ✅ Ensure that `dialContainer` is always initialized before setting visibility\n if (dialContainer) {\n dialContainer->setVisible(!dialContainer->isVisible());\n }\n\n initializeDialSound(); // ✅ Ensure sound is loaded\n\n // Inside toggleDial():\n \n if (!dialDisplay) {\n dialDisplay = new QLabel(dialContainer);\n }\n updateDialDisplay(); // ✅ Ensure it's updated before showing\n\n if (controllerManager) {\n connect(controllerManager, &SDLControllerManager::buttonHeld, this, &MainWindow::handleButtonHeld);\n connect(controllerManager, &SDLControllerManager::buttonReleased, this, &MainWindow::handleButtonReleased);\n connect(controllerManager, &SDLControllerManager::leftStickAngleChanged, pageDial, &QDial::setValue);\n connect(controllerManager, &SDLControllerManager::leftStickReleased, pageDial, &QDial::sliderReleased);\n connect(controllerManager, &SDLControllerManager::buttonSinglePress, this, &MainWindow::handleControllerButton);\n }\n\n loadButtonMappings(); // ✅ Load button mappings for the controller\n\n // Update button state to reflect dial visibility\n updateDialButtonState();\n}\n void positionDialContainer() {\n if (!dialContainer) return;\n \n // Get window dimensions\n int windowWidth = width();\n int windowHeight = height();\n \n // Get dial dimensions\n int dialWidth = dialContainer->width(); // 140px\n int dialHeight = dialContainer->height(); // 140px\n \n // Calculate toolbar height based on current layout\n int toolbarHeight = isToolbarTwoRows ? 80 : 50; // Approximate heights\n \n // Add tab bar height if visible\n int tabBarHeight = (tabBarContainer && tabBarContainer->isVisible()) ? 38 : 0;\n \n // Define margins from edges\n int rightMargin = 20; // Distance from right edge\n int topMargin = 20; // Distance from top edge (below toolbar and tabs)\n \n // Calculate ideal position (top-right corner with margins)\n int idealX = windowWidth - dialWidth - rightMargin;\n int idealY = toolbarHeight + tabBarHeight + topMargin;\n \n // Ensure dial stays within window bounds with minimum margins\n int minMargin = 10;\n int maxX = windowWidth - dialWidth - minMargin;\n int maxY = windowHeight - dialHeight - minMargin;\n \n // Clamp position to stay within bounds\n int finalX = qBound(minMargin, idealX, maxX);\n int finalY = qBound(toolbarHeight + tabBarHeight + minMargin, idealY, maxY);\n \n // Move the dial to the calculated position\n dialContainer->move(finalX, finalY);\n}\n void handleDialInput(int angle) {\n if (!tracking) {\n startAngle = angle; // ✅ Set initial position\n accumulatedRotation = 0; // ✅ Reset tracking\n tracking = true;\n lastAngle = angle;\n return;\n }\n\n int delta = angle - lastAngle;\n\n // ✅ Handle 360-degree wrapping\n if (delta > 180) delta -= 360; // Example: 350° → 10° should be -20° instead of +340°\n if (delta < -180) delta += 360; // Example: 10° → 350° should be +20° instead of -340°\n\n accumulatedRotation += delta; // ✅ Accumulate movement\n\n // ✅ Detect crossing a 45-degree boundary\n int currentClicks = accumulatedRotation / 45; // Total number of \"clicks\" crossed\n int previousClicks = (accumulatedRotation - delta) / 45; // Previous click count\n\n if (currentClicks != previousClicks) { // ✅ Play sound if a new boundary is crossed\n \n if (dialClickSound) {\n dialClickSound->play();\n \n // ✅ Vibrate controller\n SDL_Joystick *joystick = controllerManager->getJoystick();\n if (joystick) {\n // Note: SDL_JoystickRumble requires SDL 2.0.9+\n // For older versions, this will be a no-op\n #if SDL_VERSION_ATLEAST(2, 0, 9)\n SDL_JoystickRumble(joystick, 0xA000, 0xF000, 10); // Vibrate shortly\n #endif\n }\n \n grossTotalClicks += 1;\n tempClicks = currentClicks;\n updateDialDisplay();\n \n if (isLowResPreviewEnabled()) {\n int previewPage = qBound(1, getCurrentPageForCanvas(currentCanvas()) + currentClicks, 99999);\n currentCanvas()->loadPdfPreviewAsync(previewPage);\n }\n }\n }\n\n lastAngle = angle; // ✅ Store last position\n}\n void onDialReleased() {\n if (!tracking) return; // ✅ Ignore if no tracking\n\n int pagesToAdvance = fastForwardMode ? 8 : 1;\n int totalClicks = accumulatedRotation / 45; // ✅ Convert degrees to pages\n\n /*\n int leftOver = accumulatedRotation % 45; // ✅ Track remaining rotation\n if (leftOver > 22 && totalClicks >= 0) {\n totalClicks += 1; // ✅ Round up if more than halfway\n } \n else if (leftOver <= -22 && totalClicks >= 0) {\n totalClicks -= 1; // ✅ Round down if more than halfway\n }\n */\n \n\n if (totalClicks != 0 || grossTotalClicks != 0) { // ✅ Only switch pages if movement happened\n // Use concurrent autosave for smoother dial operation\n if (currentCanvas()->isEdited()) {\n saveCurrentPageConcurrent();\n }\n\n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1;\n int newPage = qBound(1, currentPage + totalClicks * pagesToAdvance, 99999);\n \n // ✅ Use direction-aware page switching for dial\n int direction = (totalClicks * pagesToAdvance > 0) ? 1 : -1;\n switchPageWithDirection(newPage, direction);\n pageInput->setValue(newPage);\n tempClicks = 0;\n updateDialDisplay(); \n /*\n if (dialClickSound) {\n dialClickSound->play();\n }\n */\n }\n\n accumulatedRotation = 0; // ✅ Reset tracking\n grossTotalClicks = 0;\n tracking = false;\n}\n void initializeDialSound() {\n if (!dialClickSound) {\n dialClickSound = new QSoundEffect(this);\n dialClickSound->setSource(QUrl::fromLocalFile(\":/resources/sounds/dial_click.wav\")); // ✅ Path to the sound file\n dialClickSound->setVolume(0.8); // ✅ Set volume (0.0 - 1.0)\n }\n}\n void changeDialMode(DialMode mode) {\n\n if (!dialContainer) return; // ✅ Ensure dial container exists\n currentDialMode = mode; // ✅ Set new mode\n updateDialDisplay();\n\n // ✅ Enable dialHiddenButton for PanAndPageScroll and ZoomControl modes\n dialHiddenButton->setEnabled(currentDialMode == PanAndPageScroll || currentDialMode == ZoomControl);\n\n // ✅ Disconnect previous slots\n disconnect(pageDial, &QDial::valueChanged, nullptr, nullptr);\n disconnect(pageDial, &QDial::sliderReleased, nullptr, nullptr);\n \n // ✅ Disconnect dialHiddenButton to reconnect with appropriate function\n disconnect(dialHiddenButton, &QPushButton::clicked, nullptr, nullptr);\n \n // ✅ Connect dialHiddenButton to appropriate function based on mode\n if (currentDialMode == PanAndPageScroll) {\n connect(dialHiddenButton, &QPushButton::clicked, this, &MainWindow::toggleControlBar);\n } else if (currentDialMode == ZoomControl) {\n connect(dialHiddenButton, &QPushButton::clicked, this, &MainWindow::cycleZoomLevels);\n }\n\n dialColorPreview->hide();\n dialDisplay->setStyleSheet(\"background-color: black; color: white; font-size: 14px; border-radius: 40px;\");\n\n // ✅ Connect the correct function set for the current mode\n switch (currentDialMode) {\n case PageSwitching:\n connect(pageDial, &QDial::valueChanged, this, &MainWindow::handleDialInput);\n connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onDialReleased);\n break;\n case ZoomControl:\n connect(pageDial, &QDial::valueChanged, this, &MainWindow::handleDialZoom);\n connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onZoomReleased);\n break;\n case ThicknessControl:\n connect(pageDial, &QDial::valueChanged, this, &MainWindow::handleDialThickness);\n connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onThicknessReleased);\n break;\n\n case ToolSwitching:\n connect(pageDial, &QDial::valueChanged, this, &MainWindow::handleToolSelection);\n connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onToolReleased);\n break;\n case PresetSelection:\n connect(pageDial, &QDial::valueChanged, this, &MainWindow::handlePresetSelection);\n connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onPresetReleased);\n break;\n case PanAndPageScroll:\n connect(pageDial, &QDial::valueChanged, this, &MainWindow::handleDialPanScroll);\n connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onPanScrollReleased);\n break;\n \n }\n}\n void handleDialZoom(int angle) {\n if (!tracking) {\n startAngle = angle; \n accumulatedRotation = 0; \n tracking = true;\n lastAngle = angle;\n return;\n }\n\n int delta = angle - lastAngle;\n\n // ✅ Handle 360-degree wrapping\n if (delta > 180) delta -= 360;\n if (delta < -180) delta += 360;\n\n accumulatedRotation += delta;\n\n if (abs(delta) < 4) { \n return; \n }\n\n // ✅ Apply zoom dynamically (instead of waiting for release)\n int oldZoom = zoomSlider->value();\n int newZoom = qBound(10, oldZoom + (delta / 4), 400); \n zoomSlider->setValue(newZoom);\n updateZoom(); // ✅ Ensure zoom updates immediately\n updateDialDisplay(); \n\n lastAngle = angle;\n}\n void handleDialThickness(int angle) {\n if (!tracking) {\n startAngle = angle;\n tracking = true;\n lastAngle = angle;\n return;\n }\n\n int delta = angle - lastAngle;\n if (delta > 180) delta -= 360;\n if (delta < -180) delta += 360;\n\n int thicknessStep = fastForwardMode ? 5 : 1;\n currentCanvas()->setPenThickness(qBound(1.0, currentCanvas()->getPenThickness() + (delta / 10.0) * thicknessStep, 50.0));\n\n updateDialDisplay();\n lastAngle = angle;\n}\n void onZoomReleased() {\n accumulatedRotation = 0;\n tracking = false;\n}\n void onThicknessReleased() {\n accumulatedRotation = 0;\n tracking = false;\n}\n void updateDialDisplay() {\n if (!dialDisplay) return;\n if (!dialColorPreview) return;\n if (!dialIconView) return;\n dialIconView->show();\n qreal dpr = initialDpr;\n QColor currentColor = currentCanvas()->getPenColor();\n switch (currentDialMode) {\n case DialMode::PageSwitching:\n if (fastForwardMode){\n dialDisplay->setText(QString(tr(\"\\n\\nPage\\n%1\").arg(getCurrentPageForCanvas(currentCanvas()) + 1 + tempClicks * 8)));\n }\n else {\n dialDisplay->setText(QString(tr(\"\\n\\nPage\\n%1\").arg(getCurrentPageForCanvas(currentCanvas()) + 1 + tempClicks)));\n }\n dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/bookpage_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n break;\n case DialMode::ThicknessControl:\n {\n QString toolName;\n switch (currentCanvas()->getCurrentTool()) {\n case ToolType::Pen:\n toolName = tr(\"Pen\");\n break;\n case ToolType::Marker:\n toolName = tr(\"Marker\");\n break;\n case ToolType::Eraser:\n toolName = tr(\"Eraser\");\n break;\n }\n dialDisplay->setText(QString(tr(\"\\n\\n%1\\n%2\").arg(toolName).arg(QString::number(currentCanvas()->getPenThickness(), 'f', 1))));\n dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/thickness_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n }\n break;\n case DialMode::ZoomControl:\n dialDisplay->setText(QString(tr(\"\\n\\nZoom\\n%1%\").arg(currentCanvas() ? currentCanvas()->getZoom() * initialDpr : zoomSlider->value() * initialDpr)));\n dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/zoom_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n break;\n \n case DialMode::ToolSwitching:\n // ✅ Convert ToolType to QString for display\n switch (currentCanvas()->getCurrentTool()) {\n case ToolType::Pen:\n dialDisplay->setText(tr(\"\\n\\n\\nPen\"));\n dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/pen_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n break;\n case ToolType::Marker:\n dialDisplay->setText(tr(\"\\n\\n\\nMarker\"));\n dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/marker_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n break;\n case ToolType::Eraser:\n dialDisplay->setText(tr(\"\\n\\n\\nEraser\"));\n dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/eraser_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n break;\n }\n break;\n case PresetSelection:\n dialColorPreview->show();\n dialIconView->hide();\n dialColorPreview->setStyleSheet(QString(\"background-color: %1; border-radius: 15px; border: 1px solid black;\")\n .arg(colorPresets[currentPresetIndex].name()));\n dialDisplay->setText(QString(tr(\"\\n\\nPreset %1\\n#%2\"))\n .arg(currentPresetIndex + 1) // ✅ Display preset index (1-based)\n .arg(colorPresets[currentPresetIndex].name().remove(\"#\"))); // ✅ Display hex color\n // dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/preset_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n break;\n case DialMode::PanAndPageScroll:\n dialIconView->setPixmap(QPixmap(\":/resources/icons/scroll_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n QString fullscreenStatus = controlBarVisible ? tr(\"Etr\") : tr(\"Exit\");\n dialDisplay->setText(QString(tr(\"\\n\\nPage %1\\n%2 FulScr\")).arg(getCurrentPageForCanvas(currentCanvas()) + 1).arg(fullscreenStatus));\n break;\n }\n}\n void handleToolSelection(int angle) {\n static int lastToolIndex = -1; // ✅ Track last tool index\n\n // ✅ Snap to closest fixed 120° step\n int snappedAngle = (angle + 60) / 120 * 120; // Round to nearest 120°\n int toolIndex = snappedAngle / 120; // Convert to tool index (0, 1, 2)\n\n if (toolIndex >= 3) toolIndex = 0; // ✅ Wrap around at 360° → Back to Pen (0)\n\n if (toolIndex != lastToolIndex) { // ✅ Only switch if tool actually changes\n toolSelector->setCurrentIndex(toolIndex); // ✅ Change tool\n lastToolIndex = toolIndex; // ✅ Update last selected tool\n\n // ✅ Play click sound when tool changes\n if (dialClickSound) {\n dialClickSound->play();\n }\n\n SDL_Joystick *joystick = controllerManager->getJoystick();\n\n if (joystick) {\n #if SDL_VERSION_ATLEAST(2, 0, 9)\n SDL_JoystickRumble(joystick, 0xA000, 0xF000, 20); // ✅ Vibrate controller\n #endif\n }\n\n updateToolButtonStates(); // ✅ Update tool button states\n updateDialDisplay(); // ✅ Update dial display]\n }\n}\n void onToolReleased() {\n \n}\n void handlePresetSelection(int angle) {\n static int lastAngle = angle;\n int delta = angle - lastAngle;\n\n // ✅ Handle 360-degree wrapping\n if (delta > 180) delta -= 360;\n if (delta < -180) delta += 360;\n\n if (abs(delta) >= 60) { // ✅ Change preset every 60° (6 presets)\n lastAngle = angle;\n currentPresetIndex = (currentPresetIndex + (delta > 0 ? 1 : -1) + colorPresets.size()) % colorPresets.size();\n \n QColor selectedColor = colorPresets[currentPresetIndex];\n currentCanvas()->setPenColor(selectedColor);\n updateCustomColorButtonStyle(selectedColor);\n updateDialDisplay();\n updateColorButtonStates(); // Update button states when preset is selected\n \n if (dialClickSound) dialClickSound->play(); // ✅ Provide feedback\n SDL_Joystick *joystick = controllerManager->getJoystick();\n if (joystick) {\n #if SDL_VERSION_ATLEAST(2, 0, 9)\n SDL_JoystickRumble(joystick, 0xA000, 0xF000, 25); // Vibrate shortly\n #endif\n }\n }\n}\n void onPresetReleased() {\n accumulatedRotation = 0;\n tracking = false;\n}\n void addColorPreset() {\n QColor currentColor = currentCanvas()->getPenColor();\n\n // ✅ Prevent duplicates\n if (!colorPresets.contains(currentColor)) {\n if (colorPresets.size() >= 6) {\n colorPresets.dequeue(); // ✅ Remove oldest color\n }\n colorPresets.enqueue(currentColor);\n }\n}\n void updateColorPalette() {\n // Clear existing presets\n colorPresets.clear();\n currentPresetIndex = 0;\n \n // Add default pen color (theme-aware)\n colorPresets.enqueue(getDefaultPenColor());\n \n // Add palette colors\n colorPresets.enqueue(getPaletteColor(\"red\"));\n colorPresets.enqueue(getPaletteColor(\"yellow\"));\n colorPresets.enqueue(getPaletteColor(\"blue\"));\n colorPresets.enqueue(getPaletteColor(\"green\"));\n colorPresets.enqueue(QColor(\"#000000\")); // Black (always same)\n colorPresets.enqueue(QColor(\"#FFFFFF\")); // White (always same)\n \n // Only update UI elements if they exist\n if (redButton && blueButton && yellowButton && greenButton) {\n bool darkMode = isDarkMode();\n \n // Update color button icons based on current palette (not theme)\n QString redIconPath = useBrighterPalette ? \":/resources/icons/pen_light_red.png\" : \":/resources/icons/pen_dark_red.png\";\n QString blueIconPath = useBrighterPalette ? \":/resources/icons/pen_light_blue.png\" : \":/resources/icons/pen_dark_blue.png\";\n QString yellowIconPath = useBrighterPalette ? \":/resources/icons/pen_light_yellow.png\" : \":/resources/icons/pen_dark_yellow.png\";\n QString greenIconPath = useBrighterPalette ? \":/resources/icons/pen_light_green.png\" : \":/resources/icons/pen_dark_green.png\";\n \n redButton->setIcon(QIcon(redIconPath));\n blueButton->setIcon(QIcon(blueIconPath));\n yellowButton->setIcon(QIcon(yellowIconPath));\n greenButton->setIcon(QIcon(greenIconPath));\n \n // Update color button states\n updateColorButtonStates();\n }\n}\n QColor getPaletteColor(const QString &colorName) {\n if (useBrighterPalette) {\n // Brighter colors (good for dark backgrounds)\n if (colorName == \"red\") return QColor(\"#FF7755\");\n if (colorName == \"yellow\") return QColor(\"#EECC00\");\n if (colorName == \"blue\") return QColor(\"#66CCFF\");\n if (colorName == \"green\") return QColor(\"#55FF77\");\n } else {\n // Darker colors (good for light backgrounds)\n if (colorName == \"red\") return QColor(\"#AA0000\");\n if (colorName == \"yellow\") return QColor(\"#997700\");\n if (colorName == \"blue\") return QColor(\"#0000AA\");\n if (colorName == \"green\") return QColor(\"#007700\");\n }\n \n // Fallback colors\n if (colorName == \"black\") return QColor(\"#000000\");\n if (colorName == \"white\") return QColor(\"#FFFFFF\");\n \n return QColor(\"#000000\"); // Default fallback\n}\n qreal getDevicePixelRatio() {\n QScreen *screen = QGuiApplication::primaryScreen();\n qreal devicePixelRatio = screen ? screen->devicePixelRatio() : 1.0; // Default to 1.0 if null\n return devicePixelRatio;\n}\n bool isDarkMode() {\n QColor bg = palette().color(QPalette::Window);\n return bg.lightness() < 128; // Lightness scale: 0 (black) - 255 (white)\n}\n QIcon loadThemedIcon(const QString& baseName) {\n QString path = isDarkMode()\n ? QString(\":/resources/icons/%1_reversed.png\").arg(baseName)\n : QString(\":/resources/icons/%1.png\").arg(baseName);\n return QIcon(path);\n}\n QString createButtonStyle(bool darkMode) {\n if (darkMode) {\n // Dark mode: Keep current white highlights (good contrast)\n return R\"(\n QPushButton {\n background: transparent;\n border: none;\n padding: 6px;\n }\n QPushButton:hover {\n background: rgba(255, 255, 255, 50);\n }\n QPushButton:pressed {\n background: rgba(0, 0, 0, 50);\n }\n QPushButton[selected=\"true\"] {\n background: rgba(255, 255, 255, 100);\n border: 2px solid rgba(255, 255, 255, 150);\n padding: 4px;\n border-radius: 4px;\n }\n QPushButton[selected=\"true\"]:hover {\n background: rgba(255, 255, 255, 120);\n }\n QPushButton[selected=\"true\"]:pressed {\n background: rgba(0, 0, 0, 50);\n }\n )\";\n } else {\n // Light mode: Use darker colors for better visibility\n return R\"(\n QPushButton {\n background: transparent;\n border: none;\n padding: 6px;\n }\n QPushButton:hover {\n background: rgba(0, 0, 0, 30);\n }\n QPushButton:pressed {\n background: rgba(0, 0, 0, 60);\n }\n QPushButton[selected=\"true\"] {\n background: rgba(0, 0, 0, 80);\n border: 2px solid rgba(0, 0, 0, 120);\n padding: 4px;\n border-radius: 4px;\n }\n QPushButton[selected=\"true\"]:hover {\n background: rgba(0, 0, 0, 100);\n }\n QPushButton[selected=\"true\"]:pressed {\n background: rgba(0, 0, 0, 140);\n }\n )\";\n }\n}\n void handleDialPanScroll(int angle) {\n if (!tracking) {\n startAngle = angle;\n accumulatedRotation = 0;\n accumulatedRotationAfterLimit = 0;\n tracking = true;\n lastAngle = angle;\n pendingPageFlip = 0;\n return;\n }\n\n int delta = angle - lastAngle;\n\n // Handle 360 wrap\n if (delta > 180) delta -= 360;\n if (delta < -180) delta += 360;\n\n accumulatedRotation += delta;\n\n // Pan scroll\n int panDelta = delta * 4; // Adjust scroll sensitivity here\n int currentPan = panYSlider->value();\n int newPan = currentPan + panDelta;\n\n // Clamp pan slider\n newPan = qBound(panYSlider->minimum(), newPan, panYSlider->maximum());\n panYSlider->setValue(newPan);\n\n // ✅ NEW → if slider reached top/bottom, accumulate AFTER LIMIT\n if (newPan == panYSlider->maximum()) {\n accumulatedRotationAfterLimit += delta;\n\n if (accumulatedRotationAfterLimit >= 120) {\n pendingPageFlip = +1; // Flip next when released\n }\n } \n else if (newPan == panYSlider->minimum()) {\n accumulatedRotationAfterLimit += delta;\n\n if (accumulatedRotationAfterLimit <= -120) {\n pendingPageFlip = -1; // Flip previous when released\n }\n } \n else {\n // Reset after limit accumulator when not at limit\n accumulatedRotationAfterLimit = 0;\n pendingPageFlip = 0;\n }\n\n lastAngle = angle;\n}\n void onPanScrollReleased() {\n // ✅ Perform page flip only when dial released and flip is pending\n if (pendingPageFlip != 0) {\n // Use concurrent saving for smooth dial operation\n if (currentCanvas()->isEdited()) {\n saveCurrentPageConcurrent();\n }\n\n int currentPage = getCurrentPageForCanvas(currentCanvas());\n int newPage = qBound(1, currentPage + pendingPageFlip + 1, 99999);\n \n // ✅ Use direction-aware page switching for pan-and-scroll dial\n switchPageWithDirection(newPage, pendingPageFlip);\n pageInput->setValue(newPage);\n updateDialDisplay();\n\n SDL_Joystick *joystick = controllerManager->getJoystick();\n if (joystick) {\n #if SDL_VERSION_ATLEAST(2, 0, 9)\n SDL_JoystickRumble(joystick, 0xA000, 0xF000, 25); // Vibrate shortly\n #endif\n }\n }\n\n // Reset states\n pendingPageFlip = 0;\n accumulatedRotation = 0;\n accumulatedRotationAfterLimit = 0;\n tracking = false;\n}\n void handleTouchZoomChange(int newZoom) {\n // Update zoom slider without triggering updateZoom again\n zoomSlider->blockSignals(true);\n int oldZoom = zoomSlider->value(); // Get the old zoom value before updating the slider\n zoomSlider->setValue(newZoom);\n zoomSlider->blockSignals(false);\n \n // Show both scrollbars during gesture\n if (panXSlider->maximum() > 0) {\n panXSlider->setVisible(true);\n }\n if (panYSlider->maximum() > 0) {\n panYSlider->setVisible(true);\n }\n scrollbarsVisible = true;\n \n // Update canvas zoom directly\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n // The canvas zoom has already been set by the gesture processing in InkCanvas::event()\n // So we don't need to set it again, just update the last zoom level\n canvas->setLastZoomLevel(newZoom);\n updatePanRange();\n \n // ✅ FIXED: Add thickness adjustment for pinch-to-zoom gestures to maintain visual consistency\n adjustThicknessForZoom(oldZoom, newZoom);\n \n updateDialDisplay();\n }\n}\n void handleTouchPanChange(int panX, int panY) {\n // Clamp values to valid ranges\n panX = qBound(panXSlider->minimum(), panX, panXSlider->maximum());\n panY = qBound(panYSlider->minimum(), panY, panYSlider->maximum());\n \n // Show both scrollbars during gesture\n if (panXSlider->maximum() > 0) {\n panXSlider->setVisible(true);\n }\n if (panYSlider->maximum() > 0) {\n panYSlider->setVisible(true);\n }\n scrollbarsVisible = true;\n \n // Update sliders without triggering their valueChanged signals\n panXSlider->blockSignals(true);\n panYSlider->blockSignals(true);\n panXSlider->setValue(panX);\n panYSlider->setValue(panY);\n panXSlider->blockSignals(false);\n panYSlider->blockSignals(false);\n \n // Update canvas pan directly\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n canvas->setPanX(panX);\n canvas->setPanY(panY);\n canvas->setLastPanX(panX);\n canvas->setLastPanY(panY);\n }\n}\n void handleTouchGestureEnd() {\n // Hide scrollbars immediately when touch gesture ends\n panXSlider->setVisible(false);\n panYSlider->setVisible(false);\n scrollbarsVisible = false;\n}\n void updateColorButtonStates() {\n // Check if there's a current canvas\n if (!currentCanvas()) return;\n \n // Get current pen color\n QColor currentColor = currentCanvas()->getPenColor();\n \n // Determine if we're in dark mode to match the correct colors\n bool darkMode = isDarkMode();\n \n // Reset all color buttons to original style\n redButton->setProperty(\"selected\", false);\n blueButton->setProperty(\"selected\", false);\n yellowButton->setProperty(\"selected\", false);\n greenButton->setProperty(\"selected\", false);\n blackButton->setProperty(\"selected\", false);\n whiteButton->setProperty(\"selected\", false);\n \n // Set the selected property for the matching color button based on current palette\n QColor redColor = getPaletteColor(\"red\");\n QColor blueColor = getPaletteColor(\"blue\");\n QColor yellowColor = getPaletteColor(\"yellow\");\n QColor greenColor = getPaletteColor(\"green\");\n \n if (currentColor == redColor) {\n redButton->setProperty(\"selected\", true);\n } else if (currentColor == blueColor) {\n blueButton->setProperty(\"selected\", true);\n } else if (currentColor == yellowColor) {\n yellowButton->setProperty(\"selected\", true);\n } else if (currentColor == greenColor) {\n greenButton->setProperty(\"selected\", true);\n } else if (currentColor == QColor(\"#000000\")) {\n blackButton->setProperty(\"selected\", true);\n } else if (currentColor == QColor(\"#FFFFFF\")) {\n whiteButton->setProperty(\"selected\", true);\n }\n \n // Force style update\n redButton->style()->unpolish(redButton);\n redButton->style()->polish(redButton);\n blueButton->style()->unpolish(blueButton);\n blueButton->style()->polish(blueButton);\n yellowButton->style()->unpolish(yellowButton);\n yellowButton->style()->polish(yellowButton);\n greenButton->style()->unpolish(greenButton);\n greenButton->style()->polish(greenButton);\n blackButton->style()->unpolish(blackButton);\n blackButton->style()->polish(blackButton);\n whiteButton->style()->unpolish(whiteButton);\n whiteButton->style()->polish(whiteButton);\n}\n void selectColorButton(QPushButton* selectedButton) {\n updateColorButtonStates();\n}\n void updateStraightLineButtonState() {\n // Check if there's a current canvas\n if (!currentCanvas()) return;\n \n // Update the button state to match the canvas straight line mode\n bool isEnabled = currentCanvas()->isStraightLineMode();\n \n // Set visual indicator that the button is active/inactive\n if (straightLineToggleButton) {\n straightLineToggleButton->setProperty(\"selected\", isEnabled);\n \n // Force style update\n straightLineToggleButton->style()->unpolish(straightLineToggleButton);\n straightLineToggleButton->style()->polish(straightLineToggleButton);\n }\n}\n void updateRopeToolButtonState() {\n // Check if there's a current canvas\n if (!currentCanvas()) return;\n\n // Update the button state to match the canvas rope tool mode\n bool isEnabled = currentCanvas()->isRopeToolMode();\n\n // Set visual indicator that the button is active/inactive\n if (ropeToolButton) {\n ropeToolButton->setProperty(\"selected\", isEnabled);\n\n // Force style update\n ropeToolButton->style()->unpolish(ropeToolButton);\n ropeToolButton->style()->polish(ropeToolButton);\n }\n}\n void updateMarkdownButtonState() {\n // Check if there's a current canvas\n if (!currentCanvas()) return;\n\n // Update the button state to match the canvas markdown selection mode\n bool isEnabled = currentCanvas()->isMarkdownSelectionMode();\n\n // Set visual indicator that the button is active/inactive\n if (markdownButton) {\n markdownButton->setProperty(\"selected\", isEnabled);\n\n // Force style update\n markdownButton->style()->unpolish(markdownButton);\n markdownButton->style()->polish(markdownButton);\n }\n}\n void setPenTool() {\n if (!currentCanvas()) return;\n currentCanvas()->setTool(ToolType::Pen);\n updateToolButtonStates();\n updateThicknessSliderForCurrentTool();\n updateDialDisplay();\n}\n void setMarkerTool() {\n if (!currentCanvas()) return;\n currentCanvas()->setTool(ToolType::Marker);\n updateToolButtonStates();\n updateThicknessSliderForCurrentTool();\n updateDialDisplay();\n}\n void setEraserTool() {\n if (!currentCanvas()) return;\n currentCanvas()->setTool(ToolType::Eraser);\n updateToolButtonStates();\n updateThicknessSliderForCurrentTool();\n updateDialDisplay();\n}\n QColor getContrastingTextColor(const QColor &backgroundColor) {\n // Calculate relative luminance using the formula from WCAG 2.0\n double r = backgroundColor.redF();\n double g = backgroundColor.greenF();\n double b = backgroundColor.blueF();\n \n // Gamma correction\n r = (r <= 0.03928) ? r/12.92 : pow((r + 0.055)/1.055, 2.4);\n g = (g <= 0.03928) ? g/12.92 : pow((g + 0.055)/1.055, 2.4);\n b = (b <= 0.03928) ? b/12.92 : pow((b + 0.055)/1.055, 2.4);\n \n // Calculate luminance\n double luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;\n \n // Use white text for darker backgrounds\n return (luminance < 0.5) ? Qt::white : Qt::black;\n}\n void updateCustomColorButtonStyle(const QColor &color) {\n QColor textColor = getContrastingTextColor(color);\n customColorButton->setStyleSheet(QString(\"background-color: %1; color: %2\")\n .arg(color.name())\n .arg(textColor.name()));\n customColorButton->setText(QString(\"%1\").arg(color.name()).toUpper());\n}\n void openRecentNotebooksDialog() {\n RecentNotebooksDialog dialog(this, recentNotebooksManager, this);\n dialog.exec();\n}\n void showPendingTooltip() {\n // This function is now unused since we disabled tablet tracking\n // Tooltips will work through normal mouse hover events instead\n // Keeping the function for potential future use\n}\n void showRopeSelectionMenu(const QPoint &position) {\n // Create context menu for rope tool selection\n QMenu *contextMenu = new QMenu(this);\n contextMenu->setAttribute(Qt::WA_DeleteOnClose);\n \n // Add Copy action\n QAction *copyAction = contextMenu->addAction(tr(\"Copy\"));\n copyAction->setIcon(loadThemedIcon(\"copy\"));\n connect(copyAction, &QAction::triggered, this, [this]() {\n if (currentCanvas()) {\n currentCanvas()->copyRopeSelection();\n }\n });\n \n // Add Delete action\n QAction *deleteAction = contextMenu->addAction(tr(\"Delete\"));\n deleteAction->setIcon(loadThemedIcon(\"trash\"));\n connect(deleteAction, &QAction::triggered, this, [this]() {\n if (currentCanvas()) {\n currentCanvas()->deleteRopeSelection();\n }\n });\n \n // Add Cancel action\n QAction *cancelAction = contextMenu->addAction(tr(\"Cancel\"));\n cancelAction->setIcon(loadThemedIcon(\"cross\"));\n connect(cancelAction, &QAction::triggered, this, [this]() {\n if (currentCanvas()) {\n currentCanvas()->cancelRopeSelection();\n }\n });\n \n // Convert position from canvas coordinates to global coordinates\n QPoint globalPos = currentCanvas()->mapToGlobal(position);\n \n // Show the menu at the specified position\n contextMenu->popup(globalPos);\n}\n void toggleOutlineSidebar() {\n outlineSidebarVisible = !outlineSidebarVisible;\n \n // Hide bookmarks sidebar if it's visible when opening outline\n if (outlineSidebarVisible && bookmarksSidebar && bookmarksSidebar->isVisible()) {\n bookmarksSidebar->setVisible(false);\n bookmarksSidebarVisible = false;\n // Update bookmarks button state\n if (toggleBookmarksButton) {\n toggleBookmarksButton->setProperty(\"selected\", false);\n toggleBookmarksButton->style()->unpolish(toggleBookmarksButton);\n toggleBookmarksButton->style()->polish(toggleBookmarksButton);\n }\n }\n \n outlineSidebar->setVisible(outlineSidebarVisible);\n \n // Update button toggle state\n if (toggleOutlineButton) {\n toggleOutlineButton->setProperty(\"selected\", outlineSidebarVisible);\n toggleOutlineButton->style()->unpolish(toggleOutlineButton);\n toggleOutlineButton->style()->polish(toggleOutlineButton);\n }\n \n // Load PDF outline when showing sidebar for the first time\n if (outlineSidebarVisible) {\n loadPdfOutline();\n }\n}\n void onOutlineItemClicked(QTreeWidgetItem *item, int column) {\n Q_UNUSED(column);\n \n if (!item) return;\n \n // Get the page number stored in the item data\n QVariant pageData = item->data(0, Qt::UserRole);\n if (pageData.isValid()) {\n int pageNumber = pageData.toInt();\n if (pageNumber >= 0) {\n // Switch to the selected page (convert from 0-based to 1-based)\n switchPage(pageNumber + 1);\n pageInput->setValue(pageNumber + 1);\n }\n }\n}\n void loadPdfOutline() {\n if (!outlineTree) return;\n \n outlineTree->clear();\n \n // Get current PDF document\n Poppler::Document* pdfDoc = getPdfDocument();\n if (!pdfDoc) return;\n \n // Get the outline from the PDF document\n QVector outlineItems = pdfDoc->outline();\n \n if (outlineItems.isEmpty()) {\n // If no outline exists, show page numbers as fallback\n int pageCount = pdfDoc->numPages();\n for (int i = 0; i < pageCount; ++i) {\n QTreeWidgetItem* item = new QTreeWidgetItem(outlineTree);\n item->setText(0, QString(tr(\"Page %1\")).arg(i + 1));\n item->setData(0, Qt::UserRole, i); // Store 0-based page index\n }\n } else {\n // Process the actual PDF outline\n for (const Poppler::OutlineItem& outlineItem : outlineItems) {\n addOutlineItem(outlineItem, nullptr);\n }\n }\n \n // Expand the first level by default\n outlineTree->expandToDepth(0);\n}\n void addOutlineItem(const Poppler::OutlineItem& outlineItem, QTreeWidgetItem* parentItem) {\n if (outlineItem.isNull()) return;\n \n QTreeWidgetItem* item;\n if (parentItem) {\n item = new QTreeWidgetItem(parentItem);\n } else {\n item = new QTreeWidgetItem(outlineTree);\n }\n \n // Set the title\n item->setText(0, outlineItem.name());\n \n // Try to get the page number from the destination\n int pageNumber = -1;\n auto destination = outlineItem.destination();\n if (destination) {\n pageNumber = destination->pageNumber();\n }\n \n // Store the page number (1-based) in the item data\n if (pageNumber >= 0) {\n item->setData(0, Qt::UserRole, pageNumber + 1); // Convert to 1-based\n }\n \n // Add child items recursively\n if (outlineItem.hasChildren()) {\n QVector children = outlineItem.children();\n for (const Poppler::OutlineItem& child : children) {\n addOutlineItem(child, item);\n }\n }\n}\n Poppler::Document* getPdfDocument();\n void toggleBookmarksSidebar() {\n if (!bookmarksSidebar) return;\n \n bool isVisible = bookmarksSidebar->isVisible();\n \n // Hide outline sidebar if it's visible\n if (!isVisible && outlineSidebar && outlineSidebar->isVisible()) {\n outlineSidebar->setVisible(false);\n outlineSidebarVisible = false;\n // Update outline button state\n if (toggleOutlineButton) {\n toggleOutlineButton->setProperty(\"selected\", false);\n toggleOutlineButton->style()->unpolish(toggleOutlineButton);\n toggleOutlineButton->style()->polish(toggleOutlineButton);\n }\n }\n \n bookmarksSidebar->setVisible(!isVisible);\n bookmarksSidebarVisible = !isVisible;\n \n // Update button toggle state\n if (toggleBookmarksButton) {\n toggleBookmarksButton->setProperty(\"selected\", bookmarksSidebarVisible);\n toggleBookmarksButton->style()->unpolish(toggleBookmarksButton);\n toggleBookmarksButton->style()->polish(toggleBookmarksButton);\n }\n \n if (bookmarksSidebarVisible) {\n loadBookmarks(); // Refresh bookmarks when opening\n }\n}\n void onBookmarkItemClicked(QTreeWidgetItem *item, int column) {\n Q_UNUSED(column);\n if (!item) return;\n \n // Get the page number from the item data\n bool ok;\n int pageNumber = item->data(0, Qt::UserRole).toInt(&ok);\n if (ok && pageNumber > 0) {\n // Navigate to the bookmarked page\n switchPageWithDirection(pageNumber, (pageNumber > getCurrentPageForCanvas(currentCanvas()) + 1) ? 1 : -1);\n pageInput->setValue(pageNumber);\n }\n}\n void loadBookmarks() {\n if (!bookmarksTree || !currentCanvas()) return;\n \n bookmarksTree->clear();\n \n // Get the current notebook's save folder\n QString saveFolder = currentCanvas()->getSaveFolder();\n if (saveFolder.isEmpty()) return;\n \n QString bookmarksFile = saveFolder + \"/.bookmarks.txt\";\n QFile file(bookmarksFile);\n \n bookmarks.clear();\n \n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n while (!in.atEnd()) {\n QString line = in.readLine().trimmed();\n if (line.isEmpty()) continue;\n \n QStringList parts = line.split('\\t', Qt::KeepEmptyParts);\n if (parts.size() >= 2) {\n bool ok;\n int pageNum = parts[0].toInt(&ok);\n if (ok) {\n QString title = parts[1];\n bookmarks[pageNum] = title;\n }\n }\n }\n file.close();\n }\n \n // Populate the tree widget\n for (auto it = bookmarks.begin(); it != bookmarks.end(); ++it) {\n QTreeWidgetItem *item = new QTreeWidgetItem(bookmarksTree);\n \n // Create a custom widget for each bookmark item\n QWidget *itemWidget = new QWidget();\n QHBoxLayout *itemLayout = new QHBoxLayout(itemWidget);\n itemLayout->setContentsMargins(5, 2, 5, 2);\n itemLayout->setSpacing(5);\n \n // Page number label (fixed width)\n QLabel *pageLabel = new QLabel(QString(tr(\"Page %1\")).arg(it.key()));\n pageLabel->setFixedWidth(60);\n pageLabel->setStyleSheet(\"font-weight: bold; color: #666;\");\n itemLayout->addWidget(pageLabel);\n \n // Editable title (supports Windows handwriting if available)\n QLineEdit *titleEdit = new QLineEdit(it.value());\n titleEdit->setPlaceholderText(\"Enter bookmark title...\");\n titleEdit->setProperty(\"pageNumber\", it.key()); // Store page number for saving\n \n // Enable IME support for multi-language input\n titleEdit->setAttribute(Qt::WA_InputMethodEnabled, true);\n titleEdit->setInputMethodHints(Qt::ImhNone); // Allow all input methods\n titleEdit->installEventFilter(this); // Install event filter for IME handling\n \n // Connect to save when editing is finished\n connect(titleEdit, &QLineEdit::editingFinished, this, [this, titleEdit]() {\n int pageNum = titleEdit->property(\"pageNumber\").toInt();\n QString newTitle = titleEdit->text().trimmed();\n \n if (newTitle.isEmpty()) {\n // Remove bookmark if title is empty\n bookmarks.remove(pageNum);\n } else {\n // Update bookmark title\n bookmarks[pageNum] = newTitle;\n }\n saveBookmarks();\n updateBookmarkButtonState(); // Update button state\n });\n \n itemLayout->addWidget(titleEdit, 1);\n \n // Store page number in item data for navigation\n item->setData(0, Qt::UserRole, it.key());\n \n // Set the custom widget\n bookmarksTree->setItemWidget(item, 0, itemWidget);\n \n // Set item height\n item->setSizeHint(0, QSize(0, 30));\n }\n \n updateBookmarkButtonState(); // Update button state after loading\n}\n void saveBookmarks() {\n if (!currentCanvas()) return;\n \n QString saveFolder = currentCanvas()->getSaveFolder();\n if (saveFolder.isEmpty()) return;\n \n QString bookmarksFile = saveFolder + \"/.bookmarks.txt\";\n QFile file(bookmarksFile);\n \n if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {\n QTextStream out(&file);\n \n // Sort bookmarks by page number\n QList sortedPages = bookmarks.keys();\n std::sort(sortedPages.begin(), sortedPages.end());\n \n for (int pageNum : sortedPages) {\n out << pageNum << '\\t' << bookmarks[pageNum] << '\\n';\n }\n \n file.close();\n }\n}\n void toggleCurrentPageBookmark() {\n if (!currentCanvas()) return;\n \n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1; // Convert to 1-based\n \n if (bookmarks.contains(currentPage)) {\n // Remove bookmark\n bookmarks.remove(currentPage);\n } else {\n // Add bookmark with default title\n QString defaultTitle = QString(tr(\"Bookmark %1\")).arg(currentPage);\n bookmarks[currentPage] = defaultTitle;\n }\n \n saveBookmarks();\n updateBookmarkButtonState();\n \n // Refresh bookmarks view if visible\n if (bookmarksSidebarVisible) {\n loadBookmarks();\n }\n}\n void updateBookmarkButtonState() {\n if (!toggleBookmarkButton || !currentCanvas()) return;\n \n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1; // Convert to 1-based\n bool isBookmarked = bookmarks.contains(currentPage);\n \n toggleBookmarkButton->setProperty(\"selected\", isBookmarked);\n \n // Update tooltip\n if (isBookmarked) {\n toggleBookmarkButton->setToolTip(tr(\"Remove Bookmark\"));\n } else {\n toggleBookmarkButton->setToolTip(tr(\"Add Bookmark\"));\n }\n \n // Force style update\n toggleBookmarkButton->style()->unpolish(toggleBookmarkButton);\n toggleBookmarkButton->style()->polish(toggleBookmarkButton);\n}\n private:\n InkCanvas *canvas;\n QPushButton *benchmarkButton;\n QLabel *benchmarkLabel;\n QTimer *benchmarkTimer;\n bool benchmarking;\n QPushButton *exportNotebookButton;\n QPushButton *importNotebookButton;\n QPushButton *redButton;\n QPushButton *blueButton;\n QPushButton *yellowButton;\n QPushButton *greenButton;\n QPushButton *blackButton;\n QPushButton *whiteButton;\n QLineEdit *customColorInput;\n QPushButton *customColorButton;\n QPushButton *thicknessButton;\n QSlider *thicknessSlider;\n QFrame *thicknessFrame;\n QComboBox *toolSelector;\n QPushButton *penToolButton;\n QPushButton *markerToolButton;\n QPushButton *eraserToolButton;\n QPushButton *deletePageButton;\n QPushButton *selectFolderButton;\n QPushButton *saveButton;\n QPushButton *saveAnnotatedButton;\n QPushButton *fullscreenButton;\n QPushButton *openControlPanelButton;\n QPushButton *openRecentNotebooksButton;\n QPushButton *loadPdfButton;\n QPushButton *clearPdfButton;\n QPushButton *pdfTextSelectButton;\n QPushButton *toggleTabBarButton;\n QMap pageMap;\n QPushButton *backgroundButton;\n QPushButton *straightLineToggleButton;\n QPushButton *ropeToolButton;\n QPushButton *markdownButton;\n QSlider *zoomSlider;\n QPushButton *zoomButton;\n QFrame *zoomFrame;\n QPushButton *dezoomButton;\n QPushButton *zoom50Button;\n QPushButton *zoom200Button;\n QWidget *zoomContainer;\n QLineEdit *zoomInput;\n QScrollBar *panXSlider;\n QScrollBar *panYSlider;\n QListWidget *tabList;\n QStackedWidget *canvasStack;\n QPushButton *addTabButton;\n QWidget *tabBarContainer;\n QWidget *outlineSidebar;\n QTreeWidget *outlineTree;\n QPushButton *toggleOutlineButton;\n bool outlineSidebarVisible = false;\n QWidget *bookmarksSidebar;\n QTreeWidget *bookmarksTree;\n QPushButton *toggleBookmarksButton;\n QPushButton *toggleBookmarkButton;\n QPushButton *touchGesturesButton;\n bool bookmarksSidebarVisible = false;\n QMap bookmarks;\n QPushButton *jumpToPageButton;\n QWidget *dialContainer = nullptr;\n QDial *pageDial = nullptr;\n QDial *modeDial = nullptr;\n QPushButton *dialToggleButton;\n bool fastForwardMode = false;\n QPushButton *fastForwardButton;\n int lastAngle = 0;\n int startAngle = 0;\n bool tracking = false;\n int accumulatedRotation = 0;\n QSoundEffect *dialClickSound = nullptr;\n int grossTotalClicks = 0;\n DialMode currentDialMode = PanAndPageScroll;\n DialMode temporaryDialMode = None;\n QComboBox *dialModeSelector;\n QPushButton *colorPreview;\n QLabel *dialDisplay = nullptr;\n QFrame *dialColorPreview;\n QLabel *dialIconView;\n QFont pixelFont;\n QPushButton *btnPageSwitch;\n QPushButton *btnZoom;\n QPushButton *btnThickness;\n QPushButton *btnTool;\n QPushButton *btnPresets;\n QPushButton *btnPannScroll;\n int tempClicks = 0;\n QPushButton *dialHiddenButton;\n QQueue colorPresets;\n QPushButton *addPresetButton;\n int currentPresetIndex = 0;\n bool useBrighterPalette = false;\n qreal initialDpr = 1.0;\n QWidget *sidebarContainer;\n QWidget *controlBar;\n void setTemporaryDialMode(DialMode mode) {\n if (temporaryDialMode == None) {\n temporaryDialMode = currentDialMode;\n }\n changeDialMode(mode);\n}\n void clearTemporaryDialMode() {\n if (temporaryDialMode != None) {\n changeDialMode(temporaryDialMode);\n temporaryDialMode = None;\n }\n}\n bool controlBarVisible = true;\n void toggleControlBar() {\n // Proper fullscreen toggle: handle both sidebar and control bar\n \n if (controlBarVisible) {\n // Going into fullscreen mode\n \n // First, remember current tab bar state\n sidebarWasVisibleBeforeFullscreen = tabBarContainer->isVisible();\n \n // Hide tab bar if it's visible\n if (tabBarContainer->isVisible()) {\n tabBarContainer->setVisible(false);\n }\n \n // Hide control bar\n controlBarVisible = false;\n controlBar->setVisible(false);\n \n // Hide floating popup widgets when control bar is hidden to prevent stacking\n if (zoomFrame && zoomFrame->isVisible()) zoomFrame->hide();\n if (thicknessFrame && thicknessFrame->isVisible()) thicknessFrame->hide();\n \n // Hide orphaned widgets that are not added to any layout\n if (colorPreview) colorPreview->hide();\n if (thicknessButton) thicknessButton->hide();\n if (jumpToPageButton) jumpToPageButton->hide();\n\n if (toolSelector) toolSelector->hide();\n if (zoomButton) zoomButton->hide();\n if (customColorInput) customColorInput->hide();\n \n // Find and hide local widgets that might be orphaned\n QList comboBoxes = findChildren();\n for (QComboBox* combo : comboBoxes) {\n if (combo->parent() == this && !combo->isVisible()) {\n // Already hidden, keep it hidden\n } else if (combo->parent() == this) {\n // This might be the orphaned dialModeSelector or similar\n combo->hide();\n }\n }\n } else {\n // Coming out of fullscreen mode\n \n // Restore control bar\n controlBarVisible = true;\n controlBar->setVisible(true);\n \n // Restore tab bar to its previous state\n tabBarContainer->setVisible(sidebarWasVisibleBeforeFullscreen);\n \n // Show orphaned widgets when control bar is visible\n // Note: These are kept hidden normally since they're not in the layout\n // Only show them if they were specifically intended to be visible\n }\n \n // Update dial display to reflect new status\n updateDialDisplay();\n \n // Force layout update to recalculate space\n if (auto *canvas = currentCanvas()) {\n QTimer::singleShot(0, this, [this, canvas]() {\n canvas->setMaximumSize(canvas->getCanvasSize());\n });\n }\n}\n void cycleZoomLevels() {\n if (!zoomSlider) return;\n \n int currentZoom = zoomSlider->value();\n int targetZoom;\n \n // Calculate the scaled zoom levels based on initial DPR\n int zoom50 = 50 / initialDpr;\n int zoom100 = 100 / initialDpr;\n int zoom200 = 200 / initialDpr;\n \n // Cycle through 0.5x -> 1x -> 2x -> 0.5x...\n if (currentZoom <= zoom50 + 5) { // Close to 0.5x (with small tolerance)\n targetZoom = zoom100; // Go to 1x\n } else if (currentZoom <= zoom100 + 5) { // Close to 1x\n targetZoom = zoom200; // Go to 2x\n } else { // Any other zoom level or close to 2x\n targetZoom = zoom50; // Go to 0.5x\n }\n \n zoomSlider->setValue(targetZoom);\n updateZoom();\n updateDialDisplay();\n}\n bool sidebarWasVisibleBeforeFullscreen = true;\n int accumulatedRotationAfterLimit = 0;\n int pendingPageFlip = 0;\n QMap buttonHoldMapping;\n QMap buttonPressMapping;\n QMap buttonPressActionMapping;\n QMap keyboardMappings;\n QMap keyboardActionMapping;\n QTimer *tooltipTimer;\n QWidget *lastHoveredWidget;\n QPoint pendingTooltipPos;\n void handleButtonHeld(const QString &buttonName) {\n QString mode = buttonHoldMapping.value(buttonName, \"None\");\n if (mode != \"None\") {\n setTemporaryDialMode(dialModeFromString(mode));\n return;\n }\n}\n void handleButtonReleased(const QString &buttonName) {\n QString mode = buttonHoldMapping.value(buttonName, \"None\");\n if (mode != \"None\") {\n clearTemporaryDialMode();\n }\n}\n void handleControllerButton(const QString &buttonName) { // This is for single press functions\n ControllerAction action = buttonPressActionMapping.value(buttonName, ControllerAction::None);\n\n switch (action) {\n case ControllerAction::ToggleFullscreen:\n fullscreenButton->click();\n break;\n case ControllerAction::ToggleDial:\n toggleDial();\n break;\n case ControllerAction::Zoom50:\n zoom50Button->click();\n break;\n case ControllerAction::ZoomOut:\n dezoomButton->click();\n break;\n case ControllerAction::Zoom200:\n zoom200Button->click();\n break;\n case ControllerAction::AddPreset:\n addPresetButton->click();\n break;\n case ControllerAction::DeletePage:\n deletePageButton->click(); // assuming you have this\n break;\n case ControllerAction::FastForward:\n fastForwardButton->click(); // assuming you have this\n break;\n case ControllerAction::OpenControlPanel:\n openControlPanelButton->click();\n break;\n case ControllerAction::RedColor:\n redButton->click();\n break;\n case ControllerAction::BlueColor:\n blueButton->click();\n break;\n case ControllerAction::YellowColor:\n yellowButton->click();\n break;\n case ControllerAction::GreenColor:\n greenButton->click();\n break;\n case ControllerAction::BlackColor:\n blackButton->click();\n break;\n case ControllerAction::WhiteColor:\n whiteButton->click();\n break;\n case ControllerAction::CustomColor:\n customColorButton->click();\n break;\n case ControllerAction::ToggleSidebar:\n toggleTabBarButton->click();\n break;\n case ControllerAction::Save:\n saveButton->click();\n break;\n case ControllerAction::StraightLineTool:\n straightLineToggleButton->click();\n break;\n case ControllerAction::RopeTool:\n ropeToolButton->click();\n break;\n case ControllerAction::SetPenTool:\n setPenTool();\n break;\n case ControllerAction::SetMarkerTool:\n setMarkerTool();\n break;\n case ControllerAction::SetEraserTool:\n setEraserTool();\n break;\n case ControllerAction::TogglePdfTextSelection:\n pdfTextSelectButton->click();\n break;\n case ControllerAction::ToggleOutline:\n toggleOutlineButton->click();\n break;\n case ControllerAction::ToggleBookmarks:\n toggleBookmarksButton->click();\n break;\n case ControllerAction::AddBookmark:\n toggleBookmarkButton->click();\n break;\n case ControllerAction::ToggleTouchGestures:\n touchGesturesButton->click();\n break;\n default:\n break;\n }\n}\n void handleKeyboardShortcut(const QString &keySequence) {\n ControllerAction action = keyboardActionMapping.value(keySequence, ControllerAction::None);\n \n // Use the same handler as Joy-Con buttons\n switch (action) {\n case ControllerAction::ToggleFullscreen:\n fullscreenButton->click();\n break;\n case ControllerAction::ToggleDial:\n toggleDial();\n break;\n case ControllerAction::Zoom50:\n zoom50Button->click();\n break;\n case ControllerAction::ZoomOut:\n dezoomButton->click();\n break;\n case ControllerAction::Zoom200:\n zoom200Button->click();\n break;\n case ControllerAction::AddPreset:\n addPresetButton->click();\n break;\n case ControllerAction::DeletePage:\n deletePageButton->click();\n break;\n case ControllerAction::FastForward:\n fastForwardButton->click();\n break;\n case ControllerAction::OpenControlPanel:\n openControlPanelButton->click();\n break;\n case ControllerAction::RedColor:\n redButton->click();\n break;\n case ControllerAction::BlueColor:\n blueButton->click();\n break;\n case ControllerAction::YellowColor:\n yellowButton->click();\n break;\n case ControllerAction::GreenColor:\n greenButton->click();\n break;\n case ControllerAction::BlackColor:\n blackButton->click();\n break;\n case ControllerAction::WhiteColor:\n whiteButton->click();\n break;\n case ControllerAction::CustomColor:\n customColorButton->click();\n break;\n case ControllerAction::ToggleSidebar:\n toggleTabBarButton->click();\n break;\n case ControllerAction::Save:\n saveButton->click();\n break;\n case ControllerAction::StraightLineTool:\n straightLineToggleButton->click();\n break;\n case ControllerAction::RopeTool:\n ropeToolButton->click();\n break;\n case ControllerAction::SetPenTool:\n setPenTool();\n break;\n case ControllerAction::SetMarkerTool:\n setMarkerTool();\n break;\n case ControllerAction::SetEraserTool:\n setEraserTool();\n break;\n case ControllerAction::TogglePdfTextSelection:\n pdfTextSelectButton->click();\n break;\n case ControllerAction::ToggleOutline:\n toggleOutlineButton->click();\n break;\n case ControllerAction::ToggleBookmarks:\n toggleBookmarksButton->click();\n break;\n case ControllerAction::AddBookmark:\n toggleBookmarkButton->click();\n break;\n case ControllerAction::ToggleTouchGestures:\n touchGesturesButton->click();\n break;\n default:\n break;\n }\n}\n void saveKeyboardMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.beginGroup(\"KeyboardMappings\");\n for (auto it = keyboardMappings.begin(); it != keyboardMappings.end(); ++it) {\n settings.setValue(it.key(), it.value());\n }\n settings.endGroup();\n}\n void loadKeyboardMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.beginGroup(\"KeyboardMappings\");\n QStringList keys = settings.allKeys();\n \n // List of IME-related shortcuts that should not be intercepted\n QStringList imeShortcuts = {\n \"Ctrl+Space\", // Primary IME toggle\n \"Ctrl+Shift\", // Language switching\n \"Ctrl+Alt\", // IME functions\n \"Shift+Alt\", // Alternative language switching\n \"Alt+Shift\" // Alternative language switching (reversed)\n };\n \n for (const QString &key : keys) {\n // Skip IME-related shortcuts\n if (imeShortcuts.contains(key)) {\n // Remove from settings if it exists\n settings.remove(key);\n continue;\n }\n \n QString value = settings.value(key).toString();\n keyboardMappings[key] = value;\n keyboardActionMapping[key] = stringToAction(value);\n }\n settings.endGroup();\n \n // Save settings to persist the removal of IME shortcuts\n settings.sync();\n}\n void ensureTabHasUniqueSaveFolder(InkCanvas* canvas) {\n if (!canvas) return;\n\n if (canvasStack->count() == 0) return;\n\n QString currentFolder = canvas->getSaveFolder();\n QString tempFolder = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\";\n\n if (currentFolder.isEmpty() || currentFolder == tempFolder) {\n\n QDir sourceDir(tempFolder);\n QStringList pageFiles = sourceDir.entryList(QStringList() << \"*.png\", QDir::Files);\n\n // No pages to save → skip prompting\n if (pageFiles.isEmpty()) {\n return;\n }\n\n QMessageBox::warning(this, tr(\"Unsaved Notebook\"),\n tr(\"This notebook is still using a temporary session folder.\\nPlease select a permanent folder to avoid data loss.\"));\n\n QString selectedFolder = QFileDialog::getExistingDirectory(this, tr(\"Select Save Folder\"));\n if (selectedFolder.isEmpty()) return;\n\n QDir destDir(selectedFolder);\n if (!destDir.exists()) {\n QDir().mkpath(selectedFolder);\n }\n\n // Copy contents from temp to selected folder\n for (const QString &file : sourceDir.entryList(QDir::Files)) {\n QString srcFilePath = tempFolder + \"/\" + file;\n QString dstFilePath = selectedFolder + \"/\" + file;\n\n // If file already exists at destination, remove it to avoid rename failure\n if (QFile::exists(dstFilePath)) {\n QFile::remove(dstFilePath);\n }\n\n QFile::rename(srcFilePath, dstFilePath); // This moves the file\n }\n\n canvas->setSaveFolder(selectedFolder);\n // updateTabLabel(); // No longer needed here, handled by the close button lambda\n }\n\n return;\n}\n RecentNotebooksManager *recentNotebooksManager;\n int pdfRenderDPI = 192;\n void setupUi() {\n \n // Ensure IME is properly enabled for the application\n QInputMethod *inputMethod = QGuiApplication::inputMethod();\n if (inputMethod) {\n inputMethod->show();\n inputMethod->reset();\n }\n \n // Create theme-aware button style\n bool darkMode = isDarkMode();\n QString buttonStyle = createButtonStyle(darkMode);\n\n\n loadPdfButton = new QPushButton(this);\n clearPdfButton = new QPushButton(this);\n loadPdfButton->setFixedSize(26, 30);\n clearPdfButton->setFixedSize(26, 30);\n QIcon pdfIcon(loadThemedIcon(\"pdf\")); // Path to your icon in resources\n QIcon pdfDeleteIcon(loadThemedIcon(\"pdfdelete\")); // Path to your icon in resources\n loadPdfButton->setIcon(pdfIcon);\n clearPdfButton->setIcon(pdfDeleteIcon);\n loadPdfButton->setStyleSheet(buttonStyle);\n clearPdfButton->setStyleSheet(buttonStyle);\n loadPdfButton->setToolTip(tr(\"Load PDF\"));\n clearPdfButton->setToolTip(tr(\"Clear PDF\"));\n connect(loadPdfButton, &QPushButton::clicked, this, &MainWindow::loadPdf);\n connect(clearPdfButton, &QPushButton::clicked, this, &MainWindow::clearPdf);\n\n pdfTextSelectButton = new QPushButton(this);\n pdfTextSelectButton->setFixedSize(26, 30);\n QIcon pdfTextIcon(loadThemedIcon(\"ibeam\"));\n pdfTextSelectButton->setIcon(pdfTextIcon);\n pdfTextSelectButton->setStyleSheet(buttonStyle);\n pdfTextSelectButton->setToolTip(tr(\"Toggle PDF Text Selection\"));\n connect(pdfTextSelectButton, &QPushButton::clicked, this, [this]() {\n if (!currentCanvas()) return;\n \n bool newMode = !currentCanvas()->isPdfTextSelectionEnabled();\n currentCanvas()->setPdfTextSelectionEnabled(newMode);\n updatePdfTextSelectButtonState();\n updateBookmarkButtonState();\n \n // Clear any existing selection when toggling\n if (!newMode) {\n currentCanvas()->clearPdfTextSelection();\n }\n });\n\n exportNotebookButton = new QPushButton(this);\n exportNotebookButton->setFixedSize(26, 30);\n QIcon exportIcon(loadThemedIcon(\"export\")); // Path to your icon in resources\n exportNotebookButton->setIcon(exportIcon);\n exportNotebookButton->setStyleSheet(buttonStyle);\n exportNotebookButton->setToolTip(tr(\"Export Notebook Into .SNPKG File\"));\n importNotebookButton = new QPushButton(this);\n importNotebookButton->setFixedSize(26, 30);\n QIcon importIcon(loadThemedIcon(\"import\")); // Path to your icon in resources\n importNotebookButton->setIcon(importIcon);\n importNotebookButton->setStyleSheet(buttonStyle);\n importNotebookButton->setToolTip(tr(\"Import Notebook From .SNPKG File\"));\n\n connect(exportNotebookButton, &QPushButton::clicked, this, [=]() {\n QString filename = QFileDialog::getSaveFileName(this, tr(\"Export Notebook\"), \"\", \"SpeedyNote Package (*.snpkg)\");\n if (!filename.isEmpty()) {\n if (!filename.endsWith(\".snpkg\")) filename += \".snpkg\";\n currentCanvas()->exportNotebook(filename);\n }\n });\n \n connect(importNotebookButton, &QPushButton::clicked, this, [=]() {\n QString filename = QFileDialog::getOpenFileName(this, tr(\"Import Notebook\"), \"\", \"SpeedyNote Package (*.snpkg)\");\n if (!filename.isEmpty()) {\n currentCanvas()->importNotebook(filename);\n }\n });\n\n benchmarkButton = new QPushButton(this);\n QIcon benchmarkIcon(loadThemedIcon(\"benchmark\")); // Path to your icon in resources\n benchmarkButton->setIcon(benchmarkIcon);\n benchmarkButton->setFixedSize(26, 30); // Make the benchmark button smaller\n benchmarkButton->setStyleSheet(buttonStyle);\n benchmarkButton->setToolTip(tr(\"Toggle Benchmark\"));\n benchmarkLabel = new QLabel(\"PR:N/A\", this);\n benchmarkLabel->setFixedHeight(30); // Make the benchmark bar smaller\n\n toggleTabBarButton = new QPushButton(this);\n toggleTabBarButton->setIcon(loadThemedIcon(\"tabs\")); // You can design separate icons for \"show\" and \"hide\"\n toggleTabBarButton->setToolTip(tr(\"Show/Hide Tab Bar\"));\n toggleTabBarButton->setFixedSize(26, 30);\n toggleTabBarButton->setStyleSheet(buttonStyle);\n toggleTabBarButton->setProperty(\"selected\", true); // Initially visible\n \n // PDF Outline Toggle Button\n toggleOutlineButton = new QPushButton(this);\n toggleOutlineButton->setIcon(loadThemedIcon(\"outline\")); // Icon to be added later\n toggleOutlineButton->setToolTip(tr(\"Show/Hide PDF Outline\"));\n toggleOutlineButton->setFixedSize(26, 30);\n toggleOutlineButton->setStyleSheet(buttonStyle);\n toggleOutlineButton->setProperty(\"selected\", false); // Initially hidden\n \n // Bookmarks Toggle Button\n toggleBookmarksButton = new QPushButton(this);\n toggleBookmarksButton->setIcon(loadThemedIcon(\"bookmark\")); // Using bookpage icon for bookmarks\n toggleBookmarksButton->setToolTip(tr(\"Show/Hide Bookmarks\"));\n toggleBookmarksButton->setFixedSize(26, 30);\n toggleBookmarksButton->setStyleSheet(buttonStyle);\n toggleBookmarksButton->setProperty(\"selected\", false); // Initially hidden\n \n // Add/Remove Bookmark Toggle Button\n toggleBookmarkButton = new QPushButton(this);\n toggleBookmarkButton->setIcon(loadThemedIcon(\"star\"));\n toggleBookmarkButton->setToolTip(tr(\"Add/Remove Bookmark\"));\n toggleBookmarkButton->setFixedSize(26, 30);\n toggleBookmarkButton->setStyleSheet(buttonStyle);\n toggleBookmarkButton->setProperty(\"selected\", false); // For toggle state styling\n\n // Touch Gestures Toggle Button\n touchGesturesButton = new QPushButton(this);\n touchGesturesButton->setIcon(loadThemedIcon(\"hand\")); // Using hand icon for touch/gesture\n touchGesturesButton->setToolTip(tr(\"Toggle Touch Gestures\"));\n touchGesturesButton->setFixedSize(26, 30);\n touchGesturesButton->setStyleSheet(buttonStyle);\n touchGesturesButton->setProperty(\"selected\", touchGesturesEnabled); // For toggle state styling\n\n selectFolderButton = new QPushButton(this);\n selectFolderButton->setFixedSize(26, 30);\n QIcon folderIcon(loadThemedIcon(\"folder\")); // Path to your icon in resources\n selectFolderButton->setIcon(folderIcon);\n selectFolderButton->setStyleSheet(buttonStyle);\n selectFolderButton->setToolTip(tr(\"Select Save Folder\"));\n connect(selectFolderButton, &QPushButton::clicked, this, &MainWindow::selectFolder);\n \n \n saveButton = new QPushButton(this);\n saveButton->setFixedSize(26, 30);\n QIcon saveIcon(loadThemedIcon(\"save\")); // Path to your icon in resources\n saveButton->setIcon(saveIcon);\n saveButton->setStyleSheet(buttonStyle);\n saveButton->setToolTip(tr(\"Save Current Page\"));\n connect(saveButton, &QPushButton::clicked, this, &MainWindow::saveCurrentPage);\n \n saveAnnotatedButton = new QPushButton(this);\n saveAnnotatedButton->setFixedSize(26, 30);\n QIcon saveAnnotatedIcon(loadThemedIcon(\"saveannotated\")); // Path to your icon in resources\n saveAnnotatedButton->setIcon(saveAnnotatedIcon);\n saveAnnotatedButton->setStyleSheet(buttonStyle);\n saveAnnotatedButton->setToolTip(tr(\"Save Page with Background\"));\n connect(saveAnnotatedButton, &QPushButton::clicked, this, &MainWindow::saveAnnotated);\n\n fullscreenButton = new QPushButton(this);\n fullscreenButton->setIcon(loadThemedIcon(\"fullscreen\")); // Load from resources\n fullscreenButton->setFixedSize(26, 30);\n fullscreenButton->setToolTip(tr(\"Toggle Fullscreen\"));\n fullscreenButton->setStyleSheet(buttonStyle);\n\n // ✅ Connect button click to toggleFullscreen() function\n connect(fullscreenButton, &QPushButton::clicked, this, &MainWindow::toggleFullscreen);\n\n // Use the darkMode variable already declared at the beginning of setupUi()\n\n redButton = new QPushButton(this);\n redButton->setFixedSize(18, 30); // Half width\n QString redIconPath = darkMode ? \":/resources/icons/pen_light_red.png\" : \":/resources/icons/pen_dark_red.png\";\n QIcon redIcon(redIconPath);\n redButton->setIcon(redIcon);\n redButton->setStyleSheet(buttonStyle);\n connect(redButton, &QPushButton::clicked, [this]() { \n handleColorButtonClick();\n currentCanvas()->setPenColor(getPaletteColor(\"red\")); \n updateDialDisplay(); \n updateColorButtonStates();\n });\n \n blueButton = new QPushButton(this);\n blueButton->setFixedSize(18, 30); // Half width\n QString blueIconPath = darkMode ? \":/resources/icons/pen_light_blue.png\" : \":/resources/icons/pen_dark_blue.png\";\n QIcon blueIcon(blueIconPath);\n blueButton->setIcon(blueIcon);\n blueButton->setStyleSheet(buttonStyle);\n connect(blueButton, &QPushButton::clicked, [this]() { \n handleColorButtonClick();\n currentCanvas()->setPenColor(getPaletteColor(\"blue\")); \n updateDialDisplay(); \n updateColorButtonStates();\n });\n\n yellowButton = new QPushButton(this);\n yellowButton->setFixedSize(18, 30); // Half width\n QString yellowIconPath = darkMode ? \":/resources/icons/pen_light_yellow.png\" : \":/resources/icons/pen_dark_yellow.png\";\n QIcon yellowIcon(yellowIconPath);\n yellowButton->setIcon(yellowIcon);\n yellowButton->setStyleSheet(buttonStyle);\n connect(yellowButton, &QPushButton::clicked, [this]() { \n handleColorButtonClick();\n currentCanvas()->setPenColor(getPaletteColor(\"yellow\")); \n updateDialDisplay(); \n updateColorButtonStates();\n });\n\n greenButton = new QPushButton(this);\n greenButton->setFixedSize(18, 30); // Half width\n QString greenIconPath = darkMode ? \":/resources/icons/pen_light_green.png\" : \":/resources/icons/pen_dark_green.png\";\n QIcon greenIcon(greenIconPath);\n greenButton->setIcon(greenIcon);\n greenButton->setStyleSheet(buttonStyle);\n connect(greenButton, &QPushButton::clicked, [this]() { \n handleColorButtonClick();\n currentCanvas()->setPenColor(getPaletteColor(\"green\")); \n updateDialDisplay(); \n updateColorButtonStates();\n });\n\n blackButton = new QPushButton(this);\n blackButton->setFixedSize(18, 30); // Half width\n QString blackIconPath = darkMode ? \":/resources/icons/pen_light_black.png\" : \":/resources/icons/pen_dark_black.png\";\n QIcon blackIcon(blackIconPath);\n blackButton->setIcon(blackIcon);\n blackButton->setStyleSheet(buttonStyle);\n connect(blackButton, &QPushButton::clicked, [this]() { \n handleColorButtonClick();\n currentCanvas()->setPenColor(QColor(\"#000000\")); \n updateDialDisplay(); \n updateColorButtonStates();\n });\n\n whiteButton = new QPushButton(this);\n whiteButton->setFixedSize(18, 30); // Half width\n QString whiteIconPath = darkMode ? \":/resources/icons/pen_light_white.png\" : \":/resources/icons/pen_dark_white.png\";\n QIcon whiteIcon(whiteIconPath);\n whiteButton->setIcon(whiteIcon);\n whiteButton->setStyleSheet(buttonStyle);\n connect(whiteButton, &QPushButton::clicked, [this]() { \n handleColorButtonClick();\n currentCanvas()->setPenColor(QColor(\"#FFFFFF\")); \n updateDialDisplay(); \n updateColorButtonStates();\n });\n \n customColorInput = new QLineEdit(this);\n customColorInput->setPlaceholderText(\"Custom HEX\");\n customColorInput->setFixedSize(85, 30);\n \n // Enable IME support for multi-language input\n customColorInput->setAttribute(Qt::WA_InputMethodEnabled, true);\n customColorInput->setInputMethodHints(Qt::ImhNone); // Allow all input methods\n customColorInput->installEventFilter(this); // Install event filter for IME handling\n \n connect(customColorInput, &QLineEdit::returnPressed, this, &MainWindow::applyCustomColor);\n\n \n thicknessButton = new QPushButton(this);\n thicknessButton->setIcon(loadThemedIcon(\"thickness\"));\n thicknessButton->setFixedSize(26, 30);\n thicknessButton->setStyleSheet(buttonStyle);\n connect(thicknessButton, &QPushButton::clicked, this, &MainWindow::toggleThicknessSlider);\n\n thicknessFrame = new QFrame(this);\n thicknessFrame->setFrameShape(QFrame::StyledPanel);\n thicknessFrame->setStyleSheet(R\"(\n background-color: black;\n border: 1px solid black;\n padding: 5px;\n )\");\n thicknessFrame->setVisible(false);\n thicknessFrame->setFixedSize(220, 40); // Adjust width/height as needed\n\n thicknessSlider = new QSlider(Qt::Horizontal, this);\n thicknessSlider->setRange(1, 50);\n thicknessSlider->setValue(5);\n thicknessSlider->setMaximumWidth(200);\n\n\n connect(thicknessSlider, &QSlider::valueChanged, this, &MainWindow::updateThickness);\n\n QVBoxLayout *popupLayoutThickness = new QVBoxLayout();\n popupLayoutThickness->setContentsMargins(10, 5, 10, 5);\n popupLayoutThickness->addWidget(thicknessSlider);\n thicknessFrame->setLayout(popupLayoutThickness);\n\n\n toolSelector = new QComboBox(this);\n toolSelector->addItem(loadThemedIcon(\"pen\"), \"\");\n toolSelector->addItem(loadThemedIcon(\"marker\"), \"\");\n toolSelector->addItem(loadThemedIcon(\"eraser\"), \"\");\n toolSelector->setFixedWidth(43);\n toolSelector->setFixedHeight(30);\n connect(toolSelector, QOverload::of(&QComboBox::currentIndexChanged), this, &MainWindow::changeTool);\n\n // ✅ Individual tool buttons\n penToolButton = new QPushButton(this);\n penToolButton->setFixedSize(26, 30);\n penToolButton->setIcon(loadThemedIcon(\"pen\"));\n penToolButton->setStyleSheet(buttonStyle);\n penToolButton->setToolTip(tr(\"Pen Tool\"));\n connect(penToolButton, &QPushButton::clicked, this, &MainWindow::setPenTool);\n\n markerToolButton = new QPushButton(this);\n markerToolButton->setFixedSize(26, 30);\n markerToolButton->setIcon(loadThemedIcon(\"marker\"));\n markerToolButton->setStyleSheet(buttonStyle);\n markerToolButton->setToolTip(tr(\"Marker Tool\"));\n connect(markerToolButton, &QPushButton::clicked, this, &MainWindow::setMarkerTool);\n\n eraserToolButton = new QPushButton(this);\n eraserToolButton->setFixedSize(26, 30);\n eraserToolButton->setIcon(loadThemedIcon(\"eraser\"));\n eraserToolButton->setStyleSheet(buttonStyle);\n eraserToolButton->setToolTip(tr(\"Eraser Tool\"));\n connect(eraserToolButton, &QPushButton::clicked, this, &MainWindow::setEraserTool);\n\n backgroundButton = new QPushButton(this);\n backgroundButton->setFixedSize(26, 30);\n QIcon bgIcon(loadThemedIcon(\"background\")); // Path to your icon in resources\n backgroundButton->setIcon(bgIcon);\n backgroundButton->setStyleSheet(buttonStyle);\n backgroundButton->setToolTip(tr(\"Set Background Pic\"));\n connect(backgroundButton, &QPushButton::clicked, this, &MainWindow::selectBackground);\n\n // Initialize straight line toggle button\n straightLineToggleButton = new QPushButton(this);\n straightLineToggleButton->setFixedSize(26, 30);\n QIcon straightLineIcon(loadThemedIcon(\"straightLine\")); // Make sure this icon exists or use a different one\n straightLineToggleButton->setIcon(straightLineIcon);\n straightLineToggleButton->setStyleSheet(buttonStyle);\n straightLineToggleButton->setToolTip(tr(\"Toggle Straight Line Mode\"));\n connect(straightLineToggleButton, &QPushButton::clicked, this, [this]() {\n if (!currentCanvas()) return;\n \n // If we're turning on straight line mode, first disable rope tool\n if (!currentCanvas()->isStraightLineMode()) {\n currentCanvas()->setRopeToolMode(false);\n updateRopeToolButtonState();\n }\n \n bool newMode = !currentCanvas()->isStraightLineMode();\n currentCanvas()->setStraightLineMode(newMode);\n updateStraightLineButtonState();\n });\n \n ropeToolButton = new QPushButton(this);\n ropeToolButton->setFixedSize(26, 30);\n QIcon ropeToolIcon(loadThemedIcon(\"rope\")); // Make sure this icon exists\n ropeToolButton->setIcon(ropeToolIcon);\n ropeToolButton->setStyleSheet(buttonStyle);\n ropeToolButton->setToolTip(tr(\"Toggle Rope Tool Mode\"));\n connect(ropeToolButton, &QPushButton::clicked, this, [this]() {\n if (!currentCanvas()) return;\n \n // If we're turning on rope tool mode, first disable straight line\n if (!currentCanvas()->isRopeToolMode()) {\n currentCanvas()->setStraightLineMode(false);\n updateStraightLineButtonState();\n }\n \n bool newMode = !currentCanvas()->isRopeToolMode();\n currentCanvas()->setRopeToolMode(newMode);\n updateRopeToolButtonState();\n });\n \n markdownButton = new QPushButton(this);\n markdownButton->setFixedSize(26, 30);\n QIcon markdownIcon(loadThemedIcon(\"markdown\")); // Using text icon for markdown\n markdownButton->setIcon(markdownIcon);\n markdownButton->setStyleSheet(buttonStyle);\n markdownButton->setToolTip(tr(\"Add Markdown Window\"));\n connect(markdownButton, &QPushButton::clicked, this, [this]() {\n if (!currentCanvas()) return;\n \n // Toggle markdown selection mode\n bool newMode = !currentCanvas()->isMarkdownSelectionMode();\n currentCanvas()->setMarkdownSelectionMode(newMode);\n updateMarkdownButtonState();\n });\n \n deletePageButton = new QPushButton(this);\n deletePageButton->setFixedSize(26, 30);\n QIcon trashIcon(loadThemedIcon(\"trash\")); // Path to your icon in resources\n deletePageButton->setIcon(trashIcon);\n deletePageButton->setStyleSheet(buttonStyle);\n deletePageButton->setToolTip(tr(\"Delete Current Page\"));\n connect(deletePageButton, &QPushButton::clicked, this, &MainWindow::deleteCurrentPage);\n\n zoomButton = new QPushButton(this);\n zoomButton->setIcon(loadThemedIcon(\"zoom\"));\n zoomButton->setFixedSize(26, 30);\n zoomButton->setStyleSheet(buttonStyle);\n connect(zoomButton, &QPushButton::clicked, this, &MainWindow::toggleZoomSlider);\n\n // ✅ Create the floating frame (Initially Hidden)\n zoomFrame = new QFrame(this);\n zoomFrame->setFrameShape(QFrame::StyledPanel);\n zoomFrame->setStyleSheet(R\"(\n background-color: black;\n border: 1px solid black;\n padding: 5px;\n )\");\n zoomFrame->setVisible(false);\n zoomFrame->setFixedSize(440, 40); // Adjust width/height as needed\n\n zoomSlider = new QSlider(Qt::Horizontal, this);\n zoomSlider->setRange(10, 400);\n zoomSlider->setValue(100);\n zoomSlider->setMaximumWidth(405);\n\n connect(zoomSlider, &QSlider::valueChanged, this, &MainWindow::onZoomSliderChanged);\n\n QVBoxLayout *popupLayout = new QVBoxLayout();\n popupLayout->setContentsMargins(10, 5, 10, 5);\n popupLayout->addWidget(zoomSlider);\n zoomFrame->setLayout(popupLayout);\n \n\n zoom50Button = new QPushButton(\"0.5x\", this);\n zoom50Button->setFixedSize(35, 30);\n zoom50Button->setStyleSheet(buttonStyle);\n zoom50Button->setToolTip(tr(\"Set Zoom to 50%\"));\n connect(zoom50Button, &QPushButton::clicked, [this]() { zoomSlider->setValue(50 / initialDpr); updateDialDisplay(); });\n\n dezoomButton = new QPushButton(\"1x\", this);\n dezoomButton->setFixedSize(26, 30);\n dezoomButton->setStyleSheet(buttonStyle);\n dezoomButton->setToolTip(tr(\"Set Zoom to 100%\"));\n connect(dezoomButton, &QPushButton::clicked, [this]() { zoomSlider->setValue(100 / initialDpr); updateDialDisplay(); });\n\n zoom200Button = new QPushButton(\"2x\", this);\n zoom200Button->setFixedSize(31, 30);\n zoom200Button->setStyleSheet(buttonStyle);\n zoom200Button->setToolTip(tr(\"Set Zoom to 200%\"));\n connect(zoom200Button, &QPushButton::clicked, [this]() { zoomSlider->setValue(200 / initialDpr); updateDialDisplay(); });\n\n panXSlider = new QScrollBar(Qt::Horizontal, this);\n panYSlider = new QScrollBar(Qt::Vertical, this);\n panYSlider->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);\n \n // Set scrollbar styling\n QString scrollBarStyle = R\"(\n QScrollBar {\n background: rgba(200, 200, 200, 80);\n border: none;\n margin: 0px;\n }\n QScrollBar:hover {\n background: rgba(200, 200, 200, 120);\n }\n QScrollBar:horizontal {\n height: 16px !important; /* Force narrow height */\n max-height: 16px !important;\n }\n QScrollBar:vertical {\n width: 16px !important; /* Force narrow width */\n max-width: 16px !important;\n }\n QScrollBar::handle {\n background: rgba(100, 100, 100, 150);\n border-radius: 2px;\n min-height: 120px; /* Longer handle for vertical scrollbar */\n min-width: 120px; /* Longer handle for horizontal scrollbar */\n }\n QScrollBar::handle:hover {\n background: rgba(80, 80, 80, 210);\n }\n /* Hide scroll buttons */\n QScrollBar::add-line, \n QScrollBar::sub-line {\n width: 0px;\n height: 0px;\n background: none;\n border: none;\n }\n /* Disable scroll page buttons */\n QScrollBar::add-page, \n QScrollBar::sub-page {\n background: transparent;\n }\n )\";\n \n panXSlider->setStyleSheet(scrollBarStyle);\n panYSlider->setStyleSheet(scrollBarStyle);\n \n // Force fixed dimensions programmatically\n panXSlider->setFixedHeight(16);\n panYSlider->setFixedWidth(16);\n \n // Set up auto-hiding\n panXSlider->setMouseTracking(true);\n panYSlider->setMouseTracking(true);\n panXSlider->installEventFilter(this);\n panYSlider->installEventFilter(this);\n panXSlider->setVisible(false);\n panYSlider->setVisible(false);\n \n // Create timer for auto-hiding\n scrollbarHideTimer = new QTimer(this);\n scrollbarHideTimer->setSingleShot(true);\n scrollbarHideTimer->setInterval(200); // Hide after 0.2 seconds\n connect(scrollbarHideTimer, &QTimer::timeout, this, [this]() {\n panXSlider->setVisible(false);\n panYSlider->setVisible(false);\n scrollbarsVisible = false;\n });\n \n // panXSlider->setFixedHeight(30);\n // panYSlider->setFixedWidth(30);\n\n connect(panXSlider, &QScrollBar::valueChanged, this, &MainWindow::updatePanX);\n \n connect(panYSlider, &QScrollBar::valueChanged, this, &MainWindow::updatePanY);\n\n\n\n\n // 🌟 PDF Outline Sidebar\n outlineSidebar = new QWidget(this);\n outlineSidebar->setFixedWidth(250);\n outlineSidebar->setVisible(false); // Hidden by default\n \n QVBoxLayout *outlineLayout = new QVBoxLayout(outlineSidebar);\n outlineLayout->setContentsMargins(5, 5, 5, 5);\n \n QLabel *outlineLabel = new QLabel(tr(\"PDF Outline\"), outlineSidebar);\n outlineLabel->setStyleSheet(\"font-weight: bold; padding: 5px;\");\n outlineLayout->addWidget(outlineLabel);\n \n outlineTree = new QTreeWidget(outlineSidebar);\n outlineTree->setHeaderHidden(true);\n outlineTree->setRootIsDecorated(true);\n outlineTree->setIndentation(15);\n outlineLayout->addWidget(outlineTree);\n \n // Connect outline tree item clicks\n connect(outlineTree, &QTreeWidget::itemClicked, this, &MainWindow::onOutlineItemClicked);\n \n // 🌟 Bookmarks Sidebar\n bookmarksSidebar = new QWidget(this);\n bookmarksSidebar->setFixedWidth(250);\n bookmarksSidebar->setVisible(false); // Hidden by default\n \n QVBoxLayout *bookmarksLayout = new QVBoxLayout(bookmarksSidebar);\n bookmarksLayout->setContentsMargins(5, 5, 5, 5);\n \n QLabel *bookmarksLabel = new QLabel(tr(\"Bookmarks\"), bookmarksSidebar);\n bookmarksLabel->setStyleSheet(\"font-weight: bold; padding: 5px;\");\n bookmarksLayout->addWidget(bookmarksLabel);\n \n bookmarksTree = new QTreeWidget(bookmarksSidebar);\n bookmarksTree->setHeaderHidden(true);\n bookmarksTree->setRootIsDecorated(false);\n bookmarksTree->setIndentation(0);\n bookmarksLayout->addWidget(bookmarksTree);\n \n // Connect bookmarks tree item clicks\n connect(bookmarksTree, &QTreeWidget::itemClicked, this, &MainWindow::onBookmarkItemClicked);\n\n // 🌟 Horizontal Tab Bar (like modern web browsers)\n tabList = new QListWidget(this);\n tabList->setFlow(QListView::LeftToRight); // Make it horizontal\n tabList->setFixedHeight(32); // Increased to accommodate scrollbar below tabs\n tabList->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);\n tabList->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n tabList->setSelectionMode(QAbstractItemView::SingleSelection);\n\n // Style the tab bar like a modern browser with transparent scrollbar\n tabList->setStyleSheet(R\"(\n QListWidget {\n background-color: rgba(240, 240, 240, 255);\n border: none;\n border-bottom: 1px solid rgba(200, 200, 200, 255);\n outline: none;\n }\n QListWidget::item {\n background-color: rgba(220, 220, 220, 255);\n border: 1px solid rgba(180, 180, 180, 255);\n border-bottom: none;\n margin-right: 1px;\n margin-top: 2px;\n padding: 0px;\n min-width: 80px;\n max-width: 120px;\n }\n QListWidget::item:selected {\n background-color: white;\n border: 1px solid rgba(180, 180, 180, 255);\n border-bottom: 1px solid white;\n margin-top: 1px;\n }\n QListWidget::item:hover:!selected {\n background-color: rgba(230, 230, 230, 255);\n }\n QScrollBar:horizontal {\n background: rgba(240, 240, 240, 255);\n height: 8px;\n border: none;\n margin: 0px;\n border-top: 1px solid rgba(200, 200, 200, 255);\n }\n QScrollBar::handle:horizontal {\n background: rgba(150, 150, 150, 120);\n border-radius: 4px;\n min-width: 20px;\n margin: 1px;\n }\n QScrollBar::handle:horizontal:hover {\n background: rgba(120, 120, 120, 200);\n }\n QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal {\n width: 0px;\n height: 0px;\n background: none;\n border: none;\n }\n QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {\n background: transparent;\n }\n )\");\n\n // 🌟 Add Button for New Tab (styled like browser + button)\n addTabButton = new QPushButton(this);\n QIcon addTab(loadThemedIcon(\"addtab\")); // Path to your icon in resources\n addTabButton->setIcon(addTab);\n addTabButton->setFixedSize(30, 30); // Even smaller to match thinner layout\n addTabButton->setStyleSheet(R\"(\n QPushButton {\n background-color: rgba(220, 220, 220, 255);\n border: 1px solid rgba(180, 180, 180, 255);\n border-radius: 15px;\n margin: 2px;\n }\n QPushButton:hover {\n background-color: rgba(200, 200, 200, 255);\n }\n QPushButton:pressed {\n background-color: rgba(180, 180, 180, 255);\n }\n )\");\n addTabButton->setToolTip(tr(\"Add New Tab\"));\n connect(addTabButton, &QPushButton::clicked, this, &MainWindow::addNewTab);\n\n if (!canvasStack) {\n canvasStack = new QStackedWidget(this);\n }\n\n connect(tabList, &QListWidget::currentRowChanged, this, &MainWindow::switchTab);\n\n // Create horizontal tab container\n tabBarContainer = new QWidget(this);\n tabBarContainer->setObjectName(\"tabBarContainer\");\n tabBarContainer->setFixedHeight(38); // Increased to accommodate scrollbar below tabs\n \n QHBoxLayout *tabBarLayout = new QHBoxLayout(tabBarContainer);\n tabBarLayout->setContentsMargins(5, 5, 5, 5);\n tabBarLayout->setSpacing(5);\n tabBarLayout->addWidget(tabList, 1); // Tab list takes most space\n tabBarLayout->addWidget(addTabButton, 0); // Add button stays at the end\n\n connect(toggleTabBarButton, &QPushButton::clicked, this, [=]() {\n bool isVisible = tabBarContainer->isVisible();\n tabBarContainer->setVisible(!isVisible);\n \n // Update button toggle state\n toggleTabBarButton->setProperty(\"selected\", !isVisible);\n toggleTabBarButton->style()->unpolish(toggleTabBarButton);\n toggleTabBarButton->style()->polish(toggleTabBarButton);\n\n QTimer::singleShot(0, this, [this]() {\n if (auto *canvas = currentCanvas()) {\n canvas->setMaximumSize(canvas->getCanvasSize());\n }\n });\n });\n \n connect(toggleOutlineButton, &QPushButton::clicked, this, &MainWindow::toggleOutlineSidebar);\n connect(toggleBookmarksButton, &QPushButton::clicked, this, &MainWindow::toggleBookmarksSidebar);\n connect(toggleBookmarkButton, &QPushButton::clicked, this, &MainWindow::toggleCurrentPageBookmark);\n connect(touchGesturesButton, &QPushButton::clicked, this, [this]() {\n setTouchGesturesEnabled(!touchGesturesEnabled);\n touchGesturesButton->setProperty(\"selected\", touchGesturesEnabled);\n touchGesturesButton->style()->unpolish(touchGesturesButton);\n touchGesturesButton->style()->polish(touchGesturesButton);\n });\n\n \n\n\n // Previous page button\n prevPageButton = new QPushButton(this);\n prevPageButton->setFixedSize(26, 30);\n prevPageButton->setText(\"◀\");\n prevPageButton->setStyleSheet(buttonStyle);\n prevPageButton->setToolTip(tr(\"Previous Page\"));\n connect(prevPageButton, &QPushButton::clicked, this, &MainWindow::goToPreviousPage);\n\n pageInput = new QSpinBox(this);\n pageInput->setFixedSize(42, 30);\n pageInput->setMinimum(1);\n pageInput->setMaximum(9999);\n pageInput->setValue(1);\n pageInput->setMaximumWidth(100);\n connect(pageInput, QOverload::of(&QSpinBox::valueChanged), this, &MainWindow::onPageInputChanged);\n\n // Next page button\n nextPageButton = new QPushButton(this);\n nextPageButton->setFixedSize(26, 30);\n nextPageButton->setText(\"▶\");\n nextPageButton->setStyleSheet(buttonStyle);\n nextPageButton->setToolTip(tr(\"Next Page\"));\n connect(nextPageButton, &QPushButton::clicked, this, &MainWindow::goToNextPage);\n\n jumpToPageButton = new QPushButton(this);\n // QIcon jumpIcon(\":/resources/icons/bookpage.png\"); // Path to your icon in resources\n jumpToPageButton->setFixedSize(26, 30);\n jumpToPageButton->setStyleSheet(buttonStyle);\n jumpToPageButton->setIcon(loadThemedIcon(\"bookpage\"));\n connect(jumpToPageButton, &QPushButton::clicked, this, &MainWindow::showJumpToPageDialog);\n\n // ✅ Dial Toggle Button\n dialToggleButton = new QPushButton(this);\n dialToggleButton->setIcon(loadThemedIcon(\"dial\")); // Icon for dial\n dialToggleButton->setFixedSize(26, 30);\n dialToggleButton->setToolTip(tr(\"Toggle Magic Dial\"));\n dialToggleButton->setStyleSheet(buttonStyle);\n\n // ✅ Connect to toggle function\n connect(dialToggleButton, &QPushButton::clicked, this, &MainWindow::toggleDial);\n\n // toggleDial();\n\n \n\n fastForwardButton = new QPushButton(this);\n fastForwardButton->setFixedSize(26, 30);\n // QIcon ffIcon(\":/resources/icons/fastforward.png\"); // Path to your icon in resources\n fastForwardButton->setIcon(loadThemedIcon(\"fastforward\"));\n fastForwardButton->setToolTip(tr(\"Toggle Fast Forward 8x\"));\n fastForwardButton->setStyleSheet(buttonStyle);\n\n // ✅ Toggle fast-forward mode\n connect(fastForwardButton, &QPushButton::clicked, [this]() {\n fastForwardMode = !fastForwardMode;\n updateFastForwardButtonState();\n });\n\n QComboBox *dialModeSelector = new QComboBox(this);\n dialModeSelector->addItem(\"Page Switch\", PageSwitching);\n dialModeSelector->addItem(\"Zoom\", ZoomControl);\n dialModeSelector->addItem(\"Thickness\", ThicknessControl);\n\n dialModeSelector->addItem(\"Tool Switch\", ToolSwitching);\n dialModeSelector->setFixedWidth(120);\n\n connect(dialModeSelector, QOverload::of(&QComboBox::currentIndexChanged), this,\n [this](int index) { changeDialMode(static_cast(index)); });\n\n\n\n colorPreview = new QPushButton(this);\n colorPreview->setFixedSize(26, 30);\n colorPreview->setStyleSheet(\"border-radius: 15px; border: 1px solid gray;\");\n colorPreview->setEnabled(false); // ✅ Prevents it from being clicked\n\n btnPageSwitch = new QPushButton(loadThemedIcon(\"bookpage\"), \"\", this);\n btnPageSwitch->setStyleSheet(buttonStyle);\n btnPageSwitch->setFixedSize(26, 30);\n btnPageSwitch->setToolTip(tr(\"Set Dial Mode to Page Switching\"));\n btnZoom = new QPushButton(loadThemedIcon(\"zoom\"), \"\", this);\n btnZoom->setStyleSheet(buttonStyle);\n btnZoom->setFixedSize(26, 30);\n btnZoom->setToolTip(tr(\"Set Dial Mode to Zoom Ctrl\"));\n btnThickness = new QPushButton(loadThemedIcon(\"thickness\"), \"\", this);\n btnThickness->setStyleSheet(buttonStyle);\n btnThickness->setFixedSize(26, 30);\n btnThickness->setToolTip(tr(\"Set Dial Mode to Pen Tip Thickness Ctrl\"));\n\n btnTool = new QPushButton(loadThemedIcon(\"pen\"), \"\", this);\n btnTool->setStyleSheet(buttonStyle);\n btnTool->setFixedSize(26, 30);\n btnTool->setToolTip(tr(\"Set Dial Mode to Tool Switching\"));\n btnPresets = new QPushButton(loadThemedIcon(\"preset\"), \"\", this);\n btnPresets->setStyleSheet(buttonStyle);\n btnPresets->setFixedSize(26, 30);\n btnPresets->setToolTip(tr(\"Set Dial Mode to Color Preset Selection\"));\n btnPannScroll = new QPushButton(loadThemedIcon(\"scroll\"), \"\", this);\n btnPannScroll->setStyleSheet(buttonStyle);\n btnPannScroll->setFixedSize(26, 30);\n btnPannScroll->setToolTip(tr(\"Slide and turn pages with the dial\"));\n\n connect(btnPageSwitch, &QPushButton::clicked, this, [this]() { changeDialMode(PageSwitching); });\n connect(btnZoom, &QPushButton::clicked, this, [this]() { changeDialMode(ZoomControl); });\n connect(btnThickness, &QPushButton::clicked, this, [this]() { changeDialMode(ThicknessControl); });\n\n connect(btnTool, &QPushButton::clicked, this, [this]() { changeDialMode(ToolSwitching); });\n connect(btnPresets, &QPushButton::clicked, this, [this]() { changeDialMode(PresetSelection); }); \n connect(btnPannScroll, &QPushButton::clicked, this, [this]() { changeDialMode(PanAndPageScroll); });\n\n\n // ✅ Initialize color presets based on palette mode (will be updated after UI setup)\n colorPresets.enqueue(getDefaultPenColor());\n colorPresets.enqueue(QColor(\"#AA0000\")); // Temporary - will be updated later\n colorPresets.enqueue(QColor(\"#997700\"));\n colorPresets.enqueue(QColor(\"#0000AA\"));\n colorPresets.enqueue(QColor(\"#007700\"));\n colorPresets.enqueue(QColor(\"#000000\"));\n colorPresets.enqueue(QColor(\"#FFFFFF\"));\n\n // ✅ Button to add current color to presets\n addPresetButton = new QPushButton(loadThemedIcon(\"savepreset\"), \"\", this);\n addPresetButton->setStyleSheet(buttonStyle);\n addPresetButton->setToolTip(tr(\"Add Current Color to Presets\"));\n addPresetButton->setFixedSize(26, 30);\n connect(addPresetButton, &QPushButton::clicked, this, &MainWindow::addColorPreset);\n\n\n\n\n openControlPanelButton = new QPushButton(this);\n openControlPanelButton->setIcon(loadThemedIcon(\"settings\")); // Replace with your actual settings icon\n openControlPanelButton->setStyleSheet(buttonStyle);\n openControlPanelButton->setToolTip(tr(\"Open Control Panel\"));\n openControlPanelButton->setFixedSize(26, 30); // Adjust to match your other buttons\n\n connect(openControlPanelButton, &QPushButton::clicked, this, [=]() {\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n ControlPanelDialog dialog(this, canvas, this);\n dialog.exec(); // Modal\n }\n });\n\n openRecentNotebooksButton = new QPushButton(this); // Create button\n openRecentNotebooksButton->setIcon(loadThemedIcon(\"recent\")); // Replace with actual icon if available\n openRecentNotebooksButton->setStyleSheet(buttonStyle);\n openRecentNotebooksButton->setToolTip(tr(\"Open Recent Notebooks\"));\n openRecentNotebooksButton->setFixedSize(26, 30);\n connect(openRecentNotebooksButton, &QPushButton::clicked, this, &MainWindow::openRecentNotebooksDialog);\n\n customColorButton = new QPushButton(this);\n customColorButton->setFixedSize(62, 30);\n QColor initialColor = getDefaultPenColor(); // Theme-aware default color\n customColorButton->setText(initialColor.name().toUpper());\n\n if (currentCanvas()) {\n initialColor = currentCanvas()->getPenColor();\n }\n\n updateCustomColorButtonStyle(initialColor);\n\n QTimer::singleShot(0, this, [=]() {\n connect(customColorButton, &QPushButton::clicked, this, [=]() {\n if (!currentCanvas()) return;\n \n handleColorButtonClick();\n \n // Get the current custom color from the button text\n QString buttonText = customColorButton->text();\n QColor customColor(buttonText);\n \n // Check if the custom color is already the current pen color\n if (currentCanvas()->getPenColor() == customColor) {\n // Second click - show color picker dialog\n QColor chosen = QColorDialog::getColor(currentCanvas()->getPenColor(), this, \"Select Pen Color\");\n if (chosen.isValid()) {\n currentCanvas()->setPenColor(chosen);\n updateCustomColorButtonStyle(chosen);\n updateDialDisplay();\n updateColorButtonStates();\n }\n } else {\n // First click - apply the custom color\n currentCanvas()->setPenColor(customColor);\n updateDialDisplay();\n updateColorButtonStates();\n }\n });\n });\n\n QHBoxLayout *controlLayout = new QHBoxLayout;\n \n controlLayout->addWidget(toggleOutlineButton);\n controlLayout->addWidget(toggleBookmarksButton);\n controlLayout->addWidget(toggleBookmarkButton);\n controlLayout->addWidget(touchGesturesButton);\n controlLayout->addWidget(toggleTabBarButton);\n controlLayout->addWidget(selectFolderButton);\n\n controlLayout->addWidget(exportNotebookButton);\n controlLayout->addWidget(importNotebookButton);\n controlLayout->addWidget(loadPdfButton);\n controlLayout->addWidget(clearPdfButton);\n controlLayout->addWidget(pdfTextSelectButton);\n controlLayout->addWidget(backgroundButton);\n controlLayout->addWidget(saveButton);\n controlLayout->addWidget(saveAnnotatedButton);\n controlLayout->addWidget(openControlPanelButton);\n controlLayout->addWidget(openRecentNotebooksButton); // Add button to layout\n controlLayout->addWidget(redButton);\n controlLayout->addWidget(blueButton);\n controlLayout->addWidget(yellowButton);\n controlLayout->addWidget(greenButton);\n controlLayout->addWidget(blackButton);\n controlLayout->addWidget(whiteButton);\n controlLayout->addWidget(customColorButton);\n controlLayout->addWidget(straightLineToggleButton);\n controlLayout->addWidget(ropeToolButton); // Add rope tool button to layout\n controlLayout->addWidget(markdownButton); // Add markdown button to layout\n // controlLayout->addWidget(colorPreview);\n // controlLayout->addWidget(thicknessButton);\n // controlLayout->addWidget(jumpToPageButton);\n controlLayout->addWidget(dialToggleButton);\n controlLayout->addWidget(fastForwardButton);\n // controlLayout->addWidget(channelSelector);\n controlLayout->addWidget(btnPageSwitch);\n controlLayout->addWidget(btnPannScroll);\n controlLayout->addWidget(btnZoom);\n controlLayout->addWidget(btnThickness);\n\n controlLayout->addWidget(btnTool);\n controlLayout->addWidget(btnPresets);\n controlLayout->addWidget(addPresetButton);\n // controlLayout->addWidget(dialModeSelector);\n // controlLayout->addStretch();\n \n // controlLayout->addWidget(toolSelector);\n controlLayout->addWidget(fullscreenButton);\n // controlLayout->addWidget(zoomButton);\n controlLayout->addWidget(zoom50Button);\n controlLayout->addWidget(dezoomButton);\n controlLayout->addWidget(zoom200Button);\n controlLayout->addStretch();\n \n \n controlLayout->addWidget(prevPageButton);\n controlLayout->addWidget(pageInput);\n controlLayout->addWidget(nextPageButton);\n controlLayout->addWidget(benchmarkButton);\n controlLayout->addWidget(benchmarkLabel);\n controlLayout->addWidget(deletePageButton);\n \n \n \n controlBar = new QWidget; // Use member variable instead of local\n controlBar->setObjectName(\"controlBar\");\n // controlBar->setLayout(controlLayout); // Commented out - responsive layout will handle this\n controlBar->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);\n\n // Theme will be applied later in loadUserSettings -> updateTheme()\n controlBar->setStyleSheet(\"\");\n\n \n \n\n canvasStack = new QStackedWidget();\n canvasStack->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);\n\n // Create a container for the canvas and scrollbars with relative positioning\n QWidget *canvasContainer = new QWidget;\n QVBoxLayout *canvasLayout = new QVBoxLayout(canvasContainer);\n canvasLayout->setContentsMargins(0, 0, 0, 0);\n canvasLayout->addWidget(canvasStack);\n\n // Enable context menu for the workaround\n canvasContainer->setContextMenuPolicy(Qt::CustomContextMenu);\n \n // Set up the scrollbars to overlay the canvas\n panXSlider->setParent(canvasContainer);\n panYSlider->setParent(canvasContainer);\n \n // Raise scrollbars to ensure they're visible above the canvas\n panXSlider->raise();\n panYSlider->raise();\n \n // Handle scrollbar intersection\n connect(canvasContainer, &QWidget::customContextMenuRequested, this, [this]() {\n // This connection is just to make sure the container exists\n // and can receive signals - a workaround for some Qt versions\n });\n \n // Position the scrollbars at the bottom and right edges\n canvasContainer->installEventFilter(this);\n \n // Update scrollbar positions initially\n QTimer::singleShot(0, this, [this, canvasContainer]() {\n updateScrollbarPositions();\n });\n\n // Main layout: toolbar -> tab bar -> canvas (vertical stack)\n QWidget *container = new QWidget;\n container->setObjectName(\"container\");\n QVBoxLayout *mainLayout = new QVBoxLayout(container);\n mainLayout->setContentsMargins(0, 0, 0, 0); // ✅ Remove extra margins\n mainLayout->setSpacing(0); // ✅ Remove spacing between components\n \n // Add components in vertical order\n mainLayout->addWidget(controlBar); // Toolbar at top\n mainLayout->addWidget(tabBarContainer); // Tab bar below toolbar\n \n // Content area with sidebars and canvas\n QHBoxLayout *contentLayout = new QHBoxLayout;\n contentLayout->setContentsMargins(0, 0, 0, 0);\n contentLayout->setSpacing(0);\n contentLayout->addWidget(outlineSidebar, 0); // Fixed width outline sidebar\n contentLayout->addWidget(bookmarksSidebar, 0); // Fixed width bookmarks sidebar\n contentLayout->addWidget(canvasContainer, 1); // Canvas takes remaining space\n \n QWidget *contentWidget = new QWidget;\n contentWidget->setLayout(contentLayout);\n mainLayout->addWidget(contentWidget, 1);\n\n setCentralWidget(container);\n\n benchmarkTimer = new QTimer(this);\n connect(benchmarkButton, &QPushButton::clicked, this, &MainWindow::toggleBenchmark);\n connect(benchmarkTimer, &QTimer::timeout, this, &MainWindow::updateBenchmarkDisplay);\n\n QString tempDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\";\n QDir dir(tempDir);\n\n // Remove all contents (but keep the directory itself)\n if (dir.exists()) {\n dir.removeRecursively(); // Careful: this wipes everything inside\n }\n QDir().mkpath(tempDir); // Recreate clean directory\n\n addNewTab();\n\n // Initialize responsive toolbar layout\n createSingleRowLayout(); // Start with single row layout\n \n // Now that all UI components are created, update the color palette\n updateColorPalette();\n\n}\n void loadUserSettings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n\n // Load low-res toggle\n lowResPreviewEnabled = settings.value(\"lowResPreviewEnabled\", true).toBool();\n setLowResPreviewEnabled(lowResPreviewEnabled);\n\n \n zoomButtonsVisible = settings.value(\"zoomButtonsVisible\", true).toBool();\n setZoomButtonsVisible(zoomButtonsVisible);\n\n scrollOnTopEnabled = settings.value(\"scrollOnTopEnabled\", true).toBool();\n setScrollOnTopEnabled(scrollOnTopEnabled);\n\n touchGesturesEnabled = settings.value(\"touchGesturesEnabled\", true).toBool();\n setTouchGesturesEnabled(touchGesturesEnabled);\n \n // Update button visual state to match loaded setting\n touchGesturesButton->setProperty(\"selected\", touchGesturesEnabled);\n touchGesturesButton->style()->unpolish(touchGesturesButton);\n touchGesturesButton->style()->polish(touchGesturesButton);\n \n // Initialize default background settings if they don't exist\n if (!settings.contains(\"defaultBackgroundStyle\")) {\n saveDefaultBackgroundSettings(BackgroundStyle::Grid, Qt::white, 30);\n }\n \n // Load keyboard mappings\n loadKeyboardMappings();\n \n // Load theme settings\n loadThemeSettings();\n}\n bool scrollbarsVisible = false;\n QTimer *scrollbarHideTimer = nullptr;\n bool eventFilter(QObject *obj, QEvent *event) override {\n static bool dragging = false;\n static QPoint lastMousePos;\n static QTimer *longPressTimer = nullptr;\n\n // Handle IME focus events for text input widgets\n QLineEdit *lineEdit = qobject_cast(obj);\n if (lineEdit) {\n if (event->type() == QEvent::FocusIn) {\n // Ensure IME is enabled when text field gets focus\n lineEdit->setAttribute(Qt::WA_InputMethodEnabled, true);\n QInputMethod *inputMethod = QGuiApplication::inputMethod();\n if (inputMethod) {\n inputMethod->show();\n }\n }\n else if (event->type() == QEvent::FocusOut) {\n // Keep IME available but reset state\n QInputMethod *inputMethod = QGuiApplication::inputMethod();\n if (inputMethod) {\n inputMethod->reset();\n }\n }\n }\n\n // Handle resize events for canvas container\n QWidget *container = canvasStack ? canvasStack->parentWidget() : nullptr;\n if (obj == container && event->type() == QEvent::Resize) {\n updateScrollbarPositions();\n return false; // Let the event propagate\n }\n\n // Handle scrollbar visibility\n if (obj == panXSlider || obj == panYSlider) {\n if (event->type() == QEvent::Enter) {\n // Mouse entered scrollbar area\n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n return false;\n } \n else if (event->type() == QEvent::Leave) {\n // Mouse left scrollbar area - start timer to hide\n if (!scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->start();\n }\n return false;\n }\n }\n\n // Check if this is a canvas event for scrollbar handling\n InkCanvas* canvas = qobject_cast(obj);\n if (canvas) {\n // Handle mouse movement for scrollbar visibility\n if (event->type() == QEvent::MouseMove) {\n QMouseEvent* mouseEvent = static_cast(event);\n handleEdgeProximity(canvas, mouseEvent->pos());\n }\n // Handle tablet events for stylus hover (safely)\n else if (event->type() == QEvent::TabletMove) {\n try {\n QTabletEvent* tabletEvent = static_cast(event);\n handleEdgeProximity(canvas, tabletEvent->position().toPoint());\n } catch (...) {\n // Ignore tablet event errors to prevent crashes\n }\n }\n // Handle mouse button press events for forward/backward navigation\n else if (event->type() == QEvent::MouseButtonPress) {\n QMouseEvent* mouseEvent = static_cast(event);\n \n // Mouse button 4 (Back button) - Previous page\n if (mouseEvent->button() == Qt::BackButton) {\n if (prevPageButton) {\n prevPageButton->click();\n }\n return true; // Consume the event\n }\n // Mouse button 5 (Forward button) - Next page\n else if (mouseEvent->button() == Qt::ForwardButton) {\n if (nextPageButton) {\n nextPageButton->click();\n }\n return true; // Consume the event\n }\n }\n // Handle wheel events for scrolling\n else if (event->type() == QEvent::Wheel) {\n QWheelEvent* wheelEvent = static_cast(event);\n \n // Check if we need scrolling\n bool needHorizontalScroll = panXSlider->maximum() > 0;\n bool needVerticalScroll = panYSlider->maximum() > 0;\n \n // Handle vertical scrolling (Y axis)\n if (wheelEvent->angleDelta().y() != 0 && needVerticalScroll) {\n // Calculate scroll amount (negative because wheel up should scroll up)\n int scrollDelta = -wheelEvent->angleDelta().y() / 8; // Convert from 1/8 degree units\n scrollDelta = scrollDelta / 15; // Convert to steps (typical wheel step is 15 degrees)\n \n // Much faster base scroll speed - aim for ~3-5 scrolls to reach bottom\n int baseScrollAmount = panYSlider->maximum() / 8; // 1/8 of total range per scroll\n scrollDelta = scrollDelta * qMax(baseScrollAmount, 50); // Minimum 50 units per scroll\n \n // Apply the scroll\n int currentPan = panYSlider->value();\n int newPan = qBound(panYSlider->minimum(), currentPan + scrollDelta, panYSlider->maximum());\n panYSlider->setValue(newPan);\n \n // Show scrollbar temporarily\n panYSlider->setVisible(true);\n scrollbarsVisible = true;\n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n scrollbarHideTimer->start();\n \n // Consume the event\n return true;\n }\n \n // Handle horizontal scrolling (X axis) - for completeness\n if (wheelEvent->angleDelta().x() != 0 && needHorizontalScroll) {\n // Calculate scroll amount\n int scrollDelta = wheelEvent->angleDelta().x() / 8; // Convert from 1/8 degree units\n scrollDelta = scrollDelta / 15; // Convert to steps\n \n // Much faster base scroll speed - same logic as vertical\n int baseScrollAmount = panXSlider->maximum() / 8; // 1/8 of total range per scroll\n scrollDelta = scrollDelta * qMax(baseScrollAmount, 50); // Minimum 50 units per scroll\n \n // Apply the scroll\n int currentPan = panXSlider->value();\n int newPan = qBound(panXSlider->minimum(), currentPan + scrollDelta, panXSlider->maximum());\n panXSlider->setValue(newPan);\n \n // Show scrollbar temporarily\n panXSlider->setVisible(true);\n scrollbarsVisible = true;\n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n scrollbarHideTimer->start();\n \n // Consume the event\n return true;\n }\n \n // If no scrolling was needed, let the event propagate\n return false;\n }\n }\n\n // Handle dial container drag events\n if (obj == dialContainer) {\n if (event->type() == QEvent::MouseButtonPress) {\n QMouseEvent *mouseEvent = static_cast(event);\n lastMousePos = mouseEvent->globalPos();\n dragging = false;\n\n if (!longPressTimer) {\n longPressTimer = new QTimer(this);\n longPressTimer->setSingleShot(true);\n connect(longPressTimer, &QTimer::timeout, [this]() {\n dragging = true; // ✅ Allow movement after long press\n });\n }\n longPressTimer->start(1500); // ✅ Start long press timer (500ms)\n return true;\n }\n\n if (event->type() == QEvent::MouseMove && dragging) {\n QMouseEvent *mouseEvent = static_cast(event);\n QPoint delta = mouseEvent->globalPos() - lastMousePos;\n dialContainer->move(dialContainer->pos() + delta);\n lastMousePos = mouseEvent->globalPos();\n return true;\n }\n\n if (event->type() == QEvent::MouseButtonRelease) {\n if (longPressTimer) longPressTimer->stop();\n dragging = false; // ✅ Stop dragging on release\n return true;\n }\n }\n\n return QObject::eventFilter(obj, event);\n}\n void updateScrollbarPositions() {\n QWidget *container = canvasStack->parentWidget();\n if (!container || !panXSlider || !panYSlider) return;\n \n // Add small margins for better visibility\n const int margin = 3;\n \n // Get scrollbar dimensions\n const int scrollbarWidth = panYSlider->width();\n const int scrollbarHeight = panXSlider->height();\n \n // Calculate sizes based on container\n int containerWidth = container->width();\n int containerHeight = container->height();\n \n // Leave a bit of space for the corner\n int cornerOffset = 15;\n \n // Position horizontal scrollbar at top\n panXSlider->setGeometry(\n cornerOffset + margin, // Leave space at left corner\n margin,\n containerWidth - cornerOffset - margin*2, // Full width minus corner and right margin\n scrollbarHeight\n );\n \n // Position vertical scrollbar at left\n panYSlider->setGeometry(\n margin,\n cornerOffset + margin, // Leave space at top corner\n scrollbarWidth,\n containerHeight - cornerOffset - margin*2 // Full height minus corner and bottom margin\n );\n}\n void handleEdgeProximity(InkCanvas* canvas, const QPoint& pos) {\n if (!canvas) return;\n \n // Get canvas dimensions\n int canvasWidth = canvas->width();\n int canvasHeight = canvas->height();\n \n // Edge detection zones - show scrollbars when pointer is within 50px of edges\n bool nearLeftEdge = pos.x() < 25; // For vertical scrollbar\n bool nearTopEdge = pos.y() < 25; // For horizontal scrollbar - entire top edge\n \n // Only show scrollbars if canvas is larger than viewport\n bool needHorizontalScroll = panXSlider->maximum() > 0;\n bool needVerticalScroll = panYSlider->maximum() > 0;\n \n // Show/hide scrollbars based on pointer position\n if (nearLeftEdge && needVerticalScroll) {\n panYSlider->setVisible(true);\n scrollbarsVisible = true;\n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n scrollbarHideTimer->start();\n }\n \n if (nearTopEdge && needHorizontalScroll) {\n panXSlider->setVisible(true);\n scrollbarsVisible = true;\n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n scrollbarHideTimer->start();\n }\n}\n bool isToolbarTwoRows = false;\n QVBoxLayout *controlLayoutVertical = nullptr;\n QHBoxLayout *controlLayoutSingle = nullptr;\n QHBoxLayout *controlLayoutFirstRow = nullptr;\n QHBoxLayout *controlLayoutSecondRow = nullptr;\n void updateToolbarLayout() {\n // Calculate scaled width using device pixel ratio\n QScreen *screen = QGuiApplication::primaryScreen();\n // qreal dpr = screen ? screen->devicePixelRatio() : 1.0;\n int scaledWidth = width();\n \n // Dynamic threshold based on zoom button visibility\n int threshold = areZoomButtonsVisible() ? 1548 : 1438;\n \n // Debug output to understand what's happening\n // qDebug() << \"Window width:\" << scaledWidth << \"Threshold:\" << threshold << \"Zoom buttons visible:\" << areZoomButtonsVisible();\n \n bool shouldBeTwoRows = scaledWidth <= threshold;\n \n // qDebug() << \"Should be two rows:\" << shouldBeTwoRows << \"Currently is two rows:\" << isToolbarTwoRows;\n \n if (shouldBeTwoRows != isToolbarTwoRows) {\n isToolbarTwoRows = shouldBeTwoRows;\n \n // qDebug() << \"Switching to\" << (isToolbarTwoRows ? \"two rows\" : \"single row\");\n \n if (isToolbarTwoRows) {\n createTwoRowLayout();\n } else {\n createSingleRowLayout();\n }\n }\n}\n void createSingleRowLayout() {\n // Delete separator line if it exists (from previous 2-row layout)\n if (separatorLine) {\n delete separatorLine;\n separatorLine = nullptr;\n }\n \n // Create new single row layout first\n QHBoxLayout *newLayout = new QHBoxLayout;\n \n // Add all widgets to single row (same order as before)\n newLayout->addWidget(toggleTabBarButton);\n newLayout->addWidget(toggleOutlineButton);\n newLayout->addWidget(toggleBookmarksButton);\n newLayout->addWidget(toggleBookmarkButton);\n newLayout->addWidget(touchGesturesButton);\n newLayout->addWidget(selectFolderButton);\n newLayout->addWidget(exportNotebookButton);\n newLayout->addWidget(importNotebookButton);\n newLayout->addWidget(loadPdfButton);\n newLayout->addWidget(clearPdfButton);\n newLayout->addWidget(pdfTextSelectButton);\n newLayout->addWidget(backgroundButton);\n newLayout->addWidget(saveButton);\n newLayout->addWidget(saveAnnotatedButton);\n newLayout->addWidget(openControlPanelButton);\n newLayout->addWidget(openRecentNotebooksButton);\n newLayout->addWidget(redButton);\n newLayout->addWidget(blueButton);\n newLayout->addWidget(yellowButton);\n newLayout->addWidget(greenButton);\n newLayout->addWidget(blackButton);\n newLayout->addWidget(whiteButton);\n newLayout->addWidget(customColorButton);\n newLayout->addWidget(penToolButton);\n newLayout->addWidget(markerToolButton);\n newLayout->addWidget(eraserToolButton);\n newLayout->addWidget(straightLineToggleButton);\n newLayout->addWidget(ropeToolButton);\n newLayout->addWidget(markdownButton);\n newLayout->addWidget(dialToggleButton);\n newLayout->addWidget(fastForwardButton);\n newLayout->addWidget(btnPageSwitch);\n newLayout->addWidget(btnPannScroll);\n newLayout->addWidget(btnZoom);\n newLayout->addWidget(btnThickness);\n\n newLayout->addWidget(btnTool);\n newLayout->addWidget(btnPresets);\n newLayout->addWidget(addPresetButton);\n newLayout->addWidget(fullscreenButton);\n \n // Only add zoom buttons if they're visible\n if (areZoomButtonsVisible()) {\n newLayout->addWidget(zoom50Button);\n newLayout->addWidget(dezoomButton);\n newLayout->addWidget(zoom200Button);\n }\n \n newLayout->addStretch();\n newLayout->addWidget(prevPageButton);\n newLayout->addWidget(pageInput);\n newLayout->addWidget(nextPageButton);\n newLayout->addWidget(benchmarkButton);\n newLayout->addWidget(benchmarkLabel);\n newLayout->addWidget(deletePageButton);\n \n // Safely replace the layout\n QLayout* oldLayout = controlBar->layout();\n if (oldLayout) {\n // Remove all items from old layout (but don't delete widgets)\n QLayoutItem* item;\n while ((item = oldLayout->takeAt(0)) != nullptr) {\n // Just removing, not deleting widgets\n }\n delete oldLayout;\n }\n \n // Set the new layout\n controlBar->setLayout(newLayout);\n controlLayoutSingle = newLayout;\n \n // Clean up other layout pointers\n controlLayoutVertical = nullptr;\n controlLayoutFirstRow = nullptr;\n controlLayoutSecondRow = nullptr;\n \n // Update pan range after layout change\n updatePanRange();\n}\n void createTwoRowLayout() {\n // Create new layouts first\n QVBoxLayout *newVerticalLayout = new QVBoxLayout;\n QHBoxLayout *newFirstRowLayout = new QHBoxLayout;\n QHBoxLayout *newSecondRowLayout = new QHBoxLayout;\n \n // Add comfortable spacing and margins for 2-row layout\n newFirstRowLayout->setContentsMargins(8, 8, 8, 6); // More generous margins\n newFirstRowLayout->setSpacing(3); // Add spacing between buttons for less cramped feel\n newSecondRowLayout->setContentsMargins(8, 6, 8, 8); // More generous margins\n newSecondRowLayout->setSpacing(3); // Add spacing between buttons for less cramped feel\n \n // First row: up to customColorButton\n newFirstRowLayout->addWidget(toggleTabBarButton);\n newFirstRowLayout->addWidget(toggleOutlineButton);\n newFirstRowLayout->addWidget(toggleBookmarksButton);\n newFirstRowLayout->addWidget(toggleBookmarkButton);\n newFirstRowLayout->addWidget(touchGesturesButton);\n newFirstRowLayout->addWidget(selectFolderButton);\n newFirstRowLayout->addWidget(exportNotebookButton);\n newFirstRowLayout->addWidget(importNotebookButton);\n newFirstRowLayout->addWidget(loadPdfButton);\n newFirstRowLayout->addWidget(clearPdfButton);\n newFirstRowLayout->addWidget(pdfTextSelectButton);\n newFirstRowLayout->addWidget(backgroundButton);\n newFirstRowLayout->addWidget(saveButton);\n newFirstRowLayout->addWidget(saveAnnotatedButton);\n newFirstRowLayout->addWidget(openControlPanelButton);\n newFirstRowLayout->addWidget(openRecentNotebooksButton);\n newFirstRowLayout->addWidget(redButton);\n newFirstRowLayout->addWidget(blueButton);\n newFirstRowLayout->addWidget(yellowButton);\n newFirstRowLayout->addWidget(greenButton);\n newFirstRowLayout->addWidget(blackButton);\n newFirstRowLayout->addWidget(whiteButton);\n newFirstRowLayout->addWidget(customColorButton);\n newFirstRowLayout->addWidget(penToolButton);\n newFirstRowLayout->addWidget(markerToolButton);\n newFirstRowLayout->addWidget(eraserToolButton);\n newFirstRowLayout->addStretch();\n \n // Create a separator line\n if (!separatorLine) {\n separatorLine = new QFrame();\n separatorLine->setFrameShape(QFrame::HLine);\n separatorLine->setFrameShadow(QFrame::Sunken);\n separatorLine->setLineWidth(1);\n separatorLine->setStyleSheet(\"QFrame { color: rgba(255, 255, 255, 255); }\");\n }\n \n // Second row: everything after customColorButton\n newSecondRowLayout->addWidget(straightLineToggleButton);\n newSecondRowLayout->addWidget(ropeToolButton);\n newSecondRowLayout->addWidget(markdownButton);\n newSecondRowLayout->addWidget(dialToggleButton);\n newSecondRowLayout->addWidget(fastForwardButton);\n newSecondRowLayout->addWidget(btnPageSwitch);\n newSecondRowLayout->addWidget(btnPannScroll);\n newSecondRowLayout->addWidget(btnZoom);\n newSecondRowLayout->addWidget(btnThickness);\n\n newSecondRowLayout->addWidget(btnTool);\n newSecondRowLayout->addWidget(btnPresets);\n newSecondRowLayout->addWidget(addPresetButton);\n newSecondRowLayout->addWidget(fullscreenButton);\n \n // Only add zoom buttons if they're visible\n if (areZoomButtonsVisible()) {\n newSecondRowLayout->addWidget(zoom50Button);\n newSecondRowLayout->addWidget(dezoomButton);\n newSecondRowLayout->addWidget(zoom200Button);\n }\n \n newSecondRowLayout->addStretch();\n newSecondRowLayout->addWidget(prevPageButton);\n newSecondRowLayout->addWidget(pageInput);\n newSecondRowLayout->addWidget(nextPageButton);\n newSecondRowLayout->addWidget(benchmarkButton);\n newSecondRowLayout->addWidget(benchmarkLabel);\n newSecondRowLayout->addWidget(deletePageButton);\n \n // Add layouts to vertical layout with separator\n newVerticalLayout->addLayout(newFirstRowLayout);\n newVerticalLayout->addWidget(separatorLine);\n newVerticalLayout->addLayout(newSecondRowLayout);\n newVerticalLayout->setContentsMargins(0, 0, 0, 0);\n newVerticalLayout->setSpacing(0); // No spacing since we have our own separator\n \n // Safely replace the layout\n QLayout* oldLayout = controlBar->layout();\n if (oldLayout) {\n // Remove all items from old layout (but don't delete widgets)\n QLayoutItem* item;\n while ((item = oldLayout->takeAt(0)) != nullptr) {\n // Just removing, not deleting widgets\n }\n delete oldLayout;\n }\n \n // Set the new layout\n controlBar->setLayout(newVerticalLayout);\n controlLayoutVertical = newVerticalLayout;\n controlLayoutFirstRow = newFirstRowLayout;\n controlLayoutSecondRow = newSecondRowLayout;\n \n // Clean up other layout pointer\n controlLayoutSingle = nullptr;\n \n // Update pan range after layout change\n updatePanRange();\n}\n QString elideTabText(const QString &text, int maxWidth) {\n // Create a font metrics object using the default font\n QFontMetrics fontMetrics(QApplication::font());\n \n // Elide the text from the right (showing the beginning)\n return fontMetrics.elidedText(text, Qt::ElideRight, maxWidth);\n}\n QTimer *layoutUpdateTimer = nullptr;\n QFrame *separatorLine = nullptr;\n protected:\n void resizeEvent(QResizeEvent *event) override {\n QMainWindow::resizeEvent(event);\n \n // Use a timer to delay layout updates during resize to prevent excessive switching\n if (!layoutUpdateTimer) {\n layoutUpdateTimer = new QTimer(this);\n layoutUpdateTimer->setSingleShot(true);\n connect(layoutUpdateTimer, &QTimer::timeout, this, [this]() {\n updateToolbarLayout();\n // Also reposition dial after resize finishes\n if (dialContainer && dialContainer->isVisible()) {\n positionDialContainer();\n }\n });\n }\n \n layoutUpdateTimer->stop();\n layoutUpdateTimer->start(100); // Wait 100ms after resize stops\n}\n void keyPressEvent(QKeyEvent *event) override {\n // Don't intercept keyboard events when text input widgets have focus\n // This prevents conflicts with Windows TextInputFramework\n QWidget *focusWidget = QApplication::focusWidget();\n if (focusWidget) {\n bool isTextInputWidget = qobject_cast(focusWidget) || \n qobject_cast(focusWidget) || \n qobject_cast(focusWidget) ||\n qobject_cast(focusWidget) ||\n qobject_cast(focusWidget);\n \n if (isTextInputWidget) {\n // Let text input widgets handle their own keyboard events\n QMainWindow::keyPressEvent(event);\n return;\n }\n }\n \n // Don't intercept IME-related keyboard shortcuts\n // These are reserved for Windows Input Method Editor\n if (event->modifiers() & Qt::ControlModifier) {\n if (event->key() == Qt::Key_Space || // Ctrl+Space (IME toggle)\n event->key() == Qt::Key_Shift || // Ctrl+Shift (language switch)\n event->key() == Qt::Key_Alt) { // Ctrl+Alt (IME functions)\n // Let Windows handle IME shortcuts\n QMainWindow::keyPressEvent(event);\n return;\n }\n }\n \n // Don't intercept Shift+Alt (another common IME shortcut)\n if ((event->modifiers() & Qt::ShiftModifier) && (event->modifiers() & Qt::AltModifier)) {\n QMainWindow::keyPressEvent(event);\n return;\n }\n \n // Build key sequence string\n QStringList modifiers;\n \n if (event->modifiers() & Qt::ControlModifier) modifiers << \"Ctrl\";\n if (event->modifiers() & Qt::ShiftModifier) modifiers << \"Shift\";\n if (event->modifiers() & Qt::AltModifier) modifiers << \"Alt\";\n if (event->modifiers() & Qt::MetaModifier) modifiers << \"Meta\";\n \n QString keyString = QKeySequence(event->key()).toString();\n \n QString fullSequence;\n if (!modifiers.isEmpty()) {\n fullSequence = modifiers.join(\"+\") + \"+\" + keyString;\n } else {\n fullSequence = keyString;\n }\n \n // Check if this sequence is mapped\n if (keyboardMappings.contains(fullSequence)) {\n handleKeyboardShortcut(fullSequence);\n event->accept();\n return;\n }\n \n // If not handled, pass to parent\n QMainWindow::keyPressEvent(event);\n}\n void tabletEvent(QTabletEvent *event) override {\n // Since tablet tracking is disabled to prevent crashes, we now only handle\n // basic tablet events that come through when stylus is touching the surface\n if (!event) {\n return;\n }\n \n // Just pass tablet events to parent safely without custom hover handling\n // (hover tooltips will work through normal mouse events instead)\n try {\n QMainWindow::tabletEvent(event);\n } catch (...) {\n // Catch any exceptions and just accept the event\n event->accept();\n }\n}\n void inputMethodEvent(QInputMethodEvent *event) override {\n // Forward IME events to the focused widget\n QWidget *focusWidget = QApplication::focusWidget();\n if (focusWidget && focusWidget != this) {\n QApplication::sendEvent(focusWidget, event);\n event->accept();\n return;\n }\n \n // Default handling\n QMainWindow::inputMethodEvent(event);\n}\n QVariant inputMethodQuery(Qt::InputMethodQuery query) const override {\n // Forward IME queries to the focused widget\n QWidget *focusWidget = QApplication::focusWidget();\n if (focusWidget && focusWidget != this) {\n return focusWidget->inputMethodQuery(query);\n }\n \n // Default handling\n return QMainWindow::inputMethodQuery(query);\n}\n};"], ["/SpeedyNote/source/InkCanvas.h", "class MarkdownWindowManager {\n Q_OBJECT\n\nsignals:\n void zoomChanged(int newZoom);\n void panChanged(int panX, int panY);\n void touchGestureEnded();\n void ropeSelectionCompleted(const QPoint &position);\n void pdfLinkClicked(int targetPage);\n void pdfTextSelected(const QString &text);\n void pdfLoaded();\n void markdownSelectionModeChanged(bool enabled);\n public:\n explicit InkCanvas(QWidget *parent = nullptr) { \n \n // Set theme-aware default pen color\n MainWindow *mainWindow = qobject_cast(parent);\n if (mainWindow) {\n penColor = mainWindow->getDefaultPenColor();\n } \n setAttribute(Qt::WA_StaticContents);\n setTabletTracking(true);\n setAttribute(Qt::WA_AcceptTouchEvents); // Enable touch events\n\n // Enable immediate updates for smoother animation\n setAttribute(Qt::WA_OpaquePaintEvent);\n setAttribute(Qt::WA_NoSystemBackground);\n \n // Detect screen resolution and set canvas size\n QScreen *screen = QGuiApplication::primaryScreen();\n if (screen) {\n QSize logicalSize = screen->availableGeometry().size() * 0.89;\n setMaximumSize(logicalSize); // Optional\n setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);\n } else {\n setFixedSize(1920, 1080); // Fallback size\n }\n \n initializeBuffer();\n QCache pdfCache(10);\n pdfCache.setMaxCost(10); // ✅ Ensures the cache holds at most 5 pages\n // No need to set auto-delete, QCache will handle deletion automatically\n \n // Initialize PDF text selection throttling timer (60 FPS = ~16.67ms)\n pdfTextSelectionTimer = new QTimer(this);\n pdfTextSelectionTimer->setSingleShot(true);\n pdfTextSelectionTimer->setInterval(16); // ~60 FPS\n connect(pdfTextSelectionTimer, &QTimer::timeout, this, &InkCanvas::processPendingTextSelection);\n \n // Initialize PDF cache timer (will be created on-demand)\n pdfCacheTimer = nullptr;\n currentCachedPage = -1;\n \n // Initialize note page cache system\n noteCache.setMaxCost(15); // Cache up to 15 note pages (more than PDF since they're smaller)\n noteCacheTimer = nullptr;\n currentCachedNotePage = -1;\n \n // Initialize markdown manager\n markdownManager = new MarkdownWindowManager(this, this);\n \n // Connect pan/zoom signals to update markdown window positions\n connect(this, &InkCanvas::panChanged, markdownManager, &MarkdownWindowManager::updateAllWindowPositions);\n connect(this, &InkCanvas::zoomChanged, markdownManager, &MarkdownWindowManager::updateAllWindowPositions);\n}\n virtual ~InkCanvas() {\n // Cleanup if needed\n}\n void startBenchmark() {\n benchmarking = true;\n processedTimestamps.clear();\n benchmarkTimer.start();\n}\n void stopBenchmark() {\n benchmarking = false;\n}\n int getProcessedRate() {\n qint64 now = benchmarkTimer.elapsed();\n while (!processedTimestamps.empty() && now - processedTimestamps.front() > 1000) {\n processedTimestamps.pop_front();\n }\n return static_cast(processedTimestamps.size());\n}\n void setPenColor(const QColor &color) {\n penColor = color;\n}\n void setPenThickness(qreal thickness) {\n // Set thickness for the current tool\n switch (currentTool) {\n case ToolType::Pen:\n penToolThickness = thickness;\n break;\n case ToolType::Marker:\n markerToolThickness = thickness;\n break;\n case ToolType::Eraser:\n eraserToolThickness = thickness;\n break;\n }\n \n // Update the current thickness for efficient drawing\n penThickness = thickness;\n}\n void adjustAllToolThicknesses(qreal zoomRatio) {\n // Adjust thickness for all tools to maintain visual consistency\n penToolThickness *= zoomRatio;\n markerToolThickness *= zoomRatio;\n eraserToolThickness *= zoomRatio;\n \n // Update the current thickness based on the current tool\n switch (currentTool) {\n case ToolType::Pen:\n penThickness = penToolThickness;\n break;\n case ToolType::Marker:\n penThickness = markerToolThickness;\n break;\n case ToolType::Eraser:\n penThickness = eraserToolThickness;\n break;\n }\n}\n void setTool(ToolType tool) {\n currentTool = tool;\n \n // Switch to the thickness for the new tool\n switch (currentTool) {\n case ToolType::Pen:\n penThickness = penToolThickness;\n break;\n case ToolType::Marker:\n penThickness = markerToolThickness;\n break;\n case ToolType::Eraser:\n penThickness = eraserToolThickness;\n break;\n }\n}\n void setSaveFolder(const QString &folderPath) {\n saveFolder = folderPath;\n clearPdfNoDelete(); \n\n if (!saveFolder.isEmpty()) {\n QDir().mkpath(saveFolder);\n loadNotebookId(); // ✅ Load notebook ID when save folder is set\n }\n\n QString bgMetaFile = saveFolder + \"/.background_config.txt\"; // This metadata is for background styles, not to be confused with pdf directories. \n if (QFile::exists(bgMetaFile)) {\n QFile file(bgMetaFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n while (!in.atEnd()) {\n QString line = in.readLine().trimmed();\n if (line.startsWith(\"style=\")) {\n QString val = line.mid(6);\n if (val == \"Grid\") backgroundStyle = BackgroundStyle::Grid;\n else if (val == \"Lines\") backgroundStyle = BackgroundStyle::Lines;\n else backgroundStyle = BackgroundStyle::None;\n } else if (line.startsWith(\"color=\")) {\n backgroundColor = QColor(line.mid(6));\n } else if (line.startsWith(\"density=\")) {\n backgroundDensity = line.mid(8).toInt();\n }\n }\n file.close();\n }\n }\n\n // ✅ Check if the folder has a saved PDF path\n QString metadataFile = saveFolder + \"/.pdf_path.txt\";\n if (!QFile::exists(metadataFile)) {\n return;\n }\n\n\n QFile file(metadataFile);\n if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n return;\n }\n\n QTextStream in(&file);\n QString storedPdfPath = in.readLine().trimmed();\n file.close();\n\n if (storedPdfPath.isEmpty()) {\n return;\n }\n\n\n // ✅ Ensure the stored PDF file still exists before loading\n if (!QFile::exists(storedPdfPath)) {\n return;\n }\n loadPdf(storedPdfPath);\n}\n void saveToFile(int pageNumber) {\n if (saveFolder.isEmpty()) {\n return;\n }\n QString filePath = saveFolder + QString(\"/%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n\n // ✅ If no file exists and the buffer is empty, do nothing\n \n if (!edited) {\n return;\n }\n\n QImage image(buffer.size(), QImage::Format_ARGB32);\n image.fill(Qt::transparent);\n QPainter painter(&image);\n painter.drawPixmap(0, 0, buffer);\n image.save(filePath, \"PNG\");\n edited = false;\n \n // Save markdown windows for this page\n if (markdownManager) {\n markdownManager->saveWindowsForPage(pageNumber);\n }\n \n // Update note cache with the saved buffer\n noteCache.insert(pageNumber, new QPixmap(buffer));\n}\n void saveCurrentPage() {\n MainWindow *mainWin = qobject_cast(parentWidget()); // ✅ Get main window\n if (!mainWin) return;\n \n int currentPage = mainWin->getCurrentPageForCanvas(this); // ✅ Get correct page\n saveToFile(currentPage);\n}\n void loadPage(int pageNumber) {\n if (saveFolder.isEmpty()) return;\n\n // Hide any markdown windows from the previous page BEFORE loading the new page content.\n // This ensures the correct repaint area and stops the transparency timer.\n if (markdownManager) {\n markdownManager->hideAllWindows();\n }\n\n // Update current note page tracker\n currentCachedNotePage = pageNumber;\n\n // Check if note page is already cached\n bool loadedFromCache = false;\n if (noteCache.contains(pageNumber)) {\n // Use cached note page immediately\n buffer = *noteCache.object(pageNumber);\n loadedFromCache = true;\n } else {\n // Load note page from disk and cache it\n loadNotePageToCache(pageNumber);\n \n // Use the newly cached page or initialize buffer if loading failed\n if (noteCache.contains(pageNumber)) {\n buffer = *noteCache.object(pageNumber);\n loadedFromCache = true;\n } else {\n initializeBuffer(); // Clear the canvas if no file exists\n loadedFromCache = false;\n }\n }\n \n // Reset edited state when loading a new page\n edited = false;\n \n // Handle background image loading (PDF or custom background)\n if (isPdfLoaded && pdfDocument && pageNumber >= 0 && pageNumber < pdfDocument->numPages()) {\n // Use PDF as background (should already be cached by loadPdfPage)\n if (pdfCache.contains(pageNumber)) {\n backgroundImage = *pdfCache.object(pageNumber);\n \n // Resize canvas buffer to match PDF page size if needed\n if (backgroundImage.size() != buffer.size()) {\n QPixmap newBuffer(backgroundImage.size());\n newBuffer.fill(Qt::transparent);\n\n // Copy existing drawings\n QPainter painter(&newBuffer);\n painter.drawPixmap(0, 0, buffer);\n\n buffer = newBuffer;\n // Don't constrain widget size - let it expand to fill available space\n // The paintEvent will center the PDF content within the widget\n \n // Update cache with resized buffer\n noteCache.insert(pageNumber, new QPixmap(buffer));\n }\n }\n } else {\n // Handle custom background images\n QString bgFileName = saveFolder + QString(\"/bg_%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n QString metadataFile = saveFolder + QString(\"/.%1_bgsize_%2.txt\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n\n int bgWidth = 0, bgHeight = 0;\n if (QFile::exists(metadataFile)) {\n QFile file(metadataFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n in >> bgWidth >> bgHeight;\n file.close();\n }\n }\n\n if (QFile::exists(bgFileName)) {\n QImage bgImage(bgFileName);\n backgroundImage = QPixmap::fromImage(bgImage);\n\n // Resize canvas **only if background resolution is different**\n if (bgWidth > 0 && bgHeight > 0 && (bgWidth != width() || bgHeight != height())) {\n // Create a new buffer\n QPixmap newBuffer(bgWidth, bgHeight);\n newBuffer.fill(Qt::transparent);\n\n // Copy existing drawings to the new buffer\n QPainter painter(&newBuffer);\n painter.drawPixmap(0, 0, buffer);\n\n // Assign the new buffer\n buffer = newBuffer;\n setMaximumSize(bgWidth, bgHeight);\n \n // Update cache with resized buffer\n noteCache.insert(pageNumber, new QPixmap(buffer));\n }\n } else {\n backgroundImage = QPixmap(); // No background for this page\n // Only apply device pixel ratio fix if buffer was NOT loaded from cache\n // This prevents resizing cached buffers that might already be correctly sized\n if (!loadedFromCache) {\n QScreen *screen = QGuiApplication::primaryScreen();\n qreal dpr = screen ? screen->devicePixelRatio() : 1.0;\n QSize logicalSize = screen ? screen->size() : QSize(1440, 900);\n QSize expectedPixelSize = logicalSize * dpr;\n \n if (buffer.size() != expectedPixelSize) {\n // Buffer is wrong size, need to resize it properly\n QPixmap newBuffer(expectedPixelSize);\n newBuffer.fill(Qt::transparent);\n \n // Copy existing drawings if buffer was smaller\n if (!buffer.isNull()) {\n QPainter painter(&newBuffer);\n painter.drawPixmap(0, 0, buffer);\n }\n \n buffer = newBuffer;\n setMaximumSize(expectedPixelSize);\n }\n }\n }\n }\n\n // Cache adjacent note pages after delay for faster navigation\n checkAndCacheAdjacentNotePages(pageNumber);\n\n update();\n adjustSize(); // Force the widget to update its size\n parentWidget()->update();\n \n // Load markdown windows AFTER canvas is fully rendered and sized\n // Use a single-shot timer to ensure the canvas is fully updated\n QTimer::singleShot(0, this, [this, pageNumber]() {\n if (markdownManager) {\n markdownManager->loadWindowsForPage(pageNumber);\n }\n });\n}\n void deletePage(int pageNumber) {\n if (saveFolder.isEmpty()) {\n return;\n }\n QString fileName = saveFolder + QString(\"/%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n QString bgFileName = saveFolder + QString(\"/bg_%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n QString metadataFileName = saveFolder + QString(\"/.%1_bgsize_%2.txt\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n \n #ifdef Q_OS_WIN\n // Remove hidden attribute before deleting in Windows\n SetFileAttributesW(reinterpret_cast(metadataFileName.utf16()), FILE_ATTRIBUTE_NORMAL);\n #endif\n \n QFile::remove(fileName);\n QFile::remove(bgFileName);\n QFile::remove(metadataFileName);\n\n // Remove deleted page from note cache\n noteCache.remove(pageNumber);\n\n // Delete markdown windows for this page\n if (markdownManager) {\n markdownManager->deleteWindowsForPage(pageNumber);\n }\n\n if (pdfDocument){\n loadPdfPage(pageNumber);\n }\n else{\n loadPage(pageNumber);\n }\n\n}\n void setBackground(const QString &filePath, int pageNumber) {\n if (saveFolder.isEmpty()) {\n return; // No save folder set\n }\n\n // Construct full path inside save folder\n QString bgFileName = saveFolder + QString(\"/bg_%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n\n // Copy the file to the save folder\n QFile::copy(filePath, bgFileName);\n\n // Load the background image\n QImage bgImage(bgFileName);\n\n if (!bgImage.isNull()) {\n // Save background resolution in metadata file\n QString metadataFile = saveFolder + QString(\"/.%1_bgsize_%2.txt\")\n .arg(notebookId)\n .arg(pageNumber, 5, 10, QChar('0'));\n QFile file(metadataFile);\n if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {\n QTextStream out(&file);\n out << bgImage.width() << \" \" << bgImage.height();\n file.close();\n }\n\n #ifdef Q_OS_WIN\n // Set hidden attribute for metadata on Windows\n SetFileAttributesW(reinterpret_cast(metadataFile.utf16()), FILE_ATTRIBUTE_HIDDEN);\n #endif \n\n // Only resize if the background size is different\n if (bgImage.width() != width() || bgImage.height() != height()) {\n // Create a new buffer with the new size\n QPixmap newBuffer(bgImage.width(), bgImage.height());\n newBuffer.fill(Qt::transparent);\n\n // Copy existing drawings\n QPainter painter(&newBuffer);\n painter.drawPixmap(0, 0, buffer);\n\n // Assign new buffer and update canvas size\n buffer = newBuffer;\n setMaximumSize(bgImage.width(), bgImage.height());\n }\n\n backgroundImage = QPixmap::fromImage(bgImage);\n \n update();\n adjustSize();\n parentWidget()->update();\n }\n\n update(); // Refresh canvas\n}\n void saveAnnotated(int pageNumber) {\n if (saveFolder.isEmpty()) return;\n\n QString filePath = saveFolder + QString(\"/annotated_%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n\n // Use the buffer size to ensure correct resolution\n QImage image(buffer.size(), QImage::Format_ARGB32);\n image.fill(Qt::transparent);\n QPainter painter(&image);\n \n if (!backgroundImage.isNull()) {\n painter.drawPixmap(0, 0, backgroundImage.scaled(buffer.size(), Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation));\n }\n \n painter.drawPixmap(0, 0, buffer);\n image.save(filePath, \"PNG\");\n}\n void setZoom(int zoomLevel) {\n int newZoom = qMax(10, qMin(zoomLevel, 400)); // Limit zoom to 10%-400%\n if (zoomFactor != newZoom) {\n zoomFactor = newZoom;\n internalZoomFactor = zoomFactor; // Sync internal zoom\n update();\n emit zoomChanged(zoomFactor);\n }\n}\n int getZoom() const {\n return zoomFactor;\n}\n void updatePanOffsets(int xOffset, int yOffset) {\n panOffsetX = xOffset;\n panOffsetY = yOffset;\n update();\n}\n int getPanOffsetX() const {\n return panOffsetX;\n}\n int getPanOffsetY() const {\n return panOffsetY;\n}\n void setPanX(int xOffset) {\n if (panOffsetX != value) {\n panOffsetX = value;\n update();\n emit panChanged(panOffsetX, panOffsetY);\n }\n}\n void setPanY(int yOffset) {\n if (panOffsetY != value) {\n panOffsetY = value;\n update();\n emit panChanged(panOffsetX, panOffsetY);\n }\n}\n void loadPdf(const QString &pdfPath) {\n pdfDocument = Poppler::Document::load(pdfPath);\n if (pdfDocument && !pdfDocument->isLocked()) {\n // Enable anti-aliasing rendering hints for better text quality\n pdfDocument->setRenderHint(Poppler::Document::Antialiasing, true);\n pdfDocument->setRenderHint(Poppler::Document::TextAntialiasing, true);\n pdfDocument->setRenderHint(Poppler::Document::TextHinting, true);\n pdfDocument->setRenderHint(Poppler::Document::TextSlightHinting, true);\n \n totalPdfPages = pdfDocument->numPages();\n isPdfLoaded = true;\n totalPdfPages = pdfDocument->numPages();\n loadPdfPage(0); // Load first page\n // ✅ Save the PDF path in the metadata file\n if (!saveFolder.isEmpty()) {\n QString metadataFile = saveFolder + \"/.pdf_path.txt\";\n QFile file(metadataFile);\n if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {\n QTextStream out(&file);\n out << pdfPath; // Store the absolute path of the PDF\n file.close();\n }\n }\n // Emit signal that PDF was loaded\n emit pdfLoaded();\n }\n}\n void loadPdfPage(int pageNumber) {\n if (!pdfDocument) return;\n\n // Update current page tracker\n currentCachedPage = pageNumber;\n\n // Check if target page is already cached\n if (pdfCache.contains(pageNumber)) {\n // Display the cached page immediately\n backgroundImage = *pdfCache.object(pageNumber);\n loadPage(pageNumber); // Load annotations\n loadPdfTextBoxes(pageNumber); // Load text boxes for PDF text selection\n update();\n \n // Check and cache adjacent pages after delay\n checkAndCacheAdjacentPages(pageNumber);\n return;\n }\n\n // Target page not in cache - render it immediately\n renderPdfPageToCache(pageNumber);\n \n // Display the newly rendered page\n if (pdfCache.contains(pageNumber)) {\n backgroundImage = *pdfCache.object(pageNumber);\n } else {\n backgroundImage = QPixmap(); // Clear background if rendering failed\n }\n \n loadPage(pageNumber); // Load existing canvas annotations\n loadPdfTextBoxes(pageNumber); // Load text boxes for PDF text selection\n update();\n \n // Cache adjacent pages after delay\n checkAndCacheAdjacentPages(pageNumber);\n}\n bool isPdfLoadedFunc() const {\n return isPdfLoaded;\n}\n int getTotalPdfPages() const {\n return totalPdfPages;\n}\n Poppler::Document* getPdfDocument() const;\n void clearPdf() {\n pdfDocument.reset();\n pdfDocument = nullptr;\n isPdfLoaded = false;\n totalPdfPages = 0;\n pdfCache.clear();\n \n // Reset cache system state\n currentCachedPage = -1;\n if (pdfCacheTimer && pdfCacheTimer->isActive()) {\n pdfCacheTimer->stop();\n }\n \n // Cancel and clean up any active PDF watchers\n for (QFutureWatcher* watcher : activePdfWatchers) {\n if (watcher && !watcher->isFinished()) {\n watcher->cancel();\n }\n watcher->deleteLater();\n }\n activePdfWatchers.clear();\n\n // ✅ Remove the PDF path file when clearing the PDF\n if (!saveFolder.isEmpty()) {\n QString metadataFile = saveFolder + \"/.pdf_path.txt\";\n QFile::remove(metadataFile);\n }\n}\n void clearPdfNoDelete() {\n pdfDocument.reset();\n pdfDocument = nullptr;\n isPdfLoaded = false;\n totalPdfPages = 0;\n pdfCache.clear();\n \n // Reset cache system state\n currentCachedPage = -1;\n if (pdfCacheTimer && pdfCacheTimer->isActive()) {\n pdfCacheTimer->stop();\n }\n \n // Cancel and clean up any active PDF watchers\n for (QFutureWatcher* watcher : activePdfWatchers) {\n if (watcher && !watcher->isFinished()) {\n watcher->cancel();\n }\n watcher->deleteLater();\n }\n activePdfWatchers.clear();\n}\n QString getSaveFolder() const {\n return saveFolder;\n}\n QColor getPenColor() {\n return penColor;\n}\n qreal getPenThickness() {\n return penThickness;\n}\n ToolType getCurrentTool() {\n return currentTool;\n}\n void loadPdfPreviewAsync(int pageNumber) {\n if (!pdfDocument || pageNumber < 0 || pageNumber >= pdfDocument->numPages()) return;\n\n QFutureWatcher *watcher = new QFutureWatcher(this);\n\n connect(watcher, &QFutureWatcher::finished, this, [this, watcher]() {\n QPixmap result = watcher->result();\n if (!result.isNull()) {\n backgroundImage = result;\n update(); // trigger repaint\n }\n watcher->deleteLater(); // Clean up\n });\n\n QFuture future = QtConcurrent::run([=]() -> QPixmap {\n std::unique_ptr page(pdfDocument->page(pageNumber));\n if (!page) return QPixmap();\n\n // Render with document-level anti-aliasing settings\n QImage pdfImage = page->renderToImage(96, 96);\n if (pdfImage.isNull()) return QPixmap();\n\n QImage upscaled = pdfImage.scaled(pdfImage.width() * (pdfRenderDPI / 96),\n pdfImage.height() * (pdfRenderDPI / 96),\n Qt::KeepAspectRatio,\n Qt::SmoothTransformation);\n\n return QPixmap::fromImage(upscaled);\n });\n\n watcher->setFuture(future);\n}\n void setBackgroundStyle(BackgroundStyle style) {\n backgroundStyle = style;\n update(); // Trigger repaint\n}\n void setBackgroundColor(const QColor &color) {\n backgroundColor = color;\n update();\n}\n void setBackgroundDensity(int density) {\n backgroundDensity = density;\n update();\n}\n void saveBackgroundMetadata() {\n if (saveFolder.isEmpty()) return;\n\n QString bgMetaFile = saveFolder + \"/.background_config.txt\";\n QFile file(bgMetaFile);\n if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {\n QTextStream out(&file);\n QString styleStr = \"None\";\n if (backgroundStyle == BackgroundStyle::Grid) styleStr = \"Grid\";\n else if (backgroundStyle == BackgroundStyle::Lines) styleStr = \"Lines\";\n\n out << \"style=\" << styleStr << \"\\n\";\n out << \"color=\" << backgroundColor.name().toUpper() << \"\\n\";\n out << \"density=\" << backgroundDensity << \"\\n\";\n file.close();\n }\n}\n void exportNotebook(const QString &destinationFile) {\n if (destinationFile.isEmpty()) {\n QMessageBox::warning(nullptr, tr(\"Export Error\"), tr(\"No export file specified.\"));\n return;\n }\n\n if (saveFolder.isEmpty()) {\n QMessageBox::warning(nullptr, tr(\"Export Error\"), tr(\"No notebook loaded (saveFolder is empty)\"));\n return;\n }\n\n QStringList files;\n\n // Collect all files from saveFolder\n QDir dir(saveFolder);\n QDirIterator it(saveFolder, QDir::Files, QDirIterator::Subdirectories);\n while (it.hasNext()) {\n QString filePath = it.next();\n QString relativePath = dir.relativeFilePath(filePath);\n files << relativePath;\n }\n\n if (files.isEmpty()) {\n QMessageBox::warning(nullptr, tr(\"Export Error\"), tr(\"No files found to export.\"));\n return;\n }\n\n // Generate temporary file list\n QString tempFileList = saveFolder + \"/filelist.txt\";\n QFile listFile(tempFileList);\n if (listFile.open(QIODevice::WriteOnly | QIODevice::Text)) {\n QTextStream out(&listFile);\n for (const QString &file : files) {\n out << file << \"\\n\";\n }\n listFile.close();\n } else {\n QMessageBox::warning(nullptr, tr(\"Export Error\"), tr(\"Failed to create temporary file list.\"));\n return;\n }\n\n#ifdef _WIN32\n QString tarExe = QCoreApplication::applicationDirPath() + \"/bsdtar.exe\";\n#else\n QString tarExe = \"tar\";\n#endif\n\n QStringList args;\n args << \"-cf\" << QDir::toNativeSeparators(destinationFile);\n\n for (const QString &file : files) {\n args << QDir::toNativeSeparators(file);\n }\n\n QProcess process;\n process.setWorkingDirectory(saveFolder);\n\n process.start(tarExe, args);\n if (!process.waitForFinished()) {\n QMessageBox::warning(nullptr, tr(\"Export Error\"), tr(\"Tar process failed to finish.\"));\n QFile::remove(tempFileList);\n return;\n }\n\n QFile::remove(tempFileList);\n\n if (process.exitStatus() != QProcess::NormalExit || process.exitCode() != 0) {\n QMessageBox::warning(nullptr, tr(\"Export Error\"), tr(\"Tar process failed.\"));\n return;\n }\n\n QMessageBox::information(nullptr, tr(\"Export\"), tr(\"Notebook exported successfully.\"));\n}\n void importNotebook(const QString &packageFile) {\n\n // Ask user for destination working folder\n QString destFolder = QFileDialog::getExistingDirectory(nullptr, tr(\"Select Destination Folder for Imported Notebook\"));\n\n if (destFolder.isEmpty()) {\n QMessageBox::warning(nullptr, tr(\"Import Canceled\"), tr(\"No destination folder selected.\"));\n return;\n }\n\n // Check if destination folder is empty (optional, good practice)\n QDir destDir(destFolder);\n if (!destDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot).isEmpty()) {\n QMessageBox::StandardButton reply = QMessageBox::question(nullptr, tr(\"Destination Not Empty\"),\n tr(\"The selected folder is not empty. Files may be overwritten. Continue?\"),\n QMessageBox::Yes | QMessageBox::No);\n if (reply != QMessageBox::Yes) {\n return;\n }\n }\n\n#ifdef _WIN32\n QString tarExe = QCoreApplication::applicationDirPath() + \"/bsdtar.exe\";\n#else\n QString tarExe = \"tar\";\n#endif\n\n // Extract package\n QStringList args;\n args << \"-xf\" << packageFile;\n\n QProcess process;\n process.setWorkingDirectory(destFolder);\n process.start(tarExe, args);\n process.waitForFinished();\n\n // Switch notebook folder\n setSaveFolder(destFolder);\n loadPage(0);\n\n QMessageBox::information(nullptr, tr(\"Import Complete\"), tr(\"Notebook imported successfully.\"));\n}\n void importNotebookTo(const QString &packageFile, const QString &destFolder) {\n\n #ifdef _WIN32\n QString tarExe = QCoreApplication::applicationDirPath() + \"/bsdtar.exe\";\n #else\n QString tarExe = \"tar\";\n #endif\n \n QStringList args;\n args << \"-xf\" << packageFile;\n \n QProcess process;\n process.setWorkingDirectory(destFolder);\n process.start(tarExe, args);\n process.waitForFinished();\n \n setSaveFolder(destFolder);\n loadNotebookId();\n loadPage(0);\n\n QMessageBox::information(nullptr, tr(\"Import\"), tr(\"Notebook imported successfully.\"));\n }\n void deleteRopeSelection() {\n if (!selectionBuffer.isNull() && !selectionRect.isEmpty()) {\n // If the selection area hasn't been cleared from the buffer yet, clear it now for deletion\n if (!selectionAreaCleared && !selectionMaskPath.isEmpty()) {\n QPainter painter(&buffer);\n painter.setCompositionMode(QPainter::CompositionMode_Clear);\n painter.fillPath(selectionMaskPath, Qt::transparent);\n painter.end();\n }\n \n // Clear the selection state\n selectionBuffer = QPixmap();\n selectionRect = QRect();\n exactSelectionRectF = QRectF();\n movingSelection = false;\n selectingWithRope = false;\n selectionJustCopied = false;\n selectionAreaCleared = false;\n selectionMaskPath = QPainterPath();\n selectionBufferRect = QRectF();\n \n // Mark as edited since we deleted content\n if (!edited) {\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n \n // Update the entire canvas to remove selection visuals\n update();\n }\n}\n void cancelRopeSelection() {\n if (!selectionBuffer.isNull() && !selectionRect.isEmpty()) {\n // Paste the selection back to its current location (where user moved it)\n QPainter painter(&buffer);\n // Explicitly set composition mode to draw on top of existing content\n painter.setCompositionMode(QPainter::CompositionMode_SourceOver);\n // Use the current selection position\n QPointF currentTopLeft = exactSelectionRectF.isEmpty() ? selectionRect.topLeft() : exactSelectionRectF.topLeft();\n QPointF bufferDest = mapLogicalWidgetToPhysicalBuffer(currentTopLeft);\n painter.drawPixmap(bufferDest.toPoint(), selectionBuffer);\n painter.end();\n \n // Store selection buffer size for update calculation before clearing it\n QSize selectionSize = selectionBuffer.size();\n QRect updateRect = QRect(currentTopLeft.toPoint(), selectionSize);\n \n // Clear the selection state\n selectionBuffer = QPixmap();\n selectionRect = QRect();\n exactSelectionRectF = QRectF();\n movingSelection = false;\n selectingWithRope = false;\n selectionJustCopied = false;\n selectionAreaCleared = false;\n selectionMaskPath = QPainterPath();\n selectionBufferRect = QRectF();\n \n // Update the restored area\n update(updateRect.adjusted(-5, -5, 5, 5));\n }\n}\n void copyRopeSelection() {\n if (!selectionBuffer.isNull() && !selectionRect.isEmpty()) {\n // Get current selection position\n QPointF currentTopLeft = exactSelectionRectF.isEmpty() ? selectionRect.topLeft() : exactSelectionRectF.topLeft();\n \n // Calculate new position (right next to the original), but ensure it stays within canvas bounds\n QPointF newTopLeft = currentTopLeft + QPointF(selectionRect.width() + 5, 0); // 5 pixels gap\n \n // Check if the new position would extend beyond buffer boundaries and adjust if needed\n QPointF currentBufferDest = mapLogicalWidgetToPhysicalBuffer(currentTopLeft);\n QPointF newBufferDest = mapLogicalWidgetToPhysicalBuffer(newTopLeft);\n \n // Ensure the copy stays within buffer bounds\n if (newBufferDest.x() + selectionBuffer.width() > buffer.width()) {\n // If it would extend beyond right edge, place it to the left of the original\n newTopLeft = currentTopLeft - QPointF(selectionRect.width() + 5, 0);\n newBufferDest = mapLogicalWidgetToPhysicalBuffer(newTopLeft);\n \n // If it still doesn't fit on the left, place it below the original\n if (newBufferDest.x() < 0) {\n newTopLeft = currentTopLeft + QPointF(0, selectionRect.height() + 5);\n newBufferDest = mapLogicalWidgetToPhysicalBuffer(newTopLeft);\n \n // If it doesn't fit below either, place it above\n if (newBufferDest.y() + selectionBuffer.height() > buffer.height()) {\n newTopLeft = currentTopLeft - QPointF(0, selectionRect.height() + 5);\n newBufferDest = mapLogicalWidgetToPhysicalBuffer(newTopLeft);\n \n // If none of the positions work, just offset slightly and let it extend\n if (newBufferDest.y() < 0) {\n newTopLeft = currentTopLeft + QPointF(10, 10);\n newBufferDest = mapLogicalWidgetToPhysicalBuffer(newTopLeft);\n }\n }\n }\n }\n if (newBufferDest.y() + selectionBuffer.height() > buffer.height()) {\n // If it would extend beyond bottom edge, place it above the original\n newTopLeft = currentTopLeft - QPointF(0, selectionRect.height() + 5);\n newBufferDest = mapLogicalWidgetToPhysicalBuffer(newTopLeft);\n }\n \n // First, paste the selection back to its current location to restore the original\n QPainter painter(&buffer);\n // Explicitly set composition mode to draw on top of existing content\n painter.setCompositionMode(QPainter::CompositionMode_SourceOver);\n painter.drawPixmap(currentBufferDest.toPoint(), selectionBuffer);\n \n // Then, paste the copy to the new location\n // We need to handle the case where the copy extends beyond buffer boundaries\n QRect targetRect(newBufferDest.toPoint(), selectionBuffer.size());\n QRect bufferBounds(0, 0, buffer.width(), buffer.height());\n QRect clippedRect = targetRect.intersected(bufferBounds);\n \n if (!clippedRect.isEmpty()) {\n // Calculate which part of the selectionBuffer to draw\n QRect sourceRect = QRect(\n clippedRect.x() - targetRect.x(),\n clippedRect.y() - targetRect.y(),\n clippedRect.width(),\n clippedRect.height()\n );\n \n painter.drawPixmap(clippedRect, selectionBuffer, sourceRect);\n }\n \n // For the selection buffer, we keep the FULL content, even if parts extend beyond canvas\n // This way when the user drags it back, the full content is preserved\n QPixmap newSelectionBuffer = selectionBuffer; // Keep the full original content\n \n // DON'T clear the copied area immediately - leave both original and copy on the canvas\n // The copy will only be cleared when the user actually starts moving the selection\n // This way, if the user cancels without moving, both original and copy remain permanently\n painter.end();\n \n // Update the selection buffer and position\n selectionBuffer = newSelectionBuffer;\n selectionRect = QRect(newTopLeft.toPoint(), selectionRect.size());\n exactSelectionRectF = QRectF(newTopLeft, selectionRect.size());\n selectionJustCopied = true; // Mark that this selection was just copied\n \n // Mark as edited since we added content\n if (!edited) {\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n \n // Update the entire affected area (original + copy + gap)\n QRect updateArea = QRect(currentTopLeft.toPoint(), selectionRect.size())\n .united(selectionRect)\n .adjusted(-10, -10, 10, 10);\n update(updateArea);\n }\n}\n void setMarkdownSelectionMode(bool enabled) {\n markdownSelectionMode = enabled;\n \n if (markdownManager) {\n markdownManager->setSelectionMode(enabled);\n }\n \n if (!enabled) {\n markdownSelecting = false;\n }\n \n // Update cursor\n setCursor(enabled ? Qt::CrossCursor : Qt::ArrowCursor);\n \n // Notify signal\n emit markdownSelectionModeChanged(enabled);\n}\n bool isMarkdownSelectionMode() const {\n return markdownSelectionMode;\n}\n void clearPdfTextSelection() {\n // Clear selection state\n selectedTextBoxes.clear();\n pdfTextSelecting = false;\n \n // Cancel any pending throttled updates\n if (pdfTextSelectionTimer && pdfTextSelectionTimer->isActive()) {\n pdfTextSelectionTimer->stop();\n }\n hasPendingSelection = false;\n \n // Refresh display\n update();\n}\n QString getSelectedPdfText() const {\n if (selectedTextBoxes.isEmpty()) {\n return QString();\n }\n \n // Pre-allocate string with estimated size for efficiency\n QString selectedText;\n selectedText.reserve(selectedTextBoxes.size() * 20); // Estimate ~20 chars per text box\n \n // Build text with space separators\n for (const Poppler::TextBox* textBox : selectedTextBoxes) {\n if (textBox && !textBox->text().isEmpty()) {\n if (!selectedText.isEmpty()) {\n selectedText += \" \";\n }\n selectedText += textBox->text();\n }\n }\n \n return selectedText;\n}\n QPointF mapWidgetToCanvas(const QPointF &widgetPoint) const {\n QPointF topLeft = mapWidgetToCanvas(widgetRect.topLeft());\n QPointF bottomRight = mapWidgetToCanvas(widgetRect.bottomRight());\n \n return QRect(topLeft.toPoint(), bottomRight.toPoint());\n}\n QPointF mapCanvasToWidget(const QPointF &canvasPoint) const {\n QPointF topLeft = mapCanvasToWidget(canvasRect.topLeft());\n QPointF bottomRight = mapCanvasToWidget(canvasRect.bottomRight());\n \n return QRect(topLeft.toPoint(), bottomRight.toPoint());\n}\n QRect mapWidgetToCanvas(const QRect &widgetRect) const {\n QPointF topLeft = mapWidgetToCanvas(widgetRect.topLeft());\n QPointF bottomRight = mapWidgetToCanvas(widgetRect.bottomRight());\n \n return QRect(topLeft.toPoint(), bottomRight.toPoint());\n}\n QRect mapCanvasToWidget(const QRect &canvasRect) const {\n QPointF topLeft = mapCanvasToWidget(canvasRect.topLeft());\n QPointF bottomRight = mapCanvasToWidget(canvasRect.bottomRight());\n \n return QRect(topLeft.toPoint(), bottomRight.toPoint());\n}\n protected:\n void paintEvent(QPaintEvent *event) override {\n QPainter painter(this);\n \n // Save the painter state before transformations\n painter.save();\n \n // Calculate the scaled canvas size\n qreal scaledCanvasWidth = buffer.width() * (internalZoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (internalZoomFactor / 100.0);\n \n // Calculate centering offsets\n qreal centerOffsetX = 0;\n qreal centerOffsetY = 0;\n \n // Center horizontally if canvas is smaller than widget\n if (scaledCanvasWidth < width()) {\n centerOffsetX = (width() - scaledCanvasWidth) / 2.0;\n }\n \n // Center vertically if canvas is smaller than widget\n if (scaledCanvasHeight < height()) {\n centerOffsetY = (height() - scaledCanvasHeight) / 2.0;\n }\n \n // Apply centering offset first\n painter.translate(centerOffsetX, centerOffsetY);\n \n // Use internal zoom factor for smoother animation\n painter.scale(internalZoomFactor / 100.0, internalZoomFactor / 100.0);\n\n // Pan offset needs to be reversed because painter works in transformed coordinates\n painter.translate(-panOffsetX, -panOffsetY);\n\n // Set clipping rectangle to canvas bounds to prevent painting outside\n painter.setClipRect(0, 0, buffer.width(), buffer.height());\n\n // 🟨 Notebook-style background rendering\n if (backgroundImage.isNull()) {\n painter.save();\n \n // Always apply background color regardless of style\n painter.fillRect(QRectF(0, 0, buffer.width(), buffer.height()), backgroundColor);\n\n // Only draw grid/lines if not \"None\" style\n if (backgroundStyle != BackgroundStyle::None) {\n QPen linePen(QColor(100, 100, 100, 100)); // Subtle gray lines\n linePen.setWidthF(1.0);\n painter.setPen(linePen);\n\n qreal scaledDensity = backgroundDensity;\n\n if (devicePixelRatioF() > 1.0)\n scaledDensity *= devicePixelRatioF(); // Optional DPI handling\n\n if (backgroundStyle == BackgroundStyle::Lines || backgroundStyle == BackgroundStyle::Grid) {\n for (int y = 0; y < buffer.height(); y += scaledDensity)\n painter.drawLine(0, y, buffer.width(), y);\n }\n if (backgroundStyle == BackgroundStyle::Grid) {\n for (int x = 0; x < buffer.width(); x += scaledDensity)\n painter.drawLine(x, 0, x, buffer.height());\n }\n }\n\n painter.restore();\n }\n\n // ✅ Draw loaded image or PDF background if available\n if (!backgroundImage.isNull()) {\n painter.drawPixmap(0, 0, backgroundImage);\n }\n\n // ✅ Draw user's strokes from the buffer (transparent overlay)\n painter.drawPixmap(0, 0, buffer);\n \n // Draw straight line preview if in straight line mode and drawing\n // Skip preview for eraser tool\n if (straightLineMode && drawing && currentTool != ToolType::Eraser) {\n // Save the current state before applying the eraser mode\n painter.save();\n \n // Store current pressure - ensure minimum is 0.5 for consistent preview\n qreal pressure = qMax(0.5, painter.device()->devicePixelRatioF() > 1.0 ? 0.8 : 1.0);\n \n // Set up the pen based on tool type\n if (currentTool == ToolType::Marker) {\n qreal thickness = penThickness * 8.0;\n QColor markerColor = penColor;\n // Increase alpha for better visibility in straight line mode\n // Using a higher value (80) instead of the regular 4 to compensate for single-pass drawing\n markerColor.setAlpha(80);\n QPen pen(markerColor, thickness, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);\n painter.setPen(pen);\n } else { // Default Pen\n // Match the exact same thickness calculation as in drawStroke\n qreal scaledThickness = penThickness * pressure;\n QPen pen(penColor, scaledThickness, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);\n painter.setPen(pen);\n }\n \n // Use the same coordinate transformation logic as in drawStroke\n // to ensure the preview line appears at the exact same position\n QPointF bufferStart, bufferEnd;\n \n // Convert screen coordinates to buffer coordinates using the same calculations as drawStroke\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n QPointF adjustedStart = straightLineStartPoint - QPointF(centerOffsetX, centerOffsetY);\n QPointF adjustedEnd = lastPoint - QPointF(centerOffsetX, centerOffsetY);\n \n bufferStart = (adjustedStart / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n bufferEnd = (adjustedEnd / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n \n // Draw the preview line using the same coordinates that will be used for the final line\n painter.drawLine(bufferStart, bufferEnd);\n \n // Restore the original painter state\n painter.restore();\n }\n\n // Draw selection rectangle if in rope tool mode and selecting, moving, or has a selection\n if (ropeToolMode && (selectingWithRope || movingSelection || (!selectionBuffer.isNull() && !selectionRect.isEmpty()))) {\n painter.save(); // Save painter state for overlays\n painter.resetTransform(); // Reset transform to draw directly in logical widget coordinates\n \n if (selectingWithRope && !lassoPathPoints.isEmpty()) {\n QPen selectionPen(Qt::DashLine);\n selectionPen.setColor(Qt::blue);\n selectionPen.setWidthF(1.5); // Width in logical pixels\n painter.setPen(selectionPen);\n painter.drawPolygon(lassoPathPoints); // lassoPathPoints are logical widget coordinates\n } else if (!selectionBuffer.isNull() && !selectionRect.isEmpty()) {\n // selectionRect is in logical widget coordinates.\n // selectionBuffer is in buffer coordinates, we need to handle scaling correctly\n QPixmap scaledBuffer = selectionBuffer;\n \n // Calculate the current zoom factor\n qreal currentZoom = internalZoomFactor / 100.0;\n \n // Scale the selection buffer to match the current zoom level\n if (currentZoom != 1.0) {\n QSize scaledSize = QSize(\n qRound(scaledBuffer.width() * currentZoom),\n qRound(scaledBuffer.height() * currentZoom)\n );\n scaledBuffer = scaledBuffer.scaled(scaledSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);\n }\n \n // Draw it at the logical position\n // Use exactSelectionRectF for smoother movement if available\n QPointF topLeft = exactSelectionRectF.isEmpty() ? selectionRect.topLeft() : exactSelectionRectF.topLeft();\n painter.drawPixmap(topLeft, scaledBuffer);\n\n QPen selectionBorderPen(Qt::DashLine);\n selectionBorderPen.setColor(Qt::darkCyan);\n selectionBorderPen.setWidthF(1.5); // Width in logical pixels\n painter.setPen(selectionBorderPen);\n \n // Use exactSelectionRectF for drawing the selection border if available\n if (!exactSelectionRectF.isEmpty()) {\n painter.drawRect(exactSelectionRectF);\n } else {\n painter.drawRect(selectionRect);\n }\n }\n painter.restore(); // Restore painter state to what it was for drawing the main buffer\n }\n \n\n \n\n \n // Restore the painter state\n painter.restore();\n \n // Fill the area outside the canvas with the widget's background color\n QRect widgetRect = rect();\n QRectF canvasRect(\n centerOffsetX - panOffsetX * (internalZoomFactor / 100.0),\n centerOffsetY - panOffsetY * (internalZoomFactor / 100.0),\n buffer.width() * (internalZoomFactor / 100.0),\n buffer.height() * (internalZoomFactor / 100.0)\n );\n \n // Create regions for areas outside the canvas\n QRegion outsideRegion(widgetRect);\n outsideRegion -= QRegion(canvasRect.toRect());\n \n // Fill the outside region with the background color\n painter.setClipRegion(outsideRegion);\n painter.fillRect(widgetRect, palette().window().color());\n \n // Reset clipping for overlay elements that should appear on top\n painter.setClipping(false);\n \n // Draw markdown selection overlay\n if (markdownSelectionMode && markdownSelecting) {\n painter.save();\n QPen selectionPen(Qt::DashLine);\n selectionPen.setColor(Qt::green);\n selectionPen.setWidthF(2.0);\n painter.setPen(selectionPen);\n \n QBrush selectionBrush(QColor(0, 255, 0, 30)); // Semi-transparent green\n painter.setBrush(selectionBrush);\n \n QRect selectionRect = QRect(markdownSelectionStart, markdownSelectionEnd).normalized();\n painter.drawRect(selectionRect);\n painter.restore();\n }\n \n // Draw PDF text selection overlay on top of everything\n if (pdfTextSelectionEnabled && isPdfLoaded) {\n painter.save(); // Save painter state for PDF text overlay\n painter.resetTransform(); // Reset transform to draw directly in logical widget coordinates\n \n // Draw selection rectangle if actively selecting\n if (pdfTextSelecting) {\n QPen selectionPen(Qt::DashLine);\n selectionPen.setColor(QColor(0, 120, 215)); // Blue selection rectangle\n selectionPen.setWidthF(2.0); // Make it more visible\n painter.setPen(selectionPen);\n \n QBrush selectionBrush(QColor(0, 120, 215, 30)); // Semi-transparent blue fill\n painter.setBrush(selectionBrush);\n \n QRectF selectionRect(pdfSelectionStart, pdfSelectionEnd);\n selectionRect = selectionRect.normalized();\n painter.drawRect(selectionRect);\n }\n \n // Draw highlights for selected text boxes\n if (!selectedTextBoxes.isEmpty()) {\n QColor highlightColor = QColor(255, 255, 0, 100); // Semi-transparent yellow\n painter.setBrush(highlightColor);\n painter.setPen(Qt::NoPen);\n \n // Draw highlight rectangles for selected text boxes\n for (const Poppler::TextBox* textBox : selectedTextBoxes) {\n if (textBox) {\n // Convert PDF coordinates to widget coordinates\n QRectF pdfRect = textBox->boundingBox();\n QPointF topLeft = mapPdfToWidgetCoordinates(pdfRect.topLeft());\n QPointF bottomRight = mapPdfToWidgetCoordinates(pdfRect.bottomRight());\n QRectF widgetRect(topLeft, bottomRight);\n widgetRect = widgetRect.normalized();\n \n painter.drawRect(widgetRect);\n }\n }\n }\n \n painter.restore(); // Restore painter state\n }\n}\n void tabletEvent(QTabletEvent *event) override {\n // ✅ PRIORITY: Handle PDF text selection with stylus when enabled\n // This redirects stylus input to text selection instead of drawing\n if (pdfTextSelectionEnabled && isPdfLoaded) {\n if (event->type() == QEvent::TabletPress) {\n pdfTextSelecting = true;\n pdfSelectionStart = event->position();\n pdfSelectionEnd = pdfSelectionStart;\n \n // Clear any existing selected text boxes without resetting pdfTextSelecting\n selectedTextBoxes.clear();\n \n setCursor(Qt::IBeamCursor); // Ensure cursor is correct\n update(); // Refresh display\n event->accept();\n return;\n } else if (event->type() == QEvent::TabletMove && pdfTextSelecting) {\n pdfSelectionEnd = event->position();\n \n // Store pending selection for throttled processing (60 FPS throttling)\n pendingSelectionStart = pdfSelectionStart;\n pendingSelectionEnd = pdfSelectionEnd;\n hasPendingSelection = true;\n \n // Start timer if not already running (throttled to 60 FPS)\n if (!pdfTextSelectionTimer->isActive()) {\n pdfTextSelectionTimer->start();\n }\n \n // NOTE: No direct update() call here - let the timer handle updates at 60 FPS\n event->accept();\n return;\n } else if (event->type() == QEvent::TabletRelease && pdfTextSelecting) {\n pdfSelectionEnd = event->position();\n \n // Process any pending selection immediately on release\n if (pdfTextSelectionTimer && pdfTextSelectionTimer->isActive()) {\n pdfTextSelectionTimer->stop();\n if (hasPendingSelection) {\n updatePdfTextSelection(pendingSelectionStart, pendingSelectionEnd);\n hasPendingSelection = false;\n }\n } else {\n // Update selection with final position\n updatePdfTextSelection(pdfSelectionStart, pdfSelectionEnd);\n }\n \n pdfTextSelecting = false;\n \n // Check for link clicks if no text was selected\n QString selectedText = getSelectedPdfText();\n if (selectedText.isEmpty()) {\n handlePdfLinkClick(event->position());\n } else {\n // Show context menu for text selection\n QPoint globalPos = mapToGlobal(event->position().toPoint());\n showPdfTextSelectionMenu(globalPos);\n }\n \n event->accept();\n return;\n }\n }\n \n // ✅ NORMAL STYLUS BEHAVIOR: Only reached when PDF text selection is OFF\n // Hardware eraser detection\n static bool hardwareEraserActive = false;\n bool wasUsingHardwareEraser = false;\n \n // Track hardware eraser state\n if (event->pointerType() == QPointingDevice::PointerType::Eraser) {\n // Hardware eraser is being used\n wasUsingHardwareEraser = true;\n \n if (event->type() == QEvent::TabletPress) {\n // Start of eraser stroke - save current tool and switch to eraser\n hardwareEraserActive = true;\n previousTool = currentTool;\n currentTool = ToolType::Eraser;\n }\n }\n \n // Maintain hardware eraser state across move events\n if (hardwareEraserActive && event->type() != QEvent::TabletRelease) {\n wasUsingHardwareEraser = true;\n }\n\n // Determine if we're in eraser mode (either hardware eraser or tool set to eraser)\n bool isErasing = (currentTool == ToolType::Eraser);\n\n if (event->type() == QEvent::TabletPress) {\n drawing = true;\n lastPoint = event->posF(); // Logical widget coordinates\n if (straightLineMode) {\n straightLineStartPoint = lastPoint;\n }\n if (ropeToolMode) {\n if (!selectionBuffer.isNull() && selectionRect.contains(lastPoint.toPoint())) {\n // Start moving an existing selection (or continue if already moving)\n movingSelection = true;\n selectingWithRope = false;\n lastMovePoint = lastPoint;\n // Initialize the exact floating-point rect if it's empty\n if (exactSelectionRectF.isEmpty()) {\n exactSelectionRectF = QRectF(selectionRect);\n }\n \n // If this selection was just copied, clear the area now that user is moving it\n if (selectionJustCopied) {\n QPainter painter(&buffer);\n painter.setCompositionMode(QPainter::CompositionMode_Clear);\n QPointF bufferDest = mapLogicalWidgetToPhysicalBuffer(selectionRect.topLeft());\n QRect clearRect(bufferDest.toPoint(), selectionBuffer.size());\n // Only clear the part that's within buffer bounds\n QRect bufferBounds(0, 0, buffer.width(), buffer.height());\n QRect clippedClearRect = clearRect.intersected(bufferBounds);\n if (!clippedClearRect.isEmpty()) {\n painter.fillRect(clippedClearRect, Qt::transparent);\n }\n painter.end();\n selectionJustCopied = false; // Clear the flag\n }\n \n // If the selection area hasn't been cleared from the buffer yet, clear it now\n if (!selectionAreaCleared && !selectionMaskPath.isEmpty()) {\n QPainter painter(&buffer);\n painter.setCompositionMode(QPainter::CompositionMode_Clear);\n painter.fillPath(selectionMaskPath, Qt::transparent);\n painter.end();\n selectionAreaCleared = true;\n }\n // selectionBuffer already has the content.\n // The original area in 'buffer' was already cleared when selection was made.\n } else {\n // Start a new selection or cancel existing one\n if (!selectionBuffer.isNull()) { // If there's an active selection, a tap outside cancels it\n selectionBuffer = QPixmap();\n selectionRect = QRect();\n lassoPathPoints.clear();\n movingSelection = false;\n selectingWithRope = false;\n selectionJustCopied = false;\n selectionAreaCleared = false;\n selectionMaskPath = QPainterPath();\n selectionBufferRect = QRectF();\n update(); // Full update to remove old selection visuals\n drawing = false; // Consumed this press for cancel\n return;\n }\n selectingWithRope = true;\n movingSelection = false;\n selectionJustCopied = false;\n selectionAreaCleared = false;\n selectionMaskPath = QPainterPath();\n selectionBufferRect = QRectF();\n lassoPathPoints.clear();\n lassoPathPoints << lastPoint; // Start the lasso path\n selectionRect = QRect();\n selectionBuffer = QPixmap();\n }\n }\n } else if (event->type() == QEvent::TabletMove && drawing) {\n if (ropeToolMode) {\n if (selectingWithRope) {\n QRectF oldPreviewBoundingRect = lassoPathPoints.boundingRect();\n lassoPathPoints << event->posF();\n lastPoint = event->posF();\n QRectF newPreviewBoundingRect = lassoPathPoints.boundingRect();\n // Update the area of the selection rectangle preview (logical widget coordinates)\n update(oldPreviewBoundingRect.united(newPreviewBoundingRect).toRect().adjusted(-5,-5,5,5));\n } else if (movingSelection) {\n QPointF delta = event->posF() - lastMovePoint; // Delta in logical widget coordinates\n QRect oldWidgetSelectionRect = selectionRect;\n \n // Update the exact floating-point rectangle first\n exactSelectionRectF.translate(delta);\n \n // Convert back to integer rect, but only when the position actually changes\n QRect newRect = exactSelectionRectF.toRect();\n if (newRect != selectionRect) {\n selectionRect = newRect;\n // Update the combined area of the old and new selection positions (logical widget coordinates)\n update(oldWidgetSelectionRect.united(selectionRect).adjusted(-2,-2,2,2));\n } else {\n // Even if the integer position didn't change, we still need to update\n // to make movement feel smoother, especially with slow movements\n update(selectionRect.adjusted(-2,-2,2,2));\n }\n \n lastMovePoint = event->posF();\n if (!edited){\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n }\n } else if (straightLineMode && !isErasing) {\n // For straight line mode with non-eraser tools, just update the last position\n // and trigger a repaint of only the affected area for preview\n static QElapsedTimer updateTimer;\n static bool timerInitialized = false;\n \n if (!timerInitialized) {\n updateTimer.start();\n timerInitialized = true;\n }\n \n // Throttle updates based on time for high CPU usage tools\n bool shouldUpdate = true;\n \n // Apply throttling for marker which can be CPU intensive\n if (currentTool == ToolType::Marker) {\n shouldUpdate = updateTimer.elapsed() > 16; // Only update every 16ms (approx 60fps)\n }\n \n if (shouldUpdate) {\n QPointF oldLastPoint = lastPoint;\n lastPoint = event->posF();\n \n // Calculate affected rectangle that needs updating\n QRectF updateRect = calculatePreviewRect(straightLineStartPoint, oldLastPoint, lastPoint);\n update(updateRect.toRect());\n \n // Reset timer\n updateTimer.restart();\n } else {\n // Just update the last point without redrawing\n lastPoint = event->posF();\n }\n } else if (straightLineMode && isErasing) {\n // For eraser in straight line mode, continuously erase from start to current point\n // This gives immediate visual feedback and smoother erasing experience\n \n // Store current point\n QPointF currentPoint = event->posF();\n \n // Clear previous stroke by redrawing with transparency\n QRectF updateRect = QRectF(straightLineStartPoint, lastPoint).normalized().adjusted(-20, -20, 20, 20);\n update(updateRect.toRect());\n \n // Erase from start point to current position\n eraseStroke(straightLineStartPoint, currentPoint, event->pressure());\n \n // Update last point\n lastPoint = currentPoint;\n \n // Only track benchmarking when enabled\n if (benchmarking) {\n processedTimestamps.push_back(benchmarkTimer.elapsed());\n }\n } else {\n // Normal drawing mode OR eraser regardless of straight line mode\n if (isErasing) {\n eraseStroke(lastPoint, event->posF(), event->pressure());\n } else {\n drawStroke(lastPoint, event->posF(), event->pressure());\n }\n lastPoint = event->posF();\n \n // Only track benchmarking when enabled\n if (benchmarking) {\n processedTimestamps.push_back(benchmarkTimer.elapsed());\n }\n }\n } else if (event->type() == QEvent::TabletRelease) {\n if (straightLineMode && !isErasing) {\n // Draw the final line on release with the current pressure\n qreal pressure = event->pressure();\n \n // Always use at least a minimum pressure\n pressure = qMax(pressure, 0.5);\n \n drawStroke(straightLineStartPoint, event->posF(), pressure);\n \n // Only track benchmarking when enabled\n if (benchmarking) {\n processedTimestamps.push_back(benchmarkTimer.elapsed());\n }\n \n // Force repaint to clear the preview line\n update();\n if (!edited){\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n } else if (straightLineMode && isErasing) {\n // For erasing in straight line mode, most of the work is done during movement\n // Just ensure one final erasing pass from start to end point\n qreal pressure = qMax(event->pressure(), 0.5);\n \n // Final pass to ensure the entire line is erased\n eraseStroke(straightLineStartPoint, event->posF(), pressure);\n \n // Force update to clear any remaining artifacts\n update();\n if (!edited){\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n }\n \n drawing = false;\n \n // Reset tool state if we were using the hardware eraser\n if (wasUsingHardwareEraser) {\n currentTool = previousTool;\n hardwareEraserActive = false; // Reset hardware eraser tracking\n }\n\n if (ropeToolMode) {\n if (selectingWithRope) {\n if (lassoPathPoints.size() > 2) { // Need at least 3 points for a polygon\n lassoPathPoints << lassoPathPoints.first(); // Close the polygon\n \n if (!lassoPathPoints.boundingRect().isEmpty()) {\n // 1. Create a QPolygonF in buffer coordinates using proper transformation\n QPolygonF bufferLassoPath;\n for (const QPointF& p_widget_logical : qAsConst(lassoPathPoints)) {\n bufferLassoPath << mapLogicalWidgetToPhysicalBuffer(p_widget_logical);\n }\n\n // 2. Get the bounding box of this path on the buffer\n QRectF bufferPathBoundingRect = bufferLassoPath.boundingRect();\n\n // 3. Copy that part of the main buffer\n QPixmap originalPiece = buffer.copy(bufferPathBoundingRect.toRect());\n\n // 4. Create the selectionBuffer (same size as originalPiece) and fill transparent\n selectionBuffer = QPixmap(originalPiece.size());\n selectionBuffer.fill(Qt::transparent);\n \n // 5. Create a mask from the lasso path\n QPainterPath maskPath;\n // The lasso path for the mask needs to be relative to originalPiece.topLeft()\n maskPath.addPolygon(bufferLassoPath.translated(-bufferPathBoundingRect.topLeft()));\n \n // 6. Paint the originalPiece onto selectionBuffer, using the mask\n QPainter selectionPainter(&selectionBuffer);\n selectionPainter.setClipPath(maskPath);\n selectionPainter.drawPixmap(0,0, originalPiece);\n selectionPainter.end();\n\n // 7. DON'T clear the selected area from the main buffer yet\n // The area will only be cleared when the user actually starts moving the selection\n // This way, if the user cancels without moving, the original content remains\n selectionAreaCleared = false;\n \n // Store the mask path and buffer rect for later clearing when movement starts\n selectionMaskPath = maskPath.translated(bufferPathBoundingRect.topLeft());\n selectionBufferRect = bufferPathBoundingRect;\n \n // 8. Calculate the correct selectionRect in logical widget coordinates\n QRectF logicalSelectionRect = mapRectBufferToWidgetLogical(bufferPathBoundingRect);\n selectionRect = logicalSelectionRect.toRect();\n exactSelectionRectF = logicalSelectionRect;\n \n // Update the area of the selection on screen\n update(logicalSelectionRect.adjusted(-2,-2,2,2).toRect());\n \n // Emit signal for context menu at the center of the selection with a delay\n // This allows the user to immediately start moving the selection if desired\n QPoint menuPosition = selectionRect.center();\n QTimer::singleShot(500, this, [this, menuPosition]() {\n // Only show menu if selection still exists and hasn't been moved\n if (!selectionBuffer.isNull() && !selectionRect.isEmpty() && !movingSelection) {\n emit ropeSelectionCompleted(menuPosition);\n }\n });\n }\n }\n lassoPathPoints.clear(); // Ready for next selection, or move\n selectingWithRope = false;\n // Now, if the user presses inside selectionRect, movingSelection will become true.\n } else if (movingSelection) {\n if (!selectionBuffer.isNull() && !selectionRect.isEmpty()) {\n QPainter painter(&buffer);\n // Explicitly set composition mode to draw on top of existing content\n painter.setCompositionMode(QPainter::CompositionMode_SourceOver);\n // Use exact floating-point position if available for more precise placement\n QPointF topLeft = exactSelectionRectF.isEmpty() ? selectionRect.topLeft() : exactSelectionRectF.topLeft();\n // Use proper coordinate transformation to get buffer coordinates\n QPointF bufferDest = mapLogicalWidgetToPhysicalBuffer(topLeft);\n painter.drawPixmap(bufferDest.toPoint(), selectionBuffer);\n painter.end();\n \n // Update the pasted area\n QRectF bufferPasteRect(bufferDest, selectionBuffer.size());\n update(mapRectBufferToWidgetLogical(bufferPasteRect).adjusted(-2,-2,2,2));\n \n // Clear selection after pasting, making it permanent\n selectionBuffer = QPixmap();\n selectionRect = QRect();\n exactSelectionRectF = QRectF();\n movingSelection = false;\n selectionJustCopied = false;\n selectionAreaCleared = false;\n selectionMaskPath = QPainterPath();\n selectionBufferRect = QRectF();\n }\n }\n }\n \n\n }\n event->accept();\n}\n void mousePressEvent(QMouseEvent *event) override {\n // Handle markdown selection when enabled\n if (markdownSelectionMode && event->button() == Qt::LeftButton) {\n markdownSelecting = true;\n markdownSelectionStart = event->pos();\n markdownSelectionEnd = markdownSelectionStart;\n event->accept();\n return;\n }\n \n // Handle PDF text selection when enabled (mouse/touch fallback - stylus handled in tabletEvent)\n if (pdfTextSelectionEnabled && isPdfLoaded) {\n if (event->button() == Qt::LeftButton) {\n pdfTextSelecting = true;\n pdfSelectionStart = event->position();\n pdfSelectionEnd = pdfSelectionStart;\n \n // Clear any existing selected text boxes without resetting pdfTextSelecting\n selectedTextBoxes.clear();\n \n setCursor(Qt::IBeamCursor); // Ensure cursor is correct\n update(); // Refresh display\n event->accept();\n return;\n }\n }\n \n // Ignore mouse/touch input on canvas for drawing (drawing only works with tablet/stylus)\n event->ignore();\n}\n void mouseMoveEvent(QMouseEvent *event) override {\n // Handle markdown selection when enabled\n if (markdownSelectionMode && markdownSelecting) {\n markdownSelectionEnd = event->pos();\n update(); // Refresh to show selection rectangle\n event->accept();\n return;\n }\n \n // Handle PDF text selection when enabled (mouse/touch fallback - stylus handled in tabletEvent)\n if (pdfTextSelectionEnabled && isPdfLoaded && pdfTextSelecting) {\n pdfSelectionEnd = event->position();\n \n // Store pending selection for throttled processing\n pendingSelectionStart = pdfSelectionStart;\n pendingSelectionEnd = pdfSelectionEnd;\n hasPendingSelection = true;\n \n // Start timer if not already running (throttled to 60 FPS)\n if (!pdfTextSelectionTimer->isActive()) {\n pdfTextSelectionTimer->start();\n }\n \n event->accept();\n return;\n }\n \n // Update cursor based on mode when not actively selecting\n if (pdfTextSelectionEnabled && isPdfLoaded && !pdfTextSelecting) {\n setCursor(Qt::IBeamCursor);\n }\n \n event->ignore();\n}\n void mouseReleaseEvent(QMouseEvent *event) override {\n // Handle markdown selection when enabled\n if (markdownSelectionMode && markdownSelecting && event->button() == Qt::LeftButton) {\n markdownSelecting = false;\n \n // Create markdown window if selection is valid\n QRect selectionRect = QRect(markdownSelectionStart, markdownSelectionEnd).normalized();\n if (selectionRect.width() > 50 && selectionRect.height() > 50 && markdownManager) {\n markdownManager->createMarkdownWindow(selectionRect);\n }\n \n // Exit selection mode\n setMarkdownSelectionMode(false);\n \n // Force screen update to clear the green selection overlay\n update();\n \n event->accept();\n return;\n }\n \n // Handle PDF text selection when enabled (mouse/touch fallback - stylus handled in tabletEvent)\n if (pdfTextSelectionEnabled && isPdfLoaded && pdfTextSelecting) {\n if (event->button() == Qt::LeftButton) {\n pdfSelectionEnd = event->position();\n \n // Process any pending selection immediately on release\n if (pdfTextSelectionTimer && pdfTextSelectionTimer->isActive()) {\n pdfTextSelectionTimer->stop();\n if (hasPendingSelection) {\n updatePdfTextSelection(pendingSelectionStart, pendingSelectionEnd);\n hasPendingSelection = false;\n }\n } else {\n // Update selection with final position\n updatePdfTextSelection(pdfSelectionStart, pdfSelectionEnd);\n }\n \n pdfTextSelecting = false;\n \n // Check for link clicks if no text was selected\n QString selectedText = getSelectedPdfText();\n if (selectedText.isEmpty()) {\n handlePdfLinkClick(event->position());\n } else {\n // Show context menu for text selection\n QPoint globalPos = mapToGlobal(event->position().toPoint());\n showPdfTextSelectionMenu(globalPos);\n }\n \n event->accept();\n return;\n }\n }\n \n\n \n event->ignore();\n}\n void resizeEvent(QResizeEvent *event) override {\n // Don't resize the buffer when the widget resizes\n // The buffer size should be determined by the PDF/document content, not the widget size\n // The paintEvent will handle centering the buffer content within the widget\n \n QWidget::resizeEvent(event);\n}\n bool event(QEvent *event) override {\n if (!touchGesturesEnabled) {\n return QWidget::event(event);\n }\n\n if (event->type() == QEvent::TouchBegin || \n event->type() == QEvent::TouchUpdate || \n event->type() == QEvent::TouchEnd) {\n \n QTouchEvent *touchEvent = static_cast(event);\n const QList touchPoints = touchEvent->points();\n \n activeTouchPoints = touchPoints.count();\n\n if (activeTouchPoints == 1) {\n // Single finger pan\n const QTouchEvent::TouchPoint &touchPoint = touchPoints.first();\n \n if (event->type() == QEvent::TouchBegin) {\n isPanning = true;\n lastTouchPos = touchPoint.position();\n } else if (event->type() == QEvent::TouchUpdate && isPanning) {\n QPointF delta = touchPoint.position() - lastTouchPos;\n \n // Make panning more responsive by using floating-point calculations\n qreal scaledDeltaX = delta.x() / (internalZoomFactor / 100.0);\n qreal scaledDeltaY = delta.y() / (internalZoomFactor / 100.0);\n \n // Calculate new pan positions with sub-pixel precision\n qreal newPanX = panOffsetX - scaledDeltaX;\n qreal newPanY = panOffsetY - scaledDeltaY;\n \n // Clamp pan values when canvas is smaller than viewport\n qreal scaledCanvasWidth = buffer.width() * (internalZoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (internalZoomFactor / 100.0);\n \n // If canvas is smaller than widget, lock pan to 0 (centered)\n if (scaledCanvasWidth < width()) {\n newPanX = 0;\n }\n if (scaledCanvasHeight < height()) {\n newPanY = 0;\n }\n \n // Emit signal with integer values for compatibility\n emit panChanged(qRound(newPanX), qRound(newPanY));\n \n lastTouchPos = touchPoint.position();\n }\n } else if (activeTouchPoints == 2) {\n // Two finger pinch zoom\n isPanning = false;\n \n const QTouchEvent::TouchPoint &touch1 = touchPoints[0];\n const QTouchEvent::TouchPoint &touch2 = touchPoints[1];\n \n // Calculate distance between touch points with higher precision\n qreal currentDist = QLineF(touch1.position(), touch2.position()).length();\n qreal startDist = QLineF(touch1.pressPosition(), touch2.pressPosition()).length();\n \n if (event->type() == QEvent::TouchBegin) {\n lastPinchScale = 1.0;\n // Store the starting internal zoom\n internalZoomFactor = zoomFactor;\n } else if (event->type() == QEvent::TouchUpdate && startDist > 0) {\n qreal scale = currentDist / startDist;\n \n // Use exponential scaling for more natural feel\n qreal scaleChange = scale / lastPinchScale;\n \n // Apply scale with higher sensitivity\n internalZoomFactor *= scaleChange;\n internalZoomFactor = qBound(10.0, internalZoomFactor, 400.0);\n \n // Calculate zoom center (midpoint between two fingers)\n QPointF center = (touch1.position() + touch2.position()) / 2.0;\n \n // Account for centering offset\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n // Adjust center point for centering offset\n QPointF adjustedCenter = center - QPointF(centerOffsetX, centerOffsetY);\n \n // Always update zoom for smooth animation\n int newZoom = qRound(internalZoomFactor);\n \n // Calculate pan adjustment to keep the zoom centered at pinch point\n QPointF bufferCenter = adjustedCenter / (zoomFactor / 100.0) + QPointF(panOffsetX, panOffsetY);\n \n // Update zoom factor before emitting\n qreal oldZoomFactor = zoomFactor;\n zoomFactor = newZoom;\n \n // Emit zoom change even for small changes\n emit zoomChanged(newZoom);\n \n // Adjust pan to keep center point fixed with sub-pixel precision\n qreal newPanX = bufferCenter.x() - adjustedCenter.x() / (internalZoomFactor / 100.0);\n qreal newPanY = bufferCenter.y() - adjustedCenter.y() / (internalZoomFactor / 100.0);\n \n // After zoom, check if we need to center\n qreal newScaledCanvasWidth = buffer.width() * (internalZoomFactor / 100.0);\n qreal newScaledCanvasHeight = buffer.height() * (internalZoomFactor / 100.0);\n \n if (newScaledCanvasWidth < width()) {\n newPanX = 0;\n }\n if (newScaledCanvasHeight < height()) {\n newPanY = 0;\n }\n \n emit panChanged(qRound(newPanX), qRound(newPanY));\n \n lastPinchScale = scale;\n \n // Request update only for visible area\n update();\n }\n } else {\n // More than 2 fingers - ignore\n isPanning = false;\n }\n \n if (event->type() == QEvent::TouchEnd) {\n isPanning = false;\n lastPinchScale = 1.0;\n activeTouchPoints = 0;\n // Sync internal zoom with actual zoom\n internalZoomFactor = zoomFactor;\n \n // Emit signal that touch gesture has ended\n emit touchGestureEnded();\n }\n \n event->accept();\n return true;\n }\n \n return QWidget::event(event);\n}\n private:\n QPointF mapLogicalWidgetToPhysicalBuffer(const QPointF& logicalWidgetPoint) {\n // Use the same coordinate transformation logic as drawStroke for consistency\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n // Convert widget position to buffer position, accounting for centering\n QPointF adjustedPoint = logicalWidgetPoint - QPointF(centerOffsetX, centerOffsetY);\n QPointF bufferPoint = (adjustedPoint / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n \n return bufferPoint;\n}\n QRect mapRectBufferToWidgetLogical(const QRectF& physicalBufferRect) {\n // Use the same coordinate transformation logic as drawStroke for consistency\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n // Convert buffer coordinates back to widget coordinates\n QRectF widgetRect = QRectF(\n (physicalBufferRect.topLeft() - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY),\n physicalBufferRect.size() * (zoomFactor / 100.0)\n );\n \n return widgetRect.toRect();\n}\n QPixmap buffer;\n QImage background;\n QPointF lastPoint;\n QPointF straightLineStartPoint;\n bool drawing;\n QColor penColor;\n qreal penThickness;\n ToolType currentTool;\n ToolType previousTool;\n qreal penToolThickness = 5.0;\n qreal markerToolThickness = 5.0;\n qreal eraserToolThickness = 5.0;\n QString saveFolder;\n QPixmap backgroundImage;\n bool straightLineMode = false;\n bool ropeToolMode = false;\n QPixmap selectionBuffer;\n QRect selectionRect;\n QRectF exactSelectionRectF;\n QPolygonF lassoPathPoints;\n bool selectingWithRope = false;\n bool movingSelection = false;\n bool selectionJustCopied = false;\n bool selectionAreaCleared = false;\n QPainterPath selectionMaskPath;\n QRectF selectionBufferRect;\n QPointF lastMovePoint;\n int zoomFactor;\n int panOffsetX;\n int panOffsetY;\n qreal internalZoomFactor = 100.0;\n void initializeBuffer() {\n QScreen *screen = QGuiApplication::primaryScreen();\n qreal dpr = screen ? screen->devicePixelRatio() : 1.0;\n\n // Get logical screen size\n QSize logicalSize = screen ? screen->size() : QSize(1440, 900);\n QSize pixelSize = logicalSize * dpr;\n\n buffer = QPixmap(pixelSize);\n buffer.fill(Qt::transparent);\n\n setMaximumSize(pixelSize); // 🔥 KEY LINE to make full canvas drawable\n}\n void drawStroke(const QPointF &start, const QPointF &end, qreal pressure) {\n if (buffer.isNull()) {\n initializeBuffer();\n }\n\n if (!edited){\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n\n QPainter painter(&buffer);\n painter.setRenderHint(QPainter::Antialiasing);\n\n qreal thickness = penThickness;\n\n qreal updatePadding = (currentTool == ToolType::Marker) ? thickness * 4.0 : 10;\n\n if (currentTool == ToolType::Marker) {\n thickness *= 8.0;\n QColor markerColor = penColor;\n // Adjust alpha based on whether we're in straight line mode\n if (straightLineMode) {\n // For straight line mode, use higher alpha to make it more visible\n markerColor.setAlpha(40);\n } else {\n // For regular drawing, use lower alpha for the usual marker effect\n markerColor.setAlpha(4);\n }\n QPen pen(markerColor, thickness, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);\n painter.setPen(pen);\n } else { // Default Pen\n qreal scaledThickness = thickness * pressure; // **Linear pressure scaling**\n QPen pen(penColor, scaledThickness, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);\n painter.setPen(pen);\n }\n\n // Calculate centering offsets\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n // Convert screen position to buffer position, accounting for centering\n QPointF adjustedStart = start - QPointF(centerOffsetX, centerOffsetY);\n QPointF adjustedEnd = end - QPointF(centerOffsetX, centerOffsetY);\n \n QPointF bufferStart = (adjustedStart / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n QPointF bufferEnd = (adjustedEnd / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n\n painter.drawLine(bufferStart, bufferEnd);\n\n QRectF updateRect = QRectF(bufferStart, bufferEnd)\n .normalized()\n .adjusted(-updatePadding, -updatePadding, updatePadding, updatePadding);\n\n QRect scaledUpdateRect = QRect(\n ((updateRect.topLeft() - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY)).toPoint(),\n ((updateRect.bottomRight() - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY)).toPoint()\n );\n update(scaledUpdateRect);\n}\n void eraseStroke(const QPointF &start, const QPointF &end, qreal pressure) {\n if (buffer.isNull()) {\n initializeBuffer();\n }\n\n if (!edited){\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n\n QPainter painter(&buffer);\n painter.setCompositionMode(QPainter::CompositionMode_Clear);\n\n qreal eraserThickness = penThickness * 6.0;\n QPen eraserPen(Qt::transparent, eraserThickness, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);\n painter.setPen(eraserPen);\n\n // Calculate centering offsets\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n // Convert screen position to buffer position, accounting for centering\n QPointF adjustedStart = start - QPointF(centerOffsetX, centerOffsetY);\n QPointF adjustedEnd = end - QPointF(centerOffsetX, centerOffsetY);\n \n QPointF bufferStart = (adjustedStart / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n QPointF bufferEnd = (adjustedEnd / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n\n painter.drawLine(bufferStart, bufferEnd);\n\n qreal updatePadding = eraserThickness / 2.0 + 5.0; // Half the eraser thickness plus some extra padding\n QRectF updateRect = QRectF(bufferStart, bufferEnd)\n .normalized()\n .adjusted(-updatePadding, -updatePadding, updatePadding, updatePadding);\n\n QRect scaledUpdateRect = QRect(\n ((updateRect.topLeft() - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY)).toPoint(),\n ((updateRect.bottomRight() - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY)).toPoint()\n );\n update(scaledUpdateRect);\n}\n QRectF calculatePreviewRect(const QPointF &start, const QPointF &oldEnd, const QPointF &newEnd) {\n // Calculate centering offsets - use the same calculation as in paintEvent\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n // Calculate the buffer coordinates for our points (same as in drawStroke)\n QPointF adjustedStart = start - QPointF(centerOffsetX, centerOffsetY);\n QPointF adjustedOldEnd = oldEnd - QPointF(centerOffsetX, centerOffsetY);\n QPointF adjustedNewEnd = newEnd - QPointF(centerOffsetX, centerOffsetY);\n \n QPointF bufferStart = (adjustedStart / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n QPointF bufferOldEnd = (adjustedOldEnd / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n QPointF bufferNewEnd = (adjustedNewEnd / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n \n // Now convert from buffer coordinates to screen coordinates\n QPointF screenStart = (bufferStart - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY);\n QPointF screenOldEnd = (bufferOldEnd - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY);\n QPointF screenNewEnd = (bufferNewEnd - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY);\n \n // Create rectangles for both the old and new lines\n QRectF oldLineRect = QRectF(screenStart, screenOldEnd).normalized();\n QRectF newLineRect = QRectF(screenStart, screenNewEnd).normalized();\n \n // Calculate padding based on pen thickness and device pixel ratio\n qreal dpr = devicePixelRatioF();\n qreal padding;\n \n if (currentTool == ToolType::Eraser) {\n padding = penThickness * 6.0 * dpr;\n } else if (currentTool == ToolType::Marker) {\n padding = penThickness * 8.0 * dpr;\n } else {\n padding = penThickness * dpr;\n }\n \n // Ensure minimum padding\n padding = qMax(padding, 15.0);\n \n // Combine rectangles with appropriate padding\n QRectF combinedRect = oldLineRect.united(newLineRect);\n return combinedRect.adjusted(-padding, -padding, padding, padding);\n}\n QCache pdfCache;\n std::unique_ptr pdfDocument;\n int currentPdfPage;\n bool isPdfLoaded = false;\n int totalPdfPages = 0;\n int lastActivePage = 0;\n int lastZoomLevel = 100;\n int lastPanX = 0;\n int lastPanY = 0;\n bool edited = false;\n bool benchmarking;\n std::deque processedTimestamps;\n QElapsedTimer benchmarkTimer;\n QString notebookId;\n void loadNotebookId() {\n QString idFile = saveFolder + \"/.notebook_id.txt\";\n if (QFile::exists(idFile)) {\n QFile file(idFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n notebookId = in.readLine().trimmed();\n }\n } else {\n // No ID file → create new random ID\n notebookId = QUuid::createUuid().toString(QUuid::WithoutBraces).replace(\"-\", \"\");\n saveNotebookId();\n }\n}\n void saveNotebookId() {\n QString idFile = saveFolder + \"/.notebook_id.txt\";\n QFile file(idFile);\n if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {\n QTextStream out(&file);\n out << notebookId;\n }\n}\n int pdfRenderDPI = 192;\n bool touchGesturesEnabled = false;\n QPointF lastTouchPos;\n qreal lastPinchScale = 1.0;\n bool isPanning = false;\n int activeTouchPoints = 0;\n BackgroundStyle backgroundStyle = BackgroundStyle::None;\n QColor backgroundColor = Qt::white;\n int backgroundDensity = 40;\n bool pdfTextSelectionEnabled = false;\n bool pdfTextSelecting = false;\n QPointF pdfSelectionStart;\n QPointF pdfSelectionEnd;\n QList currentPdfTextBoxes;\n QList selectedTextBoxes;\n std::unique_ptr currentPdfPageForText;\n QTimer* pdfTextSelectionTimer = nullptr;\n QPointF pendingSelectionStart;\n QPointF pendingSelectionEnd;\n bool hasPendingSelection = false;\n QTimer* pdfCacheTimer = nullptr;\n int currentCachedPage = -1;\n int pendingCacheTargetPage = -1;\n QList*> activePdfWatchers;\n QCache noteCache;\n QTimer* noteCacheTimer = nullptr;\n int currentCachedNotePage = -1;\n int pendingNoteCacheTargetPage = -1;\n QList*> activeNoteWatchers;\n MarkdownWindowManager* markdownManager = nullptr;\n bool markdownSelectionMode = false;\n QPoint markdownSelectionStart;\n QPoint markdownSelectionEnd;\n bool markdownSelecting = false;\n void loadPdfTextBoxes(int pageNumber) {\n // Clear existing text boxes\n qDeleteAll(currentPdfTextBoxes);\n currentPdfTextBoxes.clear();\n \n if (!pdfDocument || pageNumber < 0 || pageNumber >= pdfDocument->numPages()) {\n return;\n }\n \n // Get the page for text operations\n currentPdfPageForText = std::unique_ptr(pdfDocument->page(pageNumber));\n if (!currentPdfPageForText) {\n return;\n }\n \n // Load text boxes for the page\n auto textBoxVector = currentPdfPageForText->textList();\n currentPdfTextBoxes.clear();\n for (auto& textBox : textBoxVector) {\n currentPdfTextBoxes.append(textBox.release()); // Transfer ownership to QList\n }\n}\n QPointF mapWidgetToPdfCoordinates(const QPointF &widgetPoint) {\n if (!currentPdfPageForText || backgroundImage.isNull()) {\n return QPointF();\n }\n \n // Use the same zoom factor as in paintEvent (internalZoomFactor for smooth animations)\n qreal zoom = internalZoomFactor / 100.0;\n \n // Calculate the scaled canvas size (same as in paintEvent)\n qreal scaledCanvasWidth = buffer.width() * zoom;\n qreal scaledCanvasHeight = buffer.height() * zoom;\n \n // Calculate centering offsets (same as in paintEvent)\n qreal centerOffsetX = 0;\n qreal centerOffsetY = 0;\n \n // Center horizontally if canvas is smaller than widget\n if (scaledCanvasWidth < width()) {\n centerOffsetX = (width() - scaledCanvasWidth) / 2.0;\n }\n \n // Center vertically if canvas is smaller than widget\n if (scaledCanvasHeight < height()) {\n centerOffsetY = (height() - scaledCanvasHeight) / 2.0;\n }\n \n // Reverse the transformations applied in paintEvent\n QPointF adjustedPoint = widgetPoint;\n adjustedPoint -= QPointF(centerOffsetX, centerOffsetY);\n adjustedPoint /= zoom;\n adjustedPoint += QPointF(panOffsetX, panOffsetY);\n \n // Convert to PDF coordinates\n // Since Poppler renders the PDF in Qt coordinate system (top-left origin),\n // we don't need to flip the Y coordinate\n QSizeF pdfPageSize = currentPdfPageForText->pageSizeF();\n QSizeF imageSize = backgroundImage.size();\n \n // Scale from image coordinates to PDF coordinates\n qreal scaleX = pdfPageSize.width() / imageSize.width();\n qreal scaleY = pdfPageSize.height() / imageSize.height();\n \n QPointF pdfPoint;\n pdfPoint.setX(adjustedPoint.x() * scaleX);\n pdfPoint.setY(adjustedPoint.y() * scaleY); // No Y-axis flipping needed\n \n return pdfPoint;\n}\n QPointF mapPdfToWidgetCoordinates(const QPointF &pdfPoint) {\n if (!currentPdfPageForText || backgroundImage.isNull()) {\n return QPointF();\n }\n \n // Convert from PDF coordinates to image coordinates\n QSizeF pdfPageSize = currentPdfPageForText->pageSizeF();\n QSizeF imageSize = backgroundImage.size();\n \n // Scale from PDF coordinates to image coordinates\n qreal scaleX = imageSize.width() / pdfPageSize.width();\n qreal scaleY = imageSize.height() / pdfPageSize.height();\n \n QPointF imagePoint;\n imagePoint.setX(pdfPoint.x() * scaleX);\n imagePoint.setY(pdfPoint.y() * scaleY); // No Y-axis flipping needed\n \n // Use the same zoom factor as in paintEvent (internalZoomFactor for smooth animations)\n qreal zoom = internalZoomFactor / 100.0;\n \n // Apply the same transformations as in paintEvent\n QPointF widgetPoint = imagePoint;\n widgetPoint -= QPointF(panOffsetX, panOffsetY);\n widgetPoint *= zoom;\n \n // Calculate the scaled canvas size (same as in paintEvent)\n qreal scaledCanvasWidth = buffer.width() * zoom;\n qreal scaledCanvasHeight = buffer.height() * zoom;\n \n // Calculate centering offsets (same as in paintEvent)\n qreal centerOffsetX = 0;\n qreal centerOffsetY = 0;\n \n // Center horizontally if canvas is smaller than widget\n if (scaledCanvasWidth < width()) {\n centerOffsetX = (width() - scaledCanvasWidth) / 2.0;\n }\n \n // Center vertically if canvas is smaller than widget\n if (scaledCanvasHeight < height()) {\n centerOffsetY = (height() - scaledCanvasHeight) / 2.0;\n }\n \n widgetPoint += QPointF(centerOffsetX, centerOffsetY);\n \n return widgetPoint;\n}\n void updatePdfTextSelection(const QPointF &start, const QPointF &end) {\n // Early return if PDF is not loaded or no text boxes available\n if (!isPdfLoaded || currentPdfTextBoxes.isEmpty()) {\n return;\n }\n \n // Clear previous selection efficiently\n selectedTextBoxes.clear();\n \n // Create normalized selection rectangle in widget coordinates\n QRectF widgetSelectionRect(start, end);\n widgetSelectionRect = widgetSelectionRect.normalized();\n \n // Convert to PDF coordinate space\n QPointF pdfTopLeft = mapWidgetToPdfCoordinates(widgetSelectionRect.topLeft());\n QPointF pdfBottomRight = mapWidgetToPdfCoordinates(widgetSelectionRect.bottomRight());\n QRectF pdfSelectionRect(pdfTopLeft, pdfBottomRight);\n pdfSelectionRect = pdfSelectionRect.normalized();\n \n // Reserve space for efficiency if we expect many selections\n selectedTextBoxes.reserve(qMin(currentPdfTextBoxes.size(), 50));\n \n // Find intersecting text boxes with optimized loop\n for (const Poppler::TextBox* textBox : currentPdfTextBoxes) {\n if (textBox && textBox->boundingBox().intersects(pdfSelectionRect)) {\n selectedTextBoxes.append(const_cast(textBox));\n }\n }\n \n // Only emit signal and update if we have selected text\n if (!selectedTextBoxes.isEmpty()) {\n QString selectedText = getSelectedPdfText();\n if (!selectedText.isEmpty()) {\n emit pdfTextSelected(selectedText);\n }\n }\n \n // Trigger repaint to show selection\n update();\n}\n void handlePdfLinkClick(const QPointF &clickPoint) {\n if (!isPdfLoaded || !currentPdfPageForText) {\n return;\n }\n \n // Convert widget coordinates to PDF coordinates\n QPointF pdfPoint = mapWidgetToPdfCoordinates(position);\n \n // Get PDF page size for reference\n QSizeF pdfPageSize = currentPdfPageForText->pageSizeF();\n \n // Convert to normalized coordinates (0.0 to 1.0) to match Poppler's link coordinate system\n QPointF normalizedPoint(pdfPoint.x() / pdfPageSize.width(), pdfPoint.y() / pdfPageSize.height());\n \n // Get links for the current page\n auto links = currentPdfPageForText->links();\n \n for (const auto& link : links) {\n QRectF linkArea = link->linkArea();\n \n // Normalize the rectangle to handle negative width/height\n QRectF normalizedLinkArea = linkArea.normalized();\n \n // Check if the normalized rectangle contains the normalized point\n if (normalizedLinkArea.contains(normalizedPoint)) {\n // Handle different types of links\n if (link->linkType() == Poppler::Link::Goto) {\n Poppler::LinkGoto* gotoLink = static_cast(link.get());\n if (gotoLink && gotoLink->destination().pageNumber() >= 0) {\n int targetPage = gotoLink->destination().pageNumber() - 1; // Convert to 0-based\n emit pdfLinkClicked(targetPage);\n return;\n }\n }\n // Add other link types as needed (URI, etc.)\n }\n }\n}\n void showPdfTextSelectionMenu(const QPoint &position) {\n QString selectedText = getSelectedPdfText();\n if (selectedText.isEmpty()) {\n return; // No text selected, don't show menu\n }\n \n // Create context menu\n QMenu *contextMenu = new QMenu(this);\n contextMenu->setAttribute(Qt::WA_DeleteOnClose);\n \n // Add Copy action\n QAction *copyAction = contextMenu->addAction(tr(\"Copy\"));\n copyAction->setIcon(QIcon(\":/resources/icons/copy.png\")); // You may need to add this icon\n connect(copyAction, &QAction::triggered, this, [selectedText]() {\n QClipboard *clipboard = QGuiApplication::clipboard();\n clipboard->setText(selectedText);\n });\n \n // Add separator\n contextMenu->addSeparator();\n \n // Add Cancel action\n QAction *cancelAction = contextMenu->addAction(tr(\"Cancel\"));\n cancelAction->setIcon(QIcon(\":/resources/icons/cross.png\"));\n connect(cancelAction, &QAction::triggered, this, [this]() {\n clearPdfTextSelection();\n });\n \n // Show the menu at the specified position\n contextMenu->popup(position);\n}\n QList getTextBoxesInSelection(const QPointF &start, const QPointF &end) {\n QList selectedBoxes;\n \n if (!currentPdfPageForText) {\n // qDebug() << \"PDF text selection: No current page for text\";\n return selectedBoxes;\n }\n \n // Convert widget coordinates to PDF coordinates\n QPointF pdfStart = mapWidgetToPdfCoordinates(start);\n QPointF pdfEnd = mapWidgetToPdfCoordinates(end);\n \n // qDebug() << \"PDF text selection: Widget coords\" << start << \"to\" << end;\n // qDebug() << \"PDF text selection: PDF coords\" << pdfStart << \"to\" << pdfEnd;\n \n // Create selection rectangle in PDF coordinates\n QRectF selectionRect(pdfStart, pdfEnd);\n selectionRect = selectionRect.normalized();\n \n // qDebug() << \"PDF text selection: Selection rect in PDF coords:\" << selectionRect;\n \n // Find text boxes that intersect with the selection\n int intersectionCount = 0;\n for (Poppler::TextBox* textBox : currentPdfTextBoxes) {\n if (textBox) {\n QRectF textBoxRect = textBox->boundingBox();\n bool intersects = textBoxRect.intersects(selectionRect);\n \n if (intersects) {\n selectedBoxes.append(textBox);\n intersectionCount++;\n // qDebug() << \"PDF text selection: Text box intersects:\" << textBox->text() \n // << \"at\" << textBoxRect;\n }\n }\n }\n \n // qDebug() << \"PDF text selection: Found\" << intersectionCount << \"intersecting text boxes\";\n \n return selectedBoxes;\n}\n void renderPdfPageToCache(int pageNumber) {\n if (!pdfDocument || !isValidPageNumber(pageNumber)) {\n return;\n }\n \n // Check if already cached\n if (pdfCache.contains(pageNumber)) {\n return;\n }\n \n // Ensure the cache holds only 10 pages max\n if (pdfCache.count() >= 10) {\n auto oldestKey = pdfCache.keys().first();\n pdfCache.remove(oldestKey);\n }\n \n // Render the page and store it in the cache\n std::unique_ptr page(pdfDocument->page(pageNumber));\n if (page) {\n // Render with document-level anti-aliasing settings\n QImage pdfImage = page->renderToImage(pdfRenderDPI, pdfRenderDPI);\n if (!pdfImage.isNull()) {\n QPixmap cachedPixmap = QPixmap::fromImage(pdfImage);\n pdfCache.insert(pageNumber, new QPixmap(cachedPixmap));\n }\n }\n}\n void checkAndCacheAdjacentPages(int targetPage) {\n if (!pdfDocument || !isValidPageNumber(targetPage)) {\n return;\n }\n \n // Calculate adjacent pages\n int prevPage = targetPage - 1;\n int nextPage = targetPage + 1;\n \n // Check what needs to be cached\n bool needPrevPage = isValidPageNumber(prevPage) && !pdfCache.contains(prevPage);\n bool needCurrentPage = !pdfCache.contains(targetPage);\n bool needNextPage = isValidPageNumber(nextPage) && !pdfCache.contains(nextPage);\n \n // If all pages are cached, nothing to do\n if (!needPrevPage && !needCurrentPage && !needNextPage) {\n return;\n }\n \n // Stop any existing timer\n if (pdfCacheTimer && pdfCacheTimer->isActive()) {\n pdfCacheTimer->stop();\n }\n \n // Create timer if it doesn't exist\n if (!pdfCacheTimer) {\n pdfCacheTimer = new QTimer(this);\n pdfCacheTimer->setSingleShot(true);\n connect(pdfCacheTimer, &QTimer::timeout, this, &InkCanvas::cacheAdjacentPages);\n }\n \n // Store the target page for validation when timer fires\n pendingCacheTargetPage = targetPage;\n \n // Start 1-second delay timer\n pdfCacheTimer->start(1000);\n}\n bool isValidPageNumber(int pageNumber) const {\n return (pageNumber >= 0 && pageNumber < totalPdfPages);\n}\n void loadNotePageToCache(int pageNumber) {\n // Check if already cached\n if (noteCache.contains(pageNumber)) {\n return;\n }\n \n QString filePath = getNotePageFilePath(pageNumber);\n if (filePath.isEmpty()) {\n return;\n }\n \n // Ensure the cache doesn't exceed its limit\n if (noteCache.count() >= 15) {\n // QCache will automatically remove least recently used items\n // but we can be explicit about it\n auto keys = noteCache.keys();\n if (!keys.isEmpty()) {\n noteCache.remove(keys.first());\n }\n }\n \n // Load note page from disk if it exists\n if (QFile::exists(filePath)) {\n QPixmap notePixmap;\n if (notePixmap.load(filePath)) {\n noteCache.insert(pageNumber, new QPixmap(notePixmap));\n }\n }\n // If file doesn't exist, we don't cache anything - loadPage will handle initialization\n}\n void checkAndCacheAdjacentNotePages(int targetPage) {\n if (saveFolder.isEmpty()) {\n return;\n }\n \n // Calculate adjacent pages\n int prevPage = targetPage - 1;\n int nextPage = targetPage + 1;\n \n // Check what needs to be cached (we don't have a max page limit for notes)\n bool needPrevPage = (prevPage >= 0) && !noteCache.contains(prevPage);\n bool needCurrentPage = !noteCache.contains(targetPage);\n bool needNextPage = !noteCache.contains(nextPage); // No upper limit check for notes\n \n // If all nearby pages are cached, nothing to do\n if (!needPrevPage && !needCurrentPage && !needNextPage) {\n return;\n }\n \n // Stop any existing timer\n if (noteCacheTimer && noteCacheTimer->isActive()) {\n noteCacheTimer->stop();\n }\n \n // Create timer if it doesn't exist\n if (!noteCacheTimer) {\n noteCacheTimer = new QTimer(this);\n noteCacheTimer->setSingleShot(true);\n connect(noteCacheTimer, &QTimer::timeout, this, &InkCanvas::cacheAdjacentNotePages);\n }\n \n // Store the target page for validation when timer fires\n pendingNoteCacheTargetPage = targetPage;\n \n // Start 1-second delay timer\n noteCacheTimer->start(1000);\n}\n QString getNotePageFilePath(int pageNumber) const {\n if (saveFolder.isEmpty() || notebookId.isEmpty()) {\n return QString();\n }\n return saveFolder + QString(\"/%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n}\n void invalidateCurrentPageCache() {\n if (currentCachedNotePage >= 0) {\n noteCache.remove(currentCachedNotePage);\n }\n}\n private:\n void processPendingTextSelection() {\n if (!hasPendingSelection) {\n return;\n }\n \n // Process the pending selection update\n updatePdfTextSelection(pendingSelectionStart, pendingSelectionEnd);\n hasPendingSelection = false;\n}\n void cacheAdjacentPages() {\n if (!pdfDocument || currentCachedPage < 0) {\n return;\n }\n \n // Check if the user has moved to a different page since the timer was started\n // If so, skip caching adjacent pages as they're no longer relevant\n if (pendingCacheTargetPage != currentCachedPage) {\n return; // User switched pages, don't cache adjacent pages for old page\n }\n \n int targetPage = currentCachedPage;\n int prevPage = targetPage - 1;\n int nextPage = targetPage + 1;\n \n // Create list of pages to cache asynchronously\n QList pagesToCache;\n \n // Add previous page if needed\n if (isValidPageNumber(prevPage) && !pdfCache.contains(prevPage)) {\n pagesToCache.append(prevPage);\n }\n \n // Add next page if needed\n if (isValidPageNumber(nextPage) && !pdfCache.contains(nextPage)) {\n pagesToCache.append(nextPage);\n }\n \n // Cache pages asynchronously\n for (int pageNum : pagesToCache) {\n QFutureWatcher *watcher = new QFutureWatcher(this);\n \n // Track the watcher for cleanup\n activePdfWatchers.append(watcher);\n \n connect(watcher, &QFutureWatcher::finished, this, [this, watcher]() {\n // Remove from active list and delete\n activePdfWatchers.removeOne(watcher);\n watcher->deleteLater();\n });\n \n // Capture pageNum by value to avoid issues with lambda capture\n QFuture future = QtConcurrent::run([this, pageNum]() {\n renderPdfPageToCache(pageNum);\n });\n \n watcher->setFuture(future);\n }\n}\n void cacheAdjacentNotePages() {\n if (saveFolder.isEmpty() || currentCachedNotePage < 0) {\n return;\n }\n \n // Check if the user has moved to a different page since the timer was started\n // If so, skip caching adjacent pages as they're no longer relevant\n if (pendingNoteCacheTargetPage != currentCachedNotePage) {\n return; // User switched pages, don't cache adjacent pages for old page\n }\n \n int targetPage = currentCachedNotePage;\n int prevPage = targetPage - 1;\n int nextPage = targetPage + 1;\n \n // Create list of note pages to cache asynchronously\n QList notePagesToCache;\n \n // Add previous page if needed (check for >= 0 since notes can start from page 0)\n if (prevPage >= 0 && !noteCache.contains(prevPage)) {\n notePagesToCache.append(prevPage);\n }\n \n // Add next page if needed (no upper limit check for notes)\n if (!noteCache.contains(nextPage)) {\n notePagesToCache.append(nextPage);\n }\n \n // Cache note pages asynchronously\n for (int pageNum : notePagesToCache) {\n QFutureWatcher *watcher = new QFutureWatcher(this);\n \n // Track the watcher for cleanup\n activeNoteWatchers.append(watcher);\n \n connect(watcher, &QFutureWatcher::finished, this, [this, watcher]() {\n // Remove from active list and delete\n activeNoteWatchers.removeOne(watcher);\n watcher->deleteLater();\n });\n \n // Capture pageNum by value to avoid issues with lambda capture\n QFuture future = QtConcurrent::run([this, pageNum]() {\n loadNotePageToCache(pageNum);\n });\n \n watcher->setFuture(future);\n }\n}\n};"], ["/SpeedyNote/source/MarkdownWindow.h", "class QMarkdownTextEdit {\n Q_OBJECT\n\npublic:\n explicit MarkdownWindow(const QRect &rect, QWidget *parent = nullptr);\n ~MarkdownWindow() = default;\n QString getMarkdownContent() const {\n return markdownEditor ? markdownEditor->toPlainText() : QString();\n}\n void setMarkdownContent(const QString &content) {\n if (markdownEditor) {\n markdownEditor->setPlainText(content);\n }\n}\n QRect getWindowRect() const {\n return geometry();\n}\n void setWindowRect(const QRect &rect) {\n setGeometry(rect);\n}\n QRect getCanvasRect() const {\n return canvasRect;\n}\n void setCanvasRect(const QRect &canvasRect) {\n canvasRect = rect;\n updateScreenPosition();\n}\n void updateScreenPosition() {\n // Prevent recursive updates\n if (isUpdatingPosition) return;\n isUpdatingPosition = true;\n \n // Debug: Log when this is called due to external changes (not during mouse movement)\n if (!dragging && !resizing) {\n // qDebug() << \"MarkdownWindow::updateScreenPosition() called for window\" << this << \"Canvas rect:\" << canvasRect;\n }\n \n // Get the canvas parent to access coordinate conversion methods\n if (QWidget *canvas = parentWidget()) {\n // Try to cast to InkCanvas to use the new coordinate methods\n if (InkCanvas *inkCanvas = qobject_cast(canvas)) {\n // Use the new coordinate conversion methods\n QRect screenRect = inkCanvas->mapCanvasToWidget(canvasRect);\n // qDebug() << \"MarkdownWindow::updateScreenPosition() - Canvas rect:\" << canvasRect << \"-> Screen rect:\" << screenRect;\n // qDebug() << \" Canvas size:\" << inkCanvas->getCanvasSize() << \"Zoom:\" << inkCanvas->getZoomFactor() << \"Pan:\" << inkCanvas->getPanOffset();\n setGeometry(screenRect);\n } else {\n // Fallback: use canvas coordinates directly\n // qDebug() << \"MarkdownWindow::updateScreenPosition() - No InkCanvas parent, using canvas rect directly:\" << canvasRect;\n setGeometry(canvasRect);\n }\n } else {\n // No parent, use canvas coordinates directly\n // qDebug() << \"MarkdownWindow::updateScreenPosition() - No parent, using canvas rect directly:\" << canvasRect;\n setGeometry(canvasRect);\n }\n \n isUpdatingPosition = false;\n}\n QVariantMap serialize() const {\n QVariantMap data;\n data[\"canvas_x\"] = canvasRect.x();\n data[\"canvas_y\"] = canvasRect.y();\n data[\"canvas_width\"] = canvasRect.width();\n data[\"canvas_height\"] = canvasRect.height();\n data[\"content\"] = getMarkdownContent();\n \n // Add canvas size information for debugging and consistency checks\n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n QSize canvasSize = inkCanvas->getCanvasSize();\n data[\"canvas_buffer_width\"] = canvasSize.width();\n data[\"canvas_buffer_height\"] = canvasSize.height();\n data[\"zoom_factor\"] = inkCanvas->getZoomFactor();\n QPointF panOffset = inkCanvas->getPanOffset();\n data[\"pan_x\"] = panOffset.x();\n data[\"pan_y\"] = panOffset.y();\n }\n \n return data;\n}\n void deserialize(const QVariantMap &data) {\n int x = data.value(\"canvas_x\", 0).toInt();\n int y = data.value(\"canvas_y\", 0).toInt();\n int width = data.value(\"canvas_width\", 300).toInt();\n int height = data.value(\"canvas_height\", 200).toInt();\n QString content = data.value(\"content\", \"# New Markdown Window\").toString();\n \n QRect loadedRect = QRect(x, y, width, height);\n // qDebug() << \"MarkdownWindow::deserialize() - Loaded canvas rect:\" << loadedRect;\n // qDebug() << \" Original canvas size:\" << data.value(\"canvas_buffer_width\", -1).toInt() << \"x\" << data.value(\"canvas_buffer_height\", -1).toInt();\n \n // Apply bounds checking to loaded coordinates\n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n QRect canvasBounds = inkCanvas->getCanvasRect();\n \n // Ensure window stays within canvas bounds\n int maxX = canvasBounds.width() - loadedRect.width();\n int maxY = canvasBounds.height() - loadedRect.height();\n \n loadedRect.setX(qMax(0, qMin(loadedRect.x(), maxX)));\n loadedRect.setY(qMax(0, qMin(loadedRect.y(), maxY)));\n \n if (loadedRect != QRect(x, y, width, height)) {\n // qDebug() << \" Bounds-corrected canvas rect:\" << loadedRect << \"Canvas bounds:\" << canvasBounds;\n }\n }\n \n canvasRect = loadedRect;\n setMarkdownContent(content);\n \n // Ensure canvas connections are set up\n ensureCanvasConnections();\n \n updateScreenPosition();\n}\n void focusEditor() {\n if (markdownEditor) {\n markdownEditor->setFocus();\n }\n}\n bool isEditorFocused() const {\n return markdownEditor && markdownEditor->hasFocus();\n}\n void setTransparent(bool transparent) {\n if (isTransparentState == transparent) return;\n \n // qDebug() << \"MarkdownWindow::setTransparent(\" << transparent << \") for window\" << this;\n isTransparentState = transparent;\n \n // Apply transparency effect by changing the background style\n if (transparent) {\n // qDebug() << \"Setting window background to semi-transparent\";\n applyTransparentStyle();\n } else {\n // qDebug() << \"Setting window background to opaque\";\n applyStyle(); // Restore normal style\n }\n}\n bool isTransparent() const {\n return isTransparentState;\n}\n bool isValidForCanvas() const {\n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n QRect canvasBounds = inkCanvas->getCanvasRect();\n \n // Check if the window is at least partially within the canvas bounds\n return canvasBounds.intersects(canvasRect);\n }\n \n // If no canvas parent, assume valid\n return true;\n}\n QString getCoordinateInfo() const {\n QString info;\n info += QString(\"Canvas Coordinates: (%1, %2) %3x%4\\n\")\n .arg(canvasRect.x()).arg(canvasRect.y())\n .arg(canvasRect.width()).arg(canvasRect.height());\n \n QRect screenRect = geometry();\n info += QString(\"Screen Coordinates: (%1, %2) %3x%4\\n\")\n .arg(screenRect.x()).arg(screenRect.y())\n .arg(screenRect.width()).arg(screenRect.height());\n \n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n QSize canvasSize = inkCanvas->getCanvasSize();\n info += QString(\"Canvas Size: %1x%2\\n\")\n .arg(canvasSize.width()).arg(canvasSize.height());\n \n info += QString(\"Zoom Factor: %1\\n\").arg(inkCanvas->getZoomFactor());\n \n QPointF panOffset = inkCanvas->getPanOffset();\n info += QString(\"Pan Offset: (%1, %2)\\n\")\n .arg(panOffset.x()).arg(panOffset.y());\n \n info += QString(\"Valid for Canvas: %1\\n\").arg(isValidForCanvas() ? \"Yes\" : \"No\");\n } else {\n info += \"No InkCanvas parent found\\n\";\n }\n \n return info;\n}\n void ensureCanvasConnections() {\n // Connect to canvas pan/zoom changes to update position\n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n // Disconnect any existing connections to avoid duplicates\n disconnect(inkCanvas, &InkCanvas::panChanged, this, &MarkdownWindow::updateScreenPosition);\n disconnect(inkCanvas, &InkCanvas::zoomChanged, this, &MarkdownWindow::updateScreenPosition);\n \n // Reconnect\n connect(inkCanvas, &InkCanvas::panChanged, this, &MarkdownWindow::updateScreenPosition);\n connect(inkCanvas, &InkCanvas::zoomChanged, this, &MarkdownWindow::updateScreenPosition);\n \n // Install event filter to handle canvas resize events (for layout changes)\n inkCanvas->installEventFilter(this);\n \n // qDebug() << \"MarkdownWindow::ensureCanvasConnections() - Connected to canvas signals for window\" << this;\n } else {\n // qDebug() << \"MarkdownWindow::ensureCanvasConnections() - No InkCanvas parent found for window\" << this;\n }\n}\n void deleteRequested(MarkdownWindow *window);\n void contentChanged();\n void windowMoved(MarkdownWindow *window);\n void windowResized(MarkdownWindow *window);\n void focusChanged(MarkdownWindow *window, bool focused);\n void editorFocusChanged(MarkdownWindow *window, bool focused);\n void windowInteracted(MarkdownWindow *window);\n protected:\n void mousePressEvent(QMouseEvent *event) override {\n if (event->button() == Qt::LeftButton) {\n // Emit signal to indicate window interaction\n emit windowInteracted(this);\n \n ResizeHandle handle = getResizeHandle(event->pos());\n \n if (handle != None) {\n // Start resizing\n resizing = true;\n isUserInteracting = true;\n currentResizeHandle = handle;\n resizeStartPosition = event->globalPosition().toPoint();\n resizeStartRect = geometry();\n } else if (event->pos().y() < 24) { // Header area\n // Start dragging\n dragging = true;\n isUserInteracting = true;\n dragStartPosition = event->globalPosition().toPoint();\n windowStartPosition = pos();\n }\n }\n \n QWidget::mousePressEvent(event);\n}\n void mouseMoveEvent(QMouseEvent *event) override {\n if (resizing) {\n QPoint delta = event->globalPosition().toPoint() - resizeStartPosition;\n QRect newRect = resizeStartRect;\n \n // Apply resize based on the stored handle\n switch (currentResizeHandle) {\n case TopLeft:\n newRect.setTopLeft(newRect.topLeft() + delta);\n break;\n case TopRight:\n newRect.setTopRight(newRect.topRight() + delta);\n break;\n case BottomLeft:\n newRect.setBottomLeft(newRect.bottomLeft() + delta);\n break;\n case BottomRight:\n newRect.setBottomRight(newRect.bottomRight() + delta);\n break;\n case Top:\n newRect.setTop(newRect.top() + delta.y());\n break;\n case Bottom:\n newRect.setBottom(newRect.bottom() + delta.y());\n break;\n case Left:\n newRect.setLeft(newRect.left() + delta.x());\n break;\n case Right:\n newRect.setRight(newRect.right() + delta.x());\n break;\n default:\n break;\n }\n \n // Enforce minimum size\n newRect.setSize(newRect.size().expandedTo(QSize(200, 150)));\n \n // Keep resized window within canvas bounds\n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n // Convert to canvas coordinates to check bounds\n QRect tempCanvasRect = inkCanvas->mapWidgetToCanvas(newRect);\n QRect canvasBounds = inkCanvas->getCanvasRect();\n \n // Apply canvas bounds constraints\n int maxCanvasX = canvasBounds.width() - tempCanvasRect.width();\n int maxCanvasY = canvasBounds.height() - tempCanvasRect.height();\n \n tempCanvasRect.setX(qMax(0, qMin(tempCanvasRect.x(), maxCanvasX)));\n tempCanvasRect.setY(qMax(0, qMin(tempCanvasRect.y(), maxCanvasY)));\n \n // Also ensure the window doesn't get resized beyond canvas bounds\n if (tempCanvasRect.right() > canvasBounds.width()) {\n tempCanvasRect.setWidth(canvasBounds.width() - tempCanvasRect.x());\n }\n if (tempCanvasRect.bottom() > canvasBounds.height()) {\n tempCanvasRect.setHeight(canvasBounds.height() - tempCanvasRect.y());\n }\n \n // Convert back to screen coordinates for the constrained geometry\n newRect = inkCanvas->mapCanvasToWidget(tempCanvasRect);\n }\n \n // Update the widget geometry directly during resizing\n setGeometry(newRect);\n \n // Convert screen coordinates back to canvas coordinates\n convertScreenToCanvasRect(newRect);\n emit windowResized(this);\n } else if (dragging) {\n QPoint delta = event->globalPosition().toPoint() - dragStartPosition;\n QPoint newPos = windowStartPosition + delta;\n \n // Keep window within canvas bounds (not just parent widget bounds)\n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n // Convert current position to canvas coordinates to check bounds\n QRect tempScreenRect(newPos, size());\n QRect tempCanvasRect = inkCanvas->mapWidgetToCanvas(tempScreenRect);\n QRect canvasBounds = inkCanvas->getCanvasRect();\n \n // Apply canvas bounds constraints\n int maxCanvasX = canvasBounds.width() - tempCanvasRect.width();\n int maxCanvasY = canvasBounds.height() - tempCanvasRect.height();\n \n tempCanvasRect.setX(qMax(0, qMin(tempCanvasRect.x(), maxCanvasX)));\n tempCanvasRect.setY(qMax(0, qMin(tempCanvasRect.y(), maxCanvasY)));\n \n // Convert back to screen coordinates for the constrained position\n QRect constrainedScreenRect = inkCanvas->mapCanvasToWidget(tempCanvasRect);\n newPos = constrainedScreenRect.topLeft();\n \n // Debug: Log when position is constrained\n if (tempCanvasRect != inkCanvas->mapWidgetToCanvas(QRect(windowStartPosition + delta, size()))) {\n // qDebug() << \"MarkdownWindow: Constraining position to canvas bounds. Canvas rect:\" << tempCanvasRect;\n }\n } else {\n // Fallback: Keep window within parent bounds\n if (parentWidget()) {\n QRect parentRect = parentWidget()->rect();\n newPos.setX(qMax(0, qMin(newPos.x(), parentRect.width() - width())));\n newPos.setY(qMax(0, qMin(newPos.y(), parentRect.height() - height())));\n }\n }\n \n // Update the widget position directly during dragging\n move(newPos);\n \n // Convert screen position back to canvas coordinates\n QRect newScreenRect(newPos, size());\n convertScreenToCanvasRect(newScreenRect);\n emit windowMoved(this);\n } else {\n // Update cursor for resize handles\n updateCursor(event->pos());\n }\n \n QWidget::mouseMoveEvent(event);\n}\n void mouseReleaseEvent(QMouseEvent *event) override {\n if (event->button() == Qt::LeftButton) {\n resizing = false;\n dragging = false;\n isUserInteracting = false;\n currentResizeHandle = None;\n }\n \n QWidget::mouseReleaseEvent(event);\n}\n void resizeEvent(QResizeEvent *event) override {\n QWidget::resizeEvent(event);\n \n // Emit windowResized if this is a user-initiated resize or if we're not updating position due to canvas changes\n if (isUserInteracting || !isUpdatingPosition) {\n emit windowResized(this);\n }\n}\n void paintEvent(QPaintEvent *event) override {\n QWidget::paintEvent(event);\n \n // Draw resize handles\n QPainter painter(this);\n painter.setRenderHint(QPainter::Antialiasing);\n \n QColor handleColor = hasFocus() ? QColor(74, 144, 226) : QColor(180, 180, 180);\n painter.setPen(QPen(handleColor, 2));\n painter.setBrush(QBrush(handleColor));\n \n // Draw corner handles\n int handleSize = 6;\n painter.drawEllipse(0, 0, handleSize, handleSize); // Top-left\n painter.drawEllipse(width() - handleSize, 0, handleSize, handleSize); // Top-right\n painter.drawEllipse(0, height() - handleSize, handleSize, handleSize); // Bottom-left\n painter.drawEllipse(width() - handleSize, height() - handleSize, handleSize, handleSize); // Bottom-right\n}\n void focusInEvent(QFocusEvent *event) override {\n // qDebug() << \"MarkdownWindow::focusInEvent() - Window\" << this << \"gained focus\";\n QWidget::focusInEvent(event);\n emit focusChanged(this, true);\n}\n void focusOutEvent(QFocusEvent *event) override {\n // qDebug() << \"MarkdownWindow::focusOutEvent() - Window\" << this << \"lost focus\";\n QWidget::focusOutEvent(event);\n emit focusChanged(this, false);\n}\n bool eventFilter(QObject *obj, QEvent *event) override {\n if (obj == markdownEditor) {\n if (event->type() == QEvent::FocusIn) {\n // qDebug() << \"MarkdownWindow::eventFilter() - Editor gained focus in window\" << this;\n emit editorFocusChanged(this, true);\n } else if (event->type() == QEvent::FocusOut) {\n // qDebug() << \"MarkdownWindow::eventFilter() - Editor lost focus in window\" << this;\n emit editorFocusChanged(this, false);\n }\n } else if (obj == parentWidget() && event->type() == QEvent::Resize) {\n // Canvas widget was resized (likely due to layout changes like showing/hiding sidebars)\n // Update our screen position to maintain canvas position\n QTimer::singleShot(0, this, [this]() {\n updateScreenPosition();\n });\n }\n return QWidget::eventFilter(obj, event);\n}\n private:\n void onDeleteClicked() {\n emit deleteRequested(this);\n}\n void onMarkdownTextChanged() {\n emit contentChanged();\n}\n private:\n enum ResizeHandle {\n None,\n TopLeft,\n TopRight,\n BottomLeft,\n BottomRight,\n Top,\n Bottom,\n Left,\n Right\n };\n QMarkdownTextEdit *markdownEditor;\n QPushButton *deleteButton;\n QLabel *titleLabel;\n QVBoxLayout *mainLayout;\n QHBoxLayout *headerLayout;\n bool dragging = false;\n QPoint dragStartPosition;\n QPoint windowStartPosition;\n bool resizing = false;\n QPoint resizeStartPosition;\n QRect resizeStartRect;\n ResizeHandle currentResizeHandle = None;\n QRect canvasRect;\n bool isTransparentState = false;\n bool isUpdatingPosition = false;\n bool isUserInteracting = false;\n ResizeHandle getResizeHandle(const QPoint &pos) const {\n const int handleSize = 8;\n const QRect rect = this->rect();\n \n // Check corner handles first\n if (QRect(0, 0, handleSize, handleSize).contains(pos))\n return TopLeft;\n if (QRect(rect.width() - handleSize, 0, handleSize, handleSize).contains(pos))\n return TopRight;\n if (QRect(0, rect.height() - handleSize, handleSize, handleSize).contains(pos))\n return BottomLeft;\n if (QRect(rect.width() - handleSize, rect.height() - handleSize, handleSize, handleSize).contains(pos))\n return BottomRight;\n \n // Check edge handles\n if (QRect(0, 0, rect.width(), handleSize).contains(pos))\n return Top;\n if (QRect(0, rect.height() - handleSize, rect.width(), handleSize).contains(pos))\n return Bottom;\n if (QRect(0, 0, handleSize, rect.height()).contains(pos))\n return Left;\n if (QRect(rect.width() - handleSize, 0, handleSize, rect.height()).contains(pos))\n return Right;\n \n return None;\n}\n void updateCursor(const QPoint &pos) {\n ResizeHandle handle = getResizeHandle(pos);\n \n switch (handle) {\n case TopLeft:\n case BottomRight:\n setCursor(Qt::SizeFDiagCursor);\n break;\n case TopRight:\n case BottomLeft:\n setCursor(Qt::SizeBDiagCursor);\n break;\n case Top:\n case Bottom:\n setCursor(Qt::SizeVerCursor);\n break;\n case Left:\n case Right:\n setCursor(Qt::SizeHorCursor);\n break;\n default:\n if (pos.y() < 24) { // Header area\n setCursor(Qt::SizeAllCursor);\n } else {\n setCursor(Qt::ArrowCursor);\n }\n break;\n }\n}\n void setupUI() {\n mainLayout = new QVBoxLayout(this);\n mainLayout->setContentsMargins(2, 2, 2, 2);\n mainLayout->setSpacing(0);\n \n // Header with title and delete button\n headerLayout = new QHBoxLayout();\n headerLayout->setContentsMargins(4, 2, 4, 2);\n headerLayout->setSpacing(4);\n \n titleLabel = new QLabel(\"Markdown\", this);\n titleLabel->setStyleSheet(\"font-weight: bold; color: #333;\");\n \n deleteButton = new QPushButton(\"×\", this);\n deleteButton->setFixedSize(16, 16);\n deleteButton->setStyleSheet(R\"(\n QPushButton {\n background-color: #ff4444;\n color: white;\n border: none;\n border-radius: 8px;\n font-weight: bold;\n font-size: 10px;\n }\n QPushButton:hover {\n background-color: #ff6666;\n }\n QPushButton:pressed {\n background-color: #cc2222;\n }\n )\");\n \n connect(deleteButton, &QPushButton::clicked, this, &MarkdownWindow::onDeleteClicked);\n \n headerLayout->addWidget(titleLabel);\n headerLayout->addStretch();\n headerLayout->addWidget(deleteButton);\n \n // Markdown editor\n markdownEditor = new QMarkdownTextEdit(this);\n markdownEditor->setPlainText(\"\"); // Start with empty content\n \n connect(markdownEditor, &QMarkdownTextEdit::textChanged, this, &MarkdownWindow::onMarkdownTextChanged);\n \n // Connect editor focus events using event filter\n markdownEditor->installEventFilter(this);\n \n mainLayout->addLayout(headerLayout);\n mainLayout->addWidget(markdownEditor);\n}\n void applyStyle() {\n // Detect dark mode using the same method as MainWindow\n bool isDarkMode = palette().color(QPalette::Window).lightness() < 128;\n \n QString backgroundColor = isDarkMode ? \"#2b2b2b\" : \"white\";\n QString borderColor = isDarkMode ? \"#555555\" : \"#cccccc\";\n QString headerBackgroundColor = isDarkMode ? \"#3c3c3c\" : \"#f0f0f0\";\n QString focusBorderColor = isDarkMode ? \"#6ca9dc\" : \"#4a90e2\";\n \n setStyleSheet(QString(R\"(\n MarkdownWindow {\n background-color: %1;\n border: 2px solid %2;\n border-radius: 4px;\n }\n MarkdownWindow:focus {\n border-color: %3;\n }\n )\").arg(backgroundColor, borderColor, focusBorderColor));\n \n // Style the header\n if (headerLayout && headerLayout->parentWidget()) {\n headerLayout->parentWidget()->setStyleSheet(QString(R\"(\n background-color: %1;\n border-bottom: 1px solid %2;\n )\").arg(headerBackgroundColor, borderColor));\n }\n \n // Reset the markdown editor style to default (opaque)\n if (markdownEditor) {\n markdownEditor->setStyleSheet(\"\"); // Clear any custom styles\n }\n}\n void applyTransparentStyle() {\n // Detect dark mode using the same method as MainWindow\n bool isDarkMode = palette().color(QPalette::Window).lightness() < 128;\n \n QString backgroundColor = isDarkMode ? \"rgba(43, 43, 43, 0.3)\" : \"rgba(255, 255, 255, 0.3)\"; // 30% opacity\n QString borderColor = isDarkMode ? \"#555555\" : \"#cccccc\";\n QString headerBackgroundColor = isDarkMode ? \"rgba(60, 60, 60, 0.3)\" : \"rgba(240, 240, 240, 0.3)\"; // 30% opacity\n QString focusBorderColor = isDarkMode ? \"#6ca9dc\" : \"#4a90e2\";\n \n setStyleSheet(QString(R\"(\n MarkdownWindow {\n background-color: %1;\n border: 2px solid %2;\n border-radius: 4px;\n }\n MarkdownWindow:focus {\n border-color: %3;\n }\n )\").arg(backgroundColor, borderColor, focusBorderColor));\n \n // Style the header with transparency\n if (headerLayout && headerLayout->parentWidget()) {\n headerLayout->parentWidget()->setStyleSheet(QString(R\"(\n background-color: %1;\n border-bottom: 1px solid %2;\n )\").arg(headerBackgroundColor, borderColor));\n }\n \n // Make the markdown editor background semi-transparent too\n if (markdownEditor) {\n QString editorBg = isDarkMode ? \"rgba(43, 43, 43, 0.3)\" : \"rgba(255, 255, 255, 0.3)\";\n markdownEditor->setStyleSheet(QString(R\"(\n QMarkdownTextEdit {\n background-color: %1;\n border: none;\n }\n )\").arg(editorBg));\n }\n}\n void convertScreenToCanvasRect(const QRect &screenRect) {\n // Get the canvas parent to access coordinate conversion methods\n if (QWidget *canvas = parentWidget()) {\n // Try to cast to InkCanvas to use the new coordinate methods\n if (InkCanvas *inkCanvas = qobject_cast(canvas)) {\n // Use the new coordinate conversion methods\n QRect oldCanvasRect = canvasRect;\n QRect newCanvasRect = inkCanvas->mapWidgetToCanvas(screenRect);\n \n // Store the converted canvas coordinates without bounds checking\n // Bounds checking should only happen during user interaction (dragging/resizing)\n canvasRect = newCanvasRect;\n // Only log if there was a significant change (and not during mouse movement)\n if ((canvasRect.topLeft() - oldCanvasRect.topLeft()).manhattanLength() > 10 && !dragging && !resizing) {\n // qDebug() << \"MarkdownWindow::convertScreenToCanvasRect() - Screen rect:\" << screenRect << \"-> Canvas rect:\" << canvasRect;\n // qDebug() << \" Old canvas rect:\" << oldCanvasRect;\n }\n } else {\n // Fallback: use screen coordinates directly\n // qDebug() << \"MarkdownWindow::convertScreenToCanvasRect() - No InkCanvas parent, using screen rect directly:\" << screenRect;\n canvasRect = screenRect;\n }\n } else {\n // No parent, use screen coordinates directly\n // qDebug() << \"MarkdownWindow::convertScreenToCanvasRect() - No parent, using screen rect directly:\" << screenRect;\n canvasRect = screenRect;\n }\n}\n};"], ["/SpeedyNote/markdown/linenumberarea.h", "#ifndef LINENUMBERAREA_H\n#define LINENUMBERAREA_H\n\n#include \n#include \n#include \n#include \n\n#include \"qmarkdowntextedit.h\"\n\nclass LineNumArea final : public QWidget {\n Q_OBJECT\n\n public:\n explicit LineNumArea(QMarkdownTextEdit *parent)\n : QWidget(parent), textEdit(parent) {\n Q_ASSERT(parent);\n\n _currentLineColor = QColor(QStringLiteral(\"#eef067\"));\n _otherLinesColor = QColor(QStringLiteral(\"#a6a6a6\"));\n setHidden(true);\n\n // We always use fixed font to avoid \"width\" issues\n setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont));\n }\n\n void setCurrentLineColor(QColor color) { _currentLineColor = color; }\n\n void setOtherLineColor(QColor color) {\n _otherLinesColor = std::move(color);\n }\n\n int lineNumAreaWidth() const {\n if (!enabled) {\n return 0;\n }\n\n int digits = 2;\n int max = std::max(1, textEdit->blockCount());\n while (max >= 10) {\n max /= 10;\n ++digits;\n }\n\n#if QT_VERSION >= 0x050B00\n int space =\n 13 + textEdit->fontMetrics().horizontalAdvance(u'9') * digits;\n#else\n int space =\n 13 + textEdit->fontMetrics().width(QLatin1Char('9')) * digits;\n#endif\n\n return space;\n }\n\n bool isLineNumAreaEnabled() const { return enabled; }\n\n void setLineNumAreaEnabled(bool e) {\n enabled = e;\n setHidden(!e);\n }\n\n QSize sizeHint() const override { return {lineNumAreaWidth(), 0}; }\n\n protected:\n void paintEvent(QPaintEvent *event) override {\n QPainter painter(this);\n\n painter.fillRect(event->rect(),\n palette().color(QPalette::Active, QPalette::Window));\n\n auto block = textEdit->firstVisibleBlock();\n int blockNumber = block.blockNumber();\n qreal top = textEdit->blockBoundingGeometry(block)\n .translated(textEdit->contentOffset())\n .top();\n // Maybe the top is not 0?\n top += textEdit->viewportMargins().top();\n qreal bottom = top;\n\n const QPen currentLine = _currentLineColor;\n const QPen otherLines = _otherLinesColor;\n painter.setFont(font());\n\n while (block.isValid() && top <= event->rect().bottom()) {\n top = bottom;\n bottom = top + textEdit->blockBoundingRect(block).height();\n if (block.isVisible() && bottom >= event->rect().top()) {\n QString number = QString::number(blockNumber + 1);\n\n auto isCurrentLine =\n textEdit->textCursor().blockNumber() == blockNumber;\n painter.setPen(isCurrentLine ? currentLine : otherLines);\n\n painter.drawText(-5, top, sizeHint().width(),\n textEdit->fontMetrics().height(),\n Qt::AlignRight, number);\n }\n\n block = block.next();\n ++blockNumber;\n }\n }\n\n private:\n bool enabled = false;\n QMarkdownTextEdit *textEdit;\n QColor _currentLineColor;\n QColor _otherLinesColor;\n};\n\n#endif // LINENUMBERAREA_H\n"], ["/SpeedyNote/source/ControlPanelDialog.h", "class ControlPanelDialog {\n Q_OBJECT\n\npublic:\n explicit ControlPanelDialog(MainWindow *mainWindow, InkCanvas *targetCanvas, QWidget *parent = nullptr);\n private:\n void applyChanges() {\n if (!canvas) return;\n\n BackgroundStyle style = static_cast(\n styleCombo->currentData().toInt()\n );\n\n canvas->setBackgroundStyle(style);\n canvas->setBackgroundColor(selectedColor);\n canvas->setBackgroundDensity(densitySpin->value());\n canvas->update();\n canvas->saveBackgroundMetadata();\n\n // ✅ Save these settings as defaults for new tabs\n if (mainWindowRef) {\n mainWindowRef->saveDefaultBackgroundSettings(style, selectedColor, densitySpin->value());\n }\n\n // ✅ Apply button mappings back to MainWindow with internal keys\n if (mainWindowRef) {\n for (const QString &buttonKey : holdMappingCombos.keys()) {\n QString displayString = holdMappingCombos[buttonKey]->currentText();\n QString internalKey = ButtonMappingHelper::displayToInternalKey(displayString, true); // true = isDialMode\n mainWindowRef->setHoldMapping(buttonKey, internalKey);\n }\n for (const QString &buttonKey : pressMappingCombos.keys()) {\n QString displayString = pressMappingCombos[buttonKey]->currentText();\n QString internalKey = ButtonMappingHelper::displayToInternalKey(displayString, false); // false = isAction\n mainWindowRef->setPressMapping(buttonKey, internalKey);\n }\n\n // ✅ Save to persistent settings\n mainWindowRef->saveButtonMappings();\n \n // ✅ Apply theme settings\n mainWindowRef->setUseCustomAccentColor(useCustomAccentCheckbox->isChecked());\n if (selectedAccentColor.isValid()) {\n mainWindowRef->setCustomAccentColor(selectedAccentColor);\n }\n \n // ✅ Apply color palette setting\n mainWindowRef->setUseBrighterPalette(useBrighterPaletteCheckbox->isChecked());\n }\n}\n void chooseColor() {\n QColor chosen = QColorDialog::getColor(selectedColor, this, tr(\"Select Background Color\"));\n if (chosen.isValid()) {\n selectedColor = chosen;\n colorButton->setStyleSheet(QString(\"background-color: %1\").arg(selectedColor.name()));\n }\n}\n void addKeyboardMapping() {\n // Step 1: Capture key sequence\n KeyCaptureDialog captureDialog(this);\n if (captureDialog.exec() != QDialog::Accepted) {\n return;\n }\n \n QString keySequence = captureDialog.getCapturedKeySequence();\n if (keySequence.isEmpty()) {\n return;\n }\n \n // Check if key sequence already exists\n if (mainWindowRef && mainWindowRef->getKeyboardMappings().contains(keySequence)) {\n QMessageBox::warning(this, tr(\"Key Already Mapped\"), \n tr(\"The key sequence '%1' is already mapped. Please choose a different key combination.\").arg(keySequence));\n return;\n }\n \n // Step 2: Choose action\n QStringList actions = ButtonMappingHelper::getTranslatedActions();\n bool ok;\n QString selectedAction = QInputDialog::getItem(this, tr(\"Select Action\"), \n tr(\"Choose the action to perform when '%1' is pressed:\").arg(keySequence), \n actions, 0, false, &ok);\n \n if (!ok || selectedAction.isEmpty()) {\n return;\n }\n \n // Convert display name to internal key\n QString internalKey = ButtonMappingHelper::displayToInternalKey(selectedAction, false);\n \n // Add the mapping\n if (mainWindowRef) {\n mainWindowRef->addKeyboardMapping(keySequence, internalKey);\n \n // Update table\n int row = keyboardTable->rowCount();\n keyboardTable->insertRow(row);\n keyboardTable->setItem(row, 0, new QTableWidgetItem(keySequence));\n keyboardTable->setItem(row, 1, new QTableWidgetItem(selectedAction));\n }\n}\n void removeKeyboardMapping() {\n int currentRow = keyboardTable->currentRow();\n if (currentRow < 0) {\n QMessageBox::information(this, tr(\"No Selection\"), tr(\"Please select a mapping to remove.\"));\n return;\n }\n \n QTableWidgetItem *keyItem = keyboardTable->item(currentRow, 0);\n if (!keyItem) return;\n \n QString keySequence = keyItem->text();\n \n // Confirm removal\n int ret = QMessageBox::question(this, tr(\"Remove Mapping\"), \n tr(\"Are you sure you want to remove the keyboard shortcut '%1'?\").arg(keySequence),\n QMessageBox::Yes | QMessageBox::No, QMessageBox::No);\n \n if (ret == QMessageBox::Yes) {\n // Remove from MainWindow\n if (mainWindowRef) {\n mainWindowRef->removeKeyboardMapping(keySequence);\n }\n \n // Remove from table\n keyboardTable->removeRow(currentRow);\n }\n}\n void openControllerMapping() {\n if (!mainWindowRef) {\n QMessageBox::warning(this, tr(\"Error\"), tr(\"MainWindow reference not available.\"));\n return;\n }\n \n SDLControllerManager *controllerManager = mainWindowRef->getControllerManager();\n if (!controllerManager) {\n QMessageBox::warning(this, tr(\"Controller Not Available\"), \n tr(\"Controller manager is not available. Please ensure a controller is connected and restart the application.\"));\n return;\n }\n \n if (!controllerManager->getJoystick()) {\n QMessageBox::warning(this, tr(\"No Controller Detected\"), \n tr(\"No controller is currently connected. Please connect your controller and restart the application.\"));\n return;\n }\n \n ControllerMappingDialog dialog(controllerManager, this);\n dialog.exec();\n}\n void reconnectController() {\n if (!mainWindowRef) {\n QMessageBox::warning(this, tr(\"Error\"), tr(\"MainWindow reference not available.\"));\n return;\n }\n \n SDLControllerManager *controllerManager = mainWindowRef->getControllerManager();\n if (!controllerManager) {\n QMessageBox::warning(this, tr(\"Controller Not Available\"), \n tr(\"Controller manager is not available.\"));\n return;\n }\n \n // Show reconnecting message\n controllerStatusLabel->setText(tr(\"🔄 Reconnecting...\"));\n controllerStatusLabel->setStyleSheet(\"color: orange;\");\n \n // Force the UI to update immediately\n QApplication::processEvents();\n \n // Attempt to reconnect using thread-safe method\n QMetaObject::invokeMethod(controllerManager, \"reconnect\", Qt::BlockingQueuedConnection);\n \n // Update status after reconnection attempt\n updateControllerStatus();\n \n // Show result message\n if (controllerManager->getJoystick()) {\n // Reconnect the controller signals in MainWindow\n mainWindowRef->reconnectControllerSignals();\n \n QMessageBox::information(this, tr(\"Reconnection Successful\"), \n tr(\"Controller has been successfully reconnected!\"));\n } else {\n QMessageBox::warning(this, tr(\"Reconnection Failed\"), \n tr(\"Failed to reconnect controller. Please ensure your controller is powered on and in pairing mode, then try again.\"));\n }\n}\n private:\n InkCanvas *canvas;\n QTabWidget *tabWidget;\n QWidget *backgroundTab;\n QComboBox *styleCombo;\n QPushButton *colorButton;\n QSpinBox *densitySpin;\n QPushButton *applyButton;\n QPushButton *okButton;\n QPushButton *cancelButton;\n QColor selectedColor;\n void createBackgroundTab() {\n backgroundTab = new QWidget(this);\n\n QLabel *styleLabel = new QLabel(tr(\"Background Style:\"));\n styleCombo = new QComboBox();\n styleCombo->addItem(tr(\"None\"), static_cast(BackgroundStyle::None));\n styleCombo->addItem(tr(\"Grid\"), static_cast(BackgroundStyle::Grid));\n styleCombo->addItem(tr(\"Lines\"), static_cast(BackgroundStyle::Lines));\n\n QLabel *colorLabel = new QLabel(tr(\"Background Color:\"));\n colorButton = new QPushButton();\n connect(colorButton, &QPushButton::clicked, this, &ControlPanelDialog::chooseColor);\n\n QLabel *densityLabel = new QLabel(tr(\"Density:\"));\n densitySpin = new QSpinBox();\n densitySpin->setRange(10, 200);\n densitySpin->setSuffix(\" px\");\n densitySpin->setSingleStep(5);\n\n QGridLayout *layout = new QGridLayout(backgroundTab);\n layout->addWidget(styleLabel, 0, 0);\n layout->addWidget(styleCombo, 0, 1);\n layout->addWidget(colorLabel, 1, 0);\n layout->addWidget(colorButton, 1, 1);\n layout->addWidget(densityLabel, 2, 0);\n layout->addWidget(densitySpin, 2, 1);\n // layout->setColumnStretch(1, 1); // Stretch the second column\n layout->setRowStretch(3, 1); // Stretch the last row\n}\n void loadFromCanvas() {\n styleCombo->setCurrentIndex(static_cast(canvas->getBackgroundStyle()));\n densitySpin->setValue(canvas->getBackgroundDensity());\n selectedColor = canvas->getBackgroundColor();\n\n colorButton->setStyleSheet(QString(\"background-color: %1\").arg(selectedColor.name()));\n\n if (mainWindowRef) {\n for (const QString &buttonKey : holdMappingCombos.keys()) {\n QString internalKey = mainWindowRef->getHoldMapping(buttonKey);\n QString displayString = ButtonMappingHelper::internalKeyToDisplay(internalKey, true); // true = isDialMode\n int index = holdMappingCombos[buttonKey]->findText(displayString);\n if (index >= 0) holdMappingCombos[buttonKey]->setCurrentIndex(index);\n }\n\n for (const QString &buttonKey : pressMappingCombos.keys()) {\n QString internalKey = mainWindowRef->getPressMapping(buttonKey);\n QString displayString = ButtonMappingHelper::internalKeyToDisplay(internalKey, false); // false = isAction\n int index = pressMappingCombos[buttonKey]->findText(displayString);\n if (index >= 0) pressMappingCombos[buttonKey]->setCurrentIndex(index);\n }\n \n // Load theme settings\n useCustomAccentCheckbox->setChecked(mainWindowRef->isUsingCustomAccentColor());\n \n // Get the stored custom accent color\n selectedAccentColor = mainWindowRef->getCustomAccentColor();\n \n accentColorButton->setStyleSheet(QString(\"background-color: %1\").arg(selectedAccentColor.name()));\n accentColorButton->setEnabled(useCustomAccentCheckbox->isChecked());\n \n // Load color palette setting\n useBrighterPaletteCheckbox->setChecked(mainWindowRef->isUsingBrighterPalette());\n }\n}\n MainWindow *mainWindowRef;\n InkCanvas *canvasRef;\n QWidget *performanceTab;\n QWidget *toolbarTab;\n void createToolbarTab() {\n toolbarTab = new QWidget(this);\n QVBoxLayout *toolbarLayout = new QVBoxLayout(toolbarTab);\n\n // ✅ Checkbox to show/hide benchmark controls\n QCheckBox *benchmarkVisibilityCheckbox = new QCheckBox(tr(\"Show Benchmark Controls\"), toolbarTab);\n benchmarkVisibilityCheckbox->setChecked(mainWindowRef->areBenchmarkControlsVisible());\n toolbarLayout->addWidget(benchmarkVisibilityCheckbox);\n QLabel *benchmarkNote = new QLabel(tr(\"This will show/hide the benchmark controls on the toolbar. Press the clock button to start/stop the benchmark.\"));\n benchmarkNote->setWordWrap(true);\n benchmarkNote->setStyleSheet(\"color: gray; font-size: 10px;\");\n toolbarLayout->addWidget(benchmarkNote);\n\n // ✅ Checkbox to show/hide zoom buttons\n QCheckBox *zoomButtonsVisibilityCheckbox = new QCheckBox(tr(\"Show Zoom Buttons\"), toolbarTab);\n zoomButtonsVisibilityCheckbox->setChecked(mainWindowRef->areZoomButtonsVisible());\n toolbarLayout->addWidget(zoomButtonsVisibilityCheckbox);\n QLabel *zoomButtonsNote = new QLabel(tr(\"This will show/hide the 0.5x, 1x, and 2x zoom buttons on the toolbar\"));\n zoomButtonsNote->setWordWrap(true);\n zoomButtonsNote->setStyleSheet(\"color: gray; font-size: 10px;\");\n toolbarLayout->addWidget(zoomButtonsNote);\n\n QCheckBox *scrollOnTopCheckBox = new QCheckBox(tr(\"Scroll on Top after Page Switching\"), toolbarTab);\n scrollOnTopCheckBox->setChecked(mainWindowRef->isScrollOnTopEnabled());\n toolbarLayout->addWidget(scrollOnTopCheckBox);\n QLabel *scrollNote = new QLabel(tr(\"Enabling this will make the page scroll to the top after switching to a new page.\"));\n scrollNote->setWordWrap(true);\n scrollNote->setStyleSheet(\"color: gray; font-size: 10px;\");\n toolbarLayout->addWidget(scrollNote);\n \n toolbarLayout->addStretch();\n toolbarTab->setLayout(toolbarLayout);\n tabWidget->addTab(toolbarTab, tr(\"Features\"));\n\n\n // Connect the checkbox\n connect(benchmarkVisibilityCheckbox, &QCheckBox::toggled, mainWindowRef, &MainWindow::setBenchmarkControlsVisible);\n connect(zoomButtonsVisibilityCheckbox, &QCheckBox::toggled, mainWindowRef, &MainWindow::setZoomButtonsVisible);\n connect(scrollOnTopCheckBox, &QCheckBox::toggled, mainWindowRef, &MainWindow::setScrollOnTopEnabled);\n}\n void createPerformanceTab() {\n performanceTab = new QWidget();\n QVBoxLayout *layout = new QVBoxLayout(performanceTab);\n\n QCheckBox *previewToggle = new QCheckBox(tr(\"Enable Low-Resolution PDF Previews\"));\n previewToggle->setChecked(mainWindowRef->isLowResPreviewEnabled());\n\n connect(previewToggle, &QCheckBox::toggled, mainWindowRef, &MainWindow::setLowResPreviewEnabled);\n\n QLabel *note = new QLabel(tr(\"Disabling this may improve dial smoothness on low-end devices.\"));\n note->setWordWrap(true);\n note->setStyleSheet(\"color: gray; font-size: 10px;\");\n\n QLabel *dpiLabel = new QLabel(tr(\"PDF Rendering DPI:\"));\n QComboBox *dpiSelector = new QComboBox();\n dpiSelector->addItems({\"96\", \"192\", \"288\", \"384\", \"480\"});\n dpiSelector->setCurrentText(QString::number(mainWindowRef->getPdfDPI()));\n\n connect(dpiSelector, &QComboBox::currentTextChanged, this, [=](const QString &value) {\n mainWindowRef->setPdfDPI(value.toInt());\n });\n\n QLabel *notePDF = new QLabel(tr(\"Adjust how the PDF is rendered. Higher DPI means better quality but slower performance. DO NOT CHANGE THIS OPTION WHEN MULTIPLE TABS ARE OPEN. THIS MAY LEAD TO UNDEFINED BEHAVIOR!\"));\n notePDF->setWordWrap(true);\n notePDF->setStyleSheet(\"color: gray; font-size: 10px;\");\n\n\n layout->addWidget(previewToggle);\n layout->addWidget(note);\n layout->addWidget(dpiLabel);\n layout->addWidget(dpiSelector);\n layout->addWidget(notePDF);\n\n layout->addStretch();\n\n // return performanceTab;\n}\n QWidget *controllerMappingTab;\n QPushButton *reconnectButton;\n QLabel *controllerStatusLabel;\n QMap holdMappingCombos;\n QMap pressMappingCombos;\n void createButtonMappingTab() {\n QWidget *buttonTab = new QWidget(this);\n QVBoxLayout *layout = new QVBoxLayout(buttonTab);\n\n QStringList buttonKeys = ButtonMappingHelper::getInternalButtonKeys();\n QStringList buttonDisplayNames = ButtonMappingHelper::getTranslatedButtons();\n QStringList dialModes = ButtonMappingHelper::getTranslatedDialModes();\n QStringList actions = ButtonMappingHelper::getTranslatedActions();\n\n for (int i = 0; i < buttonKeys.size(); ++i) {\n const QString &buttonKey = buttonKeys[i];\n const QString &buttonDisplayName = buttonDisplayNames[i];\n \n QHBoxLayout *h = new QHBoxLayout();\n h->addWidget(new QLabel(buttonDisplayName)); // Use translated button name\n\n QComboBox *holdCombo = new QComboBox();\n holdCombo->addItems(dialModes); // Add translated dial mode names\n holdMappingCombos[buttonKey] = holdCombo;\n h->addWidget(new QLabel(tr(\"Hold:\")));\n h->addWidget(holdCombo);\n\n QComboBox *pressCombo = new QComboBox();\n pressCombo->addItems(actions); // Add translated action names\n pressMappingCombos[buttonKey] = pressCombo;\n h->addWidget(new QLabel(tr(\"Press:\")));\n h->addWidget(pressCombo);\n\n layout->addLayout(h);\n }\n\n layout->addStretch();\n buttonTab->setLayout(layout);\n tabWidget->addTab(buttonTab, tr(\"Button Mapping\"));\n}\n void createControllerMappingTab() {\n controllerMappingTab = new QWidget(this);\n QVBoxLayout *layout = new QVBoxLayout(controllerMappingTab);\n \n // Instructions\n QLabel *instructionLabel = new QLabel(tr(\"Configure physical controller button mappings for your Joy-Con or other controller:\"), controllerMappingTab);\n instructionLabel->setWordWrap(true);\n layout->addWidget(instructionLabel);\n \n QLabel *noteLabel = new QLabel(tr(\"Note: This maps your physical controller buttons to the logical Joy-Con functions used by the application. \"\n \"After setting up the physical mapping, you can configure what actions each logical button performs in the 'Button Mapping' tab.\"), controllerMappingTab);\n noteLabel->setWordWrap(true);\n noteLabel->setStyleSheet(\"color: gray; font-size: 10px; margin-bottom: 10px;\");\n layout->addWidget(noteLabel);\n \n // Button to open controller mapping dialog\n QPushButton *openMappingButton = new QPushButton(tr(\"Configure Controller Mapping\"), controllerMappingTab);\n openMappingButton->setMinimumHeight(40);\n connect(openMappingButton, &QPushButton::clicked, this, &ControlPanelDialog::openControllerMapping);\n layout->addWidget(openMappingButton);\n \n // Button to reconnect controller\n reconnectButton = new QPushButton(tr(\"Reconnect Controller\"), controllerMappingTab);\n reconnectButton->setMinimumHeight(40);\n reconnectButton->setStyleSheet(\"QPushButton { background-color: #4CAF50; color: white; font-weight: bold; }\");\n connect(reconnectButton, &QPushButton::clicked, this, &ControlPanelDialog::reconnectController);\n layout->addWidget(reconnectButton);\n \n // Status information\n QLabel *statusLabel = new QLabel(tr(\"Current controller status:\"), controllerMappingTab);\n statusLabel->setStyleSheet(\"font-weight: bold; margin-top: 20px;\");\n layout->addWidget(statusLabel);\n \n // Dynamic status label\n controllerStatusLabel = new QLabel(controllerMappingTab);\n updateControllerStatus();\n layout->addWidget(controllerStatusLabel);\n \n layout->addStretch();\n \n tabWidget->addTab(controllerMappingTab, tr(\"Controller Mapping\"));\n}\n void createKeyboardMappingTab() {\n keyboardTab = new QWidget(this);\n QVBoxLayout *layout = new QVBoxLayout(keyboardTab);\n \n // Instructions\n QLabel *instructionLabel = new QLabel(tr(\"Configure custom keyboard shortcuts for application actions:\"), keyboardTab);\n instructionLabel->setWordWrap(true);\n layout->addWidget(instructionLabel);\n \n // Table to show current mappings\n keyboardTable = new QTableWidget(0, 2, keyboardTab);\n keyboardTable->setHorizontalHeaderLabels({tr(\"Key Sequence\"), tr(\"Action\")});\n keyboardTable->horizontalHeader()->setStretchLastSection(true);\n keyboardTable->setSelectionBehavior(QAbstractItemView::SelectRows);\n keyboardTable->setEditTriggers(QAbstractItemView::NoEditTriggers);\n layout->addWidget(keyboardTable);\n \n // Buttons\n QHBoxLayout *buttonLayout = new QHBoxLayout();\n addKeyboardMappingButton = new QPushButton(tr(\"Add Mapping\"), keyboardTab);\n removeKeyboardMappingButton = new QPushButton(tr(\"Remove Mapping\"), keyboardTab);\n \n buttonLayout->addWidget(addKeyboardMappingButton);\n buttonLayout->addWidget(removeKeyboardMappingButton);\n buttonLayout->addStretch();\n \n layout->addLayout(buttonLayout);\n \n // Connections\n connect(addKeyboardMappingButton, &QPushButton::clicked, this, &ControlPanelDialog::addKeyboardMapping);\n connect(removeKeyboardMappingButton, &QPushButton::clicked, this, &ControlPanelDialog::removeKeyboardMapping);\n \n // Load current mappings\n if (mainWindowRef) {\n QMap mappings = mainWindowRef->getKeyboardMappings();\n keyboardTable->setRowCount(mappings.size());\n int row = 0;\n for (auto it = mappings.begin(); it != mappings.end(); ++it) {\n keyboardTable->setItem(row, 0, new QTableWidgetItem(it.key()));\n QString displayAction = ButtonMappingHelper::internalKeyToDisplay(it.value(), false);\n keyboardTable->setItem(row, 1, new QTableWidgetItem(displayAction));\n row++;\n }\n }\n \n tabWidget->addTab(keyboardTab, tr(\"Keyboard Shortcuts\"));\n}\n QWidget *keyboardTab;\n QTableWidget *keyboardTable;\n QPushButton *addKeyboardMappingButton;\n QPushButton *removeKeyboardMappingButton;\n QWidget *themeTab;\n QCheckBox *useCustomAccentCheckbox;\n QPushButton *accentColorButton;\n QColor selectedAccentColor;\n QCheckBox *useBrighterPaletteCheckbox;\n void createThemeTab() {\n themeTab = new QWidget(this);\n QVBoxLayout *layout = new QVBoxLayout(themeTab);\n \n // Custom accent color\n useCustomAccentCheckbox = new QCheckBox(tr(\"Use Custom Accent Color\"), themeTab);\n layout->addWidget(useCustomAccentCheckbox);\n \n QLabel *accentColorLabel = new QLabel(tr(\"Accent Color:\"), themeTab);\n accentColorButton = new QPushButton(themeTab);\n accentColorButton->setFixedSize(100, 30);\n connect(accentColorButton, &QPushButton::clicked, this, &ControlPanelDialog::chooseAccentColor);\n \n QHBoxLayout *accentColorLayout = new QHBoxLayout();\n accentColorLayout->addWidget(accentColorLabel);\n accentColorLayout->addWidget(accentColorButton);\n accentColorLayout->addStretch();\n layout->addLayout(accentColorLayout);\n \n QLabel *accentColorNote = new QLabel(tr(\"When enabled, use a custom accent color instead of the system accent color for the toolbar, dial, and tab selection.\"));\n accentColorNote->setWordWrap(true);\n accentColorNote->setStyleSheet(\"color: gray; font-size: 10px;\");\n layout->addWidget(accentColorNote);\n \n // Enable/disable accent color button based on checkbox\n connect(useCustomAccentCheckbox, &QCheckBox::toggled, accentColorButton, &QPushButton::setEnabled);\n connect(useCustomAccentCheckbox, &QCheckBox::toggled, accentColorLabel, &QLabel::setEnabled);\n \n // Color palette preference\n useBrighterPaletteCheckbox = new QCheckBox(tr(\"Use Brighter Color Palette\"), themeTab);\n layout->addWidget(useBrighterPaletteCheckbox);\n \n QLabel *paletteNote = new QLabel(tr(\"When enabled, use brighter colors (good for dark PDF backgrounds). When disabled, use darker colors (good for light PDF backgrounds). This setting is independent of the UI theme.\"));\n paletteNote->setWordWrap(true);\n paletteNote->setStyleSheet(\"color: gray; font-size: 10px;\");\n layout->addWidget(paletteNote);\n \n layout->addStretch();\n \n tabWidget->addTab(themeTab, tr(\"Theme\"));\n}\n void chooseAccentColor() {\n QColor chosen = QColorDialog::getColor(selectedAccentColor, this, tr(\"Select Accent Color\"));\n if (chosen.isValid()) {\n selectedAccentColor = chosen;\n accentColorButton->setStyleSheet(QString(\"background-color: %1\").arg(selectedAccentColor.name()));\n }\n}\n void updateControllerStatus() {\n if (!mainWindowRef || !controllerStatusLabel) return;\n \n SDLControllerManager *controllerManager = mainWindowRef->getControllerManager();\n if (!controllerManager) {\n controllerStatusLabel->setText(tr(\"✗ Controller manager not available\"));\n controllerStatusLabel->setStyleSheet(\"color: red;\");\n return;\n }\n \n if (controllerManager->getJoystick()) {\n controllerStatusLabel->setText(tr(\"✓ Controller connected\"));\n controllerStatusLabel->setStyleSheet(\"color: green; font-weight: bold;\");\n } else {\n controllerStatusLabel->setText(tr(\"✗ No controller detected\"));\n controllerStatusLabel->setStyleSheet(\"color: red; font-weight: bold;\");\n }\n}\n};"], ["/SpeedyNote/source/ControllerMappingDialog.h", "class SDLControllerManager {\n Q_OBJECT\n\npublic:\n explicit ControllerMappingDialog(SDLControllerManager *controllerManager, QWidget *parent = nullptr);\n private:\n void startButtonMapping(const QString &logicalButton) {\n if (!controller) return;\n \n // Disable all mapping buttons during mapping\n for (auto button : mappingButtons) {\n button->setEnabled(false);\n }\n \n // Update the current button being mapped\n currentMappingButton = logicalButton;\n mappingButtons[logicalButton]->setText(tr(\"Press button...\"));\n \n // Start button detection mode\n controller->startButtonDetection();\n \n // Start timeout timer\n mappingTimeoutTimer->start();\n \n // Show status message\n QApplication::setOverrideCursor(Qt::WaitCursor);\n}\n void onRawButtonPressed(int sdlButton, const QString &buttonName) {\n if (currentMappingButton.isEmpty()) return;\n \n // Stop detection and timeout\n controller->stopButtonDetection();\n mappingTimeoutTimer->stop();\n QApplication::restoreOverrideCursor();\n \n // Check if this button is already mapped to another function\n QMap currentMappings = controller->getAllPhysicalMappings();\n QString conflictingButton;\n for (auto it = currentMappings.begin(); it != currentMappings.end(); ++it) {\n if (it.value() == sdlButton && it.key() != currentMappingButton) {\n conflictingButton = it.key();\n break;\n }\n }\n \n if (!conflictingButton.isEmpty()) {\n int ret = QMessageBox::question(this, tr(\"Button Conflict\"), \n tr(\"The button '%1' is already mapped to '%2'.\\n\\nDo you want to reassign it to '%3'?\")\n .arg(buttonName).arg(conflictingButton).arg(currentMappingButton),\n QMessageBox::Yes | QMessageBox::No);\n \n if (ret != QMessageBox::Yes) {\n // Reset UI and return\n mappingButtons[currentMappingButton]->setText(tr(\"Map\"));\n for (auto button : mappingButtons) {\n button->setEnabled(true);\n }\n currentMappingButton.clear();\n return;\n }\n \n // Clear the conflicting mapping\n controller->setPhysicalButtonMapping(conflictingButton, -1);\n currentMappingLabels[conflictingButton]->setText(\"Not mapped\");\n currentMappingLabels[conflictingButton]->setStyleSheet(\"color: gray;\");\n }\n \n // Set the new mapping\n controller->setPhysicalButtonMapping(currentMappingButton, sdlButton);\n \n // Get appropriate text color for current theme\n QString textColor = isDarkMode() ? \"white\" : \"black\";\n \n // Update UI\n currentMappingLabels[currentMappingButton]->setText(buttonName);\n currentMappingLabels[currentMappingButton]->setStyleSheet(QString(\"color: %1; font-weight: bold;\").arg(textColor));\n mappingButtons[currentMappingButton]->setText(tr(\"Map\"));\n \n // Re-enable all buttons\n for (auto button : mappingButtons) {\n button->setEnabled(true);\n }\n \n currentMappingButton.clear();\n \n QMessageBox::information(this, tr(\"Mapping Complete\"), \n tr(\"Button '%1' has been successfully mapped!\").arg(buttonName));\n}\n void resetToDefaults() {\n int ret = QMessageBox::question(this, tr(\"Reset to Defaults\"), \n tr(\"Are you sure you want to reset all button mappings to their default values?\\n\\nThis will overwrite your current configuration.\"),\n QMessageBox::Yes | QMessageBox::No);\n \n if (ret == QMessageBox::Yes) {\n // Get default mappings and apply them\n QMap defaults = controller->getDefaultMappings();\n for (auto it = defaults.begin(); it != defaults.end(); ++it) {\n controller->setPhysicalButtonMapping(it.key(), it.value());\n }\n \n // Update display\n updateMappingDisplay();\n \n QMessageBox::information(this, tr(\"Reset Complete\"), \n tr(\"All button mappings have been reset to their default values.\"));\n }\n}\n void applyMappings() {\n // Mappings are already applied in real-time, just close the dialog\n accept();\n}\n private:\n SDLControllerManager *controller;\n QGridLayout *mappingLayout;\n QMap buttonLabels;\n QMap currentMappingLabels;\n QMap mappingButtons;\n QPushButton *resetButton;\n QPushButton *applyButton;\n QPushButton *cancelButton;\n QString currentMappingButton;\n QTimer *mappingTimeoutTimer;\n void setupUI() {\n QVBoxLayout *mainLayout = new QVBoxLayout(this);\n \n // Instructions\n QLabel *instructionLabel = new QLabel(tr(\"Map your physical controller buttons to Joy-Con functions.\\n\"\n \"Click 'Map' next to each function, then press the corresponding button on your controller.\"), this);\n instructionLabel->setWordWrap(true);\n instructionLabel->setStyleSheet(\"font-weight: bold; margin-bottom: 10px;\");\n mainLayout->addWidget(instructionLabel);\n \n // Mapping grid\n QWidget *mappingWidget = new QWidget(this);\n mappingLayout = new QGridLayout(mappingWidget);\n \n // Headers\n mappingLayout->addWidget(new QLabel(tr(\"Joy-Con Function\"), this), 0, 0);\n mappingLayout->addWidget(new QLabel(tr(\"Description\"), this), 0, 1);\n mappingLayout->addWidget(new QLabel(tr(\"Current Mapping\"), this), 0, 2);\n mappingLayout->addWidget(new QLabel(tr(\"Action\"), this), 0, 3);\n \n // Get logical button descriptions\n QMap descriptions = getLogicalButtonDescriptions();\n \n // Create mapping rows for each logical button\n QStringList logicalButtons = {\"LEFTSHOULDER\", \"RIGHTSHOULDER\", \"PADDLE2\", \"PADDLE4\", \n \"Y\", \"A\", \"B\", \"X\", \"LEFTSTICK\", \"START\", \"GUIDE\"};\n \n int row = 1;\n for (const QString &logicalButton : logicalButtons) {\n // Function name\n QLabel *functionLabel = new QLabel(logicalButton, this);\n functionLabel->setStyleSheet(\"font-weight: bold;\");\n buttonLabels[logicalButton] = functionLabel;\n mappingLayout->addWidget(functionLabel, row, 0);\n \n // Description\n QLabel *descLabel = new QLabel(descriptions.value(logicalButton, \"Unknown\"), this);\n descLabel->setWordWrap(true);\n mappingLayout->addWidget(descLabel, row, 1);\n \n // Current mapping display\n QLabel *currentLabel = new QLabel(\"Not mapped\", this);\n currentLabel->setStyleSheet(\"color: gray;\");\n currentMappingLabels[logicalButton] = currentLabel;\n mappingLayout->addWidget(currentLabel, row, 2);\n \n // Map button\n QPushButton *mapButton = new QPushButton(tr(\"Map\"), this);\n mappingButtons[logicalButton] = mapButton;\n connect(mapButton, &QPushButton::clicked, this, [this, logicalButton]() {\n startButtonMapping(logicalButton);\n });\n mappingLayout->addWidget(mapButton, row, 3);\n \n row++;\n }\n \n mainLayout->addWidget(mappingWidget);\n \n // Buttons\n QHBoxLayout *buttonLayout = new QHBoxLayout();\n \n resetButton = new QPushButton(tr(\"Reset to Defaults\"), this);\n connect(resetButton, &QPushButton::clicked, this, &ControllerMappingDialog::resetToDefaults);\n buttonLayout->addWidget(resetButton);\n \n buttonLayout->addStretch();\n \n applyButton = new QPushButton(tr(\"Apply\"), this);\n connect(applyButton, &QPushButton::clicked, this, &ControllerMappingDialog::applyMappings);\n buttonLayout->addWidget(applyButton);\n \n cancelButton = new QPushButton(tr(\"Cancel\"), this);\n connect(cancelButton, &QPushButton::clicked, this, &QDialog::reject);\n buttonLayout->addWidget(cancelButton);\n \n mainLayout->addLayout(buttonLayout);\n}\n QMap getLogicalButtonDescriptions() const {\n QMap descriptions;\n descriptions[\"LEFTSHOULDER\"] = tr(\"L Button (Left Shoulder)\");\n descriptions[\"RIGHTSHOULDER\"] = tr(\"ZL Button (Left Trigger)\");\n descriptions[\"PADDLE2\"] = tr(\"SL Button (Side Left)\");\n descriptions[\"PADDLE4\"] = tr(\"SR Button (Side Right)\");\n descriptions[\"Y\"] = tr(\"Up Arrow (D-Pad Up)\");\n descriptions[\"A\"] = tr(\"Down Arrow (D-Pad Down)\");\n descriptions[\"B\"] = tr(\"Left Arrow (D-Pad Left)\");\n descriptions[\"X\"] = tr(\"Right Arrow (D-Pad Right)\");\n descriptions[\"LEFTSTICK\"] = tr(\"Analog Stick Press\");\n descriptions[\"START\"] = tr(\"Minus Button (-)\");\n descriptions[\"GUIDE\"] = tr(\"Screenshot Button\");\n return descriptions;\n}\n void loadCurrentMappings() {\n QMap currentMappings = controller->getAllPhysicalMappings();\n \n // Get appropriate text color for current theme\n QString textColor = isDarkMode() ? \"white\" : \"black\";\n \n for (auto it = currentMappings.begin(); it != currentMappings.end(); ++it) {\n const QString &logicalButton = it.key();\n int physicalButton = it.value();\n \n if (currentMappingLabels.contains(logicalButton)) {\n QString physicalName = controller->getPhysicalButtonName(physicalButton);\n currentMappingLabels[logicalButton]->setText(physicalName);\n currentMappingLabels[logicalButton]->setStyleSheet(QString(\"color: %1; font-weight: bold;\").arg(textColor));\n }\n }\n}\n void updateMappingDisplay() {\n loadCurrentMappings();\n}\n bool isDarkMode() const {\n // Same logic as MainWindow::isDarkMode()\n QColor bg = palette().color(QPalette::Window);\n return bg.lightness() < 128; // Lightness scale: 0 (black) - 255 (white)\n}\n};"], ["/SpeedyNote/source/MarkdownWindowManager.h", "class MarkdownWindow {\n Q_OBJECT\n\npublic:\n explicit MarkdownWindowManager(InkCanvas *canvas, QObject *parent = nullptr);\n ~MarkdownWindowManager() {\n clearAllWindows();\n}\n MarkdownWindow* createMarkdownWindow(const QRect &rect);\n void removeMarkdownWindow(MarkdownWindow *window) {\n if (!window) return;\n \n // Remove from current windows\n currentWindows.removeAll(window);\n \n // Remove from all page windows\n for (auto it = pageWindows.begin(); it != pageWindows.end(); ++it) {\n it.value().removeAll(window);\n }\n \n emit windowRemoved(window);\n \n // Delete the window\n window->deleteLater();\n}\n void clearAllWindows() {\n // Stop transparency timer\n transparencyTimer->stop();\n currentlyFocusedWindow = nullptr;\n windowsAreTransparent = false;\n \n // Clear current windows\n for (MarkdownWindow *window : currentWindows) {\n window->deleteLater();\n }\n currentWindows.clear();\n \n // Clear page windows\n for (auto it = pageWindows.begin(); it != pageWindows.end(); ++it) {\n for (MarkdownWindow *window : it.value()) {\n window->deleteLater();\n }\n }\n pageWindows.clear();\n}\n void saveWindowsForPage(int pageNumber) {\n if (!canvas || currentWindows.isEmpty()) return;\n \n // Update page windows map\n pageWindows[pageNumber] = currentWindows;\n \n // Save to file\n saveWindowData(pageNumber, currentWindows);\n}\n void loadWindowsForPage(int pageNumber) {\n if (!canvas) return;\n\n // qDebug() << \"MarkdownWindowManager::loadWindowsForPage(\" << pageNumber << \")\";\n\n // This method is now only responsible for loading and showing the\n // windows for the specified page. Hiding of old windows is handled before this.\n\n QList newPageWindows;\n\n // Check if we have windows for this page in memory\n if (pageWindows.contains(pageNumber)) {\n // qDebug() << \"Found windows in memory for page\" << pageNumber;\n newPageWindows = pageWindows[pageNumber];\n } else {\n // qDebug() << \"Loading windows from file for page\" << pageNumber;\n // Load from file\n newPageWindows = loadWindowData(pageNumber);\n\n // Update page windows map\n if (!newPageWindows.isEmpty()) {\n pageWindows[pageNumber] = newPageWindows;\n }\n }\n\n // qDebug() << \"Loaded\" << newPageWindows.size() << \"windows for page\" << pageNumber;\n\n // Update the current window list and show the windows\n currentWindows = newPageWindows;\n for (MarkdownWindow *window : currentWindows) {\n // Validate that the window is within canvas bounds\n if (!window->isValidForCanvas()) {\n // qDebug() << \"Warning: Markdown window at\" << window->getCanvasRect() \n // << \"is outside canvas bounds\" << canvas->getCanvasRect();\n // Optionally adjust the window position to fit within bounds\n QRect canvasBounds = canvas->getCanvasRect();\n QRect windowRect = window->getCanvasRect();\n \n // Clamp the window position to canvas bounds\n int newX = qMax(0, qMin(windowRect.x(), canvasBounds.width() - windowRect.width()));\n int newY = qMax(0, qMin(windowRect.y(), canvasBounds.height() - windowRect.height()));\n \n if (newX != windowRect.x() || newY != windowRect.y()) {\n QRect adjustedRect(newX, newY, windowRect.width(), windowRect.height());\n window->setCanvasRect(adjustedRect);\n // qDebug() << \"Adjusted window position to\" << adjustedRect;\n }\n }\n \n // Ensure canvas connections are set up for loaded windows\n window->ensureCanvasConnections();\n \n window->show();\n window->updateScreenPosition();\n // Make sure window is not transparent when loaded\n window->setTransparent(false);\n }\n \n // Start transparency timer if there are windows but none are focused\n if (!currentWindows.isEmpty()) {\n // qDebug() << \"Starting transparency timer for\" << currentWindows.size() << \"windows\";\n resetTransparencyTimer();\n } else {\n // qDebug() << \"No windows to show, not starting timer\";\n }\n}\n void deleteWindowsForPage(int pageNumber) {\n // Remove windows from memory\n if (pageWindows.contains(pageNumber)) {\n QList windows = pageWindows[pageNumber];\n for (MarkdownWindow *window : windows) {\n window->deleteLater();\n }\n pageWindows.remove(pageNumber);\n }\n \n // Delete file\n QString filePath = getWindowDataFilePath(pageNumber);\n if (QFile::exists(filePath)) {\n QFile::remove(filePath);\n }\n \n // Clear current windows if they belong to this page\n if (pageWindows.value(pageNumber) == currentWindows) {\n currentWindows.clear();\n }\n}\n void setSelectionMode(bool enabled) {\n selectionMode = enabled;\n \n // Change cursor for canvas\n if (canvas) {\n canvas->setCursor(enabled ? Qt::CrossCursor : Qt::ArrowCursor);\n }\n}\n QList getCurrentPageWindows() const {\n return currentWindows;\n}\n void resetTransparencyTimer() {\n // qDebug() << \"MarkdownWindowManager::resetTransparencyTimer() called\";\n transparencyTimer->stop();\n \n // DON'T make all windows opaque here - only stop the timer\n // The focused window should be made opaque by the caller if needed\n windowsAreTransparent = false; // Reset the state\n \n // Start the timer again\n transparencyTimer->start();\n // qDebug() << \"Transparency timer started for 10 seconds\";\n}\n void setWindowsTransparent(bool transparent) {\n if (windowsAreTransparent == transparent) return;\n \n // qDebug() << \"MarkdownWindowManager::setWindowsTransparent(\" << transparent << \")\";\n // qDebug() << \"Current windows count:\" << currentWindows.size();\n // qDebug() << \"Currently focused window:\" << currentlyFocusedWindow;\n \n windowsAreTransparent = transparent;\n \n // Apply transparency logic:\n // - If transparent=true: make all windows except focused one transparent\n // - If transparent=false: make all windows opaque\n for (MarkdownWindow *window : currentWindows) {\n if (transparent) {\n // When making transparent, only make non-focused windows transparent\n if (window != currentlyFocusedWindow) {\n // qDebug() << \"Setting unfocused window\" << window << \"transparent: true\";\n window->setTransparent(true);\n } else {\n // qDebug() << \"Keeping focused window\" << window << \"opaque\";\n window->setTransparent(false);\n }\n } else {\n // When making opaque, make all windows opaque\n // qDebug() << \"Setting window\" << window << \"transparent: false\";\n window->setTransparent(false);\n }\n }\n}\n void hideAllWindows() {\n // Stop transparency timer when hiding windows\n transparencyTimer->stop();\n currentlyFocusedWindow = nullptr;\n windowsAreTransparent = false;\n \n // Hide all current windows\n for (MarkdownWindow *window : currentWindows) {\n window->hide();\n window->setTransparent(false); // Reset transparency state\n }\n}\n void windowCreated(MarkdownWindow *window);\n void windowRemoved(MarkdownWindow *window);\n private:\n void onWindowDeleteRequested(MarkdownWindow *window) {\n removeMarkdownWindow(window);\n \n // Mark canvas as edited since we deleted a markdown window\n if (canvas) {\n canvas->setEdited(true);\n }\n \n // Save current state\n if (canvas) {\n MainWindow *mainWindow = qobject_cast(canvas->parent());\n if (mainWindow) {\n int currentPage = mainWindow->getCurrentPageForCanvas(canvas);\n saveWindowsForPage(currentPage);\n }\n }\n}\n void onWindowFocusChanged(MarkdownWindow *window, bool focused) {\n // qDebug() << \"MarkdownWindowManager::onWindowFocusChanged(\" << window << \", \" << focused << \")\";\n \n if (focused) {\n // A window gained focus - make it opaque immediately and reset timer\n // qDebug() << \"Window gained focus, setting as currently focused\";\n currentlyFocusedWindow = window;\n \n // Make the focused window opaque immediately\n window->setTransparent(false);\n \n // Reset timer to start counting down for making other windows transparent\n resetTransparencyTimer();\n } else {\n // A window lost focus\n // qDebug() << \"Window lost focus\";\n if (currentlyFocusedWindow == window) {\n // qDebug() << \"Clearing currently focused window\";\n currentlyFocusedWindow = nullptr;\n }\n \n // Check if any window still has focus\n bool anyWindowFocused = false;\n for (MarkdownWindow *w : currentWindows) {\n if (w->isEditorFocused()) {\n // qDebug() << \"Found another focused window:\" << w;\n anyWindowFocused = true;\n currentlyFocusedWindow = w;\n // Make the newly focused window opaque\n w->setTransparent(false);\n break;\n }\n }\n \n if (!anyWindowFocused) {\n // qDebug() << \"No window has focus, starting transparency timer\";\n // No window has focus, start transparency timer\n resetTransparencyTimer();\n } else {\n // qDebug() << \"Another window still has focus, resetting timer\";\n // Another window has focus, reset timer\n resetTransparencyTimer();\n }\n }\n}\n void onWindowContentChanged(MarkdownWindow *window) {\n // qDebug() << \"MarkdownWindowManager::onWindowContentChanged(\" << window << \")\";\n \n // Content changed, make this window the focused one and reset transparency timer\n currentlyFocusedWindow = window;\n window->setTransparent(false); // Make the active window opaque\n \n // Reset transparency timer\n resetTransparencyTimer();\n}\n void onTransparencyTimerTimeout() {\n // qDebug() << \"MarkdownWindowManager::onTransparencyTimerTimeout() - Timer expired!\";\n // Make all windows except the focused one semi-transparent\n setWindowsTransparent(true);\n}\n private:\n InkCanvas *canvas;\n bool selectionMode = false;\n QMap> pageWindows;\n QList currentWindows;\n QTimer *transparencyTimer;\n MarkdownWindow *currentlyFocusedWindow = nullptr;\n bool windowsAreTransparent = false;\n QString getWindowDataFilePath(int pageNumber) const {\n QString saveFolder = getSaveFolder();\n QString notebookId = getNotebookId();\n \n if (saveFolder.isEmpty() || notebookId.isEmpty()) {\n return QString();\n }\n \n return saveFolder + QString(\"/.%1_markdown_%2.json\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n}\n void saveWindowData(int pageNumber, const QList &windows) {\n QString filePath = getWindowDataFilePath(pageNumber);\n if (filePath.isEmpty()) return;\n \n QJsonArray windowsArray;\n for (MarkdownWindow *window : windows) {\n QVariantMap windowData = window->serialize();\n windowsArray.append(QJsonObject::fromVariantMap(windowData));\n }\n \n QJsonDocument doc(windowsArray);\n \n QFile file(filePath);\n if (file.open(QIODevice::WriteOnly)) {\n file.write(doc.toJson());\n file.close();\n \n #ifdef Q_OS_WIN\n // Set hidden attribute on Windows\n SetFileAttributesW(reinterpret_cast(filePath.utf16()), FILE_ATTRIBUTE_HIDDEN);\n #endif\n }\n}\n QList loadWindowData(int pageNumber) {\n QList windows;\n \n QString filePath = getWindowDataFilePath(pageNumber);\n if (filePath.isEmpty() || !QFile::exists(filePath)) {\n return windows;\n }\n \n QFile file(filePath);\n if (!file.open(QIODevice::ReadOnly)) {\n return windows;\n }\n \n QByteArray data = file.readAll();\n file.close();\n \n QJsonParseError error;\n QJsonDocument doc = QJsonDocument::fromJson(data, &error);\n if (error.error != QJsonParseError::NoError) {\n qWarning() << \"Failed to parse markdown window data:\" << error.errorString();\n return windows;\n }\n \n QJsonArray windowsArray = doc.array();\n for (const QJsonValue &value : windowsArray) {\n QJsonObject windowObj = value.toObject();\n QVariantMap windowData = windowObj.toVariantMap();\n \n // Create window with default rect (will be updated by deserialize)\n MarkdownWindow *window = new MarkdownWindow(QRect(0, 0, 300, 200), canvas);\n window->deserialize(windowData);\n \n // Connect signals\n connectWindowSignals(window);\n \n windows.append(window);\n window->show();\n }\n \n return windows;\n}\n QString getSaveFolder() const {\n return canvas ? canvas->getSaveFolder() : QString();\n}\n QString getNotebookId() const {\n if (!canvas) return QString();\n \n QString saveFolder = canvas->getSaveFolder();\n if (saveFolder.isEmpty()) return QString();\n \n QString idFile = saveFolder + \"/.notebook_id.txt\";\n if (QFile::exists(idFile)) {\n QFile file(idFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString notebookId = in.readLine().trimmed();\n file.close();\n return notebookId;\n }\n }\n \n return \"notebook\"; // Default fallback\n}\n QRect convertScreenToCanvasRect(const QRect &screenRect) const {\n if (!canvas) {\n // qDebug() << \"MarkdownWindowManager::convertScreenToCanvasRect() - No canvas, returning screen rect:\" << screenRect;\n return screenRect;\n }\n \n // Use the new coordinate conversion methods from InkCanvas\n QRect canvasRect = canvas->mapWidgetToCanvas(screenRect);\n // qDebug() << \"MarkdownWindowManager::convertScreenToCanvasRect() - Screen rect:\" << screenRect << \"-> Canvas rect:\" << canvasRect;\n // qDebug() << \" Canvas size:\" << canvas->getCanvasSize() << \"Zoom:\" << canvas->getZoomFactor() << \"Pan:\" << canvas->getPanOffset();\n return canvasRect;\n}\n void connectWindowSignals(MarkdownWindow *window) {\n // qDebug() << \"MarkdownWindowManager::connectWindowSignals() - Connecting signals for window\" << window;\n \n // Connect existing signals\n connect(window, &MarkdownWindow::deleteRequested, this, &MarkdownWindowManager::onWindowDeleteRequested);\n connect(window, &MarkdownWindow::contentChanged, this, [this, window]() {\n onWindowContentChanged(window);\n \n // Mark canvas as edited since markdown content changed\n if (canvas) {\n canvas->setEdited(true);\n \n // Get current page and save windows\n MainWindow *mainWindow = qobject_cast(canvas->parent());\n if (mainWindow) {\n int currentPage = mainWindow->getCurrentPageForCanvas(canvas);\n saveWindowsForPage(currentPage);\n }\n }\n });\n connect(window, &MarkdownWindow::windowMoved, this, [this, window](MarkdownWindow*) {\n // qDebug() << \"Window moved:\" << window;\n \n // Window was moved, make it the focused one and reset transparency timer\n currentlyFocusedWindow = window;\n window->setTransparent(false); // Make the active window opaque\n resetTransparencyTimer();\n \n // Mark canvas as edited since window was moved\n if (canvas) {\n canvas->setEdited(true);\n }\n });\n connect(window, &MarkdownWindow::windowResized, this, [this, window](MarkdownWindow*) {\n // qDebug() << \"Window resized:\" << window;\n \n // Window was resized, make it the focused one and reset transparency timer\n currentlyFocusedWindow = window;\n window->setTransparent(false); // Make the active window opaque\n resetTransparencyTimer();\n \n // Mark canvas as edited since window was resized\n if (canvas) {\n canvas->setEdited(true);\n }\n });\n \n // Connect new transparency-related signals\n connect(window, &MarkdownWindow::focusChanged, this, &MarkdownWindowManager::onWindowFocusChanged);\n connect(window, &MarkdownWindow::editorFocusChanged, this, &MarkdownWindowManager::onWindowFocusChanged);\n connect(window, &MarkdownWindow::windowInteracted, this, [this, window](MarkdownWindow*) {\n // qDebug() << \"Window interacted:\" << window;\n \n // Window was clicked/interacted with, make it the focused one and reset transparency timer\n currentlyFocusedWindow = window;\n window->setTransparent(false); // Make the active window opaque\n resetTransparencyTimer();\n });\n \n // qDebug() << \"All signals connected for window\" << window;\n}\n public:\n void updateAllWindowPositions() {\n // Update positions of all current windows\n for (MarkdownWindow *window : currentWindows) {\n if (window) {\n window->updateScreenPosition();\n }\n }\n}\n};"], ["/SpeedyNote/source/PdfOpenDialog.h", "class PdfOpenDialog {\n Q_OBJECT\n\npublic:\n enum Result {\n Cancel,\n CreateNewFolder,\n UseExistingFolder\n };\n explicit PdfOpenDialog(const QString &pdfPath, QWidget *parent = nullptr) {\n setWindowTitle(tr(\"Open PDF with SpeedyNote\"));\n setWindowIcon(QIcon(\":/resources/icons/mainicon.png\"));\n setModal(true);\n \n // Remove setFixedSize and use proper size management instead\n // Calculate size based on DPI\n QScreen *screen = QGuiApplication::primaryScreen();\n qreal dpr = screen ? screen->devicePixelRatio() : 1.0;\n \n // Set minimum and maximum sizes instead of fixed size\n int baseWidth = 500;\n int baseHeight = 200;\n \n // Scale sizes appropriately for DPI\n int scaledWidth = static_cast(baseWidth * qMax(1.0, dpr * 0.8));\n int scaledHeight = static_cast(baseHeight * qMax(1.0, dpr * 0.8));\n \n setMinimumSize(scaledWidth, scaledHeight);\n setMaximumSize(scaledWidth + 100, scaledHeight + 50); // Allow some flexibility\n \n // Set size policy to prevent unwanted resizing\n setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);\n \n setupUI();\n \n // Ensure the dialog is properly sized after UI setup\n adjustSize();\n \n // Center the dialog on parent or screen\n if (parent) {\n move(parent->geometry().center() - rect().center());\n } else {\n move(screen->geometry().center() - rect().center());\n }\n}\n static bool hasValidNotebookFolder(const QString &pdfPath, QString &folderPath) {\n QFileInfo fileInfo(pdfPath);\n QString suggestedFolderName = fileInfo.baseName(); // Filename without extension\n QString pdfDir = fileInfo.absolutePath(); // Directory containing the PDF\n QString potentialFolderPath = pdfDir + \"/\" + suggestedFolderName;\n \n if (isValidNotebookFolder(potentialFolderPath, pdfPath)) {\n folderPath = potentialFolderPath;\n return true;\n }\n \n return false;\n}\n protected:\n void resizeEvent(QResizeEvent *event) override {\n // Handle resize events smoothly to prevent jitter during window dragging\n if (event->size() != event->oldSize()) {\n // Only process if size actually changed\n QDialog::resizeEvent(event);\n \n // Ensure the dialog stays within reasonable bounds\n QSize newSize = event->size();\n QSize minSize = minimumSize();\n QSize maxSize = maximumSize();\n \n // Clamp the size to prevent unwanted resizing\n newSize = newSize.expandedTo(minSize).boundedTo(maxSize);\n \n if (newSize != event->size()) {\n // If size needs to be adjusted, do it without triggering another resize event\n resize(newSize);\n }\n } else {\n // If size hasn't changed, just call parent implementation\n QDialog::resizeEvent(event);\n }\n}\n private:\n void onCreateNewFolder() {\n QFileInfo fileInfo(pdfPath);\n QString suggestedFolderName = fileInfo.baseName();\n \n // Get the directory where the PDF is located\n QString pdfDir = fileInfo.absolutePath();\n QString newFolderPath = pdfDir + \"/\" + suggestedFolderName;\n \n // Check if folder already exists\n if (QDir(newFolderPath).exists()) {\n QMessageBox::StandardButton reply = QMessageBox::question(\n this, \n tr(\"Folder Exists\"), \n tr(\"A folder named \\\"%1\\\" already exists in the same directory as the PDF.\\n\\nDo you want to use this existing folder?\").arg(suggestedFolderName),\n QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel\n );\n \n if (reply == QMessageBox::Yes) {\n selectedFolder = newFolderPath;\n result = UseExistingFolder;\n accept();\n return;\n } else if (reply == QMessageBox::Cancel) {\n return; // Stay in dialog\n }\n // If No, continue to create with different name\n \n // Try to create with incremented name\n int counter = 1;\n do {\n newFolderPath = pdfDir + \"/\" + suggestedFolderName + QString(\"_%1\").arg(counter);\n counter++;\n } while (QDir(newFolderPath).exists() && counter < 100);\n \n if (counter >= 100) {\n QMessageBox::warning(this, tr(\"Error\"), tr(\"Could not create a unique folder name.\"));\n return;\n }\n }\n \n // Create the new folder\n QDir dir;\n if (dir.mkpath(newFolderPath)) {\n selectedFolder = newFolderPath;\n result = CreateNewFolder;\n accept();\n } else {\n QMessageBox::warning(this, tr(\"Error\"), tr(\"Failed to create folder: %1\").arg(newFolderPath));\n }\n}\n void onUseExistingFolder() {\n QString folder = QFileDialog::getExistingDirectory(\n this, \n tr(\"Select Existing Notebook Folder\"), \n QFileInfo(pdfPath).absolutePath()\n );\n \n if (!folder.isEmpty()) {\n selectedFolder = folder;\n result = UseExistingFolder;\n accept();\n }\n}\n void onCancel() {\n result = Cancel;\n reject();\n}\n private:\n void setupUI() {\n QVBoxLayout *mainLayout = new QVBoxLayout(this);\n mainLayout->setSpacing(15);\n mainLayout->setContentsMargins(20, 20, 20, 20);\n \n // Set layout size constraint to prevent unwanted resizing\n mainLayout->setSizeConstraint(QLayout::SetMinAndMaxSize);\n \n // Icon and title\n QHBoxLayout *headerLayout = new QHBoxLayout();\n headerLayout->setSpacing(10);\n \n QLabel *iconLabel = new QLabel();\n QPixmap icon = QIcon(\":/resources/icons/mainicon.png\").pixmap(48, 48);\n iconLabel->setPixmap(icon);\n iconLabel->setFixedSize(48, 48);\n iconLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);\n \n QLabel *titleLabel = new QLabel(tr(\"Open PDF with SpeedyNote\"));\n titleLabel->setStyleSheet(\"font-size: 16px; font-weight: bold;\");\n titleLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);\n \n headerLayout->addWidget(iconLabel);\n headerLayout->addWidget(titleLabel);\n headerLayout->addStretch();\n \n mainLayout->addLayout(headerLayout);\n \n // PDF file info\n QFileInfo fileInfo(pdfPath);\n QString fileName = fileInfo.fileName();\n QString folderName = fileInfo.baseName(); // Filename without extension\n \n QLabel *messageLabel = new QLabel(tr(\"PDF File: %1\\n\\nHow would you like to open this PDF?\").arg(fileName));\n messageLabel->setWordWrap(true);\n messageLabel->setStyleSheet(\"font-size: 12px; color: #666;\");\n messageLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);\n \n mainLayout->addWidget(messageLabel);\n \n // Buttons\n QVBoxLayout *buttonLayout = new QVBoxLayout();\n buttonLayout->setSpacing(10);\n \n // Create new folder button\n QPushButton *createFolderBtn = new QPushButton(tr(\"Create New Notebook Folder (\\\"%1\\\")\").arg(folderName));\n createFolderBtn->setIcon(QApplication::style()->standardIcon(QStyle::SP_DirIcon));\n createFolderBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);\n createFolderBtn->setMinimumHeight(40);\n createFolderBtn->setStyleSheet(R\"(\n QPushButton {\n text-align: left;\n padding: 10px;\n border: 1px solid palette(mid);\n border-radius: 5px;\n background: palette(button);\n }\n QPushButton:hover {\n background: palette(light);\n border-color: palette(dark);\n }\n QPushButton:pressed {\n background: palette(midlight);\n }\n )\");\n connect(createFolderBtn, &QPushButton::clicked, this, &PdfOpenDialog::onCreateNewFolder);\n \n // Use existing folder button\n QPushButton *existingFolderBtn = new QPushButton(tr(\"Use Existing Notebook Folder...\"));\n existingFolderBtn->setIcon(QApplication::style()->standardIcon(QStyle::SP_DirOpenIcon));\n existingFolderBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);\n existingFolderBtn->setMinimumHeight(40);\n existingFolderBtn->setStyleSheet(R\"(\n QPushButton {\n text-align: left;\n padding: 10px;\n border: 1px solid palette(mid);\n border-radius: 5px;\n background: palette(button);\n }\n QPushButton:hover {\n background: palette(light);\n border-color: palette(dark);\n }\n QPushButton:pressed {\n background: palette(midlight);\n }\n )\");\n connect(existingFolderBtn, &QPushButton::clicked, this, &PdfOpenDialog::onUseExistingFolder);\n \n buttonLayout->addWidget(createFolderBtn);\n buttonLayout->addWidget(existingFolderBtn);\n \n mainLayout->addLayout(buttonLayout);\n \n // Cancel button\n QHBoxLayout *cancelLayout = new QHBoxLayout();\n cancelLayout->addStretch();\n \n QPushButton *cancelBtn = new QPushButton(tr(\"Cancel\"));\n cancelBtn->setIcon(QApplication::style()->standardIcon(QStyle::SP_DialogCancelButton));\n cancelBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);\n cancelBtn->setMinimumSize(80, 30);\n cancelBtn->setStyleSheet(R\"(\n QPushButton {\n padding: 8px 20px;\n border: 1px solid palette(mid);\n border-radius: 3px;\n background: palette(button);\n }\n QPushButton:hover {\n background: palette(light);\n }\n QPushButton:pressed {\n background: palette(midlight);\n }\n )\");\n connect(cancelBtn, &QPushButton::clicked, this, &PdfOpenDialog::onCancel);\n \n cancelLayout->addWidget(cancelBtn);\n mainLayout->addLayout(cancelLayout);\n}\n static bool isValidNotebookFolder(const QString &folderPath, const QString &pdfPath) {\n QDir folder(folderPath);\n if (!folder.exists()) {\n return false;\n }\n \n // Priority 1: Check for .pdf_path.txt file with matching PDF path\n QString pdfPathFile = folderPath + \"/.pdf_path.txt\";\n if (QFile::exists(pdfPathFile)) {\n QFile file(pdfPathFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString storedPdfPath = in.readLine().trimmed();\n file.close();\n \n if (!storedPdfPath.isEmpty()) {\n // Compare absolute paths to handle relative path differences\n QFileInfo currentPdf(pdfPath);\n QFileInfo storedPdf(storedPdfPath);\n \n // Check if the stored PDF file still exists and matches\n if (storedPdf.exists() && \n currentPdf.absoluteFilePath() == storedPdf.absoluteFilePath()) {\n return true;\n }\n }\n }\n }\n \n // Priority 2: Check for .notebook_id.txt file (SpeedyNote notebook folder)\n QString notebookIdFile = folderPath + \"/.notebook_id.txt\";\n if (QFile::exists(notebookIdFile)) {\n // Additional check: ensure this folder has some notebook content\n QStringList contentFiles = folder.entryList(\n QStringList() << \"*.png\" << \".pdf_path.txt\" << \".bookmarks.txt\" << \".background_config.txt\", \n QDir::Files\n );\n \n // If it has notebook-related files, it's likely a valid SpeedyNote folder\n // but not necessarily for this specific PDF\n if (!contentFiles.isEmpty()) {\n // This is a SpeedyNote notebook, but for a different PDF\n // Return false so the user gets the dialog to choose what to do\n return false;\n }\n }\n \n return false;\n}\n Result result;\n QString selectedFolder;\n QString pdfPath;\n};"], ["/SpeedyNote/source/SDLControllerManager.h", "class SDLControllerManager {\n Q_OBJECT\npublic:\n explicit SDLControllerManager(QObject *parent = nullptr);\n ~SDLControllerManager() {\n if (joystick) SDL_JoystickClose(joystick);\n if (sdlInitialized) SDL_QuitSubSystem(SDL_INIT_JOYSTICK);\n}\n void setPhysicalButtonMapping(const QString &logicalButton, int physicalSDLButton) {\n physicalButtonMappings[logicalButton] = physicalSDLButton;\n saveControllerMappings();\n}\n int getPhysicalButtonMapping(const QString &logicalButton) const {\n return physicalButtonMappings.value(logicalButton, -1);\n}\n QMap getAllPhysicalMappings() const {\n return physicalButtonMappings;\n}\n void saveControllerMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.beginGroup(\"ControllerPhysicalMappings\");\n for (auto it = physicalButtonMappings.begin(); it != physicalButtonMappings.end(); ++it) {\n settings.setValue(it.key(), it.value());\n }\n settings.endGroup();\n}\n void loadControllerMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.beginGroup(\"ControllerPhysicalMappings\");\n QStringList keys = settings.allKeys();\n \n if (keys.isEmpty()) {\n // No saved mappings, use defaults\n physicalButtonMappings = getDefaultMappings();\n saveControllerMappings(); // Save defaults for next time\n } else {\n // Load saved mappings\n for (const QString &key : keys) {\n physicalButtonMappings[key] = settings.value(key).toInt();\n }\n }\n settings.endGroup();\n}\n QStringList getAvailablePhysicalButtons() const {\n QStringList buttons;\n if (joystick) {\n int buttonCount = SDL_JoystickNumButtons(joystick);\n for (int i = 0; i < buttonCount; ++i) {\n buttons << getPhysicalButtonName(i);\n }\n } else {\n // If no joystick connected, show a reasonable range\n for (int i = 0; i < 20; ++i) {\n buttons << getPhysicalButtonName(i);\n }\n }\n return buttons;\n}\n QString getPhysicalButtonName(int sdlButton) const {\n // Return human-readable names for physical SDL joystick buttons\n // Since we're using raw joystick buttons, we'll use generic names\n return QString(\"Button %1\").arg(sdlButton);\n}\n int getJoystickButtonCount() const {\n if (joystick) {\n return SDL_JoystickNumButtons(joystick);\n }\n return 0;\n}\n QMap getDefaultMappings() const {\n // Default mappings for Joy-Con L using raw button indices\n // These will need to be adjusted based on actual Joy-Con button indices\n QMap defaults;\n defaults[\"LEFTSHOULDER\"] = 4; // L button\n defaults[\"RIGHTSHOULDER\"] = 6; // ZL button \n defaults[\"PADDLE2\"] = 14; // SL button\n defaults[\"PADDLE4\"] = 15; // SR button\n defaults[\"Y\"] = 0; // Up arrow\n defaults[\"A\"] = 1; // Down arrow\n defaults[\"B\"] = 2; // Left arrow\n defaults[\"X\"] = 3; // Right arrow\n defaults[\"LEFTSTICK\"] = 10; // Stick press\n defaults[\"START\"] = 8; // Minus button\n defaults[\"GUIDE\"] = 13; // Screenshot button\n return defaults;\n}\n void buttonHeld(QString buttonName);\n void buttonReleased(QString buttonName);\n void buttonSinglePress(QString buttonName);\n void leftStickAngleChanged(int angle);\n void leftStickReleased();\n void rawButtonPressed(int sdlButton, QString buttonName);\n public:\n void start() {\n if (!sdlInitialized) {\n if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) != 0) {\n qWarning() << \"Failed to initialize SDL joystick subsystem:\" << SDL_GetError();\n return;\n }\n sdlInitialized = true;\n }\n\n SDL_JoystickEventState(SDL_ENABLE); // ✅ Enable joystick events\n\n // Look for any available joystick\n int numJoysticks = SDL_NumJoysticks();\n // qDebug() << \"Found\" << numJoysticks << \"joystick(s)\";\n \n for (int i = 0; i < numJoysticks; ++i) {\n const char* joystickName = SDL_JoystickNameForIndex(i);\n // qDebug() << \"Joystick\" << i << \":\" << (joystickName ? joystickName : \"Unknown\");\n \n joystick = SDL_JoystickOpen(i);\n if (joystick) {\n // qDebug() << \"Joystick connected!\";\n // qDebug() << \"Number of buttons:\" << SDL_JoystickNumButtons(joystick);\n // qDebug() << \"Number of axes:\" << SDL_JoystickNumAxes(joystick);\n // qDebug() << \"Number of hats:\" << SDL_JoystickNumHats(joystick);\n break;\n }\n }\n\n if (!joystick) {\n qWarning() << \"No joystick could be opened\";\n }\n\n pollTimer->start(16); // 60 FPS polling\n}\n void stop() {\n pollTimer->stop();\n}\n void reconnect() {\n // Stop current polling\n pollTimer->stop();\n \n // Close existing joystick if open\n if (joystick) {\n SDL_JoystickClose(joystick);\n joystick = nullptr;\n }\n \n // Clear any cached state\n buttonPressTime.clear();\n buttonHeldEmitted.clear();\n lastAngle = -1;\n leftStickActive = false;\n buttonDetectionMode = false;\n \n // Re-initialize SDL joystick subsystem\n SDL_QuitSubSystem(SDL_INIT_JOYSTICK);\n if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) != 0) {\n qWarning() << \"Failed to re-initialize SDL joystick subsystem:\" << SDL_GetError();\n sdlInitialized = false;\n return;\n }\n sdlInitialized = true;\n \n SDL_JoystickEventState(SDL_ENABLE);\n \n // Look for any available joystick\n int numJoysticks = SDL_NumJoysticks();\n qDebug() << \"Reconnect: Found\" << numJoysticks << \"joystick(s)\";\n \n for (int i = 0; i < numJoysticks; ++i) {\n const char* joystickName = SDL_JoystickNameForIndex(i);\n qDebug() << \"Reconnect: Trying joystick\" << i << \":\" << (joystickName ? joystickName : \"Unknown\");\n \n joystick = SDL_JoystickOpen(i);\n if (joystick) {\n qDebug() << \"Reconnect: Joystick connected successfully!\";\n qDebug() << \"Number of buttons:\" << SDL_JoystickNumButtons(joystick);\n qDebug() << \"Number of axes:\" << SDL_JoystickNumAxes(joystick);\n qDebug() << \"Number of hats:\" << SDL_JoystickNumHats(joystick);\n break;\n }\n }\n \n if (!joystick) {\n qWarning() << \"Reconnect: No joystick could be opened\";\n }\n \n // Restart polling\n pollTimer->start(16); // 60 FPS polling\n}\n void startButtonDetection() {\n buttonDetectionMode = true;\n}\n void stopButtonDetection() {\n buttonDetectionMode = false;\n}\n private:\n QTimer *pollTimer;\n SDL_Joystick *joystick = nullptr;\n bool sdlInitialized = false;\n bool leftStickActive = false;\n bool buttonDetectionMode = false;\n int lastAngle = -1;\n QString getButtonName(Uint8 sdlButton) {\n // This method is now deprecated in favor of getLogicalButtonName\n return getLogicalButtonName(sdlButton);\n}\n QString getLogicalButtonName(Uint8 sdlButton) {\n // Find which logical button this physical button is mapped to\n for (auto it = physicalButtonMappings.begin(); it != physicalButtonMappings.end(); ++it) {\n if (it.value() == sdlButton) {\n return it.key(); // Return the logical button name\n }\n }\n return QString(); // Return empty string if not mapped\n}\n QMap physicalButtonMappings;\n QMap buttonPressTime;\n QMap buttonHeldEmitted;\n const quint32 HOLD_THRESHOLD = 300;\n const quint32 POLL_INTERVAL = 16;\n};"], ["/SpeedyNote/source/RecentNotebooksDialog.h", "class QPushButton {\n Q_OBJECT\n\npublic:\n explicit RecentNotebooksDialog(MainWindow *mainWindow, RecentNotebooksManager *manager, QWidget *parent = nullptr);\n private:\n void onNotebookClicked() {\n QPushButton *button = qobject_cast(sender());\n if (button) {\n QString notebookPath = button->property(\"notebookPath\").toString();\n if (!notebookPath.isEmpty() && mainWindowRef) {\n // This logic is similar to MainWindow::selectFolder but directly sets the folder.\n InkCanvas *canvas = mainWindowRef->currentCanvas(); // Get current canvas from MainWindow\n if (canvas) {\n if (canvas->isEdited()){\n mainWindowRef->saveCurrentPage(); // Use MainWindow's save method\n }\n canvas->setSaveFolder(notebookPath);\n mainWindowRef->switchPageWithDirection(1, 1); // Use MainWindow's direction-aware switchPage method\n mainWindowRef->pageInput->setValue(1); // Update pageInput in MainWindow\n mainWindowRef->updateTabLabel(); // Update tab label in MainWindow\n \n // Update recent notebooks list and refresh cover page\n if (notebookManager) {\n // Generate and save fresh cover preview\n notebookManager->generateAndSaveCoverPreview(notebookPath, canvas);\n // Add/update in recent list (this moves it to the top)\n notebookManager->addRecentNotebook(notebookPath, canvas);\n }\n }\n accept(); // Close the dialog\n }\n }\n}\n private:\n void setupUi() {\n QVBoxLayout *mainLayout = new QVBoxLayout(this);\n QScrollArea *scrollArea = new QScrollArea(this);\n scrollArea->setWidgetResizable(true);\n QWidget *gridContainer = new QWidget();\n gridLayout = new QGridLayout(gridContainer);\n gridLayout->setSpacing(15);\n\n scrollArea->setWidget(gridContainer);\n mainLayout->addWidget(scrollArea);\n setLayout(mainLayout);\n}\n void populateGrid() {\n QStringList recentPaths = notebookManager->getRecentNotebooks();\n int row = 0;\n int col = 0;\n const int numCols = 4;\n\n for (const QString &path : recentPaths) {\n if (path.isEmpty()) continue;\n\n QPushButton *button = new QPushButton(this);\n button->setFixedSize(180, 180); // Larger buttons\n button->setProperty(\"notebookPath\", path); // Store path for slot\n connect(button, &QPushButton::clicked, this, &RecentNotebooksDialog::onNotebookClicked);\n\n QVBoxLayout *buttonLayout = new QVBoxLayout(button);\n buttonLayout->setContentsMargins(5,5,5,5);\n\n QLabel *coverLabel = new QLabel(this);\n coverLabel->setFixedSize(170, 127); // 4:3 aspect ratio for cover\n coverLabel->setAlignment(Qt::AlignCenter);\n QString coverPath = notebookManager->getCoverImagePathForNotebook(path);\n if (!coverPath.isEmpty()) {\n QPixmap coverPixmap(coverPath);\n coverLabel->setPixmap(coverPixmap.scaled(coverLabel->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));\n } else {\n coverLabel->setText(tr(\"No Preview\"));\n }\n coverLabel->setStyleSheet(\"border: 1px solid gray;\");\n\n QLabel *nameLabel = new QLabel(notebookManager->getNotebookDisplayName(path), this);\n nameLabel->setAlignment(Qt::AlignCenter);\n nameLabel->setWordWrap(true);\n nameLabel->setFixedHeight(40); // Fixed height for name label\n\n buttonLayout->addWidget(coverLabel);\n buttonLayout->addWidget(nameLabel);\n button->setLayout(buttonLayout);\n\n gridLayout->addWidget(button, row, col);\n\n col++;\n if (col >= numCols) {\n col = 0;\n row++;\n }\n }\n}\n RecentNotebooksManager *notebookManager;\n QGridLayout *gridLayout;\n MainWindow *mainWindowRef;\n};"], ["/SpeedyNote/source/RecentNotebooksManager.h", "class InkCanvas {\n Q_OBJECT\n\npublic:\n explicit RecentNotebooksManager(QObject *parent = nullptr);\n void addRecentNotebook(const QString& folderPath, InkCanvas* canvasForPreview = nullptr) {\n if (folderPath.isEmpty()) return;\n\n // Remove if already exists to move it to the front\n recentNotebookPaths.removeAll(folderPath);\n recentNotebookPaths.prepend(folderPath);\n\n // Trim the list if it exceeds the maximum size\n while (recentNotebookPaths.size() > MAX_RECENT_NOTEBOOKS) {\n recentNotebookPaths.removeLast();\n }\n\n generateAndSaveCoverPreview(folderPath, canvasForPreview);\n saveRecentNotebooks();\n}\n QStringList getRecentNotebooks() const {\n return recentNotebookPaths;\n}\n QString getCoverImagePathForNotebook(const QString& folderPath) const {\n QString coverDir = getCoverImageDir();\n QString coverFileName = sanitizeFolderName(folderPath) + \"_cover.png\";\n QString coverFilePath = coverDir + coverFileName;\n if (QFile::exists(coverFilePath)) {\n return coverFilePath;\n }\n return \"\"; // Return empty if no cover exists\n}\n QString getNotebookDisplayName(const QString& folderPath) const {\n // Check for PDF metadata first\n QString metadataFile = folderPath + \"/.pdf_path.txt\";\n if (QFile::exists(metadataFile)) {\n QFile file(metadataFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString pdfPath = in.readLine().trimmed();\n file.close();\n if (!pdfPath.isEmpty()) {\n return QFileInfo(pdfPath).fileName();\n }\n }\n }\n // Fallback to folder name\n return QFileInfo(folderPath).fileName();\n}\n void generateAndSaveCoverPreview(const QString& folderPath, InkCanvas* optionalCanvas = nullptr) {\n QString coverDir = getCoverImageDir();\n QString coverFileName = sanitizeFolderName(folderPath) + \"_cover.png\";\n QString coverFilePath = coverDir + coverFileName;\n\n QImage coverImage(400, 300, QImage::Format_ARGB32_Premultiplied);\n coverImage.fill(Qt::white); // Default background\n QPainter painter(&coverImage);\n painter.setRenderHint(QPainter::SmoothPixmapTransform);\n\n if (optionalCanvas && optionalCanvas->width() > 0 && optionalCanvas->height() > 0) {\n int logicalCanvasWidth = optionalCanvas->width();\n int logicalCanvasHeight = optionalCanvas->height();\n\n double targetAspectRatio = 4.0 / 3.0;\n double canvasAspectRatio = (double)logicalCanvasWidth / logicalCanvasHeight;\n\n int grabWidth, grabHeight;\n int xOffset = 0, yOffset = 0;\n\n if (canvasAspectRatio > targetAspectRatio) { // Canvas is wider than target 4:3\n grabHeight = logicalCanvasHeight;\n grabWidth = qRound(logicalCanvasHeight * targetAspectRatio);\n xOffset = (logicalCanvasWidth - grabWidth) / 2;\n } else { // Canvas is taller than or equal to target 4:3\n grabWidth = logicalCanvasWidth;\n grabHeight = qRound(logicalCanvasWidth / targetAspectRatio);\n yOffset = (logicalCanvasHeight - grabHeight) / 2;\n }\n\n if (grabWidth > 0 && grabHeight > 0) {\n QRect grabRect(xOffset, yOffset, grabWidth, grabHeight);\n QPixmap capturedView = optionalCanvas->grab(grabRect);\n painter.drawPixmap(coverImage.rect(), capturedView, capturedView.rect());\n } else {\n // Fallback if calculated grab dimensions are invalid, draw placeholder or fill\n // This case should ideally not be hit if canvas width/height > 0\n painter.fillRect(coverImage.rect(), Qt::lightGray);\n painter.setPen(Qt::black);\n painter.drawText(coverImage.rect(), Qt::AlignCenter, tr(\"Preview Error\"));\n }\n } else {\n // Fallback: check for a saved \"annotated_..._00000.png\" or the first page\n // This part remains the same as it deals with pre-rendered images.\n QString notebookIdStr;\n InkCanvas tempCanvas(nullptr); // Temporary canvas to access potential notebookId property logic if it were there\n // However, notebookId is specific to an instance with a saveFolder.\n // For a generic fallback, we might need a different way or assume a common naming if notebookId is unknown.\n // For now, let's assume a simple naming or improve this fallback if needed.\n \n // Attempt to get notebookId if folderPath is a valid notebook with an ID file\n QFile idFile(folderPath + \"/.notebook_id.txt\");\n if (idFile.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&idFile);\n notebookIdStr = in.readLine().trimmed();\n idFile.close();\n }\n\n QString firstPagePath, firstAnnotatedPagePath;\n if (!notebookIdStr.isEmpty()) {\n firstPagePath = folderPath + QString(\"/%1_00000.png\").arg(notebookIdStr);\n firstAnnotatedPagePath = folderPath + QString(\"/annotated_%1_00000.png\").arg(notebookIdStr);\n } else {\n // Fallback if no ID, try a generic name (less ideal)\n // This situation should be rare if notebooks are managed properly\n // For robustness, one might iterate files or use a known default page name\n // For this example, we'll stick to a pattern that might not always work without an ID\n // Consider that `InkCanvas(nullptr).property(\"notebookId\")` was problematic as `notebookId` is instance specific.\n }\n\n QImage pageImage;\n if (!firstAnnotatedPagePath.isEmpty() && QFile::exists(firstAnnotatedPagePath)) {\n pageImage.load(firstAnnotatedPagePath);\n } else if (!firstPagePath.isEmpty() && QFile::exists(firstPagePath)) {\n pageImage.load(firstPagePath);\n }\n\n if (!pageImage.isNull()) {\n painter.drawImage(coverImage.rect(), pageImage, pageImage.rect());\n } else {\n // If no image found, draw a placeholder\n painter.fillRect(coverImage.rect(), Qt::darkGray);\n painter.setPen(Qt::white);\n painter.drawText(coverImage.rect(), Qt::AlignCenter, tr(\"No Page 0 Preview\"));\n }\n }\n coverImage.save(coverFilePath, \"PNG\");\n}\n private:\n void loadRecentNotebooks() {\n recentNotebookPaths = settings.value(\"recentNotebooks\").toStringList();\n}\n void saveRecentNotebooks() {\n settings.setValue(\"recentNotebooks\", recentNotebookPaths);\n}\n QString getCoverImageDir() const {\n return QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/RecentCovers/\";\n}\n QString sanitizeFolderName(const QString& folderPath) const {\n return QFileInfo(folderPath).baseName().replace(QRegularExpression(\"[^a-zA-Z0-9_]\"), \"_\");\n}\n QStringList recentNotebookPaths;\n const int MAX_RECENT_NOTEBOOKS = 16;\n QSettings settings;\n};"], ["/SpeedyNote/source/KeyCaptureDialog.h", "class KeyCaptureDialog {\n Q_OBJECT\n\npublic:\n explicit KeyCaptureDialog(QWidget *parent = nullptr);\n protected:\n void keyPressEvent(QKeyEvent *event) override {\n // Build key sequence string\n QStringList modifiers;\n \n if (event->modifiers() & Qt::ControlModifier) modifiers << \"Ctrl\";\n if (event->modifiers() & Qt::ShiftModifier) modifiers << \"Shift\";\n if (event->modifiers() & Qt::AltModifier) modifiers << \"Alt\";\n if (event->modifiers() & Qt::MetaModifier) modifiers << \"Meta\";\n \n // Don't capture modifier keys alone\n if (event->key() == Qt::Key_Control || event->key() == Qt::Key_Shift ||\n event->key() == Qt::Key_Alt || event->key() == Qt::Key_Meta) {\n return;\n }\n \n // Don't capture Escape (let it close the dialog)\n if (event->key() == Qt::Key_Escape) {\n QDialog::keyPressEvent(event);\n return;\n }\n \n QString keyString = QKeySequence(event->key()).toString();\n \n if (!modifiers.isEmpty()) {\n capturedSequence = modifiers.join(\"+\") + \"+\" + keyString;\n } else {\n capturedSequence = keyString;\n }\n \n updateDisplay();\n event->accept();\n}\n private:\n void clearSequence() {\n capturedSequence.clear();\n updateDisplay();\n setFocus(); // Return focus to dialog for key capture\n}\n private:\n QLabel *instructionLabel;\n QLabel *capturedLabel;\n QPushButton *clearButton;\n QPushButton *okButton;\n QPushButton *cancelButton;\n QString capturedSequence;\n void updateDisplay() {\n if (capturedSequence.isEmpty()) {\n capturedLabel->setText(tr(\"(No key captured yet)\"));\n okButton->setEnabled(false);\n } else {\n capturedLabel->setText(capturedSequence);\n okButton->setEnabled(true);\n }\n}\n};"], ["/SpeedyNote/source/ButtonMappingTypes.h", "class InternalDialMode {\n Q_DECLARE_TR_FUNCTIONS(ButtonMappingHelper)\n public:\n static QString dialModeToInternalKey(InternalDialMode mode) {\n switch (mode) {\n case InternalDialMode::None: return \"none\";\n case InternalDialMode::PageSwitching: return \"page_switching\";\n case InternalDialMode::ZoomControl: return \"zoom_control\";\n case InternalDialMode::ThicknessControl: return \"thickness_control\";\n\n case InternalDialMode::ToolSwitching: return \"tool_switching\";\n case InternalDialMode::PresetSelection: return \"preset_selection\";\n case InternalDialMode::PanAndPageScroll: return \"pan_and_page_scroll\";\n }\n return \"none\";\n}\n static QString actionToInternalKey(InternalControllerAction action) {\n switch (action) {\n case InternalControllerAction::None: return \"none\";\n case InternalControllerAction::ToggleFullscreen: return \"toggle_fullscreen\";\n case InternalControllerAction::ToggleDial: return \"toggle_dial\";\n case InternalControllerAction::Zoom50: return \"zoom_50\";\n case InternalControllerAction::ZoomOut: return \"zoom_out\";\n case InternalControllerAction::Zoom200: return \"zoom_200\";\n case InternalControllerAction::AddPreset: return \"add_preset\";\n case InternalControllerAction::DeletePage: return \"delete_page\";\n case InternalControllerAction::FastForward: return \"fast_forward\";\n case InternalControllerAction::OpenControlPanel: return \"open_control_panel\";\n case InternalControllerAction::RedColor: return \"red_color\";\n case InternalControllerAction::BlueColor: return \"blue_color\";\n case InternalControllerAction::YellowColor: return \"yellow_color\";\n case InternalControllerAction::GreenColor: return \"green_color\";\n case InternalControllerAction::BlackColor: return \"black_color\";\n case InternalControllerAction::WhiteColor: return \"white_color\";\n case InternalControllerAction::CustomColor: return \"custom_color\";\n case InternalControllerAction::ToggleSidebar: return \"toggle_sidebar\";\n case InternalControllerAction::Save: return \"save\";\n case InternalControllerAction::StraightLineTool: return \"straight_line_tool\";\n case InternalControllerAction::RopeTool: return \"rope_tool\";\n case InternalControllerAction::SetPenTool: return \"set_pen_tool\";\n case InternalControllerAction::SetMarkerTool: return \"set_marker_tool\";\n case InternalControllerAction::SetEraserTool: return \"set_eraser_tool\";\n case InternalControllerAction::TogglePdfTextSelection: return \"toggle_pdf_text_selection\";\n case InternalControllerAction::ToggleOutline: return \"toggle_outline\";\n case InternalControllerAction::ToggleBookmarks: return \"toggle_bookmarks\";\n case InternalControllerAction::AddBookmark: return \"add_bookmark\";\n case InternalControllerAction::ToggleTouchGestures: return \"toggle_touch_gestures\";\n }\n return \"none\";\n}\n static InternalDialMode internalKeyToDialMode(const QString &key) {\n if (key == \"none\") return InternalDialMode::None;\n if (key == \"page_switching\") return InternalDialMode::PageSwitching;\n if (key == \"zoom_control\") return InternalDialMode::ZoomControl;\n if (key == \"thickness_control\") return InternalDialMode::ThicknessControl;\n\n if (key == \"tool_switching\") return InternalDialMode::ToolSwitching;\n if (key == \"preset_selection\") return InternalDialMode::PresetSelection;\n if (key == \"pan_and_page_scroll\") return InternalDialMode::PanAndPageScroll;\n return InternalDialMode::None;\n}\n static InternalControllerAction internalKeyToAction(const QString &key) {\n if (key == \"none\") return InternalControllerAction::None;\n if (key == \"toggle_fullscreen\") return InternalControllerAction::ToggleFullscreen;\n if (key == \"toggle_dial\") return InternalControllerAction::ToggleDial;\n if (key == \"zoom_50\") return InternalControllerAction::Zoom50;\n if (key == \"zoom_out\") return InternalControllerAction::ZoomOut;\n if (key == \"zoom_200\") return InternalControllerAction::Zoom200;\n if (key == \"add_preset\") return InternalControllerAction::AddPreset;\n if (key == \"delete_page\") return InternalControllerAction::DeletePage;\n if (key == \"fast_forward\") return InternalControllerAction::FastForward;\n if (key == \"open_control_panel\") return InternalControllerAction::OpenControlPanel;\n if (key == \"red_color\") return InternalControllerAction::RedColor;\n if (key == \"blue_color\") return InternalControllerAction::BlueColor;\n if (key == \"yellow_color\") return InternalControllerAction::YellowColor;\n if (key == \"green_color\") return InternalControllerAction::GreenColor;\n if (key == \"black_color\") return InternalControllerAction::BlackColor;\n if (key == \"white_color\") return InternalControllerAction::WhiteColor;\n if (key == \"custom_color\") return InternalControllerAction::CustomColor;\n if (key == \"toggle_sidebar\") return InternalControllerAction::ToggleSidebar;\n if (key == \"save\") return InternalControllerAction::Save;\n if (key == \"straight_line_tool\") return InternalControllerAction::StraightLineTool;\n if (key == \"rope_tool\") return InternalControllerAction::RopeTool;\n if (key == \"set_pen_tool\") return InternalControllerAction::SetPenTool;\n if (key == \"set_marker_tool\") return InternalControllerAction::SetMarkerTool;\n if (key == \"set_eraser_tool\") return InternalControllerAction::SetEraserTool;\n if (key == \"toggle_pdf_text_selection\") return InternalControllerAction::TogglePdfTextSelection;\n if (key == \"toggle_outline\") return InternalControllerAction::ToggleOutline;\n if (key == \"toggle_bookmarks\") return InternalControllerAction::ToggleBookmarks;\n if (key == \"add_bookmark\") return InternalControllerAction::AddBookmark;\n if (key == \"toggle_touch_gestures\") return InternalControllerAction::ToggleTouchGestures;\n return InternalControllerAction::None;\n}\n static QStringList getTranslatedDialModes() {\n return {\n tr(\"None\"),\n tr(\"Page Switching\"),\n tr(\"Zoom Control\"),\n tr(\"Thickness Control\"),\n\n tr(\"Tool Switching\"),\n tr(\"Preset Selection\"),\n tr(\"Pan and Page Scroll\")\n };\n}\n static QStringList getTranslatedActions() {\n return {\n tr(\"None\"),\n tr(\"Toggle Fullscreen\"),\n tr(\"Toggle Dial\"),\n tr(\"Zoom 50%\"),\n tr(\"Zoom Out\"),\n tr(\"Zoom 200%\"),\n tr(\"Add Preset\"),\n tr(\"Delete Page\"),\n tr(\"Fast Forward\"),\n tr(\"Open Control Panel\"),\n tr(\"Red\"),\n tr(\"Blue\"),\n tr(\"Yellow\"),\n tr(\"Green\"),\n tr(\"Black\"),\n tr(\"White\"),\n tr(\"Custom Color\"),\n tr(\"Toggle Sidebar\"),\n tr(\"Save\"),\n tr(\"Straight Line Tool\"),\n tr(\"Rope Tool\"),\n tr(\"Set Pen Tool\"),\n tr(\"Set Marker Tool\"),\n tr(\"Set Eraser Tool\"),\n tr(\"Toggle PDF Text Selection\"),\n tr(\"Toggle PDF Outline\"),\n tr(\"Toggle Bookmarks\"),\n tr(\"Add/Remove Bookmark\"),\n tr(\"Toggle Touch Gestures\")\n };\n}\n static QStringList getTranslatedButtons() {\n return {\n tr(\"Left Shoulder\"),\n tr(\"Right Shoulder\"),\n tr(\"Paddle 2\"),\n tr(\"Paddle 4\"),\n tr(\"Y Button\"),\n tr(\"A Button\"),\n tr(\"B Button\"),\n tr(\"X Button\"),\n tr(\"Left Stick\"),\n tr(\"Start Button\"),\n tr(\"Guide Button\")\n };\n}\n static QStringList getInternalDialModeKeys() {\n return {\n \"none\",\n \"page_switching\",\n \"zoom_control\",\n \"thickness_control\",\n\n \"tool_switching\",\n \"preset_selection\",\n \"pan_and_page_scroll\"\n };\n}\n static QStringList getInternalActionKeys() {\n return {\n \"none\",\n \"toggle_fullscreen\",\n \"toggle_dial\",\n \"zoom_50\",\n \"zoom_out\",\n \"zoom_200\",\n \"add_preset\",\n \"delete_page\",\n \"fast_forward\",\n \"open_control_panel\",\n \"red_color\",\n \"blue_color\",\n \"yellow_color\",\n \"green_color\",\n \"black_color\",\n \"white_color\",\n \"custom_color\",\n \"toggle_sidebar\",\n \"save\",\n \"straight_line_tool\",\n \"rope_tool\",\n \"set_pen_tool\",\n \"set_marker_tool\",\n \"set_eraser_tool\",\n \"toggle_pdf_text_selection\",\n \"toggle_outline\",\n \"toggle_bookmarks\",\n \"add_bookmark\",\n \"toggle_touch_gestures\"\n };\n}\n static QStringList getInternalButtonKeys() {\n return {\n \"LEFTSHOULDER\",\n \"RIGHTSHOULDER\", \n \"PADDLE2\",\n \"PADDLE4\",\n \"Y\",\n \"A\",\n \"B\",\n \"X\",\n \"LEFTSTICK\",\n \"START\",\n \"GUIDE\"\n };\n}\n static QString displayToInternalKey(const QString &displayString, bool isDialMode) {\n if (isDialMode) {\n QStringList translated = getTranslatedDialModes();\n QStringList internal = getInternalDialModeKeys();\n int index = translated.indexOf(displayString);\n return (index >= 0) ? internal[index] : \"none\";\n } else {\n QStringList translated = getTranslatedActions();\n QStringList internal = getInternalActionKeys();\n int index = translated.indexOf(displayString);\n return (index >= 0) ? internal[index] : \"none\";\n }\n}\n static QString internalKeyToDisplay(const QString &internalKey, bool isDialMode) {\n if (isDialMode) {\n QStringList translated = getTranslatedDialModes();\n QStringList internal = getInternalDialModeKeys();\n int index = internal.indexOf(internalKey);\n return (index >= 0) ? translated[index] : tr(\"None\");\n } else {\n QStringList translated = getTranslatedActions();\n QStringList internal = getInternalActionKeys();\n int index = internal.indexOf(internalKey);\n return (index >= 0) ? translated[index] : tr(\"None\");\n }\n}\n};"], ["/SpeedyNote/source/Main.cpp", "#ifdef _WIN32\n#include \n#endif\n\n#include \n#include \n#include \n#include \"MainWindow.h\"\n\nint main(int argc, char *argv[]) {\n#ifdef _WIN32\n FreeConsole(); // Hide console safely on Windows\n\n /*\n AllocConsole();\n freopen(\"CONOUT$\", \"w\", stdout);\n freopen(\"CONOUT$\", \"w\", stderr);\n */\n \n \n // to show console for debugging\n \n \n#endif\n SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI, \"1\");\n SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_SWITCH, \"1\");\n SDL_Init(SDL_INIT_GAMECONTROLLER | SDL_INIT_JOYSTICK);\n\n /*\n qDebug() << \"SDL2 version:\" << SDL_GetRevision();\n qDebug() << \"Num Joysticks:\" << SDL_NumJoysticks();\n\n for (int i = 0; i < SDL_NumJoysticks(); ++i) {\n if (SDL_IsGameController(i)) {\n qDebug() << \"Controller\" << i << \"is\" << SDL_GameControllerNameForIndex(i);\n } else {\n qDebug() << \"Joystick\" << i << \"is not a recognized controller\";\n }\n }\n */ // For sdl2 debugging\n \n\n\n // Enable Windows IME support for multi-language input\n QApplication app(argc, argv);\n \n // Ensure IME is properly enabled for Windows\n #ifdef _WIN32\n app.setAttribute(Qt::AA_EnableHighDpiScaling, true);\n app.setAttribute(Qt::AA_UseHighDpiPixmaps, true);\n #endif\n\n \n QTranslator translator;\n QString locale = QLocale::system().name(); // e.g., \"zh_CN\", \"es_ES\"\n QString langCode = locale.section('_', 0, 0); // e.g., \"zh\"\n\n // printf(\"Locale: %s\\n\", locale.toStdString().c_str());\n // printf(\"Language Code: %s\\n\", langCode.toStdString().c_str());\n\n // QString locale = \"es-ES\"; // e.g., \"zh_CN\", \"es_ES\"\n // QString langCode = \"es\"; // e.g., \"zh\"\n QString translationsPath = QCoreApplication::applicationDirPath();\n\n if (translator.load(translationsPath + \"/app_\" + langCode + \".qm\")) {\n app.installTranslator(&translator);\n }\n\n QString inputFile;\n if (argc >= 2) {\n inputFile = QString::fromLocal8Bit(argv[1]);\n // qDebug() << \"Input file received:\" << inputFile;\n }\n\n MainWindow w;\n if (!inputFile.isEmpty()) {\n // Check file extension to determine how to handle it\n if (inputFile.toLower().endsWith(\".pdf\")) {\n // Handle PDF file association\n w.show(); // Show window first for dialog parent\n w.openPdfFile(inputFile);\n } else if (inputFile.toLower().endsWith(\".snpkg\")) {\n // Handle notebook package import\n w.importNotebookFromFile(inputFile);\n w.show();\n } else {\n // Unknown file type, just show the application\n w.show();\n }\n } else {\n w.show();\n }\n return app.exec();\n}\n"], ["/SpeedyNote/markdown/mainwindow.h", "class MainWindow {\n Q_OBJECT\n\n public:\n explicit MainWindow(QWidget *parent = nullptr);\n ~MainWindow() { delete ui; }\n private:\n Ui::MainWindow *ui;\n};"], ["/SpeedyNote/markdown/main.cpp", "/*\n * MIT License\n *\n * Copyright (c) 2014-2025 Patrizio Bekerle -- \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#include \n\n#include \"mainwindow.h\"\n\nint main(int argc, char *argv[]) {\n QApplication a(argc, argv);\n MainWindow w;\n w.show();\n\n return a.exec();\n}\n"], ["/SpeedyNote/source/ToolType.h", "#ifndef TOOLTYPE_H\n#define TOOLTYPE_H\n\n// ✅ Now it can be used anywhere\nenum class ToolType {\n Pen,\n Marker,\n Eraser\n};\n\n#endif // TOOLTYPE_H"], ["/SpeedyNote/markdown/markdownhighlighter.h", "class QTextDocument {\n};"], ["/SpeedyNote/markdown/qownlanguagedata.h", "class qownlanguagedata {\n};"]], "task_instance_info": {"created_time": "2025-08-20 19:30:37", "created_task_model": "DeepSeek-R1", "class_skeleton": "class\nQPlainTextEditSearchWidget\n{\nQ_OBJECT\n\n public:\n enum SearchMode { PlainTextMode, WholeWordsMode, RegularExpressionMode };\nexplicit QPlainTextEditSearchWidget(QPlainTextEdit *parent = nullptr) {}\nbool doSearch(bool searchDown = true, bool allowRestartAtTop = true,\n bool updateUI = true) {}\nvoid setDarkMode(bool enabled) {}\n~QPlainTextEditSearchWidget() {}\nvoid setSearchText(const QString &searchText) {}\nvoid setSearchMode(SearchMode searchMode) {}\nvoid setDebounceDelay(uint debounceDelay) {}\nvoid activate(bool focus) {}\nvoid clearSearchExtraSelections() {}\nvoid updateSearchExtraSelections() {}\nprivate:\nUi::QPlainTextEditSearchWidget *ui;\nint _searchResultCount;\nint _currentSearchResult;\nQList _searchExtraSelections;\nQColor selectionColor;\nQTimer _debounceTimer;\nQString _searchTerm;\nvoid setSearchExtraSelections() const {}\nvoid stopDebounce() {}\nprotected:\nQPlainTextEdit *_textEdit;\nbool _darkMode;\nbool eventFilter(QObject *obj, QEvent *event) override {}\npublic:\nvoid activate() {}\nvoid deactivate() {}\nvoid doSearchDown() {}\nvoid doSearchUp() {}\nvoid setReplaceMode(bool enabled) {}\nvoid activateReplace() {}\nbool doReplace(bool forAll = false) {}\nvoid doReplaceAll() {}\nvoid reset() {}\nvoid doSearchCount() {}\nprotected:\nvoid searchLineEditTextChanged(const QString &arg1) {}\nvoid performSearch() {}\nvoid updateSearchCountLabelText() {}\nvoid setSearchSelectionColor(const QColor &color) {}\nprivate:\nvoid on_modeComboBox_currentIndexChanged(int index) {}\nvoid on_matchCaseSensitiveButton_toggled(bool checked) {}\n};", "code_description": "This code segment functions to: Provide interactive search and replace capabilities within a text editing component, including navigation between matches, highlighting of results, multiple search modes, and visual feedback for user actions."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```cpp\n[TASK_BEGIN]\nclass QPlainTextEditSearchWidget\n{\n Q_OBJECT\n\npublic:\n enum SearchMode { PlainTextMode, WholeWordsMode, RegularExpressionMode };\n \n explicit QPlainTextEditSearchWidget(QPlainTextEdit *parent = nullptr) {}\n bool doSearch(bool searchDown = true, bool allowRestartAtTop = true, bool updateUI = true) { return false; }\n void setDarkMode(bool enabled) {}\n ~QPlainTextEditSearchWidget() {}\n void setSearchText(const QString &searchText) {}\n void setSearchMode(SearchMode searchMode) {}\n void setDebounceDelay(uint debounceDelay) {}\n void activate(bool focus) {}\n void clearSearchExtraSelections() {}\n void updateSearchExtraSelections() {}\n\nprivate:\n Ui::QPlainTextEditSearchWidget *ui;\n int _searchResultCount;\n int _currentSearchResult;\n QList _searchExtraSelections;\n QColor selectionColor;\n QTimer _debounceTimer;\n QString _searchTerm;\n void setSearchExtraSelections() const {}\n void stopDebounce() {}\n\nprotected:\n QPlainTextEdit *_textEdit;\n bool _darkMode;\n bool eventFilter(QObject *obj, QEvent *event) override { return false; }\n\npublic:\n void activate() {}\n void deactivate() {}\n void doSearchDown() {}\n void doSearchUp() {}\n void setReplaceMode(bool enabled) {}\n void activateReplace() {}\n bool doReplace(bool forAll = false) { return false; }\n void doReplaceAll() {}\n void reset() {}\n void doSearchCount() {}\n\nprotected:\n void searchLineEditTextChanged(const QString &arg1) {}\n void performSearch() {}\n void updateSearchCountLabelText() {}\n void setSearchSelectionColor(const QColor &color) {}\n\nprivate:\n void on_modeComboBox_currentIndexChanged(int index) {}\n void on_matchCaseSensitiveButton_toggled(bool checked) {}\n};\n[TASK_END]\n```", "inference_time": "2025-08-20 19-31-18"}, "editdistance_info": {"edit_distance": 11.8538, "calculate_time": "2025-08-20 19:31:18", "true_code_clean": "class QPlainTextEditSearchWidget {\n Q_OBJECT\n public:\n enum SearchMode { PlainTextMode, WholeWordsMode, RegularExpressionMode };\n explicit QPlainTextEditSearchWidget(QPlainTextEdit *parent = nullptr) {\n ui->setupUi(this);\n _textEdit = parent;\n _darkMode = false;\n hide();\n ui->searchCountLabel->setStyleSheet(QStringLiteral(\"* {color: grey}\"));\n ui->searchCountLabel->setEnabled(false);\n _currentSearchResult = 0;\n _searchResultCount = 0;\n connect(ui->closeButton, &QPushButton::clicked, this,\n &QPlainTextEditSearchWidget::deactivate);\n connect(ui->searchLineEdit, &QLineEdit::textChanged, this,\n &QPlainTextEditSearchWidget::searchLineEditTextChanged);\n connect(ui->searchDownButton, &QPushButton::clicked, this,\n &QPlainTextEditSearchWidget::doSearchDown);\n connect(ui->searchUpButton, &QPushButton::clicked, this,\n &QPlainTextEditSearchWidget::doSearchUp);\n connect(ui->replaceToggleButton, &QPushButton::toggled, this,\n &QPlainTextEditSearchWidget::setReplaceMode);\n connect(ui->replaceButton, &QPushButton::clicked, this,\n &QPlainTextEditSearchWidget::doReplace);\n connect(ui->replaceAllButton, &QPushButton::clicked, this,\n &QPlainTextEditSearchWidget::doReplaceAll);\n connect(&_debounceTimer, &QTimer::timeout, this,\n &QPlainTextEditSearchWidget::performSearch);\n installEventFilter(this);\n ui->searchLineEdit->installEventFilter(this);\n ui->replaceLineEdit->installEventFilter(this);\n#ifdef Q_OS_MAC\n layout()->setSpacing(8);\n ui->buttonFrame->layout()->setSpacing(9);\n QString buttonStyle = QStringLiteral(\"QPushButton {margin: 0}\");\n ui->closeButton->setStyleSheet(buttonStyle);\n ui->searchDownButton->setStyleSheet(buttonStyle);\n ui->searchUpButton->setStyleSheet(buttonStyle);\n ui->replaceToggleButton->setStyleSheet(buttonStyle);\n ui->matchCaseSensitiveButton->setStyleSheet(buttonStyle);\n#endif\n}\n bool doSearch(bool searchDown = true, bool allowRestartAtTop = true,\n bool updateUI = true) {\n if (_debounceTimer.isActive()) {\n stopDebounce();\n }\n const QString text = ui->searchLineEdit->text();\n if (text.isEmpty()) {\n if (updateUI) {\n ui->searchLineEdit->setStyleSheet(QLatin1String(\"\"));\n }\n return false;\n }\n const int searchMode = ui->modeComboBox->currentIndex();\n const bool caseSensitive = ui->matchCaseSensitiveButton->isChecked();\n QFlags options =\n searchDown ? QTextDocument::FindFlag(0) : QTextDocument::FindBackward;\n if (searchMode == WholeWordsMode) {\n options |= QTextDocument::FindWholeWords;\n }\n if (caseSensitive) {\n options |= QTextDocument::FindCaseSensitively;\n }\n _textEdit->blockSignals(true);\n bool found =\n searchMode == RegularExpressionMode\n ?\n#if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0))\n _textEdit->find(\n QRegularExpression(\n text, caseSensitive\n ? QRegularExpression::NoPatternOption\n : QRegularExpression::CaseInsensitiveOption),\n options)\n :\n#else\n _textEdit->find(QRegExp(text, caseSensitive ? Qt::CaseSensitive\n : Qt::CaseInsensitive),\n options)\n :\n#endif\n _textEdit->find(text, options);\n _textEdit->blockSignals(false);\n if (found) {\n const int result =\n searchDown ? ++_currentSearchResult : --_currentSearchResult;\n _currentSearchResult = std::min(result, _searchResultCount);\n updateSearchCountLabelText();\n }\n if (!found && allowRestartAtTop) {\n _textEdit->moveCursor(searchDown ? QTextCursor::Start\n : QTextCursor::End);\n found =\n searchMode == RegularExpressionMode\n ?\n#if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0))\n _textEdit->find(\n QRegularExpression(\n text, caseSensitive\n ? QRegularExpression::NoPatternOption\n : QRegularExpression::CaseInsensitiveOption),\n options)\n :\n#else\n _textEdit->find(\n QRegExp(text, caseSensitive ? Qt::CaseSensitive\n : Qt::CaseInsensitive),\n options)\n :\n#endif\n _textEdit->find(text, options);\n if (found && updateUI) {\n _currentSearchResult = searchDown ? 1 : _searchResultCount;\n updateSearchCountLabelText();\n }\n }\n if (updateUI) {\n const QRect rect = _textEdit->cursorRect();\n QMargins margins = _textEdit->layout()->contentsMargins();\n const int searchWidgetHotArea = _textEdit->height() - this->height();\n const int marginBottom =\n (rect.y() > searchWidgetHotArea) ? (this->height() + 10) : 0;\n if (margins.bottom() != marginBottom) {\n margins.setBottom(marginBottom);\n _textEdit->layout()->setContentsMargins(margins);\n }\n const QString bgColorCode = _darkMode\n ? (found ? QStringLiteral(\"#135a13\")\n : QStringLiteral(\"#8d2b36\"))\n : found ? QStringLiteral(\"#D5FAE2\")\n : QStringLiteral(\"#FAE9EB\");\n const QString fgColorCode =\n _darkMode ? QStringLiteral(\"#cccccc\") : QStringLiteral(\"#404040\");\n ui->searchLineEdit->setStyleSheet(\n QStringLiteral(\"* { background: \") + bgColorCode +\n QStringLiteral(\"; color: \") + fgColorCode + QStringLiteral(\"; }\"));\n this->setSearchExtraSelections();\n }\n return found;\n}\n void setDarkMode(bool enabled) {\n _darkMode = enabled;\n}\n ~QPlainTextEditSearchWidget() { delete ui; }\n void setSearchText(const QString &searchText) {\n ui->searchLineEdit->setText(searchText);\n}\n void setSearchMode(SearchMode searchMode) {\n ui->modeComboBox->setCurrentIndex(searchMode);\n}\n void setDebounceDelay(uint debounceDelay) {\n _debounceTimer.setInterval(static_cast(debounceDelay));\n}\n void activate(bool focus) {\n setReplaceMode(ui->modeComboBox->currentIndex() !=\n SearchMode::PlainTextMode);\n show();\n const QString selectedText = _textEdit->textCursor().selectedText();\n if (!selectedText.isEmpty() && ui->searchLineEdit->text().isEmpty()) {\n ui->searchLineEdit->setText(selectedText);\n }\n if (focus) {\n ui->searchLineEdit->setFocus();\n }\n ui->searchLineEdit->selectAll();\n updateSearchExtraSelections();\n doSearchDown();\n}\n void clearSearchExtraSelections() {\n _searchExtraSelections.clear();\n setSearchExtraSelections();\n}\n void updateSearchExtraSelections() {\n _searchExtraSelections.clear();\n const auto textCursor = _textEdit->textCursor();\n _textEdit->moveCursor(QTextCursor::Start);\n const QColor color = selectionColor;\n QTextCharFormat extraFmt;\n extraFmt.setBackground(color);\n int findCounter = 0;\n const int searchMode = ui->modeComboBox->currentIndex();\n while (doSearch(true, false, false)) {\n findCounter++;\n if (searchMode == RegularExpressionMode && findCounter >= 10000) {\n break;\n }\n QTextEdit::ExtraSelection extra = QTextEdit::ExtraSelection();\n extra.format = extraFmt;\n extra.cursor = _textEdit->textCursor();\n _searchExtraSelections.append(extra);\n }\n _textEdit->setTextCursor(textCursor);\n this->setSearchExtraSelections();\n}\n private:\n Ui::QPlainTextEditSearchWidget *ui;\n int _searchResultCount;\n int _currentSearchResult;\n QList _searchExtraSelections;\n QColor selectionColor;\n QTimer _debounceTimer;\n QString _searchTerm;\n void setSearchExtraSelections() const {\n this->_textEdit->setExtraSelections(this->_searchExtraSelections);\n}\n void stopDebounce() {\n _debounceTimer.stop();\n ui->searchDownButton->setEnabled(true);\n ui->searchUpButton->setEnabled(true);\n}\n protected:\n QPlainTextEdit *_textEdit;\n bool _darkMode;\n bool eventFilter(QObject *obj, QEvent *event) override {\n if (event->type() == QEvent::KeyPress) {\n auto *keyEvent = static_cast(event);\n if (keyEvent->key() == Qt::Key_Escape) {\n deactivate();\n return true;\n } else if ((!_debounceTimer.isActive() &&\n keyEvent->modifiers().testFlag(Qt::ShiftModifier) &&\n (keyEvent->key() == Qt::Key_Return)) ||\n (keyEvent->key() == Qt::Key_Up)) {\n doSearchUp();\n return true;\n } else if (!_debounceTimer.isActive() &&\n ((keyEvent->key() == Qt::Key_Return) ||\n (keyEvent->key() == Qt::Key_Down))) {\n doSearchDown();\n return true;\n } else if (!_debounceTimer.isActive() &&\n keyEvent->key() == Qt::Key_F3) {\n doSearch(!keyEvent->modifiers().testFlag(Qt::ShiftModifier));\n return true;\n }\n return false;\n }\n return QWidget::eventFilter(obj, event);\n}\n public:\n void activate() {\n setReplaceMode(ui->modeComboBox->currentIndex() !=\n SearchMode::PlainTextMode);\n show();\n const QString selectedText = _textEdit->textCursor().selectedText();\n if (!selectedText.isEmpty() && ui->searchLineEdit->text().isEmpty()) {\n ui->searchLineEdit->setText(selectedText);\n }\n if (focus) {\n ui->searchLineEdit->setFocus();\n }\n ui->searchLineEdit->selectAll();\n updateSearchExtraSelections();\n doSearchDown();\n}\n void deactivate() {\n stopDebounce();\n hide();\n clearSearchExtraSelections();\n _textEdit->setFocus();\n}\n void doSearchDown() { doSearch(true); }\n void doSearchUp() { doSearch(false); }\n void setReplaceMode(bool enabled) {\n ui->replaceToggleButton->setChecked(enabled);\n ui->replaceLabel->setVisible(enabled);\n ui->replaceLineEdit->setVisible(enabled);\n ui->modeLabel->setVisible(enabled);\n ui->buttonFrame->setVisible(enabled);\n ui->matchCaseSensitiveButton->setVisible(enabled);\n}\n void activateReplace() {\n if (_textEdit->isReadOnly()) {\n return;\n }\n ui->searchLineEdit->setText(_textEdit->textCursor().selectedText());\n ui->searchLineEdit->selectAll();\n activate();\n setReplaceMode(true);\n}\n bool doReplace(bool forAll = false) {\n if (_textEdit->isReadOnly()) {\n return false;\n }\n QTextCursor cursor = _textEdit->textCursor();\n if (!forAll && cursor.selectedText().isEmpty()) {\n return false;\n }\n const int searchMode = ui->modeComboBox->currentIndex();\n if (searchMode == RegularExpressionMode) {\n QString text = cursor.selectedText();\n text.replace(QRegularExpression(ui->searchLineEdit->text()),\n ui->replaceLineEdit->text());\n cursor.insertText(text);\n } else {\n cursor.insertText(ui->replaceLineEdit->text());\n }\n if (!forAll) {\n const int position = cursor.position();\n if (!doSearch(true)) {\n cursor.setPosition(position);\n _textEdit->setTextCursor(cursor);\n }\n }\n return true;\n}\n void doReplaceAll() {\n if (_textEdit->isReadOnly()) {\n return;\n }\n _textEdit->moveCursor(QTextCursor::Start);\n while (doSearch(true, false) && doReplace(true)) {\n }\n}\n void reset() {\n ui->searchLineEdit->clear();\n setSearchMode(SearchMode::PlainTextMode);\n setReplaceMode(false);\n ui->searchCountLabel->setEnabled(false);\n}\n void doSearchCount() {\n _textEdit->moveCursor(QTextCursor::Start, QTextCursor::MoveAnchor);\n bool found;\n _searchResultCount = 0;\n _currentSearchResult = 0;\n const int searchMode = ui->modeComboBox->currentIndex();\n do {\n found = doSearch(true, false, false);\n if (found) {\n _searchResultCount++;\n }\n if (searchMode == RegularExpressionMode &&\n _searchResultCount >= 10000) {\n break;\n }\n } while (found);\n updateSearchCountLabelText();\n}\n protected:\n void searchLineEditTextChanged(const QString &arg1) {\n _searchTerm = arg1;\n if (_debounceTimer.interval() != 0 && !_searchTerm.isEmpty()) {\n _debounceTimer.start();\n ui->searchDownButton->setEnabled(false);\n ui->searchUpButton->setEnabled(false);\n } else {\n performSearch();\n }\n}\n void performSearch() {\n doSearchCount();\n updateSearchExtraSelections();\n doSearchDown();\n}\n void updateSearchCountLabelText() {\n ui->searchCountLabel->setEnabled(true);\n ui->searchCountLabel->setText(QStringLiteral(\"%1/%2\").arg(\n _currentSearchResult == 0 ? QChar('-')\n : QString::number(_currentSearchResult),\n _searchResultCount == 0 ? QChar('-')\n : QString::number(_searchResultCount)));\n}\n void setSearchSelectionColor(const QColor &color) {\n selectionColor = color;\n}\n private:\n void on_modeComboBox_currentIndexChanged(int index) {\n Q_UNUSED(index)\n doSearchCount();\n doSearchDown();\n}\n void on_matchCaseSensitiveButton_toggled(bool checked) {\n Q_UNUSED(checked)\n doSearchCount();\n doSearchDown();\n}\n}", "predict_code_clean": "class QPlainTextEditSearchWidget\n{\n Q_OBJECT\npublic:\n enum SearchMode { PlainTextMode, WholeWordsMode, RegularExpressionMode };\n explicit QPlainTextEditSearchWidget(QPlainTextEdit *parent = nullptr) {}\n bool doSearch(bool searchDown = true, bool allowRestartAtTop = true, bool updateUI = true) { return false; }\n void setDarkMode(bool enabled) {}\n ~QPlainTextEditSearchWidget() {}\n void setSearchText(const QString &searchText) {}\n void setSearchMode(SearchMode searchMode) {}\n void setDebounceDelay(uint debounceDelay) {}\n void activate(bool focus) {}\n void clearSearchExtraSelections() {}\n void updateSearchExtraSelections() {}\nprivate:\n Ui::QPlainTextEditSearchWidget *ui;\n int _searchResultCount;\n int _currentSearchResult;\n QList _searchExtraSelections;\n QColor selectionColor;\n QTimer _debounceTimer;\n QString _searchTerm;\n void setSearchExtraSelections() const {}\n void stopDebounce() {}\nprotected:\n QPlainTextEdit *_textEdit;\n bool _darkMode;\n bool eventFilter(QObject *obj, QEvent *event) override { return false; }\npublic:\n void activate() {}\n void deactivate() {}\n void doSearchDown() {}\n void doSearchUp() {}\n void setReplaceMode(bool enabled) {}\n void activateReplace() {}\n bool doReplace(bool forAll = false) { return false; }\n void doReplaceAll() {}\n void reset() {}\n void doSearchCount() {}\nprotected:\n void searchLineEditTextChanged(const QString &arg1) {}\n void performSearch() {}\n void updateSearchCountLabelText() {}\n void setSearchSelectionColor(const QColor &color) {}\nprivate:\n void on_modeComboBox_currentIndexChanged(int index) {}\n void on_matchCaseSensitiveButton_toggled(bool checked) {}\n};"}} {"repo_name": "SpeedyNote", "file_name": "/SpeedyNote/source/MarkdownWindowManager.h", "inference_info": {"prefix_code": "", "suffix_code": ";", "middle_code": "class MarkdownWindow {\n Q_OBJECT\npublic:\n explicit MarkdownWindowManager(InkCanvas *canvas, QObject *parent = nullptr);\n ~MarkdownWindowManager() {\n clearAllWindows();\n}\n MarkdownWindow* createMarkdownWindow(const QRect &rect);\n void removeMarkdownWindow(MarkdownWindow *window) {\n if (!window) return;\n currentWindows.removeAll(window);\n for (auto it = pageWindows.begin(); it != pageWindows.end(); ++it) {\n it.value().removeAll(window);\n }\n emit windowRemoved(window);\n window->deleteLater();\n}\n void clearAllWindows() {\n transparencyTimer->stop();\n currentlyFocusedWindow = nullptr;\n windowsAreTransparent = false;\n for (MarkdownWindow *window : currentWindows) {\n window->deleteLater();\n }\n currentWindows.clear();\n for (auto it = pageWindows.begin(); it != pageWindows.end(); ++it) {\n for (MarkdownWindow *window : it.value()) {\n window->deleteLater();\n }\n }\n pageWindows.clear();\n}\n void saveWindowsForPage(int pageNumber) {\n if (!canvas || currentWindows.isEmpty()) return;\n pageWindows[pageNumber] = currentWindows;\n saveWindowData(pageNumber, currentWindows);\n}\n void loadWindowsForPage(int pageNumber) {\n if (!canvas) return;\n QList newPageWindows;\n if (pageWindows.contains(pageNumber)) {\n newPageWindows = pageWindows[pageNumber];\n } else {\n newPageWindows = loadWindowData(pageNumber);\n if (!newPageWindows.isEmpty()) {\n pageWindows[pageNumber] = newPageWindows;\n }\n }\n currentWindows = newPageWindows;\n for (MarkdownWindow *window : currentWindows) {\n if (!window->isValidForCanvas()) {\n QRect canvasBounds = canvas->getCanvasRect();\n QRect windowRect = window->getCanvasRect();\n int newX = qMax(0, qMin(windowRect.x(), canvasBounds.width() - windowRect.width()));\n int newY = qMax(0, qMin(windowRect.y(), canvasBounds.height() - windowRect.height()));\n if (newX != windowRect.x() || newY != windowRect.y()) {\n QRect adjustedRect(newX, newY, windowRect.width(), windowRect.height());\n window->setCanvasRect(adjustedRect);\n }\n }\n window->ensureCanvasConnections();\n window->show();\n window->updateScreenPosition();\n window->setTransparent(false);\n }\n if (!currentWindows.isEmpty()) {\n resetTransparencyTimer();\n } else {\n }\n}\n void deleteWindowsForPage(int pageNumber) {\n if (pageWindows.contains(pageNumber)) {\n QList windows = pageWindows[pageNumber];\n for (MarkdownWindow *window : windows) {\n window->deleteLater();\n }\n pageWindows.remove(pageNumber);\n }\n QString filePath = getWindowDataFilePath(pageNumber);\n if (QFile::exists(filePath)) {\n QFile::remove(filePath);\n }\n if (pageWindows.value(pageNumber) == currentWindows) {\n currentWindows.clear();\n }\n}\n void setSelectionMode(bool enabled) {\n selectionMode = enabled;\n if (canvas) {\n canvas->setCursor(enabled ? Qt::CrossCursor : Qt::ArrowCursor);\n }\n}\n QList getCurrentPageWindows() const {\n return currentWindows;\n}\n void resetTransparencyTimer() {\n transparencyTimer->stop();\n windowsAreTransparent = false; \n transparencyTimer->start();\n}\n void setWindowsTransparent(bool transparent) {\n if (windowsAreTransparent == transparent) return;\n windowsAreTransparent = transparent;\n for (MarkdownWindow *window : currentWindows) {\n if (transparent) {\n if (window != currentlyFocusedWindow) {\n window->setTransparent(true);\n } else {\n window->setTransparent(false);\n }\n } else {\n window->setTransparent(false);\n }\n }\n}\n void hideAllWindows() {\n transparencyTimer->stop();\n currentlyFocusedWindow = nullptr;\n windowsAreTransparent = false;\n for (MarkdownWindow *window : currentWindows) {\n window->hide();\n window->setTransparent(false); \n }\n}\n void windowCreated(MarkdownWindow *window);\n void windowRemoved(MarkdownWindow *window);\n private:\n void onWindowDeleteRequested(MarkdownWindow *window) {\n removeMarkdownWindow(window);\n if (canvas) {\n canvas->setEdited(true);\n }\n if (canvas) {\n MainWindow *mainWindow = qobject_cast(canvas->parent());\n if (mainWindow) {\n int currentPage = mainWindow->getCurrentPageForCanvas(canvas);\n saveWindowsForPage(currentPage);\n }\n }\n}\n void onWindowFocusChanged(MarkdownWindow *window, bool focused) {\n if (focused) {\n currentlyFocusedWindow = window;\n window->setTransparent(false);\n resetTransparencyTimer();\n } else {\n if (currentlyFocusedWindow == window) {\n currentlyFocusedWindow = nullptr;\n }\n bool anyWindowFocused = false;\n for (MarkdownWindow *w : currentWindows) {\n if (w->isEditorFocused()) {\n anyWindowFocused = true;\n currentlyFocusedWindow = w;\n w->setTransparent(false);\n break;\n }\n }\n if (!anyWindowFocused) {\n resetTransparencyTimer();\n } else {\n resetTransparencyTimer();\n }\n }\n}\n void onWindowContentChanged(MarkdownWindow *window) {\n currentlyFocusedWindow = window;\n window->setTransparent(false); \n resetTransparencyTimer();\n}\n void onTransparencyTimerTimeout() {\n setWindowsTransparent(true);\n}\n private:\n InkCanvas *canvas;\n bool selectionMode = false;\n QMap> pageWindows;\n QList currentWindows;\n QTimer *transparencyTimer;\n MarkdownWindow *currentlyFocusedWindow = nullptr;\n bool windowsAreTransparent = false;\n QString getWindowDataFilePath(int pageNumber) const {\n QString saveFolder = getSaveFolder();\n QString notebookId = getNotebookId();\n if (saveFolder.isEmpty() || notebookId.isEmpty()) {\n return QString();\n }\n return saveFolder + QString(\"/.%1_markdown_%2.json\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n}\n void saveWindowData(int pageNumber, const QList &windows) {\n QString filePath = getWindowDataFilePath(pageNumber);\n if (filePath.isEmpty()) return;\n QJsonArray windowsArray;\n for (MarkdownWindow *window : windows) {\n QVariantMap windowData = window->serialize();\n windowsArray.append(QJsonObject::fromVariantMap(windowData));\n }\n QJsonDocument doc(windowsArray);\n QFile file(filePath);\n if (file.open(QIODevice::WriteOnly)) {\n file.write(doc.toJson());\n file.close();\n #ifdef Q_OS_WIN\n SetFileAttributesW(reinterpret_cast(filePath.utf16()), FILE_ATTRIBUTE_HIDDEN);\n #endif\n }\n}\n QList loadWindowData(int pageNumber) {\n QList windows;\n QString filePath = getWindowDataFilePath(pageNumber);\n if (filePath.isEmpty() || !QFile::exists(filePath)) {\n return windows;\n }\n QFile file(filePath);\n if (!file.open(QIODevice::ReadOnly)) {\n return windows;\n }\n QByteArray data = file.readAll();\n file.close();\n QJsonParseError error;\n QJsonDocument doc = QJsonDocument::fromJson(data, &error);\n if (error.error != QJsonParseError::NoError) {\n qWarning() << \"Failed to parse markdown window data:\" << error.errorString();\n return windows;\n }\n QJsonArray windowsArray = doc.array();\n for (const QJsonValue &value : windowsArray) {\n QJsonObject windowObj = value.toObject();\n QVariantMap windowData = windowObj.toVariantMap();\n MarkdownWindow *window = new MarkdownWindow(QRect(0, 0, 300, 200), canvas);\n window->deserialize(windowData);\n connectWindowSignals(window);\n windows.append(window);\n window->show();\n }\n return windows;\n}\n QString getSaveFolder() const {\n return canvas ? canvas->getSaveFolder() : QString();\n}\n QString getNotebookId() const {\n if (!canvas) return QString();\n QString saveFolder = canvas->getSaveFolder();\n if (saveFolder.isEmpty()) return QString();\n QString idFile = saveFolder + \"/.notebook_id.txt\";\n if (QFile::exists(idFile)) {\n QFile file(idFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString notebookId = in.readLine().trimmed();\n file.close();\n return notebookId;\n }\n }\n return \"notebook\"; \n}\n QRect convertScreenToCanvasRect(const QRect &screenRect) const {\n if (!canvas) {\n return screenRect;\n }\n QRect canvasRect = canvas->mapWidgetToCanvas(screenRect);\n return canvasRect;\n}\n void connectWindowSignals(MarkdownWindow *window) {\n connect(window, &MarkdownWindow::deleteRequested, this, &MarkdownWindowManager::onWindowDeleteRequested);\n connect(window, &MarkdownWindow::contentChanged, this, [this, window]() {\n onWindowContentChanged(window);\n if (canvas) {\n canvas->setEdited(true);\n MainWindow *mainWindow = qobject_cast(canvas->parent());\n if (mainWindow) {\n int currentPage = mainWindow->getCurrentPageForCanvas(canvas);\n saveWindowsForPage(currentPage);\n }\n }\n });\n connect(window, &MarkdownWindow::windowMoved, this, [this, window](MarkdownWindow*) {\n currentlyFocusedWindow = window;\n window->setTransparent(false); \n resetTransparencyTimer();\n if (canvas) {\n canvas->setEdited(true);\n }\n });\n connect(window, &MarkdownWindow::windowResized, this, [this, window](MarkdownWindow*) {\n currentlyFocusedWindow = window;\n window->setTransparent(false); \n resetTransparencyTimer();\n if (canvas) {\n canvas->setEdited(true);\n }\n });\n connect(window, &MarkdownWindow::focusChanged, this, &MarkdownWindowManager::onWindowFocusChanged);\n connect(window, &MarkdownWindow::editorFocusChanged, this, &MarkdownWindowManager::onWindowFocusChanged);\n connect(window, &MarkdownWindow::windowInteracted, this, [this, window](MarkdownWindow*) {\n currentlyFocusedWindow = window;\n window->setTransparent(false); \n resetTransparencyTimer();\n });\n}\n public:\n void updateAllWindowPositions() {\n for (MarkdownWindow *window : currentWindows) {\n if (window) {\n window->updateScreenPosition();\n }\n }\n}\n}", "code_description": null, "fill_type": "CLASS_TYPE", "language_type": "cpp", "sub_task_type": null}, "context_code": [["/SpeedyNote/source/InkCanvas.h", "class MarkdownWindowManager {\n Q_OBJECT\n\nsignals:\n void zoomChanged(int newZoom);\n void panChanged(int panX, int panY);\n void touchGestureEnded();\n void ropeSelectionCompleted(const QPoint &position);\n void pdfLinkClicked(int targetPage);\n void pdfTextSelected(const QString &text);\n void pdfLoaded();\n void markdownSelectionModeChanged(bool enabled);\n public:\n explicit InkCanvas(QWidget *parent = nullptr) { \n \n // Set theme-aware default pen color\n MainWindow *mainWindow = qobject_cast(parent);\n if (mainWindow) {\n penColor = mainWindow->getDefaultPenColor();\n } \n setAttribute(Qt::WA_StaticContents);\n setTabletTracking(true);\n setAttribute(Qt::WA_AcceptTouchEvents); // Enable touch events\n\n // Enable immediate updates for smoother animation\n setAttribute(Qt::WA_OpaquePaintEvent);\n setAttribute(Qt::WA_NoSystemBackground);\n \n // Detect screen resolution and set canvas size\n QScreen *screen = QGuiApplication::primaryScreen();\n if (screen) {\n QSize logicalSize = screen->availableGeometry().size() * 0.89;\n setMaximumSize(logicalSize); // Optional\n setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);\n } else {\n setFixedSize(1920, 1080); // Fallback size\n }\n \n initializeBuffer();\n QCache pdfCache(10);\n pdfCache.setMaxCost(10); // ✅ Ensures the cache holds at most 5 pages\n // No need to set auto-delete, QCache will handle deletion automatically\n \n // Initialize PDF text selection throttling timer (60 FPS = ~16.67ms)\n pdfTextSelectionTimer = new QTimer(this);\n pdfTextSelectionTimer->setSingleShot(true);\n pdfTextSelectionTimer->setInterval(16); // ~60 FPS\n connect(pdfTextSelectionTimer, &QTimer::timeout, this, &InkCanvas::processPendingTextSelection);\n \n // Initialize PDF cache timer (will be created on-demand)\n pdfCacheTimer = nullptr;\n currentCachedPage = -1;\n \n // Initialize note page cache system\n noteCache.setMaxCost(15); // Cache up to 15 note pages (more than PDF since they're smaller)\n noteCacheTimer = nullptr;\n currentCachedNotePage = -1;\n \n // Initialize markdown manager\n markdownManager = new MarkdownWindowManager(this, this);\n \n // Connect pan/zoom signals to update markdown window positions\n connect(this, &InkCanvas::panChanged, markdownManager, &MarkdownWindowManager::updateAllWindowPositions);\n connect(this, &InkCanvas::zoomChanged, markdownManager, &MarkdownWindowManager::updateAllWindowPositions);\n}\n virtual ~InkCanvas() {\n // Cleanup if needed\n}\n void startBenchmark() {\n benchmarking = true;\n processedTimestamps.clear();\n benchmarkTimer.start();\n}\n void stopBenchmark() {\n benchmarking = false;\n}\n int getProcessedRate() {\n qint64 now = benchmarkTimer.elapsed();\n while (!processedTimestamps.empty() && now - processedTimestamps.front() > 1000) {\n processedTimestamps.pop_front();\n }\n return static_cast(processedTimestamps.size());\n}\n void setPenColor(const QColor &color) {\n penColor = color;\n}\n void setPenThickness(qreal thickness) {\n // Set thickness for the current tool\n switch (currentTool) {\n case ToolType::Pen:\n penToolThickness = thickness;\n break;\n case ToolType::Marker:\n markerToolThickness = thickness;\n break;\n case ToolType::Eraser:\n eraserToolThickness = thickness;\n break;\n }\n \n // Update the current thickness for efficient drawing\n penThickness = thickness;\n}\n void adjustAllToolThicknesses(qreal zoomRatio) {\n // Adjust thickness for all tools to maintain visual consistency\n penToolThickness *= zoomRatio;\n markerToolThickness *= zoomRatio;\n eraserToolThickness *= zoomRatio;\n \n // Update the current thickness based on the current tool\n switch (currentTool) {\n case ToolType::Pen:\n penThickness = penToolThickness;\n break;\n case ToolType::Marker:\n penThickness = markerToolThickness;\n break;\n case ToolType::Eraser:\n penThickness = eraserToolThickness;\n break;\n }\n}\n void setTool(ToolType tool) {\n currentTool = tool;\n \n // Switch to the thickness for the new tool\n switch (currentTool) {\n case ToolType::Pen:\n penThickness = penToolThickness;\n break;\n case ToolType::Marker:\n penThickness = markerToolThickness;\n break;\n case ToolType::Eraser:\n penThickness = eraserToolThickness;\n break;\n }\n}\n void setSaveFolder(const QString &folderPath) {\n saveFolder = folderPath;\n clearPdfNoDelete(); \n\n if (!saveFolder.isEmpty()) {\n QDir().mkpath(saveFolder);\n loadNotebookId(); // ✅ Load notebook ID when save folder is set\n }\n\n QString bgMetaFile = saveFolder + \"/.background_config.txt\"; // This metadata is for background styles, not to be confused with pdf directories. \n if (QFile::exists(bgMetaFile)) {\n QFile file(bgMetaFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n while (!in.atEnd()) {\n QString line = in.readLine().trimmed();\n if (line.startsWith(\"style=\")) {\n QString val = line.mid(6);\n if (val == \"Grid\") backgroundStyle = BackgroundStyle::Grid;\n else if (val == \"Lines\") backgroundStyle = BackgroundStyle::Lines;\n else backgroundStyle = BackgroundStyle::None;\n } else if (line.startsWith(\"color=\")) {\n backgroundColor = QColor(line.mid(6));\n } else if (line.startsWith(\"density=\")) {\n backgroundDensity = line.mid(8).toInt();\n }\n }\n file.close();\n }\n }\n\n // ✅ Check if the folder has a saved PDF path\n QString metadataFile = saveFolder + \"/.pdf_path.txt\";\n if (!QFile::exists(metadataFile)) {\n return;\n }\n\n\n QFile file(metadataFile);\n if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n return;\n }\n\n QTextStream in(&file);\n QString storedPdfPath = in.readLine().trimmed();\n file.close();\n\n if (storedPdfPath.isEmpty()) {\n return;\n }\n\n\n // ✅ Ensure the stored PDF file still exists before loading\n if (!QFile::exists(storedPdfPath)) {\n return;\n }\n loadPdf(storedPdfPath);\n}\n void saveToFile(int pageNumber) {\n if (saveFolder.isEmpty()) {\n return;\n }\n QString filePath = saveFolder + QString(\"/%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n\n // ✅ If no file exists and the buffer is empty, do nothing\n \n if (!edited) {\n return;\n }\n\n QImage image(buffer.size(), QImage::Format_ARGB32);\n image.fill(Qt::transparent);\n QPainter painter(&image);\n painter.drawPixmap(0, 0, buffer);\n image.save(filePath, \"PNG\");\n edited = false;\n \n // Save markdown windows for this page\n if (markdownManager) {\n markdownManager->saveWindowsForPage(pageNumber);\n }\n \n // Update note cache with the saved buffer\n noteCache.insert(pageNumber, new QPixmap(buffer));\n}\n void saveCurrentPage() {\n MainWindow *mainWin = qobject_cast(parentWidget()); // ✅ Get main window\n if (!mainWin) return;\n \n int currentPage = mainWin->getCurrentPageForCanvas(this); // ✅ Get correct page\n saveToFile(currentPage);\n}\n void loadPage(int pageNumber) {\n if (saveFolder.isEmpty()) return;\n\n // Hide any markdown windows from the previous page BEFORE loading the new page content.\n // This ensures the correct repaint area and stops the transparency timer.\n if (markdownManager) {\n markdownManager->hideAllWindows();\n }\n\n // Update current note page tracker\n currentCachedNotePage = pageNumber;\n\n // Check if note page is already cached\n bool loadedFromCache = false;\n if (noteCache.contains(pageNumber)) {\n // Use cached note page immediately\n buffer = *noteCache.object(pageNumber);\n loadedFromCache = true;\n } else {\n // Load note page from disk and cache it\n loadNotePageToCache(pageNumber);\n \n // Use the newly cached page or initialize buffer if loading failed\n if (noteCache.contains(pageNumber)) {\n buffer = *noteCache.object(pageNumber);\n loadedFromCache = true;\n } else {\n initializeBuffer(); // Clear the canvas if no file exists\n loadedFromCache = false;\n }\n }\n \n // Reset edited state when loading a new page\n edited = false;\n \n // Handle background image loading (PDF or custom background)\n if (isPdfLoaded && pdfDocument && pageNumber >= 0 && pageNumber < pdfDocument->numPages()) {\n // Use PDF as background (should already be cached by loadPdfPage)\n if (pdfCache.contains(pageNumber)) {\n backgroundImage = *pdfCache.object(pageNumber);\n \n // Resize canvas buffer to match PDF page size if needed\n if (backgroundImage.size() != buffer.size()) {\n QPixmap newBuffer(backgroundImage.size());\n newBuffer.fill(Qt::transparent);\n\n // Copy existing drawings\n QPainter painter(&newBuffer);\n painter.drawPixmap(0, 0, buffer);\n\n buffer = newBuffer;\n // Don't constrain widget size - let it expand to fill available space\n // The paintEvent will center the PDF content within the widget\n \n // Update cache with resized buffer\n noteCache.insert(pageNumber, new QPixmap(buffer));\n }\n }\n } else {\n // Handle custom background images\n QString bgFileName = saveFolder + QString(\"/bg_%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n QString metadataFile = saveFolder + QString(\"/.%1_bgsize_%2.txt\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n\n int bgWidth = 0, bgHeight = 0;\n if (QFile::exists(metadataFile)) {\n QFile file(metadataFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n in >> bgWidth >> bgHeight;\n file.close();\n }\n }\n\n if (QFile::exists(bgFileName)) {\n QImage bgImage(bgFileName);\n backgroundImage = QPixmap::fromImage(bgImage);\n\n // Resize canvas **only if background resolution is different**\n if (bgWidth > 0 && bgHeight > 0 && (bgWidth != width() || bgHeight != height())) {\n // Create a new buffer\n QPixmap newBuffer(bgWidth, bgHeight);\n newBuffer.fill(Qt::transparent);\n\n // Copy existing drawings to the new buffer\n QPainter painter(&newBuffer);\n painter.drawPixmap(0, 0, buffer);\n\n // Assign the new buffer\n buffer = newBuffer;\n setMaximumSize(bgWidth, bgHeight);\n \n // Update cache with resized buffer\n noteCache.insert(pageNumber, new QPixmap(buffer));\n }\n } else {\n backgroundImage = QPixmap(); // No background for this page\n // Only apply device pixel ratio fix if buffer was NOT loaded from cache\n // This prevents resizing cached buffers that might already be correctly sized\n if (!loadedFromCache) {\n QScreen *screen = QGuiApplication::primaryScreen();\n qreal dpr = screen ? screen->devicePixelRatio() : 1.0;\n QSize logicalSize = screen ? screen->size() : QSize(1440, 900);\n QSize expectedPixelSize = logicalSize * dpr;\n \n if (buffer.size() != expectedPixelSize) {\n // Buffer is wrong size, need to resize it properly\n QPixmap newBuffer(expectedPixelSize);\n newBuffer.fill(Qt::transparent);\n \n // Copy existing drawings if buffer was smaller\n if (!buffer.isNull()) {\n QPainter painter(&newBuffer);\n painter.drawPixmap(0, 0, buffer);\n }\n \n buffer = newBuffer;\n setMaximumSize(expectedPixelSize);\n }\n }\n }\n }\n\n // Cache adjacent note pages after delay for faster navigation\n checkAndCacheAdjacentNotePages(pageNumber);\n\n update();\n adjustSize(); // Force the widget to update its size\n parentWidget()->update();\n \n // Load markdown windows AFTER canvas is fully rendered and sized\n // Use a single-shot timer to ensure the canvas is fully updated\n QTimer::singleShot(0, this, [this, pageNumber]() {\n if (markdownManager) {\n markdownManager->loadWindowsForPage(pageNumber);\n }\n });\n}\n void deletePage(int pageNumber) {\n if (saveFolder.isEmpty()) {\n return;\n }\n QString fileName = saveFolder + QString(\"/%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n QString bgFileName = saveFolder + QString(\"/bg_%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n QString metadataFileName = saveFolder + QString(\"/.%1_bgsize_%2.txt\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n \n #ifdef Q_OS_WIN\n // Remove hidden attribute before deleting in Windows\n SetFileAttributesW(reinterpret_cast(metadataFileName.utf16()), FILE_ATTRIBUTE_NORMAL);\n #endif\n \n QFile::remove(fileName);\n QFile::remove(bgFileName);\n QFile::remove(metadataFileName);\n\n // Remove deleted page from note cache\n noteCache.remove(pageNumber);\n\n // Delete markdown windows for this page\n if (markdownManager) {\n markdownManager->deleteWindowsForPage(pageNumber);\n }\n\n if (pdfDocument){\n loadPdfPage(pageNumber);\n }\n else{\n loadPage(pageNumber);\n }\n\n}\n void setBackground(const QString &filePath, int pageNumber) {\n if (saveFolder.isEmpty()) {\n return; // No save folder set\n }\n\n // Construct full path inside save folder\n QString bgFileName = saveFolder + QString(\"/bg_%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n\n // Copy the file to the save folder\n QFile::copy(filePath, bgFileName);\n\n // Load the background image\n QImage bgImage(bgFileName);\n\n if (!bgImage.isNull()) {\n // Save background resolution in metadata file\n QString metadataFile = saveFolder + QString(\"/.%1_bgsize_%2.txt\")\n .arg(notebookId)\n .arg(pageNumber, 5, 10, QChar('0'));\n QFile file(metadataFile);\n if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {\n QTextStream out(&file);\n out << bgImage.width() << \" \" << bgImage.height();\n file.close();\n }\n\n #ifdef Q_OS_WIN\n // Set hidden attribute for metadata on Windows\n SetFileAttributesW(reinterpret_cast(metadataFile.utf16()), FILE_ATTRIBUTE_HIDDEN);\n #endif \n\n // Only resize if the background size is different\n if (bgImage.width() != width() || bgImage.height() != height()) {\n // Create a new buffer with the new size\n QPixmap newBuffer(bgImage.width(), bgImage.height());\n newBuffer.fill(Qt::transparent);\n\n // Copy existing drawings\n QPainter painter(&newBuffer);\n painter.drawPixmap(0, 0, buffer);\n\n // Assign new buffer and update canvas size\n buffer = newBuffer;\n setMaximumSize(bgImage.width(), bgImage.height());\n }\n\n backgroundImage = QPixmap::fromImage(bgImage);\n \n update();\n adjustSize();\n parentWidget()->update();\n }\n\n update(); // Refresh canvas\n}\n void saveAnnotated(int pageNumber) {\n if (saveFolder.isEmpty()) return;\n\n QString filePath = saveFolder + QString(\"/annotated_%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n\n // Use the buffer size to ensure correct resolution\n QImage image(buffer.size(), QImage::Format_ARGB32);\n image.fill(Qt::transparent);\n QPainter painter(&image);\n \n if (!backgroundImage.isNull()) {\n painter.drawPixmap(0, 0, backgroundImage.scaled(buffer.size(), Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation));\n }\n \n painter.drawPixmap(0, 0, buffer);\n image.save(filePath, \"PNG\");\n}\n void setZoom(int zoomLevel) {\n int newZoom = qMax(10, qMin(zoomLevel, 400)); // Limit zoom to 10%-400%\n if (zoomFactor != newZoom) {\n zoomFactor = newZoom;\n internalZoomFactor = zoomFactor; // Sync internal zoom\n update();\n emit zoomChanged(zoomFactor);\n }\n}\n int getZoom() const {\n return zoomFactor;\n}\n void updatePanOffsets(int xOffset, int yOffset) {\n panOffsetX = xOffset;\n panOffsetY = yOffset;\n update();\n}\n int getPanOffsetX() const {\n return panOffsetX;\n}\n int getPanOffsetY() const {\n return panOffsetY;\n}\n void setPanX(int xOffset) {\n if (panOffsetX != value) {\n panOffsetX = value;\n update();\n emit panChanged(panOffsetX, panOffsetY);\n }\n}\n void setPanY(int yOffset) {\n if (panOffsetY != value) {\n panOffsetY = value;\n update();\n emit panChanged(panOffsetX, panOffsetY);\n }\n}\n void loadPdf(const QString &pdfPath) {\n pdfDocument = Poppler::Document::load(pdfPath);\n if (pdfDocument && !pdfDocument->isLocked()) {\n // Enable anti-aliasing rendering hints for better text quality\n pdfDocument->setRenderHint(Poppler::Document::Antialiasing, true);\n pdfDocument->setRenderHint(Poppler::Document::TextAntialiasing, true);\n pdfDocument->setRenderHint(Poppler::Document::TextHinting, true);\n pdfDocument->setRenderHint(Poppler::Document::TextSlightHinting, true);\n \n totalPdfPages = pdfDocument->numPages();\n isPdfLoaded = true;\n totalPdfPages = pdfDocument->numPages();\n loadPdfPage(0); // Load first page\n // ✅ Save the PDF path in the metadata file\n if (!saveFolder.isEmpty()) {\n QString metadataFile = saveFolder + \"/.pdf_path.txt\";\n QFile file(metadataFile);\n if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {\n QTextStream out(&file);\n out << pdfPath; // Store the absolute path of the PDF\n file.close();\n }\n }\n // Emit signal that PDF was loaded\n emit pdfLoaded();\n }\n}\n void loadPdfPage(int pageNumber) {\n if (!pdfDocument) return;\n\n // Update current page tracker\n currentCachedPage = pageNumber;\n\n // Check if target page is already cached\n if (pdfCache.contains(pageNumber)) {\n // Display the cached page immediately\n backgroundImage = *pdfCache.object(pageNumber);\n loadPage(pageNumber); // Load annotations\n loadPdfTextBoxes(pageNumber); // Load text boxes for PDF text selection\n update();\n \n // Check and cache adjacent pages after delay\n checkAndCacheAdjacentPages(pageNumber);\n return;\n }\n\n // Target page not in cache - render it immediately\n renderPdfPageToCache(pageNumber);\n \n // Display the newly rendered page\n if (pdfCache.contains(pageNumber)) {\n backgroundImage = *pdfCache.object(pageNumber);\n } else {\n backgroundImage = QPixmap(); // Clear background if rendering failed\n }\n \n loadPage(pageNumber); // Load existing canvas annotations\n loadPdfTextBoxes(pageNumber); // Load text boxes for PDF text selection\n update();\n \n // Cache adjacent pages after delay\n checkAndCacheAdjacentPages(pageNumber);\n}\n bool isPdfLoadedFunc() const {\n return isPdfLoaded;\n}\n int getTotalPdfPages() const {\n return totalPdfPages;\n}\n Poppler::Document* getPdfDocument() const;\n void clearPdf() {\n pdfDocument.reset();\n pdfDocument = nullptr;\n isPdfLoaded = false;\n totalPdfPages = 0;\n pdfCache.clear();\n \n // Reset cache system state\n currentCachedPage = -1;\n if (pdfCacheTimer && pdfCacheTimer->isActive()) {\n pdfCacheTimer->stop();\n }\n \n // Cancel and clean up any active PDF watchers\n for (QFutureWatcher* watcher : activePdfWatchers) {\n if (watcher && !watcher->isFinished()) {\n watcher->cancel();\n }\n watcher->deleteLater();\n }\n activePdfWatchers.clear();\n\n // ✅ Remove the PDF path file when clearing the PDF\n if (!saveFolder.isEmpty()) {\n QString metadataFile = saveFolder + \"/.pdf_path.txt\";\n QFile::remove(metadataFile);\n }\n}\n void clearPdfNoDelete() {\n pdfDocument.reset();\n pdfDocument = nullptr;\n isPdfLoaded = false;\n totalPdfPages = 0;\n pdfCache.clear();\n \n // Reset cache system state\n currentCachedPage = -1;\n if (pdfCacheTimer && pdfCacheTimer->isActive()) {\n pdfCacheTimer->stop();\n }\n \n // Cancel and clean up any active PDF watchers\n for (QFutureWatcher* watcher : activePdfWatchers) {\n if (watcher && !watcher->isFinished()) {\n watcher->cancel();\n }\n watcher->deleteLater();\n }\n activePdfWatchers.clear();\n}\n QString getSaveFolder() const {\n return saveFolder;\n}\n QColor getPenColor() {\n return penColor;\n}\n qreal getPenThickness() {\n return penThickness;\n}\n ToolType getCurrentTool() {\n return currentTool;\n}\n void loadPdfPreviewAsync(int pageNumber) {\n if (!pdfDocument || pageNumber < 0 || pageNumber >= pdfDocument->numPages()) return;\n\n QFutureWatcher *watcher = new QFutureWatcher(this);\n\n connect(watcher, &QFutureWatcher::finished, this, [this, watcher]() {\n QPixmap result = watcher->result();\n if (!result.isNull()) {\n backgroundImage = result;\n update(); // trigger repaint\n }\n watcher->deleteLater(); // Clean up\n });\n\n QFuture future = QtConcurrent::run([=]() -> QPixmap {\n std::unique_ptr page(pdfDocument->page(pageNumber));\n if (!page) return QPixmap();\n\n // Render with document-level anti-aliasing settings\n QImage pdfImage = page->renderToImage(96, 96);\n if (pdfImage.isNull()) return QPixmap();\n\n QImage upscaled = pdfImage.scaled(pdfImage.width() * (pdfRenderDPI / 96),\n pdfImage.height() * (pdfRenderDPI / 96),\n Qt::KeepAspectRatio,\n Qt::SmoothTransformation);\n\n return QPixmap::fromImage(upscaled);\n });\n\n watcher->setFuture(future);\n}\n void setBackgroundStyle(BackgroundStyle style) {\n backgroundStyle = style;\n update(); // Trigger repaint\n}\n void setBackgroundColor(const QColor &color) {\n backgroundColor = color;\n update();\n}\n void setBackgroundDensity(int density) {\n backgroundDensity = density;\n update();\n}\n void saveBackgroundMetadata() {\n if (saveFolder.isEmpty()) return;\n\n QString bgMetaFile = saveFolder + \"/.background_config.txt\";\n QFile file(bgMetaFile);\n if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {\n QTextStream out(&file);\n QString styleStr = \"None\";\n if (backgroundStyle == BackgroundStyle::Grid) styleStr = \"Grid\";\n else if (backgroundStyle == BackgroundStyle::Lines) styleStr = \"Lines\";\n\n out << \"style=\" << styleStr << \"\\n\";\n out << \"color=\" << backgroundColor.name().toUpper() << \"\\n\";\n out << \"density=\" << backgroundDensity << \"\\n\";\n file.close();\n }\n}\n void exportNotebook(const QString &destinationFile) {\n if (destinationFile.isEmpty()) {\n QMessageBox::warning(nullptr, tr(\"Export Error\"), tr(\"No export file specified.\"));\n return;\n }\n\n if (saveFolder.isEmpty()) {\n QMessageBox::warning(nullptr, tr(\"Export Error\"), tr(\"No notebook loaded (saveFolder is empty)\"));\n return;\n }\n\n QStringList files;\n\n // Collect all files from saveFolder\n QDir dir(saveFolder);\n QDirIterator it(saveFolder, QDir::Files, QDirIterator::Subdirectories);\n while (it.hasNext()) {\n QString filePath = it.next();\n QString relativePath = dir.relativeFilePath(filePath);\n files << relativePath;\n }\n\n if (files.isEmpty()) {\n QMessageBox::warning(nullptr, tr(\"Export Error\"), tr(\"No files found to export.\"));\n return;\n }\n\n // Generate temporary file list\n QString tempFileList = saveFolder + \"/filelist.txt\";\n QFile listFile(tempFileList);\n if (listFile.open(QIODevice::WriteOnly | QIODevice::Text)) {\n QTextStream out(&listFile);\n for (const QString &file : files) {\n out << file << \"\\n\";\n }\n listFile.close();\n } else {\n QMessageBox::warning(nullptr, tr(\"Export Error\"), tr(\"Failed to create temporary file list.\"));\n return;\n }\n\n#ifdef _WIN32\n QString tarExe = QCoreApplication::applicationDirPath() + \"/bsdtar.exe\";\n#else\n QString tarExe = \"tar\";\n#endif\n\n QStringList args;\n args << \"-cf\" << QDir::toNativeSeparators(destinationFile);\n\n for (const QString &file : files) {\n args << QDir::toNativeSeparators(file);\n }\n\n QProcess process;\n process.setWorkingDirectory(saveFolder);\n\n process.start(tarExe, args);\n if (!process.waitForFinished()) {\n QMessageBox::warning(nullptr, tr(\"Export Error\"), tr(\"Tar process failed to finish.\"));\n QFile::remove(tempFileList);\n return;\n }\n\n QFile::remove(tempFileList);\n\n if (process.exitStatus() != QProcess::NormalExit || process.exitCode() != 0) {\n QMessageBox::warning(nullptr, tr(\"Export Error\"), tr(\"Tar process failed.\"));\n return;\n }\n\n QMessageBox::information(nullptr, tr(\"Export\"), tr(\"Notebook exported successfully.\"));\n}\n void importNotebook(const QString &packageFile) {\n\n // Ask user for destination working folder\n QString destFolder = QFileDialog::getExistingDirectory(nullptr, tr(\"Select Destination Folder for Imported Notebook\"));\n\n if (destFolder.isEmpty()) {\n QMessageBox::warning(nullptr, tr(\"Import Canceled\"), tr(\"No destination folder selected.\"));\n return;\n }\n\n // Check if destination folder is empty (optional, good practice)\n QDir destDir(destFolder);\n if (!destDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot).isEmpty()) {\n QMessageBox::StandardButton reply = QMessageBox::question(nullptr, tr(\"Destination Not Empty\"),\n tr(\"The selected folder is not empty. Files may be overwritten. Continue?\"),\n QMessageBox::Yes | QMessageBox::No);\n if (reply != QMessageBox::Yes) {\n return;\n }\n }\n\n#ifdef _WIN32\n QString tarExe = QCoreApplication::applicationDirPath() + \"/bsdtar.exe\";\n#else\n QString tarExe = \"tar\";\n#endif\n\n // Extract package\n QStringList args;\n args << \"-xf\" << packageFile;\n\n QProcess process;\n process.setWorkingDirectory(destFolder);\n process.start(tarExe, args);\n process.waitForFinished();\n\n // Switch notebook folder\n setSaveFolder(destFolder);\n loadPage(0);\n\n QMessageBox::information(nullptr, tr(\"Import Complete\"), tr(\"Notebook imported successfully.\"));\n}\n void importNotebookTo(const QString &packageFile, const QString &destFolder) {\n\n #ifdef _WIN32\n QString tarExe = QCoreApplication::applicationDirPath() + \"/bsdtar.exe\";\n #else\n QString tarExe = \"tar\";\n #endif\n \n QStringList args;\n args << \"-xf\" << packageFile;\n \n QProcess process;\n process.setWorkingDirectory(destFolder);\n process.start(tarExe, args);\n process.waitForFinished();\n \n setSaveFolder(destFolder);\n loadNotebookId();\n loadPage(0);\n\n QMessageBox::information(nullptr, tr(\"Import\"), tr(\"Notebook imported successfully.\"));\n }\n void deleteRopeSelection() {\n if (!selectionBuffer.isNull() && !selectionRect.isEmpty()) {\n // If the selection area hasn't been cleared from the buffer yet, clear it now for deletion\n if (!selectionAreaCleared && !selectionMaskPath.isEmpty()) {\n QPainter painter(&buffer);\n painter.setCompositionMode(QPainter::CompositionMode_Clear);\n painter.fillPath(selectionMaskPath, Qt::transparent);\n painter.end();\n }\n \n // Clear the selection state\n selectionBuffer = QPixmap();\n selectionRect = QRect();\n exactSelectionRectF = QRectF();\n movingSelection = false;\n selectingWithRope = false;\n selectionJustCopied = false;\n selectionAreaCleared = false;\n selectionMaskPath = QPainterPath();\n selectionBufferRect = QRectF();\n \n // Mark as edited since we deleted content\n if (!edited) {\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n \n // Update the entire canvas to remove selection visuals\n update();\n }\n}\n void cancelRopeSelection() {\n if (!selectionBuffer.isNull() && !selectionRect.isEmpty()) {\n // Paste the selection back to its current location (where user moved it)\n QPainter painter(&buffer);\n // Explicitly set composition mode to draw on top of existing content\n painter.setCompositionMode(QPainter::CompositionMode_SourceOver);\n // Use the current selection position\n QPointF currentTopLeft = exactSelectionRectF.isEmpty() ? selectionRect.topLeft() : exactSelectionRectF.topLeft();\n QPointF bufferDest = mapLogicalWidgetToPhysicalBuffer(currentTopLeft);\n painter.drawPixmap(bufferDest.toPoint(), selectionBuffer);\n painter.end();\n \n // Store selection buffer size for update calculation before clearing it\n QSize selectionSize = selectionBuffer.size();\n QRect updateRect = QRect(currentTopLeft.toPoint(), selectionSize);\n \n // Clear the selection state\n selectionBuffer = QPixmap();\n selectionRect = QRect();\n exactSelectionRectF = QRectF();\n movingSelection = false;\n selectingWithRope = false;\n selectionJustCopied = false;\n selectionAreaCleared = false;\n selectionMaskPath = QPainterPath();\n selectionBufferRect = QRectF();\n \n // Update the restored area\n update(updateRect.adjusted(-5, -5, 5, 5));\n }\n}\n void copyRopeSelection() {\n if (!selectionBuffer.isNull() && !selectionRect.isEmpty()) {\n // Get current selection position\n QPointF currentTopLeft = exactSelectionRectF.isEmpty() ? selectionRect.topLeft() : exactSelectionRectF.topLeft();\n \n // Calculate new position (right next to the original), but ensure it stays within canvas bounds\n QPointF newTopLeft = currentTopLeft + QPointF(selectionRect.width() + 5, 0); // 5 pixels gap\n \n // Check if the new position would extend beyond buffer boundaries and adjust if needed\n QPointF currentBufferDest = mapLogicalWidgetToPhysicalBuffer(currentTopLeft);\n QPointF newBufferDest = mapLogicalWidgetToPhysicalBuffer(newTopLeft);\n \n // Ensure the copy stays within buffer bounds\n if (newBufferDest.x() + selectionBuffer.width() > buffer.width()) {\n // If it would extend beyond right edge, place it to the left of the original\n newTopLeft = currentTopLeft - QPointF(selectionRect.width() + 5, 0);\n newBufferDest = mapLogicalWidgetToPhysicalBuffer(newTopLeft);\n \n // If it still doesn't fit on the left, place it below the original\n if (newBufferDest.x() < 0) {\n newTopLeft = currentTopLeft + QPointF(0, selectionRect.height() + 5);\n newBufferDest = mapLogicalWidgetToPhysicalBuffer(newTopLeft);\n \n // If it doesn't fit below either, place it above\n if (newBufferDest.y() + selectionBuffer.height() > buffer.height()) {\n newTopLeft = currentTopLeft - QPointF(0, selectionRect.height() + 5);\n newBufferDest = mapLogicalWidgetToPhysicalBuffer(newTopLeft);\n \n // If none of the positions work, just offset slightly and let it extend\n if (newBufferDest.y() < 0) {\n newTopLeft = currentTopLeft + QPointF(10, 10);\n newBufferDest = mapLogicalWidgetToPhysicalBuffer(newTopLeft);\n }\n }\n }\n }\n if (newBufferDest.y() + selectionBuffer.height() > buffer.height()) {\n // If it would extend beyond bottom edge, place it above the original\n newTopLeft = currentTopLeft - QPointF(0, selectionRect.height() + 5);\n newBufferDest = mapLogicalWidgetToPhysicalBuffer(newTopLeft);\n }\n \n // First, paste the selection back to its current location to restore the original\n QPainter painter(&buffer);\n // Explicitly set composition mode to draw on top of existing content\n painter.setCompositionMode(QPainter::CompositionMode_SourceOver);\n painter.drawPixmap(currentBufferDest.toPoint(), selectionBuffer);\n \n // Then, paste the copy to the new location\n // We need to handle the case where the copy extends beyond buffer boundaries\n QRect targetRect(newBufferDest.toPoint(), selectionBuffer.size());\n QRect bufferBounds(0, 0, buffer.width(), buffer.height());\n QRect clippedRect = targetRect.intersected(bufferBounds);\n \n if (!clippedRect.isEmpty()) {\n // Calculate which part of the selectionBuffer to draw\n QRect sourceRect = QRect(\n clippedRect.x() - targetRect.x(),\n clippedRect.y() - targetRect.y(),\n clippedRect.width(),\n clippedRect.height()\n );\n \n painter.drawPixmap(clippedRect, selectionBuffer, sourceRect);\n }\n \n // For the selection buffer, we keep the FULL content, even if parts extend beyond canvas\n // This way when the user drags it back, the full content is preserved\n QPixmap newSelectionBuffer = selectionBuffer; // Keep the full original content\n \n // DON'T clear the copied area immediately - leave both original and copy on the canvas\n // The copy will only be cleared when the user actually starts moving the selection\n // This way, if the user cancels without moving, both original and copy remain permanently\n painter.end();\n \n // Update the selection buffer and position\n selectionBuffer = newSelectionBuffer;\n selectionRect = QRect(newTopLeft.toPoint(), selectionRect.size());\n exactSelectionRectF = QRectF(newTopLeft, selectionRect.size());\n selectionJustCopied = true; // Mark that this selection was just copied\n \n // Mark as edited since we added content\n if (!edited) {\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n \n // Update the entire affected area (original + copy + gap)\n QRect updateArea = QRect(currentTopLeft.toPoint(), selectionRect.size())\n .united(selectionRect)\n .adjusted(-10, -10, 10, 10);\n update(updateArea);\n }\n}\n void setMarkdownSelectionMode(bool enabled) {\n markdownSelectionMode = enabled;\n \n if (markdownManager) {\n markdownManager->setSelectionMode(enabled);\n }\n \n if (!enabled) {\n markdownSelecting = false;\n }\n \n // Update cursor\n setCursor(enabled ? Qt::CrossCursor : Qt::ArrowCursor);\n \n // Notify signal\n emit markdownSelectionModeChanged(enabled);\n}\n bool isMarkdownSelectionMode() const {\n return markdownSelectionMode;\n}\n void clearPdfTextSelection() {\n // Clear selection state\n selectedTextBoxes.clear();\n pdfTextSelecting = false;\n \n // Cancel any pending throttled updates\n if (pdfTextSelectionTimer && pdfTextSelectionTimer->isActive()) {\n pdfTextSelectionTimer->stop();\n }\n hasPendingSelection = false;\n \n // Refresh display\n update();\n}\n QString getSelectedPdfText() const {\n if (selectedTextBoxes.isEmpty()) {\n return QString();\n }\n \n // Pre-allocate string with estimated size for efficiency\n QString selectedText;\n selectedText.reserve(selectedTextBoxes.size() * 20); // Estimate ~20 chars per text box\n \n // Build text with space separators\n for (const Poppler::TextBox* textBox : selectedTextBoxes) {\n if (textBox && !textBox->text().isEmpty()) {\n if (!selectedText.isEmpty()) {\n selectedText += \" \";\n }\n selectedText += textBox->text();\n }\n }\n \n return selectedText;\n}\n QPointF mapWidgetToCanvas(const QPointF &widgetPoint) const {\n QPointF topLeft = mapWidgetToCanvas(widgetRect.topLeft());\n QPointF bottomRight = mapWidgetToCanvas(widgetRect.bottomRight());\n \n return QRect(topLeft.toPoint(), bottomRight.toPoint());\n}\n QPointF mapCanvasToWidget(const QPointF &canvasPoint) const {\n QPointF topLeft = mapCanvasToWidget(canvasRect.topLeft());\n QPointF bottomRight = mapCanvasToWidget(canvasRect.bottomRight());\n \n return QRect(topLeft.toPoint(), bottomRight.toPoint());\n}\n QRect mapWidgetToCanvas(const QRect &widgetRect) const {\n QPointF topLeft = mapWidgetToCanvas(widgetRect.topLeft());\n QPointF bottomRight = mapWidgetToCanvas(widgetRect.bottomRight());\n \n return QRect(topLeft.toPoint(), bottomRight.toPoint());\n}\n QRect mapCanvasToWidget(const QRect &canvasRect) const {\n QPointF topLeft = mapCanvasToWidget(canvasRect.topLeft());\n QPointF bottomRight = mapCanvasToWidget(canvasRect.bottomRight());\n \n return QRect(topLeft.toPoint(), bottomRight.toPoint());\n}\n protected:\n void paintEvent(QPaintEvent *event) override {\n QPainter painter(this);\n \n // Save the painter state before transformations\n painter.save();\n \n // Calculate the scaled canvas size\n qreal scaledCanvasWidth = buffer.width() * (internalZoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (internalZoomFactor / 100.0);\n \n // Calculate centering offsets\n qreal centerOffsetX = 0;\n qreal centerOffsetY = 0;\n \n // Center horizontally if canvas is smaller than widget\n if (scaledCanvasWidth < width()) {\n centerOffsetX = (width() - scaledCanvasWidth) / 2.0;\n }\n \n // Center vertically if canvas is smaller than widget\n if (scaledCanvasHeight < height()) {\n centerOffsetY = (height() - scaledCanvasHeight) / 2.0;\n }\n \n // Apply centering offset first\n painter.translate(centerOffsetX, centerOffsetY);\n \n // Use internal zoom factor for smoother animation\n painter.scale(internalZoomFactor / 100.0, internalZoomFactor / 100.0);\n\n // Pan offset needs to be reversed because painter works in transformed coordinates\n painter.translate(-panOffsetX, -panOffsetY);\n\n // Set clipping rectangle to canvas bounds to prevent painting outside\n painter.setClipRect(0, 0, buffer.width(), buffer.height());\n\n // 🟨 Notebook-style background rendering\n if (backgroundImage.isNull()) {\n painter.save();\n \n // Always apply background color regardless of style\n painter.fillRect(QRectF(0, 0, buffer.width(), buffer.height()), backgroundColor);\n\n // Only draw grid/lines if not \"None\" style\n if (backgroundStyle != BackgroundStyle::None) {\n QPen linePen(QColor(100, 100, 100, 100)); // Subtle gray lines\n linePen.setWidthF(1.0);\n painter.setPen(linePen);\n\n qreal scaledDensity = backgroundDensity;\n\n if (devicePixelRatioF() > 1.0)\n scaledDensity *= devicePixelRatioF(); // Optional DPI handling\n\n if (backgroundStyle == BackgroundStyle::Lines || backgroundStyle == BackgroundStyle::Grid) {\n for (int y = 0; y < buffer.height(); y += scaledDensity)\n painter.drawLine(0, y, buffer.width(), y);\n }\n if (backgroundStyle == BackgroundStyle::Grid) {\n for (int x = 0; x < buffer.width(); x += scaledDensity)\n painter.drawLine(x, 0, x, buffer.height());\n }\n }\n\n painter.restore();\n }\n\n // ✅ Draw loaded image or PDF background if available\n if (!backgroundImage.isNull()) {\n painter.drawPixmap(0, 0, backgroundImage);\n }\n\n // ✅ Draw user's strokes from the buffer (transparent overlay)\n painter.drawPixmap(0, 0, buffer);\n \n // Draw straight line preview if in straight line mode and drawing\n // Skip preview for eraser tool\n if (straightLineMode && drawing && currentTool != ToolType::Eraser) {\n // Save the current state before applying the eraser mode\n painter.save();\n \n // Store current pressure - ensure minimum is 0.5 for consistent preview\n qreal pressure = qMax(0.5, painter.device()->devicePixelRatioF() > 1.0 ? 0.8 : 1.0);\n \n // Set up the pen based on tool type\n if (currentTool == ToolType::Marker) {\n qreal thickness = penThickness * 8.0;\n QColor markerColor = penColor;\n // Increase alpha for better visibility in straight line mode\n // Using a higher value (80) instead of the regular 4 to compensate for single-pass drawing\n markerColor.setAlpha(80);\n QPen pen(markerColor, thickness, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);\n painter.setPen(pen);\n } else { // Default Pen\n // Match the exact same thickness calculation as in drawStroke\n qreal scaledThickness = penThickness * pressure;\n QPen pen(penColor, scaledThickness, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);\n painter.setPen(pen);\n }\n \n // Use the same coordinate transformation logic as in drawStroke\n // to ensure the preview line appears at the exact same position\n QPointF bufferStart, bufferEnd;\n \n // Convert screen coordinates to buffer coordinates using the same calculations as drawStroke\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n QPointF adjustedStart = straightLineStartPoint - QPointF(centerOffsetX, centerOffsetY);\n QPointF adjustedEnd = lastPoint - QPointF(centerOffsetX, centerOffsetY);\n \n bufferStart = (adjustedStart / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n bufferEnd = (adjustedEnd / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n \n // Draw the preview line using the same coordinates that will be used for the final line\n painter.drawLine(bufferStart, bufferEnd);\n \n // Restore the original painter state\n painter.restore();\n }\n\n // Draw selection rectangle if in rope tool mode and selecting, moving, or has a selection\n if (ropeToolMode && (selectingWithRope || movingSelection || (!selectionBuffer.isNull() && !selectionRect.isEmpty()))) {\n painter.save(); // Save painter state for overlays\n painter.resetTransform(); // Reset transform to draw directly in logical widget coordinates\n \n if (selectingWithRope && !lassoPathPoints.isEmpty()) {\n QPen selectionPen(Qt::DashLine);\n selectionPen.setColor(Qt::blue);\n selectionPen.setWidthF(1.5); // Width in logical pixels\n painter.setPen(selectionPen);\n painter.drawPolygon(lassoPathPoints); // lassoPathPoints are logical widget coordinates\n } else if (!selectionBuffer.isNull() && !selectionRect.isEmpty()) {\n // selectionRect is in logical widget coordinates.\n // selectionBuffer is in buffer coordinates, we need to handle scaling correctly\n QPixmap scaledBuffer = selectionBuffer;\n \n // Calculate the current zoom factor\n qreal currentZoom = internalZoomFactor / 100.0;\n \n // Scale the selection buffer to match the current zoom level\n if (currentZoom != 1.0) {\n QSize scaledSize = QSize(\n qRound(scaledBuffer.width() * currentZoom),\n qRound(scaledBuffer.height() * currentZoom)\n );\n scaledBuffer = scaledBuffer.scaled(scaledSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);\n }\n \n // Draw it at the logical position\n // Use exactSelectionRectF for smoother movement if available\n QPointF topLeft = exactSelectionRectF.isEmpty() ? selectionRect.topLeft() : exactSelectionRectF.topLeft();\n painter.drawPixmap(topLeft, scaledBuffer);\n\n QPen selectionBorderPen(Qt::DashLine);\n selectionBorderPen.setColor(Qt::darkCyan);\n selectionBorderPen.setWidthF(1.5); // Width in logical pixels\n painter.setPen(selectionBorderPen);\n \n // Use exactSelectionRectF for drawing the selection border if available\n if (!exactSelectionRectF.isEmpty()) {\n painter.drawRect(exactSelectionRectF);\n } else {\n painter.drawRect(selectionRect);\n }\n }\n painter.restore(); // Restore painter state to what it was for drawing the main buffer\n }\n \n\n \n\n \n // Restore the painter state\n painter.restore();\n \n // Fill the area outside the canvas with the widget's background color\n QRect widgetRect = rect();\n QRectF canvasRect(\n centerOffsetX - panOffsetX * (internalZoomFactor / 100.0),\n centerOffsetY - panOffsetY * (internalZoomFactor / 100.0),\n buffer.width() * (internalZoomFactor / 100.0),\n buffer.height() * (internalZoomFactor / 100.0)\n );\n \n // Create regions for areas outside the canvas\n QRegion outsideRegion(widgetRect);\n outsideRegion -= QRegion(canvasRect.toRect());\n \n // Fill the outside region with the background color\n painter.setClipRegion(outsideRegion);\n painter.fillRect(widgetRect, palette().window().color());\n \n // Reset clipping for overlay elements that should appear on top\n painter.setClipping(false);\n \n // Draw markdown selection overlay\n if (markdownSelectionMode && markdownSelecting) {\n painter.save();\n QPen selectionPen(Qt::DashLine);\n selectionPen.setColor(Qt::green);\n selectionPen.setWidthF(2.0);\n painter.setPen(selectionPen);\n \n QBrush selectionBrush(QColor(0, 255, 0, 30)); // Semi-transparent green\n painter.setBrush(selectionBrush);\n \n QRect selectionRect = QRect(markdownSelectionStart, markdownSelectionEnd).normalized();\n painter.drawRect(selectionRect);\n painter.restore();\n }\n \n // Draw PDF text selection overlay on top of everything\n if (pdfTextSelectionEnabled && isPdfLoaded) {\n painter.save(); // Save painter state for PDF text overlay\n painter.resetTransform(); // Reset transform to draw directly in logical widget coordinates\n \n // Draw selection rectangle if actively selecting\n if (pdfTextSelecting) {\n QPen selectionPen(Qt::DashLine);\n selectionPen.setColor(QColor(0, 120, 215)); // Blue selection rectangle\n selectionPen.setWidthF(2.0); // Make it more visible\n painter.setPen(selectionPen);\n \n QBrush selectionBrush(QColor(0, 120, 215, 30)); // Semi-transparent blue fill\n painter.setBrush(selectionBrush);\n \n QRectF selectionRect(pdfSelectionStart, pdfSelectionEnd);\n selectionRect = selectionRect.normalized();\n painter.drawRect(selectionRect);\n }\n \n // Draw highlights for selected text boxes\n if (!selectedTextBoxes.isEmpty()) {\n QColor highlightColor = QColor(255, 255, 0, 100); // Semi-transparent yellow\n painter.setBrush(highlightColor);\n painter.setPen(Qt::NoPen);\n \n // Draw highlight rectangles for selected text boxes\n for (const Poppler::TextBox* textBox : selectedTextBoxes) {\n if (textBox) {\n // Convert PDF coordinates to widget coordinates\n QRectF pdfRect = textBox->boundingBox();\n QPointF topLeft = mapPdfToWidgetCoordinates(pdfRect.topLeft());\n QPointF bottomRight = mapPdfToWidgetCoordinates(pdfRect.bottomRight());\n QRectF widgetRect(topLeft, bottomRight);\n widgetRect = widgetRect.normalized();\n \n painter.drawRect(widgetRect);\n }\n }\n }\n \n painter.restore(); // Restore painter state\n }\n}\n void tabletEvent(QTabletEvent *event) override {\n // ✅ PRIORITY: Handle PDF text selection with stylus when enabled\n // This redirects stylus input to text selection instead of drawing\n if (pdfTextSelectionEnabled && isPdfLoaded) {\n if (event->type() == QEvent::TabletPress) {\n pdfTextSelecting = true;\n pdfSelectionStart = event->position();\n pdfSelectionEnd = pdfSelectionStart;\n \n // Clear any existing selected text boxes without resetting pdfTextSelecting\n selectedTextBoxes.clear();\n \n setCursor(Qt::IBeamCursor); // Ensure cursor is correct\n update(); // Refresh display\n event->accept();\n return;\n } else if (event->type() == QEvent::TabletMove && pdfTextSelecting) {\n pdfSelectionEnd = event->position();\n \n // Store pending selection for throttled processing (60 FPS throttling)\n pendingSelectionStart = pdfSelectionStart;\n pendingSelectionEnd = pdfSelectionEnd;\n hasPendingSelection = true;\n \n // Start timer if not already running (throttled to 60 FPS)\n if (!pdfTextSelectionTimer->isActive()) {\n pdfTextSelectionTimer->start();\n }\n \n // NOTE: No direct update() call here - let the timer handle updates at 60 FPS\n event->accept();\n return;\n } else if (event->type() == QEvent::TabletRelease && pdfTextSelecting) {\n pdfSelectionEnd = event->position();\n \n // Process any pending selection immediately on release\n if (pdfTextSelectionTimer && pdfTextSelectionTimer->isActive()) {\n pdfTextSelectionTimer->stop();\n if (hasPendingSelection) {\n updatePdfTextSelection(pendingSelectionStart, pendingSelectionEnd);\n hasPendingSelection = false;\n }\n } else {\n // Update selection with final position\n updatePdfTextSelection(pdfSelectionStart, pdfSelectionEnd);\n }\n \n pdfTextSelecting = false;\n \n // Check for link clicks if no text was selected\n QString selectedText = getSelectedPdfText();\n if (selectedText.isEmpty()) {\n handlePdfLinkClick(event->position());\n } else {\n // Show context menu for text selection\n QPoint globalPos = mapToGlobal(event->position().toPoint());\n showPdfTextSelectionMenu(globalPos);\n }\n \n event->accept();\n return;\n }\n }\n \n // ✅ NORMAL STYLUS BEHAVIOR: Only reached when PDF text selection is OFF\n // Hardware eraser detection\n static bool hardwareEraserActive = false;\n bool wasUsingHardwareEraser = false;\n \n // Track hardware eraser state\n if (event->pointerType() == QPointingDevice::PointerType::Eraser) {\n // Hardware eraser is being used\n wasUsingHardwareEraser = true;\n \n if (event->type() == QEvent::TabletPress) {\n // Start of eraser stroke - save current tool and switch to eraser\n hardwareEraserActive = true;\n previousTool = currentTool;\n currentTool = ToolType::Eraser;\n }\n }\n \n // Maintain hardware eraser state across move events\n if (hardwareEraserActive && event->type() != QEvent::TabletRelease) {\n wasUsingHardwareEraser = true;\n }\n\n // Determine if we're in eraser mode (either hardware eraser or tool set to eraser)\n bool isErasing = (currentTool == ToolType::Eraser);\n\n if (event->type() == QEvent::TabletPress) {\n drawing = true;\n lastPoint = event->posF(); // Logical widget coordinates\n if (straightLineMode) {\n straightLineStartPoint = lastPoint;\n }\n if (ropeToolMode) {\n if (!selectionBuffer.isNull() && selectionRect.contains(lastPoint.toPoint())) {\n // Start moving an existing selection (or continue if already moving)\n movingSelection = true;\n selectingWithRope = false;\n lastMovePoint = lastPoint;\n // Initialize the exact floating-point rect if it's empty\n if (exactSelectionRectF.isEmpty()) {\n exactSelectionRectF = QRectF(selectionRect);\n }\n \n // If this selection was just copied, clear the area now that user is moving it\n if (selectionJustCopied) {\n QPainter painter(&buffer);\n painter.setCompositionMode(QPainter::CompositionMode_Clear);\n QPointF bufferDest = mapLogicalWidgetToPhysicalBuffer(selectionRect.topLeft());\n QRect clearRect(bufferDest.toPoint(), selectionBuffer.size());\n // Only clear the part that's within buffer bounds\n QRect bufferBounds(0, 0, buffer.width(), buffer.height());\n QRect clippedClearRect = clearRect.intersected(bufferBounds);\n if (!clippedClearRect.isEmpty()) {\n painter.fillRect(clippedClearRect, Qt::transparent);\n }\n painter.end();\n selectionJustCopied = false; // Clear the flag\n }\n \n // If the selection area hasn't been cleared from the buffer yet, clear it now\n if (!selectionAreaCleared && !selectionMaskPath.isEmpty()) {\n QPainter painter(&buffer);\n painter.setCompositionMode(QPainter::CompositionMode_Clear);\n painter.fillPath(selectionMaskPath, Qt::transparent);\n painter.end();\n selectionAreaCleared = true;\n }\n // selectionBuffer already has the content.\n // The original area in 'buffer' was already cleared when selection was made.\n } else {\n // Start a new selection or cancel existing one\n if (!selectionBuffer.isNull()) { // If there's an active selection, a tap outside cancels it\n selectionBuffer = QPixmap();\n selectionRect = QRect();\n lassoPathPoints.clear();\n movingSelection = false;\n selectingWithRope = false;\n selectionJustCopied = false;\n selectionAreaCleared = false;\n selectionMaskPath = QPainterPath();\n selectionBufferRect = QRectF();\n update(); // Full update to remove old selection visuals\n drawing = false; // Consumed this press for cancel\n return;\n }\n selectingWithRope = true;\n movingSelection = false;\n selectionJustCopied = false;\n selectionAreaCleared = false;\n selectionMaskPath = QPainterPath();\n selectionBufferRect = QRectF();\n lassoPathPoints.clear();\n lassoPathPoints << lastPoint; // Start the lasso path\n selectionRect = QRect();\n selectionBuffer = QPixmap();\n }\n }\n } else if (event->type() == QEvent::TabletMove && drawing) {\n if (ropeToolMode) {\n if (selectingWithRope) {\n QRectF oldPreviewBoundingRect = lassoPathPoints.boundingRect();\n lassoPathPoints << event->posF();\n lastPoint = event->posF();\n QRectF newPreviewBoundingRect = lassoPathPoints.boundingRect();\n // Update the area of the selection rectangle preview (logical widget coordinates)\n update(oldPreviewBoundingRect.united(newPreviewBoundingRect).toRect().adjusted(-5,-5,5,5));\n } else if (movingSelection) {\n QPointF delta = event->posF() - lastMovePoint; // Delta in logical widget coordinates\n QRect oldWidgetSelectionRect = selectionRect;\n \n // Update the exact floating-point rectangle first\n exactSelectionRectF.translate(delta);\n \n // Convert back to integer rect, but only when the position actually changes\n QRect newRect = exactSelectionRectF.toRect();\n if (newRect != selectionRect) {\n selectionRect = newRect;\n // Update the combined area of the old and new selection positions (logical widget coordinates)\n update(oldWidgetSelectionRect.united(selectionRect).adjusted(-2,-2,2,2));\n } else {\n // Even if the integer position didn't change, we still need to update\n // to make movement feel smoother, especially with slow movements\n update(selectionRect.adjusted(-2,-2,2,2));\n }\n \n lastMovePoint = event->posF();\n if (!edited){\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n }\n } else if (straightLineMode && !isErasing) {\n // For straight line mode with non-eraser tools, just update the last position\n // and trigger a repaint of only the affected area for preview\n static QElapsedTimer updateTimer;\n static bool timerInitialized = false;\n \n if (!timerInitialized) {\n updateTimer.start();\n timerInitialized = true;\n }\n \n // Throttle updates based on time for high CPU usage tools\n bool shouldUpdate = true;\n \n // Apply throttling for marker which can be CPU intensive\n if (currentTool == ToolType::Marker) {\n shouldUpdate = updateTimer.elapsed() > 16; // Only update every 16ms (approx 60fps)\n }\n \n if (shouldUpdate) {\n QPointF oldLastPoint = lastPoint;\n lastPoint = event->posF();\n \n // Calculate affected rectangle that needs updating\n QRectF updateRect = calculatePreviewRect(straightLineStartPoint, oldLastPoint, lastPoint);\n update(updateRect.toRect());\n \n // Reset timer\n updateTimer.restart();\n } else {\n // Just update the last point without redrawing\n lastPoint = event->posF();\n }\n } else if (straightLineMode && isErasing) {\n // For eraser in straight line mode, continuously erase from start to current point\n // This gives immediate visual feedback and smoother erasing experience\n \n // Store current point\n QPointF currentPoint = event->posF();\n \n // Clear previous stroke by redrawing with transparency\n QRectF updateRect = QRectF(straightLineStartPoint, lastPoint).normalized().adjusted(-20, -20, 20, 20);\n update(updateRect.toRect());\n \n // Erase from start point to current position\n eraseStroke(straightLineStartPoint, currentPoint, event->pressure());\n \n // Update last point\n lastPoint = currentPoint;\n \n // Only track benchmarking when enabled\n if (benchmarking) {\n processedTimestamps.push_back(benchmarkTimer.elapsed());\n }\n } else {\n // Normal drawing mode OR eraser regardless of straight line mode\n if (isErasing) {\n eraseStroke(lastPoint, event->posF(), event->pressure());\n } else {\n drawStroke(lastPoint, event->posF(), event->pressure());\n }\n lastPoint = event->posF();\n \n // Only track benchmarking when enabled\n if (benchmarking) {\n processedTimestamps.push_back(benchmarkTimer.elapsed());\n }\n }\n } else if (event->type() == QEvent::TabletRelease) {\n if (straightLineMode && !isErasing) {\n // Draw the final line on release with the current pressure\n qreal pressure = event->pressure();\n \n // Always use at least a minimum pressure\n pressure = qMax(pressure, 0.5);\n \n drawStroke(straightLineStartPoint, event->posF(), pressure);\n \n // Only track benchmarking when enabled\n if (benchmarking) {\n processedTimestamps.push_back(benchmarkTimer.elapsed());\n }\n \n // Force repaint to clear the preview line\n update();\n if (!edited){\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n } else if (straightLineMode && isErasing) {\n // For erasing in straight line mode, most of the work is done during movement\n // Just ensure one final erasing pass from start to end point\n qreal pressure = qMax(event->pressure(), 0.5);\n \n // Final pass to ensure the entire line is erased\n eraseStroke(straightLineStartPoint, event->posF(), pressure);\n \n // Force update to clear any remaining artifacts\n update();\n if (!edited){\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n }\n \n drawing = false;\n \n // Reset tool state if we were using the hardware eraser\n if (wasUsingHardwareEraser) {\n currentTool = previousTool;\n hardwareEraserActive = false; // Reset hardware eraser tracking\n }\n\n if (ropeToolMode) {\n if (selectingWithRope) {\n if (lassoPathPoints.size() > 2) { // Need at least 3 points for a polygon\n lassoPathPoints << lassoPathPoints.first(); // Close the polygon\n \n if (!lassoPathPoints.boundingRect().isEmpty()) {\n // 1. Create a QPolygonF in buffer coordinates using proper transformation\n QPolygonF bufferLassoPath;\n for (const QPointF& p_widget_logical : qAsConst(lassoPathPoints)) {\n bufferLassoPath << mapLogicalWidgetToPhysicalBuffer(p_widget_logical);\n }\n\n // 2. Get the bounding box of this path on the buffer\n QRectF bufferPathBoundingRect = bufferLassoPath.boundingRect();\n\n // 3. Copy that part of the main buffer\n QPixmap originalPiece = buffer.copy(bufferPathBoundingRect.toRect());\n\n // 4. Create the selectionBuffer (same size as originalPiece) and fill transparent\n selectionBuffer = QPixmap(originalPiece.size());\n selectionBuffer.fill(Qt::transparent);\n \n // 5. Create a mask from the lasso path\n QPainterPath maskPath;\n // The lasso path for the mask needs to be relative to originalPiece.topLeft()\n maskPath.addPolygon(bufferLassoPath.translated(-bufferPathBoundingRect.topLeft()));\n \n // 6. Paint the originalPiece onto selectionBuffer, using the mask\n QPainter selectionPainter(&selectionBuffer);\n selectionPainter.setClipPath(maskPath);\n selectionPainter.drawPixmap(0,0, originalPiece);\n selectionPainter.end();\n\n // 7. DON'T clear the selected area from the main buffer yet\n // The area will only be cleared when the user actually starts moving the selection\n // This way, if the user cancels without moving, the original content remains\n selectionAreaCleared = false;\n \n // Store the mask path and buffer rect for later clearing when movement starts\n selectionMaskPath = maskPath.translated(bufferPathBoundingRect.topLeft());\n selectionBufferRect = bufferPathBoundingRect;\n \n // 8. Calculate the correct selectionRect in logical widget coordinates\n QRectF logicalSelectionRect = mapRectBufferToWidgetLogical(bufferPathBoundingRect);\n selectionRect = logicalSelectionRect.toRect();\n exactSelectionRectF = logicalSelectionRect;\n \n // Update the area of the selection on screen\n update(logicalSelectionRect.adjusted(-2,-2,2,2).toRect());\n \n // Emit signal for context menu at the center of the selection with a delay\n // This allows the user to immediately start moving the selection if desired\n QPoint menuPosition = selectionRect.center();\n QTimer::singleShot(500, this, [this, menuPosition]() {\n // Only show menu if selection still exists and hasn't been moved\n if (!selectionBuffer.isNull() && !selectionRect.isEmpty() && !movingSelection) {\n emit ropeSelectionCompleted(menuPosition);\n }\n });\n }\n }\n lassoPathPoints.clear(); // Ready for next selection, or move\n selectingWithRope = false;\n // Now, if the user presses inside selectionRect, movingSelection will become true.\n } else if (movingSelection) {\n if (!selectionBuffer.isNull() && !selectionRect.isEmpty()) {\n QPainter painter(&buffer);\n // Explicitly set composition mode to draw on top of existing content\n painter.setCompositionMode(QPainter::CompositionMode_SourceOver);\n // Use exact floating-point position if available for more precise placement\n QPointF topLeft = exactSelectionRectF.isEmpty() ? selectionRect.topLeft() : exactSelectionRectF.topLeft();\n // Use proper coordinate transformation to get buffer coordinates\n QPointF bufferDest = mapLogicalWidgetToPhysicalBuffer(topLeft);\n painter.drawPixmap(bufferDest.toPoint(), selectionBuffer);\n painter.end();\n \n // Update the pasted area\n QRectF bufferPasteRect(bufferDest, selectionBuffer.size());\n update(mapRectBufferToWidgetLogical(bufferPasteRect).adjusted(-2,-2,2,2));\n \n // Clear selection after pasting, making it permanent\n selectionBuffer = QPixmap();\n selectionRect = QRect();\n exactSelectionRectF = QRectF();\n movingSelection = false;\n selectionJustCopied = false;\n selectionAreaCleared = false;\n selectionMaskPath = QPainterPath();\n selectionBufferRect = QRectF();\n }\n }\n }\n \n\n }\n event->accept();\n}\n void mousePressEvent(QMouseEvent *event) override {\n // Handle markdown selection when enabled\n if (markdownSelectionMode && event->button() == Qt::LeftButton) {\n markdownSelecting = true;\n markdownSelectionStart = event->pos();\n markdownSelectionEnd = markdownSelectionStart;\n event->accept();\n return;\n }\n \n // Handle PDF text selection when enabled (mouse/touch fallback - stylus handled in tabletEvent)\n if (pdfTextSelectionEnabled && isPdfLoaded) {\n if (event->button() == Qt::LeftButton) {\n pdfTextSelecting = true;\n pdfSelectionStart = event->position();\n pdfSelectionEnd = pdfSelectionStart;\n \n // Clear any existing selected text boxes without resetting pdfTextSelecting\n selectedTextBoxes.clear();\n \n setCursor(Qt::IBeamCursor); // Ensure cursor is correct\n update(); // Refresh display\n event->accept();\n return;\n }\n }\n \n // Ignore mouse/touch input on canvas for drawing (drawing only works with tablet/stylus)\n event->ignore();\n}\n void mouseMoveEvent(QMouseEvent *event) override {\n // Handle markdown selection when enabled\n if (markdownSelectionMode && markdownSelecting) {\n markdownSelectionEnd = event->pos();\n update(); // Refresh to show selection rectangle\n event->accept();\n return;\n }\n \n // Handle PDF text selection when enabled (mouse/touch fallback - stylus handled in tabletEvent)\n if (pdfTextSelectionEnabled && isPdfLoaded && pdfTextSelecting) {\n pdfSelectionEnd = event->position();\n \n // Store pending selection for throttled processing\n pendingSelectionStart = pdfSelectionStart;\n pendingSelectionEnd = pdfSelectionEnd;\n hasPendingSelection = true;\n \n // Start timer if not already running (throttled to 60 FPS)\n if (!pdfTextSelectionTimer->isActive()) {\n pdfTextSelectionTimer->start();\n }\n \n event->accept();\n return;\n }\n \n // Update cursor based on mode when not actively selecting\n if (pdfTextSelectionEnabled && isPdfLoaded && !pdfTextSelecting) {\n setCursor(Qt::IBeamCursor);\n }\n \n event->ignore();\n}\n void mouseReleaseEvent(QMouseEvent *event) override {\n // Handle markdown selection when enabled\n if (markdownSelectionMode && markdownSelecting && event->button() == Qt::LeftButton) {\n markdownSelecting = false;\n \n // Create markdown window if selection is valid\n QRect selectionRect = QRect(markdownSelectionStart, markdownSelectionEnd).normalized();\n if (selectionRect.width() > 50 && selectionRect.height() > 50 && markdownManager) {\n markdownManager->createMarkdownWindow(selectionRect);\n }\n \n // Exit selection mode\n setMarkdownSelectionMode(false);\n \n // Force screen update to clear the green selection overlay\n update();\n \n event->accept();\n return;\n }\n \n // Handle PDF text selection when enabled (mouse/touch fallback - stylus handled in tabletEvent)\n if (pdfTextSelectionEnabled && isPdfLoaded && pdfTextSelecting) {\n if (event->button() == Qt::LeftButton) {\n pdfSelectionEnd = event->position();\n \n // Process any pending selection immediately on release\n if (pdfTextSelectionTimer && pdfTextSelectionTimer->isActive()) {\n pdfTextSelectionTimer->stop();\n if (hasPendingSelection) {\n updatePdfTextSelection(pendingSelectionStart, pendingSelectionEnd);\n hasPendingSelection = false;\n }\n } else {\n // Update selection with final position\n updatePdfTextSelection(pdfSelectionStart, pdfSelectionEnd);\n }\n \n pdfTextSelecting = false;\n \n // Check for link clicks if no text was selected\n QString selectedText = getSelectedPdfText();\n if (selectedText.isEmpty()) {\n handlePdfLinkClick(event->position());\n } else {\n // Show context menu for text selection\n QPoint globalPos = mapToGlobal(event->position().toPoint());\n showPdfTextSelectionMenu(globalPos);\n }\n \n event->accept();\n return;\n }\n }\n \n\n \n event->ignore();\n}\n void resizeEvent(QResizeEvent *event) override {\n // Don't resize the buffer when the widget resizes\n // The buffer size should be determined by the PDF/document content, not the widget size\n // The paintEvent will handle centering the buffer content within the widget\n \n QWidget::resizeEvent(event);\n}\n bool event(QEvent *event) override {\n if (!touchGesturesEnabled) {\n return QWidget::event(event);\n }\n\n if (event->type() == QEvent::TouchBegin || \n event->type() == QEvent::TouchUpdate || \n event->type() == QEvent::TouchEnd) {\n \n QTouchEvent *touchEvent = static_cast(event);\n const QList touchPoints = touchEvent->points();\n \n activeTouchPoints = touchPoints.count();\n\n if (activeTouchPoints == 1) {\n // Single finger pan\n const QTouchEvent::TouchPoint &touchPoint = touchPoints.first();\n \n if (event->type() == QEvent::TouchBegin) {\n isPanning = true;\n lastTouchPos = touchPoint.position();\n } else if (event->type() == QEvent::TouchUpdate && isPanning) {\n QPointF delta = touchPoint.position() - lastTouchPos;\n \n // Make panning more responsive by using floating-point calculations\n qreal scaledDeltaX = delta.x() / (internalZoomFactor / 100.0);\n qreal scaledDeltaY = delta.y() / (internalZoomFactor / 100.0);\n \n // Calculate new pan positions with sub-pixel precision\n qreal newPanX = panOffsetX - scaledDeltaX;\n qreal newPanY = panOffsetY - scaledDeltaY;\n \n // Clamp pan values when canvas is smaller than viewport\n qreal scaledCanvasWidth = buffer.width() * (internalZoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (internalZoomFactor / 100.0);\n \n // If canvas is smaller than widget, lock pan to 0 (centered)\n if (scaledCanvasWidth < width()) {\n newPanX = 0;\n }\n if (scaledCanvasHeight < height()) {\n newPanY = 0;\n }\n \n // Emit signal with integer values for compatibility\n emit panChanged(qRound(newPanX), qRound(newPanY));\n \n lastTouchPos = touchPoint.position();\n }\n } else if (activeTouchPoints == 2) {\n // Two finger pinch zoom\n isPanning = false;\n \n const QTouchEvent::TouchPoint &touch1 = touchPoints[0];\n const QTouchEvent::TouchPoint &touch2 = touchPoints[1];\n \n // Calculate distance between touch points with higher precision\n qreal currentDist = QLineF(touch1.position(), touch2.position()).length();\n qreal startDist = QLineF(touch1.pressPosition(), touch2.pressPosition()).length();\n \n if (event->type() == QEvent::TouchBegin) {\n lastPinchScale = 1.0;\n // Store the starting internal zoom\n internalZoomFactor = zoomFactor;\n } else if (event->type() == QEvent::TouchUpdate && startDist > 0) {\n qreal scale = currentDist / startDist;\n \n // Use exponential scaling for more natural feel\n qreal scaleChange = scale / lastPinchScale;\n \n // Apply scale with higher sensitivity\n internalZoomFactor *= scaleChange;\n internalZoomFactor = qBound(10.0, internalZoomFactor, 400.0);\n \n // Calculate zoom center (midpoint between two fingers)\n QPointF center = (touch1.position() + touch2.position()) / 2.0;\n \n // Account for centering offset\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n // Adjust center point for centering offset\n QPointF adjustedCenter = center - QPointF(centerOffsetX, centerOffsetY);\n \n // Always update zoom for smooth animation\n int newZoom = qRound(internalZoomFactor);\n \n // Calculate pan adjustment to keep the zoom centered at pinch point\n QPointF bufferCenter = adjustedCenter / (zoomFactor / 100.0) + QPointF(panOffsetX, panOffsetY);\n \n // Update zoom factor before emitting\n qreal oldZoomFactor = zoomFactor;\n zoomFactor = newZoom;\n \n // Emit zoom change even for small changes\n emit zoomChanged(newZoom);\n \n // Adjust pan to keep center point fixed with sub-pixel precision\n qreal newPanX = bufferCenter.x() - adjustedCenter.x() / (internalZoomFactor / 100.0);\n qreal newPanY = bufferCenter.y() - adjustedCenter.y() / (internalZoomFactor / 100.0);\n \n // After zoom, check if we need to center\n qreal newScaledCanvasWidth = buffer.width() * (internalZoomFactor / 100.0);\n qreal newScaledCanvasHeight = buffer.height() * (internalZoomFactor / 100.0);\n \n if (newScaledCanvasWidth < width()) {\n newPanX = 0;\n }\n if (newScaledCanvasHeight < height()) {\n newPanY = 0;\n }\n \n emit panChanged(qRound(newPanX), qRound(newPanY));\n \n lastPinchScale = scale;\n \n // Request update only for visible area\n update();\n }\n } else {\n // More than 2 fingers - ignore\n isPanning = false;\n }\n \n if (event->type() == QEvent::TouchEnd) {\n isPanning = false;\n lastPinchScale = 1.0;\n activeTouchPoints = 0;\n // Sync internal zoom with actual zoom\n internalZoomFactor = zoomFactor;\n \n // Emit signal that touch gesture has ended\n emit touchGestureEnded();\n }\n \n event->accept();\n return true;\n }\n \n return QWidget::event(event);\n}\n private:\n QPointF mapLogicalWidgetToPhysicalBuffer(const QPointF& logicalWidgetPoint) {\n // Use the same coordinate transformation logic as drawStroke for consistency\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n // Convert widget position to buffer position, accounting for centering\n QPointF adjustedPoint = logicalWidgetPoint - QPointF(centerOffsetX, centerOffsetY);\n QPointF bufferPoint = (adjustedPoint / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n \n return bufferPoint;\n}\n QRect mapRectBufferToWidgetLogical(const QRectF& physicalBufferRect) {\n // Use the same coordinate transformation logic as drawStroke for consistency\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n // Convert buffer coordinates back to widget coordinates\n QRectF widgetRect = QRectF(\n (physicalBufferRect.topLeft() - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY),\n physicalBufferRect.size() * (zoomFactor / 100.0)\n );\n \n return widgetRect.toRect();\n}\n QPixmap buffer;\n QImage background;\n QPointF lastPoint;\n QPointF straightLineStartPoint;\n bool drawing;\n QColor penColor;\n qreal penThickness;\n ToolType currentTool;\n ToolType previousTool;\n qreal penToolThickness = 5.0;\n qreal markerToolThickness = 5.0;\n qreal eraserToolThickness = 5.0;\n QString saveFolder;\n QPixmap backgroundImage;\n bool straightLineMode = false;\n bool ropeToolMode = false;\n QPixmap selectionBuffer;\n QRect selectionRect;\n QRectF exactSelectionRectF;\n QPolygonF lassoPathPoints;\n bool selectingWithRope = false;\n bool movingSelection = false;\n bool selectionJustCopied = false;\n bool selectionAreaCleared = false;\n QPainterPath selectionMaskPath;\n QRectF selectionBufferRect;\n QPointF lastMovePoint;\n int zoomFactor;\n int panOffsetX;\n int panOffsetY;\n qreal internalZoomFactor = 100.0;\n void initializeBuffer() {\n QScreen *screen = QGuiApplication::primaryScreen();\n qreal dpr = screen ? screen->devicePixelRatio() : 1.0;\n\n // Get logical screen size\n QSize logicalSize = screen ? screen->size() : QSize(1440, 900);\n QSize pixelSize = logicalSize * dpr;\n\n buffer = QPixmap(pixelSize);\n buffer.fill(Qt::transparent);\n\n setMaximumSize(pixelSize); // 🔥 KEY LINE to make full canvas drawable\n}\n void drawStroke(const QPointF &start, const QPointF &end, qreal pressure) {\n if (buffer.isNull()) {\n initializeBuffer();\n }\n\n if (!edited){\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n\n QPainter painter(&buffer);\n painter.setRenderHint(QPainter::Antialiasing);\n\n qreal thickness = penThickness;\n\n qreal updatePadding = (currentTool == ToolType::Marker) ? thickness * 4.0 : 10;\n\n if (currentTool == ToolType::Marker) {\n thickness *= 8.0;\n QColor markerColor = penColor;\n // Adjust alpha based on whether we're in straight line mode\n if (straightLineMode) {\n // For straight line mode, use higher alpha to make it more visible\n markerColor.setAlpha(40);\n } else {\n // For regular drawing, use lower alpha for the usual marker effect\n markerColor.setAlpha(4);\n }\n QPen pen(markerColor, thickness, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);\n painter.setPen(pen);\n } else { // Default Pen\n qreal scaledThickness = thickness * pressure; // **Linear pressure scaling**\n QPen pen(penColor, scaledThickness, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);\n painter.setPen(pen);\n }\n\n // Calculate centering offsets\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n // Convert screen position to buffer position, accounting for centering\n QPointF adjustedStart = start - QPointF(centerOffsetX, centerOffsetY);\n QPointF adjustedEnd = end - QPointF(centerOffsetX, centerOffsetY);\n \n QPointF bufferStart = (adjustedStart / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n QPointF bufferEnd = (adjustedEnd / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n\n painter.drawLine(bufferStart, bufferEnd);\n\n QRectF updateRect = QRectF(bufferStart, bufferEnd)\n .normalized()\n .adjusted(-updatePadding, -updatePadding, updatePadding, updatePadding);\n\n QRect scaledUpdateRect = QRect(\n ((updateRect.topLeft() - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY)).toPoint(),\n ((updateRect.bottomRight() - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY)).toPoint()\n );\n update(scaledUpdateRect);\n}\n void eraseStroke(const QPointF &start, const QPointF &end, qreal pressure) {\n if (buffer.isNull()) {\n initializeBuffer();\n }\n\n if (!edited){\n edited = true;\n // Invalidate cache for current page since it's been modified\n invalidateCurrentPageCache();\n }\n\n QPainter painter(&buffer);\n painter.setCompositionMode(QPainter::CompositionMode_Clear);\n\n qreal eraserThickness = penThickness * 6.0;\n QPen eraserPen(Qt::transparent, eraserThickness, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);\n painter.setPen(eraserPen);\n\n // Calculate centering offsets\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n // Convert screen position to buffer position, accounting for centering\n QPointF adjustedStart = start - QPointF(centerOffsetX, centerOffsetY);\n QPointF adjustedEnd = end - QPointF(centerOffsetX, centerOffsetY);\n \n QPointF bufferStart = (adjustedStart / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n QPointF bufferEnd = (adjustedEnd / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n\n painter.drawLine(bufferStart, bufferEnd);\n\n qreal updatePadding = eraserThickness / 2.0 + 5.0; // Half the eraser thickness plus some extra padding\n QRectF updateRect = QRectF(bufferStart, bufferEnd)\n .normalized()\n .adjusted(-updatePadding, -updatePadding, updatePadding, updatePadding);\n\n QRect scaledUpdateRect = QRect(\n ((updateRect.topLeft() - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY)).toPoint(),\n ((updateRect.bottomRight() - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY)).toPoint()\n );\n update(scaledUpdateRect);\n}\n QRectF calculatePreviewRect(const QPointF &start, const QPointF &oldEnd, const QPointF &newEnd) {\n // Calculate centering offsets - use the same calculation as in paintEvent\n qreal scaledCanvasWidth = buffer.width() * (zoomFactor / 100.0);\n qreal scaledCanvasHeight = buffer.height() * (zoomFactor / 100.0);\n qreal centerOffsetX = (scaledCanvasWidth < width()) ? (width() - scaledCanvasWidth) / 2.0 : 0;\n qreal centerOffsetY = (scaledCanvasHeight < height()) ? (height() - scaledCanvasHeight) / 2.0 : 0;\n \n // Calculate the buffer coordinates for our points (same as in drawStroke)\n QPointF adjustedStart = start - QPointF(centerOffsetX, centerOffsetY);\n QPointF adjustedOldEnd = oldEnd - QPointF(centerOffsetX, centerOffsetY);\n QPointF adjustedNewEnd = newEnd - QPointF(centerOffsetX, centerOffsetY);\n \n QPointF bufferStart = (adjustedStart / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n QPointF bufferOldEnd = (adjustedOldEnd / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n QPointF bufferNewEnd = (adjustedNewEnd / (zoomFactor / 100.0)) + QPointF(panOffsetX, panOffsetY);\n \n // Now convert from buffer coordinates to screen coordinates\n QPointF screenStart = (bufferStart - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY);\n QPointF screenOldEnd = (bufferOldEnd - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY);\n QPointF screenNewEnd = (bufferNewEnd - QPointF(panOffsetX, panOffsetY)) * (zoomFactor / 100.0) + QPointF(centerOffsetX, centerOffsetY);\n \n // Create rectangles for both the old and new lines\n QRectF oldLineRect = QRectF(screenStart, screenOldEnd).normalized();\n QRectF newLineRect = QRectF(screenStart, screenNewEnd).normalized();\n \n // Calculate padding based on pen thickness and device pixel ratio\n qreal dpr = devicePixelRatioF();\n qreal padding;\n \n if (currentTool == ToolType::Eraser) {\n padding = penThickness * 6.0 * dpr;\n } else if (currentTool == ToolType::Marker) {\n padding = penThickness * 8.0 * dpr;\n } else {\n padding = penThickness * dpr;\n }\n \n // Ensure minimum padding\n padding = qMax(padding, 15.0);\n \n // Combine rectangles with appropriate padding\n QRectF combinedRect = oldLineRect.united(newLineRect);\n return combinedRect.adjusted(-padding, -padding, padding, padding);\n}\n QCache pdfCache;\n std::unique_ptr pdfDocument;\n int currentPdfPage;\n bool isPdfLoaded = false;\n int totalPdfPages = 0;\n int lastActivePage = 0;\n int lastZoomLevel = 100;\n int lastPanX = 0;\n int lastPanY = 0;\n bool edited = false;\n bool benchmarking;\n std::deque processedTimestamps;\n QElapsedTimer benchmarkTimer;\n QString notebookId;\n void loadNotebookId() {\n QString idFile = saveFolder + \"/.notebook_id.txt\";\n if (QFile::exists(idFile)) {\n QFile file(idFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n notebookId = in.readLine().trimmed();\n }\n } else {\n // No ID file → create new random ID\n notebookId = QUuid::createUuid().toString(QUuid::WithoutBraces).replace(\"-\", \"\");\n saveNotebookId();\n }\n}\n void saveNotebookId() {\n QString idFile = saveFolder + \"/.notebook_id.txt\";\n QFile file(idFile);\n if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {\n QTextStream out(&file);\n out << notebookId;\n }\n}\n int pdfRenderDPI = 192;\n bool touchGesturesEnabled = false;\n QPointF lastTouchPos;\n qreal lastPinchScale = 1.0;\n bool isPanning = false;\n int activeTouchPoints = 0;\n BackgroundStyle backgroundStyle = BackgroundStyle::None;\n QColor backgroundColor = Qt::white;\n int backgroundDensity = 40;\n bool pdfTextSelectionEnabled = false;\n bool pdfTextSelecting = false;\n QPointF pdfSelectionStart;\n QPointF pdfSelectionEnd;\n QList currentPdfTextBoxes;\n QList selectedTextBoxes;\n std::unique_ptr currentPdfPageForText;\n QTimer* pdfTextSelectionTimer = nullptr;\n QPointF pendingSelectionStart;\n QPointF pendingSelectionEnd;\n bool hasPendingSelection = false;\n QTimer* pdfCacheTimer = nullptr;\n int currentCachedPage = -1;\n int pendingCacheTargetPage = -1;\n QList*> activePdfWatchers;\n QCache noteCache;\n QTimer* noteCacheTimer = nullptr;\n int currentCachedNotePage = -1;\n int pendingNoteCacheTargetPage = -1;\n QList*> activeNoteWatchers;\n MarkdownWindowManager* markdownManager = nullptr;\n bool markdownSelectionMode = false;\n QPoint markdownSelectionStart;\n QPoint markdownSelectionEnd;\n bool markdownSelecting = false;\n void loadPdfTextBoxes(int pageNumber) {\n // Clear existing text boxes\n qDeleteAll(currentPdfTextBoxes);\n currentPdfTextBoxes.clear();\n \n if (!pdfDocument || pageNumber < 0 || pageNumber >= pdfDocument->numPages()) {\n return;\n }\n \n // Get the page for text operations\n currentPdfPageForText = std::unique_ptr(pdfDocument->page(pageNumber));\n if (!currentPdfPageForText) {\n return;\n }\n \n // Load text boxes for the page\n auto textBoxVector = currentPdfPageForText->textList();\n currentPdfTextBoxes.clear();\n for (auto& textBox : textBoxVector) {\n currentPdfTextBoxes.append(textBox.release()); // Transfer ownership to QList\n }\n}\n QPointF mapWidgetToPdfCoordinates(const QPointF &widgetPoint) {\n if (!currentPdfPageForText || backgroundImage.isNull()) {\n return QPointF();\n }\n \n // Use the same zoom factor as in paintEvent (internalZoomFactor for smooth animations)\n qreal zoom = internalZoomFactor / 100.0;\n \n // Calculate the scaled canvas size (same as in paintEvent)\n qreal scaledCanvasWidth = buffer.width() * zoom;\n qreal scaledCanvasHeight = buffer.height() * zoom;\n \n // Calculate centering offsets (same as in paintEvent)\n qreal centerOffsetX = 0;\n qreal centerOffsetY = 0;\n \n // Center horizontally if canvas is smaller than widget\n if (scaledCanvasWidth < width()) {\n centerOffsetX = (width() - scaledCanvasWidth) / 2.0;\n }\n \n // Center vertically if canvas is smaller than widget\n if (scaledCanvasHeight < height()) {\n centerOffsetY = (height() - scaledCanvasHeight) / 2.0;\n }\n \n // Reverse the transformations applied in paintEvent\n QPointF adjustedPoint = widgetPoint;\n adjustedPoint -= QPointF(centerOffsetX, centerOffsetY);\n adjustedPoint /= zoom;\n adjustedPoint += QPointF(panOffsetX, panOffsetY);\n \n // Convert to PDF coordinates\n // Since Poppler renders the PDF in Qt coordinate system (top-left origin),\n // we don't need to flip the Y coordinate\n QSizeF pdfPageSize = currentPdfPageForText->pageSizeF();\n QSizeF imageSize = backgroundImage.size();\n \n // Scale from image coordinates to PDF coordinates\n qreal scaleX = pdfPageSize.width() / imageSize.width();\n qreal scaleY = pdfPageSize.height() / imageSize.height();\n \n QPointF pdfPoint;\n pdfPoint.setX(adjustedPoint.x() * scaleX);\n pdfPoint.setY(adjustedPoint.y() * scaleY); // No Y-axis flipping needed\n \n return pdfPoint;\n}\n QPointF mapPdfToWidgetCoordinates(const QPointF &pdfPoint) {\n if (!currentPdfPageForText || backgroundImage.isNull()) {\n return QPointF();\n }\n \n // Convert from PDF coordinates to image coordinates\n QSizeF pdfPageSize = currentPdfPageForText->pageSizeF();\n QSizeF imageSize = backgroundImage.size();\n \n // Scale from PDF coordinates to image coordinates\n qreal scaleX = imageSize.width() / pdfPageSize.width();\n qreal scaleY = imageSize.height() / pdfPageSize.height();\n \n QPointF imagePoint;\n imagePoint.setX(pdfPoint.x() * scaleX);\n imagePoint.setY(pdfPoint.y() * scaleY); // No Y-axis flipping needed\n \n // Use the same zoom factor as in paintEvent (internalZoomFactor for smooth animations)\n qreal zoom = internalZoomFactor / 100.0;\n \n // Apply the same transformations as in paintEvent\n QPointF widgetPoint = imagePoint;\n widgetPoint -= QPointF(panOffsetX, panOffsetY);\n widgetPoint *= zoom;\n \n // Calculate the scaled canvas size (same as in paintEvent)\n qreal scaledCanvasWidth = buffer.width() * zoom;\n qreal scaledCanvasHeight = buffer.height() * zoom;\n \n // Calculate centering offsets (same as in paintEvent)\n qreal centerOffsetX = 0;\n qreal centerOffsetY = 0;\n \n // Center horizontally if canvas is smaller than widget\n if (scaledCanvasWidth < width()) {\n centerOffsetX = (width() - scaledCanvasWidth) / 2.0;\n }\n \n // Center vertically if canvas is smaller than widget\n if (scaledCanvasHeight < height()) {\n centerOffsetY = (height() - scaledCanvasHeight) / 2.0;\n }\n \n widgetPoint += QPointF(centerOffsetX, centerOffsetY);\n \n return widgetPoint;\n}\n void updatePdfTextSelection(const QPointF &start, const QPointF &end) {\n // Early return if PDF is not loaded or no text boxes available\n if (!isPdfLoaded || currentPdfTextBoxes.isEmpty()) {\n return;\n }\n \n // Clear previous selection efficiently\n selectedTextBoxes.clear();\n \n // Create normalized selection rectangle in widget coordinates\n QRectF widgetSelectionRect(start, end);\n widgetSelectionRect = widgetSelectionRect.normalized();\n \n // Convert to PDF coordinate space\n QPointF pdfTopLeft = mapWidgetToPdfCoordinates(widgetSelectionRect.topLeft());\n QPointF pdfBottomRight = mapWidgetToPdfCoordinates(widgetSelectionRect.bottomRight());\n QRectF pdfSelectionRect(pdfTopLeft, pdfBottomRight);\n pdfSelectionRect = pdfSelectionRect.normalized();\n \n // Reserve space for efficiency if we expect many selections\n selectedTextBoxes.reserve(qMin(currentPdfTextBoxes.size(), 50));\n \n // Find intersecting text boxes with optimized loop\n for (const Poppler::TextBox* textBox : currentPdfTextBoxes) {\n if (textBox && textBox->boundingBox().intersects(pdfSelectionRect)) {\n selectedTextBoxes.append(const_cast(textBox));\n }\n }\n \n // Only emit signal and update if we have selected text\n if (!selectedTextBoxes.isEmpty()) {\n QString selectedText = getSelectedPdfText();\n if (!selectedText.isEmpty()) {\n emit pdfTextSelected(selectedText);\n }\n }\n \n // Trigger repaint to show selection\n update();\n}\n void handlePdfLinkClick(const QPointF &clickPoint) {\n if (!isPdfLoaded || !currentPdfPageForText) {\n return;\n }\n \n // Convert widget coordinates to PDF coordinates\n QPointF pdfPoint = mapWidgetToPdfCoordinates(position);\n \n // Get PDF page size for reference\n QSizeF pdfPageSize = currentPdfPageForText->pageSizeF();\n \n // Convert to normalized coordinates (0.0 to 1.0) to match Poppler's link coordinate system\n QPointF normalizedPoint(pdfPoint.x() / pdfPageSize.width(), pdfPoint.y() / pdfPageSize.height());\n \n // Get links for the current page\n auto links = currentPdfPageForText->links();\n \n for (const auto& link : links) {\n QRectF linkArea = link->linkArea();\n \n // Normalize the rectangle to handle negative width/height\n QRectF normalizedLinkArea = linkArea.normalized();\n \n // Check if the normalized rectangle contains the normalized point\n if (normalizedLinkArea.contains(normalizedPoint)) {\n // Handle different types of links\n if (link->linkType() == Poppler::Link::Goto) {\n Poppler::LinkGoto* gotoLink = static_cast(link.get());\n if (gotoLink && gotoLink->destination().pageNumber() >= 0) {\n int targetPage = gotoLink->destination().pageNumber() - 1; // Convert to 0-based\n emit pdfLinkClicked(targetPage);\n return;\n }\n }\n // Add other link types as needed (URI, etc.)\n }\n }\n}\n void showPdfTextSelectionMenu(const QPoint &position) {\n QString selectedText = getSelectedPdfText();\n if (selectedText.isEmpty()) {\n return; // No text selected, don't show menu\n }\n \n // Create context menu\n QMenu *contextMenu = new QMenu(this);\n contextMenu->setAttribute(Qt::WA_DeleteOnClose);\n \n // Add Copy action\n QAction *copyAction = contextMenu->addAction(tr(\"Copy\"));\n copyAction->setIcon(QIcon(\":/resources/icons/copy.png\")); // You may need to add this icon\n connect(copyAction, &QAction::triggered, this, [selectedText]() {\n QClipboard *clipboard = QGuiApplication::clipboard();\n clipboard->setText(selectedText);\n });\n \n // Add separator\n contextMenu->addSeparator();\n \n // Add Cancel action\n QAction *cancelAction = contextMenu->addAction(tr(\"Cancel\"));\n cancelAction->setIcon(QIcon(\":/resources/icons/cross.png\"));\n connect(cancelAction, &QAction::triggered, this, [this]() {\n clearPdfTextSelection();\n });\n \n // Show the menu at the specified position\n contextMenu->popup(position);\n}\n QList getTextBoxesInSelection(const QPointF &start, const QPointF &end) {\n QList selectedBoxes;\n \n if (!currentPdfPageForText) {\n // qDebug() << \"PDF text selection: No current page for text\";\n return selectedBoxes;\n }\n \n // Convert widget coordinates to PDF coordinates\n QPointF pdfStart = mapWidgetToPdfCoordinates(start);\n QPointF pdfEnd = mapWidgetToPdfCoordinates(end);\n \n // qDebug() << \"PDF text selection: Widget coords\" << start << \"to\" << end;\n // qDebug() << \"PDF text selection: PDF coords\" << pdfStart << \"to\" << pdfEnd;\n \n // Create selection rectangle in PDF coordinates\n QRectF selectionRect(pdfStart, pdfEnd);\n selectionRect = selectionRect.normalized();\n \n // qDebug() << \"PDF text selection: Selection rect in PDF coords:\" << selectionRect;\n \n // Find text boxes that intersect with the selection\n int intersectionCount = 0;\n for (Poppler::TextBox* textBox : currentPdfTextBoxes) {\n if (textBox) {\n QRectF textBoxRect = textBox->boundingBox();\n bool intersects = textBoxRect.intersects(selectionRect);\n \n if (intersects) {\n selectedBoxes.append(textBox);\n intersectionCount++;\n // qDebug() << \"PDF text selection: Text box intersects:\" << textBox->text() \n // << \"at\" << textBoxRect;\n }\n }\n }\n \n // qDebug() << \"PDF text selection: Found\" << intersectionCount << \"intersecting text boxes\";\n \n return selectedBoxes;\n}\n void renderPdfPageToCache(int pageNumber) {\n if (!pdfDocument || !isValidPageNumber(pageNumber)) {\n return;\n }\n \n // Check if already cached\n if (pdfCache.contains(pageNumber)) {\n return;\n }\n \n // Ensure the cache holds only 10 pages max\n if (pdfCache.count() >= 10) {\n auto oldestKey = pdfCache.keys().first();\n pdfCache.remove(oldestKey);\n }\n \n // Render the page and store it in the cache\n std::unique_ptr page(pdfDocument->page(pageNumber));\n if (page) {\n // Render with document-level anti-aliasing settings\n QImage pdfImage = page->renderToImage(pdfRenderDPI, pdfRenderDPI);\n if (!pdfImage.isNull()) {\n QPixmap cachedPixmap = QPixmap::fromImage(pdfImage);\n pdfCache.insert(pageNumber, new QPixmap(cachedPixmap));\n }\n }\n}\n void checkAndCacheAdjacentPages(int targetPage) {\n if (!pdfDocument || !isValidPageNumber(targetPage)) {\n return;\n }\n \n // Calculate adjacent pages\n int prevPage = targetPage - 1;\n int nextPage = targetPage + 1;\n \n // Check what needs to be cached\n bool needPrevPage = isValidPageNumber(prevPage) && !pdfCache.contains(prevPage);\n bool needCurrentPage = !pdfCache.contains(targetPage);\n bool needNextPage = isValidPageNumber(nextPage) && !pdfCache.contains(nextPage);\n \n // If all pages are cached, nothing to do\n if (!needPrevPage && !needCurrentPage && !needNextPage) {\n return;\n }\n \n // Stop any existing timer\n if (pdfCacheTimer && pdfCacheTimer->isActive()) {\n pdfCacheTimer->stop();\n }\n \n // Create timer if it doesn't exist\n if (!pdfCacheTimer) {\n pdfCacheTimer = new QTimer(this);\n pdfCacheTimer->setSingleShot(true);\n connect(pdfCacheTimer, &QTimer::timeout, this, &InkCanvas::cacheAdjacentPages);\n }\n \n // Store the target page for validation when timer fires\n pendingCacheTargetPage = targetPage;\n \n // Start 1-second delay timer\n pdfCacheTimer->start(1000);\n}\n bool isValidPageNumber(int pageNumber) const {\n return (pageNumber >= 0 && pageNumber < totalPdfPages);\n}\n void loadNotePageToCache(int pageNumber) {\n // Check if already cached\n if (noteCache.contains(pageNumber)) {\n return;\n }\n \n QString filePath = getNotePageFilePath(pageNumber);\n if (filePath.isEmpty()) {\n return;\n }\n \n // Ensure the cache doesn't exceed its limit\n if (noteCache.count() >= 15) {\n // QCache will automatically remove least recently used items\n // but we can be explicit about it\n auto keys = noteCache.keys();\n if (!keys.isEmpty()) {\n noteCache.remove(keys.first());\n }\n }\n \n // Load note page from disk if it exists\n if (QFile::exists(filePath)) {\n QPixmap notePixmap;\n if (notePixmap.load(filePath)) {\n noteCache.insert(pageNumber, new QPixmap(notePixmap));\n }\n }\n // If file doesn't exist, we don't cache anything - loadPage will handle initialization\n}\n void checkAndCacheAdjacentNotePages(int targetPage) {\n if (saveFolder.isEmpty()) {\n return;\n }\n \n // Calculate adjacent pages\n int prevPage = targetPage - 1;\n int nextPage = targetPage + 1;\n \n // Check what needs to be cached (we don't have a max page limit for notes)\n bool needPrevPage = (prevPage >= 0) && !noteCache.contains(prevPage);\n bool needCurrentPage = !noteCache.contains(targetPage);\n bool needNextPage = !noteCache.contains(nextPage); // No upper limit check for notes\n \n // If all nearby pages are cached, nothing to do\n if (!needPrevPage && !needCurrentPage && !needNextPage) {\n return;\n }\n \n // Stop any existing timer\n if (noteCacheTimer && noteCacheTimer->isActive()) {\n noteCacheTimer->stop();\n }\n \n // Create timer if it doesn't exist\n if (!noteCacheTimer) {\n noteCacheTimer = new QTimer(this);\n noteCacheTimer->setSingleShot(true);\n connect(noteCacheTimer, &QTimer::timeout, this, &InkCanvas::cacheAdjacentNotePages);\n }\n \n // Store the target page for validation when timer fires\n pendingNoteCacheTargetPage = targetPage;\n \n // Start 1-second delay timer\n noteCacheTimer->start(1000);\n}\n QString getNotePageFilePath(int pageNumber) const {\n if (saveFolder.isEmpty() || notebookId.isEmpty()) {\n return QString();\n }\n return saveFolder + QString(\"/%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n}\n void invalidateCurrentPageCache() {\n if (currentCachedNotePage >= 0) {\n noteCache.remove(currentCachedNotePage);\n }\n}\n private:\n void processPendingTextSelection() {\n if (!hasPendingSelection) {\n return;\n }\n \n // Process the pending selection update\n updatePdfTextSelection(pendingSelectionStart, pendingSelectionEnd);\n hasPendingSelection = false;\n}\n void cacheAdjacentPages() {\n if (!pdfDocument || currentCachedPage < 0) {\n return;\n }\n \n // Check if the user has moved to a different page since the timer was started\n // If so, skip caching adjacent pages as they're no longer relevant\n if (pendingCacheTargetPage != currentCachedPage) {\n return; // User switched pages, don't cache adjacent pages for old page\n }\n \n int targetPage = currentCachedPage;\n int prevPage = targetPage - 1;\n int nextPage = targetPage + 1;\n \n // Create list of pages to cache asynchronously\n QList pagesToCache;\n \n // Add previous page if needed\n if (isValidPageNumber(prevPage) && !pdfCache.contains(prevPage)) {\n pagesToCache.append(prevPage);\n }\n \n // Add next page if needed\n if (isValidPageNumber(nextPage) && !pdfCache.contains(nextPage)) {\n pagesToCache.append(nextPage);\n }\n \n // Cache pages asynchronously\n for (int pageNum : pagesToCache) {\n QFutureWatcher *watcher = new QFutureWatcher(this);\n \n // Track the watcher for cleanup\n activePdfWatchers.append(watcher);\n \n connect(watcher, &QFutureWatcher::finished, this, [this, watcher]() {\n // Remove from active list and delete\n activePdfWatchers.removeOne(watcher);\n watcher->deleteLater();\n });\n \n // Capture pageNum by value to avoid issues with lambda capture\n QFuture future = QtConcurrent::run([this, pageNum]() {\n renderPdfPageToCache(pageNum);\n });\n \n watcher->setFuture(future);\n }\n}\n void cacheAdjacentNotePages() {\n if (saveFolder.isEmpty() || currentCachedNotePage < 0) {\n return;\n }\n \n // Check if the user has moved to a different page since the timer was started\n // If so, skip caching adjacent pages as they're no longer relevant\n if (pendingNoteCacheTargetPage != currentCachedNotePage) {\n return; // User switched pages, don't cache adjacent pages for old page\n }\n \n int targetPage = currentCachedNotePage;\n int prevPage = targetPage - 1;\n int nextPage = targetPage + 1;\n \n // Create list of note pages to cache asynchronously\n QList notePagesToCache;\n \n // Add previous page if needed (check for >= 0 since notes can start from page 0)\n if (prevPage >= 0 && !noteCache.contains(prevPage)) {\n notePagesToCache.append(prevPage);\n }\n \n // Add next page if needed (no upper limit check for notes)\n if (!noteCache.contains(nextPage)) {\n notePagesToCache.append(nextPage);\n }\n \n // Cache note pages asynchronously\n for (int pageNum : notePagesToCache) {\n QFutureWatcher *watcher = new QFutureWatcher(this);\n \n // Track the watcher for cleanup\n activeNoteWatchers.append(watcher);\n \n connect(watcher, &QFutureWatcher::finished, this, [this, watcher]() {\n // Remove from active list and delete\n activeNoteWatchers.removeOne(watcher);\n watcher->deleteLater();\n });\n \n // Capture pageNum by value to avoid issues with lambda capture\n QFuture future = QtConcurrent::run([this, pageNum]() {\n loadNotePageToCache(pageNum);\n });\n \n watcher->setFuture(future);\n }\n}\n};"], ["/SpeedyNote/source/MarkdownWindow.h", "class QMarkdownTextEdit {\n Q_OBJECT\n\npublic:\n explicit MarkdownWindow(const QRect &rect, QWidget *parent = nullptr);\n ~MarkdownWindow() = default;\n QString getMarkdownContent() const {\n return markdownEditor ? markdownEditor->toPlainText() : QString();\n}\n void setMarkdownContent(const QString &content) {\n if (markdownEditor) {\n markdownEditor->setPlainText(content);\n }\n}\n QRect getWindowRect() const {\n return geometry();\n}\n void setWindowRect(const QRect &rect) {\n setGeometry(rect);\n}\n QRect getCanvasRect() const {\n return canvasRect;\n}\n void setCanvasRect(const QRect &canvasRect) {\n canvasRect = rect;\n updateScreenPosition();\n}\n void updateScreenPosition() {\n // Prevent recursive updates\n if (isUpdatingPosition) return;\n isUpdatingPosition = true;\n \n // Debug: Log when this is called due to external changes (not during mouse movement)\n if (!dragging && !resizing) {\n // qDebug() << \"MarkdownWindow::updateScreenPosition() called for window\" << this << \"Canvas rect:\" << canvasRect;\n }\n \n // Get the canvas parent to access coordinate conversion methods\n if (QWidget *canvas = parentWidget()) {\n // Try to cast to InkCanvas to use the new coordinate methods\n if (InkCanvas *inkCanvas = qobject_cast(canvas)) {\n // Use the new coordinate conversion methods\n QRect screenRect = inkCanvas->mapCanvasToWidget(canvasRect);\n // qDebug() << \"MarkdownWindow::updateScreenPosition() - Canvas rect:\" << canvasRect << \"-> Screen rect:\" << screenRect;\n // qDebug() << \" Canvas size:\" << inkCanvas->getCanvasSize() << \"Zoom:\" << inkCanvas->getZoomFactor() << \"Pan:\" << inkCanvas->getPanOffset();\n setGeometry(screenRect);\n } else {\n // Fallback: use canvas coordinates directly\n // qDebug() << \"MarkdownWindow::updateScreenPosition() - No InkCanvas parent, using canvas rect directly:\" << canvasRect;\n setGeometry(canvasRect);\n }\n } else {\n // No parent, use canvas coordinates directly\n // qDebug() << \"MarkdownWindow::updateScreenPosition() - No parent, using canvas rect directly:\" << canvasRect;\n setGeometry(canvasRect);\n }\n \n isUpdatingPosition = false;\n}\n QVariantMap serialize() const {\n QVariantMap data;\n data[\"canvas_x\"] = canvasRect.x();\n data[\"canvas_y\"] = canvasRect.y();\n data[\"canvas_width\"] = canvasRect.width();\n data[\"canvas_height\"] = canvasRect.height();\n data[\"content\"] = getMarkdownContent();\n \n // Add canvas size information for debugging and consistency checks\n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n QSize canvasSize = inkCanvas->getCanvasSize();\n data[\"canvas_buffer_width\"] = canvasSize.width();\n data[\"canvas_buffer_height\"] = canvasSize.height();\n data[\"zoom_factor\"] = inkCanvas->getZoomFactor();\n QPointF panOffset = inkCanvas->getPanOffset();\n data[\"pan_x\"] = panOffset.x();\n data[\"pan_y\"] = panOffset.y();\n }\n \n return data;\n}\n void deserialize(const QVariantMap &data) {\n int x = data.value(\"canvas_x\", 0).toInt();\n int y = data.value(\"canvas_y\", 0).toInt();\n int width = data.value(\"canvas_width\", 300).toInt();\n int height = data.value(\"canvas_height\", 200).toInt();\n QString content = data.value(\"content\", \"# New Markdown Window\").toString();\n \n QRect loadedRect = QRect(x, y, width, height);\n // qDebug() << \"MarkdownWindow::deserialize() - Loaded canvas rect:\" << loadedRect;\n // qDebug() << \" Original canvas size:\" << data.value(\"canvas_buffer_width\", -1).toInt() << \"x\" << data.value(\"canvas_buffer_height\", -1).toInt();\n \n // Apply bounds checking to loaded coordinates\n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n QRect canvasBounds = inkCanvas->getCanvasRect();\n \n // Ensure window stays within canvas bounds\n int maxX = canvasBounds.width() - loadedRect.width();\n int maxY = canvasBounds.height() - loadedRect.height();\n \n loadedRect.setX(qMax(0, qMin(loadedRect.x(), maxX)));\n loadedRect.setY(qMax(0, qMin(loadedRect.y(), maxY)));\n \n if (loadedRect != QRect(x, y, width, height)) {\n // qDebug() << \" Bounds-corrected canvas rect:\" << loadedRect << \"Canvas bounds:\" << canvasBounds;\n }\n }\n \n canvasRect = loadedRect;\n setMarkdownContent(content);\n \n // Ensure canvas connections are set up\n ensureCanvasConnections();\n \n updateScreenPosition();\n}\n void focusEditor() {\n if (markdownEditor) {\n markdownEditor->setFocus();\n }\n}\n bool isEditorFocused() const {\n return markdownEditor && markdownEditor->hasFocus();\n}\n void setTransparent(bool transparent) {\n if (isTransparentState == transparent) return;\n \n // qDebug() << \"MarkdownWindow::setTransparent(\" << transparent << \") for window\" << this;\n isTransparentState = transparent;\n \n // Apply transparency effect by changing the background style\n if (transparent) {\n // qDebug() << \"Setting window background to semi-transparent\";\n applyTransparentStyle();\n } else {\n // qDebug() << \"Setting window background to opaque\";\n applyStyle(); // Restore normal style\n }\n}\n bool isTransparent() const {\n return isTransparentState;\n}\n bool isValidForCanvas() const {\n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n QRect canvasBounds = inkCanvas->getCanvasRect();\n \n // Check if the window is at least partially within the canvas bounds\n return canvasBounds.intersects(canvasRect);\n }\n \n // If no canvas parent, assume valid\n return true;\n}\n QString getCoordinateInfo() const {\n QString info;\n info += QString(\"Canvas Coordinates: (%1, %2) %3x%4\\n\")\n .arg(canvasRect.x()).arg(canvasRect.y())\n .arg(canvasRect.width()).arg(canvasRect.height());\n \n QRect screenRect = geometry();\n info += QString(\"Screen Coordinates: (%1, %2) %3x%4\\n\")\n .arg(screenRect.x()).arg(screenRect.y())\n .arg(screenRect.width()).arg(screenRect.height());\n \n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n QSize canvasSize = inkCanvas->getCanvasSize();\n info += QString(\"Canvas Size: %1x%2\\n\")\n .arg(canvasSize.width()).arg(canvasSize.height());\n \n info += QString(\"Zoom Factor: %1\\n\").arg(inkCanvas->getZoomFactor());\n \n QPointF panOffset = inkCanvas->getPanOffset();\n info += QString(\"Pan Offset: (%1, %2)\\n\")\n .arg(panOffset.x()).arg(panOffset.y());\n \n info += QString(\"Valid for Canvas: %1\\n\").arg(isValidForCanvas() ? \"Yes\" : \"No\");\n } else {\n info += \"No InkCanvas parent found\\n\";\n }\n \n return info;\n}\n void ensureCanvasConnections() {\n // Connect to canvas pan/zoom changes to update position\n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n // Disconnect any existing connections to avoid duplicates\n disconnect(inkCanvas, &InkCanvas::panChanged, this, &MarkdownWindow::updateScreenPosition);\n disconnect(inkCanvas, &InkCanvas::zoomChanged, this, &MarkdownWindow::updateScreenPosition);\n \n // Reconnect\n connect(inkCanvas, &InkCanvas::panChanged, this, &MarkdownWindow::updateScreenPosition);\n connect(inkCanvas, &InkCanvas::zoomChanged, this, &MarkdownWindow::updateScreenPosition);\n \n // Install event filter to handle canvas resize events (for layout changes)\n inkCanvas->installEventFilter(this);\n \n // qDebug() << \"MarkdownWindow::ensureCanvasConnections() - Connected to canvas signals for window\" << this;\n } else {\n // qDebug() << \"MarkdownWindow::ensureCanvasConnections() - No InkCanvas parent found for window\" << this;\n }\n}\n void deleteRequested(MarkdownWindow *window);\n void contentChanged();\n void windowMoved(MarkdownWindow *window);\n void windowResized(MarkdownWindow *window);\n void focusChanged(MarkdownWindow *window, bool focused);\n void editorFocusChanged(MarkdownWindow *window, bool focused);\n void windowInteracted(MarkdownWindow *window);\n protected:\n void mousePressEvent(QMouseEvent *event) override {\n if (event->button() == Qt::LeftButton) {\n // Emit signal to indicate window interaction\n emit windowInteracted(this);\n \n ResizeHandle handle = getResizeHandle(event->pos());\n \n if (handle != None) {\n // Start resizing\n resizing = true;\n isUserInteracting = true;\n currentResizeHandle = handle;\n resizeStartPosition = event->globalPosition().toPoint();\n resizeStartRect = geometry();\n } else if (event->pos().y() < 24) { // Header area\n // Start dragging\n dragging = true;\n isUserInteracting = true;\n dragStartPosition = event->globalPosition().toPoint();\n windowStartPosition = pos();\n }\n }\n \n QWidget::mousePressEvent(event);\n}\n void mouseMoveEvent(QMouseEvent *event) override {\n if (resizing) {\n QPoint delta = event->globalPosition().toPoint() - resizeStartPosition;\n QRect newRect = resizeStartRect;\n \n // Apply resize based on the stored handle\n switch (currentResizeHandle) {\n case TopLeft:\n newRect.setTopLeft(newRect.topLeft() + delta);\n break;\n case TopRight:\n newRect.setTopRight(newRect.topRight() + delta);\n break;\n case BottomLeft:\n newRect.setBottomLeft(newRect.bottomLeft() + delta);\n break;\n case BottomRight:\n newRect.setBottomRight(newRect.bottomRight() + delta);\n break;\n case Top:\n newRect.setTop(newRect.top() + delta.y());\n break;\n case Bottom:\n newRect.setBottom(newRect.bottom() + delta.y());\n break;\n case Left:\n newRect.setLeft(newRect.left() + delta.x());\n break;\n case Right:\n newRect.setRight(newRect.right() + delta.x());\n break;\n default:\n break;\n }\n \n // Enforce minimum size\n newRect.setSize(newRect.size().expandedTo(QSize(200, 150)));\n \n // Keep resized window within canvas bounds\n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n // Convert to canvas coordinates to check bounds\n QRect tempCanvasRect = inkCanvas->mapWidgetToCanvas(newRect);\n QRect canvasBounds = inkCanvas->getCanvasRect();\n \n // Apply canvas bounds constraints\n int maxCanvasX = canvasBounds.width() - tempCanvasRect.width();\n int maxCanvasY = canvasBounds.height() - tempCanvasRect.height();\n \n tempCanvasRect.setX(qMax(0, qMin(tempCanvasRect.x(), maxCanvasX)));\n tempCanvasRect.setY(qMax(0, qMin(tempCanvasRect.y(), maxCanvasY)));\n \n // Also ensure the window doesn't get resized beyond canvas bounds\n if (tempCanvasRect.right() > canvasBounds.width()) {\n tempCanvasRect.setWidth(canvasBounds.width() - tempCanvasRect.x());\n }\n if (tempCanvasRect.bottom() > canvasBounds.height()) {\n tempCanvasRect.setHeight(canvasBounds.height() - tempCanvasRect.y());\n }\n \n // Convert back to screen coordinates for the constrained geometry\n newRect = inkCanvas->mapCanvasToWidget(tempCanvasRect);\n }\n \n // Update the widget geometry directly during resizing\n setGeometry(newRect);\n \n // Convert screen coordinates back to canvas coordinates\n convertScreenToCanvasRect(newRect);\n emit windowResized(this);\n } else if (dragging) {\n QPoint delta = event->globalPosition().toPoint() - dragStartPosition;\n QPoint newPos = windowStartPosition + delta;\n \n // Keep window within canvas bounds (not just parent widget bounds)\n if (InkCanvas *inkCanvas = qobject_cast(parentWidget())) {\n // Convert current position to canvas coordinates to check bounds\n QRect tempScreenRect(newPos, size());\n QRect tempCanvasRect = inkCanvas->mapWidgetToCanvas(tempScreenRect);\n QRect canvasBounds = inkCanvas->getCanvasRect();\n \n // Apply canvas bounds constraints\n int maxCanvasX = canvasBounds.width() - tempCanvasRect.width();\n int maxCanvasY = canvasBounds.height() - tempCanvasRect.height();\n \n tempCanvasRect.setX(qMax(0, qMin(tempCanvasRect.x(), maxCanvasX)));\n tempCanvasRect.setY(qMax(0, qMin(tempCanvasRect.y(), maxCanvasY)));\n \n // Convert back to screen coordinates for the constrained position\n QRect constrainedScreenRect = inkCanvas->mapCanvasToWidget(tempCanvasRect);\n newPos = constrainedScreenRect.topLeft();\n \n // Debug: Log when position is constrained\n if (tempCanvasRect != inkCanvas->mapWidgetToCanvas(QRect(windowStartPosition + delta, size()))) {\n // qDebug() << \"MarkdownWindow: Constraining position to canvas bounds. Canvas rect:\" << tempCanvasRect;\n }\n } else {\n // Fallback: Keep window within parent bounds\n if (parentWidget()) {\n QRect parentRect = parentWidget()->rect();\n newPos.setX(qMax(0, qMin(newPos.x(), parentRect.width() - width())));\n newPos.setY(qMax(0, qMin(newPos.y(), parentRect.height() - height())));\n }\n }\n \n // Update the widget position directly during dragging\n move(newPos);\n \n // Convert screen position back to canvas coordinates\n QRect newScreenRect(newPos, size());\n convertScreenToCanvasRect(newScreenRect);\n emit windowMoved(this);\n } else {\n // Update cursor for resize handles\n updateCursor(event->pos());\n }\n \n QWidget::mouseMoveEvent(event);\n}\n void mouseReleaseEvent(QMouseEvent *event) override {\n if (event->button() == Qt::LeftButton) {\n resizing = false;\n dragging = false;\n isUserInteracting = false;\n currentResizeHandle = None;\n }\n \n QWidget::mouseReleaseEvent(event);\n}\n void resizeEvent(QResizeEvent *event) override {\n QWidget::resizeEvent(event);\n \n // Emit windowResized if this is a user-initiated resize or if we're not updating position due to canvas changes\n if (isUserInteracting || !isUpdatingPosition) {\n emit windowResized(this);\n }\n}\n void paintEvent(QPaintEvent *event) override {\n QWidget::paintEvent(event);\n \n // Draw resize handles\n QPainter painter(this);\n painter.setRenderHint(QPainter::Antialiasing);\n \n QColor handleColor = hasFocus() ? QColor(74, 144, 226) : QColor(180, 180, 180);\n painter.setPen(QPen(handleColor, 2));\n painter.setBrush(QBrush(handleColor));\n \n // Draw corner handles\n int handleSize = 6;\n painter.drawEllipse(0, 0, handleSize, handleSize); // Top-left\n painter.drawEllipse(width() - handleSize, 0, handleSize, handleSize); // Top-right\n painter.drawEllipse(0, height() - handleSize, handleSize, handleSize); // Bottom-left\n painter.drawEllipse(width() - handleSize, height() - handleSize, handleSize, handleSize); // Bottom-right\n}\n void focusInEvent(QFocusEvent *event) override {\n // qDebug() << \"MarkdownWindow::focusInEvent() - Window\" << this << \"gained focus\";\n QWidget::focusInEvent(event);\n emit focusChanged(this, true);\n}\n void focusOutEvent(QFocusEvent *event) override {\n // qDebug() << \"MarkdownWindow::focusOutEvent() - Window\" << this << \"lost focus\";\n QWidget::focusOutEvent(event);\n emit focusChanged(this, false);\n}\n bool eventFilter(QObject *obj, QEvent *event) override {\n if (obj == markdownEditor) {\n if (event->type() == QEvent::FocusIn) {\n // qDebug() << \"MarkdownWindow::eventFilter() - Editor gained focus in window\" << this;\n emit editorFocusChanged(this, true);\n } else if (event->type() == QEvent::FocusOut) {\n // qDebug() << \"MarkdownWindow::eventFilter() - Editor lost focus in window\" << this;\n emit editorFocusChanged(this, false);\n }\n } else if (obj == parentWidget() && event->type() == QEvent::Resize) {\n // Canvas widget was resized (likely due to layout changes like showing/hiding sidebars)\n // Update our screen position to maintain canvas position\n QTimer::singleShot(0, this, [this]() {\n updateScreenPosition();\n });\n }\n return QWidget::eventFilter(obj, event);\n}\n private:\n void onDeleteClicked() {\n emit deleteRequested(this);\n}\n void onMarkdownTextChanged() {\n emit contentChanged();\n}\n private:\n enum ResizeHandle {\n None,\n TopLeft,\n TopRight,\n BottomLeft,\n BottomRight,\n Top,\n Bottom,\n Left,\n Right\n };\n QMarkdownTextEdit *markdownEditor;\n QPushButton *deleteButton;\n QLabel *titleLabel;\n QVBoxLayout *mainLayout;\n QHBoxLayout *headerLayout;\n bool dragging = false;\n QPoint dragStartPosition;\n QPoint windowStartPosition;\n bool resizing = false;\n QPoint resizeStartPosition;\n QRect resizeStartRect;\n ResizeHandle currentResizeHandle = None;\n QRect canvasRect;\n bool isTransparentState = false;\n bool isUpdatingPosition = false;\n bool isUserInteracting = false;\n ResizeHandle getResizeHandle(const QPoint &pos) const {\n const int handleSize = 8;\n const QRect rect = this->rect();\n \n // Check corner handles first\n if (QRect(0, 0, handleSize, handleSize).contains(pos))\n return TopLeft;\n if (QRect(rect.width() - handleSize, 0, handleSize, handleSize).contains(pos))\n return TopRight;\n if (QRect(0, rect.height() - handleSize, handleSize, handleSize).contains(pos))\n return BottomLeft;\n if (QRect(rect.width() - handleSize, rect.height() - handleSize, handleSize, handleSize).contains(pos))\n return BottomRight;\n \n // Check edge handles\n if (QRect(0, 0, rect.width(), handleSize).contains(pos))\n return Top;\n if (QRect(0, rect.height() - handleSize, rect.width(), handleSize).contains(pos))\n return Bottom;\n if (QRect(0, 0, handleSize, rect.height()).contains(pos))\n return Left;\n if (QRect(rect.width() - handleSize, 0, handleSize, rect.height()).contains(pos))\n return Right;\n \n return None;\n}\n void updateCursor(const QPoint &pos) {\n ResizeHandle handle = getResizeHandle(pos);\n \n switch (handle) {\n case TopLeft:\n case BottomRight:\n setCursor(Qt::SizeFDiagCursor);\n break;\n case TopRight:\n case BottomLeft:\n setCursor(Qt::SizeBDiagCursor);\n break;\n case Top:\n case Bottom:\n setCursor(Qt::SizeVerCursor);\n break;\n case Left:\n case Right:\n setCursor(Qt::SizeHorCursor);\n break;\n default:\n if (pos.y() < 24) { // Header area\n setCursor(Qt::SizeAllCursor);\n } else {\n setCursor(Qt::ArrowCursor);\n }\n break;\n }\n}\n void setupUI() {\n mainLayout = new QVBoxLayout(this);\n mainLayout->setContentsMargins(2, 2, 2, 2);\n mainLayout->setSpacing(0);\n \n // Header with title and delete button\n headerLayout = new QHBoxLayout();\n headerLayout->setContentsMargins(4, 2, 4, 2);\n headerLayout->setSpacing(4);\n \n titleLabel = new QLabel(\"Markdown\", this);\n titleLabel->setStyleSheet(\"font-weight: bold; color: #333;\");\n \n deleteButton = new QPushButton(\"×\", this);\n deleteButton->setFixedSize(16, 16);\n deleteButton->setStyleSheet(R\"(\n QPushButton {\n background-color: #ff4444;\n color: white;\n border: none;\n border-radius: 8px;\n font-weight: bold;\n font-size: 10px;\n }\n QPushButton:hover {\n background-color: #ff6666;\n }\n QPushButton:pressed {\n background-color: #cc2222;\n }\n )\");\n \n connect(deleteButton, &QPushButton::clicked, this, &MarkdownWindow::onDeleteClicked);\n \n headerLayout->addWidget(titleLabel);\n headerLayout->addStretch();\n headerLayout->addWidget(deleteButton);\n \n // Markdown editor\n markdownEditor = new QMarkdownTextEdit(this);\n markdownEditor->setPlainText(\"\"); // Start with empty content\n \n connect(markdownEditor, &QMarkdownTextEdit::textChanged, this, &MarkdownWindow::onMarkdownTextChanged);\n \n // Connect editor focus events using event filter\n markdownEditor->installEventFilter(this);\n \n mainLayout->addLayout(headerLayout);\n mainLayout->addWidget(markdownEditor);\n}\n void applyStyle() {\n // Detect dark mode using the same method as MainWindow\n bool isDarkMode = palette().color(QPalette::Window).lightness() < 128;\n \n QString backgroundColor = isDarkMode ? \"#2b2b2b\" : \"white\";\n QString borderColor = isDarkMode ? \"#555555\" : \"#cccccc\";\n QString headerBackgroundColor = isDarkMode ? \"#3c3c3c\" : \"#f0f0f0\";\n QString focusBorderColor = isDarkMode ? \"#6ca9dc\" : \"#4a90e2\";\n \n setStyleSheet(QString(R\"(\n MarkdownWindow {\n background-color: %1;\n border: 2px solid %2;\n border-radius: 4px;\n }\n MarkdownWindow:focus {\n border-color: %3;\n }\n )\").arg(backgroundColor, borderColor, focusBorderColor));\n \n // Style the header\n if (headerLayout && headerLayout->parentWidget()) {\n headerLayout->parentWidget()->setStyleSheet(QString(R\"(\n background-color: %1;\n border-bottom: 1px solid %2;\n )\").arg(headerBackgroundColor, borderColor));\n }\n \n // Reset the markdown editor style to default (opaque)\n if (markdownEditor) {\n markdownEditor->setStyleSheet(\"\"); // Clear any custom styles\n }\n}\n void applyTransparentStyle() {\n // Detect dark mode using the same method as MainWindow\n bool isDarkMode = palette().color(QPalette::Window).lightness() < 128;\n \n QString backgroundColor = isDarkMode ? \"rgba(43, 43, 43, 0.3)\" : \"rgba(255, 255, 255, 0.3)\"; // 30% opacity\n QString borderColor = isDarkMode ? \"#555555\" : \"#cccccc\";\n QString headerBackgroundColor = isDarkMode ? \"rgba(60, 60, 60, 0.3)\" : \"rgba(240, 240, 240, 0.3)\"; // 30% opacity\n QString focusBorderColor = isDarkMode ? \"#6ca9dc\" : \"#4a90e2\";\n \n setStyleSheet(QString(R\"(\n MarkdownWindow {\n background-color: %1;\n border: 2px solid %2;\n border-radius: 4px;\n }\n MarkdownWindow:focus {\n border-color: %3;\n }\n )\").arg(backgroundColor, borderColor, focusBorderColor));\n \n // Style the header with transparency\n if (headerLayout && headerLayout->parentWidget()) {\n headerLayout->parentWidget()->setStyleSheet(QString(R\"(\n background-color: %1;\n border-bottom: 1px solid %2;\n )\").arg(headerBackgroundColor, borderColor));\n }\n \n // Make the markdown editor background semi-transparent too\n if (markdownEditor) {\n QString editorBg = isDarkMode ? \"rgba(43, 43, 43, 0.3)\" : \"rgba(255, 255, 255, 0.3)\";\n markdownEditor->setStyleSheet(QString(R\"(\n QMarkdownTextEdit {\n background-color: %1;\n border: none;\n }\n )\").arg(editorBg));\n }\n}\n void convertScreenToCanvasRect(const QRect &screenRect) {\n // Get the canvas parent to access coordinate conversion methods\n if (QWidget *canvas = parentWidget()) {\n // Try to cast to InkCanvas to use the new coordinate methods\n if (InkCanvas *inkCanvas = qobject_cast(canvas)) {\n // Use the new coordinate conversion methods\n QRect oldCanvasRect = canvasRect;\n QRect newCanvasRect = inkCanvas->mapWidgetToCanvas(screenRect);\n \n // Store the converted canvas coordinates without bounds checking\n // Bounds checking should only happen during user interaction (dragging/resizing)\n canvasRect = newCanvasRect;\n // Only log if there was a significant change (and not during mouse movement)\n if ((canvasRect.topLeft() - oldCanvasRect.topLeft()).manhattanLength() > 10 && !dragging && !resizing) {\n // qDebug() << \"MarkdownWindow::convertScreenToCanvasRect() - Screen rect:\" << screenRect << \"-> Canvas rect:\" << canvasRect;\n // qDebug() << \" Old canvas rect:\" << oldCanvasRect;\n }\n } else {\n // Fallback: use screen coordinates directly\n // qDebug() << \"MarkdownWindow::convertScreenToCanvasRect() - No InkCanvas parent, using screen rect directly:\" << screenRect;\n canvasRect = screenRect;\n }\n } else {\n // No parent, use screen coordinates directly\n // qDebug() << \"MarkdownWindow::convertScreenToCanvasRect() - No parent, using screen rect directly:\" << screenRect;\n canvasRect = screenRect;\n }\n}\n};"], ["/SpeedyNote/source/MainWindow.h", "class QTreeWidgetItem {\n Q_OBJECT\n\npublic:\n explicit MainWindow(QWidget *parent = nullptr);\n virtual ~MainWindow() {\n\n saveButtonMappings(); // ✅ Save on exit, as backup\n delete canvas;\n}\n int getCurrentPageForCanvas(InkCanvas *canvas) {\n return pageMap.contains(canvas) ? pageMap[canvas] : 0;\n}\n bool lowResPreviewEnabled = true;\n void setLowResPreviewEnabled(bool enabled) {\n lowResPreviewEnabled = enabled;\n\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"lowResPreviewEnabled\", enabled);\n}\n bool isLowResPreviewEnabled() const {\n return lowResPreviewEnabled;\n}\n bool areBenchmarkControlsVisible() const {\n return benchmarkButton->isVisible() && benchmarkLabel->isVisible();\n}\n void setBenchmarkControlsVisible(bool visible) {\n benchmarkButton->setVisible(visible);\n benchmarkLabel->setVisible(visible);\n}\n bool zoomButtonsVisible = true;\n bool areZoomButtonsVisible() const {\n return zoomButtonsVisible;\n}\n void setZoomButtonsVisible(bool visible) {\n zoom50Button->setVisible(visible);\n dezoomButton->setVisible(visible);\n zoom200Button->setVisible(visible);\n\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"zoomButtonsVisible\", visible);\n \n // Update zoomButtonsVisible flag and trigger layout update\n zoomButtonsVisible = visible;\n \n // Trigger layout update to adjust responsive thresholds\n if (layoutUpdateTimer) {\n layoutUpdateTimer->stop();\n layoutUpdateTimer->start(50); // Quick update for settings change\n } else {\n updateToolbarLayout(); // Direct update if no timer exists yet\n }\n}\n bool scrollOnTopEnabled = false;\n bool isScrollOnTopEnabled() const {\n return scrollOnTopEnabled;\n}\n void setScrollOnTopEnabled(bool enabled) {\n scrollOnTopEnabled = enabled;\n\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"scrollOnTopEnabled\", enabled);\n}\n bool touchGesturesEnabled = true;\n bool areTouchGesturesEnabled() const {\n return touchGesturesEnabled;\n}\n void setTouchGesturesEnabled(bool enabled) {\n touchGesturesEnabled = enabled;\n \n // Apply to all canvases\n for (int i = 0; i < canvasStack->count(); ++i) {\n InkCanvas *canvas = qobject_cast(canvasStack->widget(i));\n if (canvas) {\n canvas->setTouchGesturesEnabled(enabled);\n }\n }\n \n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"touchGesturesEnabled\", enabled);\n}\n QColor customAccentColor;\n bool useCustomAccentColor = false;\n QColor getAccentColor() const {\n if (useCustomAccentColor && customAccentColor.isValid()) {\n return customAccentColor;\n }\n \n // Return system accent color\n QPalette palette = QGuiApplication::palette();\n return palette.highlight().color();\n}\n void setCustomAccentColor(const QColor &color) {\n if (customAccentColor != color) {\n customAccentColor = color;\n saveThemeSettings();\n // Always update theme if custom accent color is enabled\n if (useCustomAccentColor) {\n updateTheme();\n }\n }\n}\n void setUseCustomAccentColor(bool use) {\n if (useCustomAccentColor != use) {\n useCustomAccentColor = use;\n updateTheme();\n saveThemeSettings();\n }\n}\n void setUseBrighterPalette(bool use) {\n if (useBrighterPalette != use) {\n useBrighterPalette = use;\n \n // Update all colors - call updateColorPalette which handles null checks\n updateColorPalette();\n \n // Save preference\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"useBrighterPalette\", useBrighterPalette);\n }\n}\n QColor getDefaultPenColor() {\n return isDarkMode() ? Qt::white : Qt::black;\n}\n SDLControllerManager *controllerManager = nullptr;\n QThread *controllerThread = nullptr;\n QString getHoldMapping(const QString &buttonName) {\n return buttonHoldMapping.value(buttonName, \"None\");\n}\n QString getPressMapping(const QString &buttonName) {\n return buttonPressMapping.value(buttonName, \"None\");\n}\n void saveButtonMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n\n settings.beginGroup(\"ButtonHoldMappings\");\n for (auto it = buttonHoldMapping.begin(); it != buttonHoldMapping.end(); ++it) {\n settings.setValue(it.key(), it.value());\n }\n settings.endGroup();\n\n settings.beginGroup(\"ButtonPressMappings\");\n for (auto it = buttonPressMapping.begin(); it != buttonPressMapping.end(); ++it) {\n settings.setValue(it.key(), it.value());\n }\n settings.endGroup();\n}\n void loadButtonMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n\n // First, check if we need to migrate old settings\n migrateOldButtonMappings();\n\n settings.beginGroup(\"ButtonHoldMappings\");\n QStringList holdKeys = settings.allKeys();\n for (const QString &key : holdKeys) {\n buttonHoldMapping[key] = settings.value(key, \"none\").toString();\n }\n settings.endGroup();\n\n settings.beginGroup(\"ButtonPressMappings\");\n QStringList pressKeys = settings.allKeys();\n for (const QString &key : pressKeys) {\n QString value = settings.value(key, \"none\").toString();\n buttonPressMapping[key] = value;\n\n // ✅ Convert internal key to action enum\n buttonPressActionMapping[key] = stringToAction(value);\n }\n settings.endGroup();\n}\n void setHoldMapping(const QString &buttonName, const QString &dialMode) {\n buttonHoldMapping[buttonName] = dialMode;\n}\n void setPressMapping(const QString &buttonName, const QString &action) {\n buttonPressMapping[buttonName] = action;\n buttonPressActionMapping[buttonName] = stringToAction(action); // ✅ THIS LINE WAS MISSING\n}\n DialMode dialModeFromString(const QString &mode) {\n // Convert internal key to our existing DialMode enum\n InternalDialMode internalMode = ButtonMappingHelper::internalKeyToDialMode(mode);\n \n switch (internalMode) {\n case InternalDialMode::None: return PageSwitching; // Default fallback\n case InternalDialMode::PageSwitching: return PageSwitching;\n case InternalDialMode::ZoomControl: return ZoomControl;\n case InternalDialMode::ThicknessControl: return ThicknessControl;\n\n case InternalDialMode::ToolSwitching: return ToolSwitching;\n case InternalDialMode::PresetSelection: return PresetSelection;\n case InternalDialMode::PanAndPageScroll: return PanAndPageScroll;\n }\n return PanAndPageScroll; // Default fallback\n}\n void importNotebookFromFile(const QString &packageFile) {\n\n QString destDir = QFileDialog::getExistingDirectory(this, tr(\"Select Working Directory for Notebook\"));\n\n if (destDir.isEmpty()) {\n QMessageBox::warning(this, tr(\"Import Cancelled\"), tr(\"No directory selected. Notebook will not be opened.\"));\n return;\n }\n\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n\n canvas->importNotebookTo(packageFile, destDir);\n\n // Change saveFolder in InkCanvas\n canvas->setSaveFolder(destDir);\n canvas->loadPage(0);\n updateZoom(); // ✅ Update zoom and pan range after importing notebook\n}\n void openPdfFile(const QString &pdfPath) {\n // Check if the PDF file exists\n if (!QFile::exists(pdfPath)) {\n QMessageBox::warning(this, tr(\"File Not Found\"), tr(\"The PDF file could not be found:\\n%1\").arg(pdfPath));\n return;\n }\n \n // First, check if there's already a valid notebook folder for this PDF\n QString existingFolderPath;\n if (PdfOpenDialog::hasValidNotebookFolder(pdfPath, existingFolderPath)) {\n // Found a valid notebook folder, open it directly without showing dialog\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n \n // Save current work if edited\n if (canvas->isEdited()) {\n saveCurrentPage();\n }\n \n // Set the existing folder as save folder\n canvas->setSaveFolder(existingFolderPath);\n \n // Load the PDF\n canvas->loadPdf(pdfPath);\n \n // Update tab label and recent notebooks\n updateTabLabel();\n if (recentNotebooksManager) {\n recentNotebooksManager->addRecentNotebook(existingFolderPath, canvas);\n }\n \n // Switch to page 1 and update UI\n switchPageWithDirection(1, 1);\n pageInput->setValue(1);\n updateZoom();\n updatePanRange();\n \n return; // Exit early, no need to show dialog\n }\n \n // No valid notebook folder found, show the dialog with options\n PdfOpenDialog dialog(pdfPath, this);\n dialog.exec();\n \n PdfOpenDialog::Result result = dialog.getResult();\n QString selectedFolder = dialog.getSelectedFolder();\n \n if (result == PdfOpenDialog::Cancel) {\n return; // User cancelled, do nothing\n }\n \n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n \n // Save current work if edited\n if (canvas->isEdited()) {\n saveCurrentPage();\n }\n \n if (result == PdfOpenDialog::CreateNewFolder) {\n // Set the new folder as save folder\n canvas->setSaveFolder(selectedFolder);\n \n // Load the PDF\n canvas->loadPdf(pdfPath);\n \n // Update tab label and recent notebooks\n updateTabLabel();\n if (recentNotebooksManager) {\n recentNotebooksManager->addRecentNotebook(selectedFolder, canvas);\n }\n \n // Switch to page 1 and update UI\n switchPageWithDirection(1, 1);\n pageInput->setValue(1);\n updateZoom();\n updatePanRange();\n \n } else if (result == PdfOpenDialog::UseExistingFolder) {\n // Check if the existing folder is linked to the same PDF\n QString metadataFile = selectedFolder + \"/.pdf_path.txt\";\n bool isLinkedToSamePdf = false;\n \n if (QFile::exists(metadataFile)) {\n QFile file(metadataFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString existingPdfPath = in.readLine().trimmed();\n file.close();\n \n // Compare absolute paths\n QFileInfo existingInfo(existingPdfPath);\n QFileInfo newInfo(pdfPath);\n isLinkedToSamePdf = (existingInfo.absoluteFilePath() == newInfo.absoluteFilePath());\n }\n }\n \n if (!isLinkedToSamePdf && QFile::exists(metadataFile)) {\n // Folder is linked to a different PDF, ask user what to do\n QMessageBox::StandardButton reply = QMessageBox::question(\n this,\n tr(\"Different PDF Linked\"),\n tr(\"This notebook folder is already linked to a different PDF file.\\n\\nDo you want to replace the link with the new PDF?\"),\n QMessageBox::Yes | QMessageBox::No\n );\n \n if (reply == QMessageBox::No) {\n return; // User chose not to replace\n }\n }\n \n // Set the existing folder as save folder\n canvas->setSaveFolder(selectedFolder);\n \n // Load the PDF\n canvas->loadPdf(pdfPath);\n \n // Update tab label and recent notebooks\n updateTabLabel();\n if (recentNotebooksManager) {\n recentNotebooksManager->addRecentNotebook(selectedFolder, canvas);\n }\n \n // Switch to page 1 and update UI\n switchPageWithDirection(1, 1);\n pageInput->setValue(1);\n updateZoom();\n updatePanRange();\n }\n}\n void setPdfDPI(int dpi) {\n if (dpi != pdfRenderDPI) {\n pdfRenderDPI = dpi;\n savePdfDPI(dpi);\n\n // Apply immediately to current canvas if needed\n if (currentCanvas()) {\n currentCanvas()->setPDFRenderDPI(dpi);\n currentCanvas()->clearPdfCache();\n currentCanvas()->loadPdfPage(getCurrentPageForCanvas(currentCanvas())); // Optional: add this if needed\n updateZoom();\n updatePanRange();\n }\n }\n}\n void savePdfDPI(int dpi) {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"pdfRenderDPI\", dpi);\n}\n void saveDefaultBackgroundSettings(BackgroundStyle style, QColor color, int density) {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"defaultBackgroundStyle\", static_cast(style));\n settings.setValue(\"defaultBackgroundColor\", color.name());\n settings.setValue(\"defaultBackgroundDensity\", density);\n}\n void loadDefaultBackgroundSettings(BackgroundStyle &style, QColor &color, int &density) {\n QSettings settings(\"SpeedyNote\", \"App\");\n style = static_cast(settings.value(\"defaultBackgroundStyle\", static_cast(BackgroundStyle::Grid)).toInt());\n color = QColor(settings.value(\"defaultBackgroundColor\", \"#FFFFFF\").toString());\n density = settings.value(\"defaultBackgroundDensity\", 30).toInt();\n \n // Ensure valid values\n if (!color.isValid()) color = Qt::white;\n if (density < 10) density = 10;\n if (density > 200) density = 200;\n}\n void saveThemeSettings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.setValue(\"useCustomAccentColor\", useCustomAccentColor);\n if (customAccentColor.isValid()) {\n settings.setValue(\"customAccentColor\", customAccentColor.name());\n }\n settings.setValue(\"useBrighterPalette\", useBrighterPalette);\n}\n void loadThemeSettings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n useCustomAccentColor = settings.value(\"useCustomAccentColor\", false).toBool();\n QString colorName = settings.value(\"customAccentColor\", \"#0078D4\").toString();\n customAccentColor = QColor(colorName);\n useBrighterPalette = settings.value(\"useBrighterPalette\", false).toBool();\n \n // Ensure valid values\n if (!customAccentColor.isValid()) {\n customAccentColor = QColor(\"#0078D4\"); // Default blue\n }\n \n // Apply theme immediately after loading\n updateTheme();\n}\n void updateTheme() {\n // Update control bar background color\n QColor accentColor = getAccentColor();\n if (controlBar) {\n controlBar->setStyleSheet(QString(R\"(\n QWidget#controlBar {\n background-color: %1;\n }\n )\").arg(accentColor.name()));\n }\n \n // Update dial background color\n if (pageDial) {\n pageDial->setStyleSheet(QString(R\"(\n QDial {\n background-color: %1;\n }\n )\").arg(accentColor.name()));\n }\n \n // Update add tab button styling\n if (addTabButton) {\n bool darkMode = isDarkMode();\n QString buttonBgColor = darkMode ? \"rgba(80, 80, 80, 255)\" : \"rgba(220, 220, 220, 255)\";\n QString buttonHoverColor = darkMode ? \"rgba(90, 90, 90, 255)\" : \"rgba(200, 200, 200, 255)\";\n QString buttonPressColor = darkMode ? \"rgba(70, 70, 70, 255)\" : \"rgba(180, 180, 180, 255)\";\n QString borderColor = darkMode ? \"rgba(100, 100, 100, 255)\" : \"rgba(180, 180, 180, 255)\";\n \n addTabButton->setStyleSheet(QString(R\"(\n QPushButton {\n background-color: %1;\n border: 1px solid %2;\n border-radius: 12px;\n margin: 2px;\n }\n QPushButton:hover {\n background-color: %3;\n }\n QPushButton:pressed {\n background-color: %4;\n }\n )\").arg(buttonBgColor).arg(borderColor).arg(buttonHoverColor).arg(buttonPressColor));\n }\n \n // Update PDF outline sidebar styling\n if (outlineSidebar && outlineTree) {\n bool darkMode = isDarkMode();\n QString bgColor = darkMode ? \"rgba(45, 45, 45, 255)\" : \"rgba(250, 250, 250, 255)\";\n QString borderColor = darkMode ? \"rgba(80, 80, 80, 255)\" : \"rgba(200, 200, 200, 255)\";\n QString textColor = darkMode ? \"#E0E0E0\" : \"#333\";\n QString hoverColor = darkMode ? \"rgba(60, 60, 60, 255)\" : \"rgba(240, 240, 240, 255)\";\n QString selectedColor = QString(\"rgba(%1, %2, %3, 100)\").arg(accentColor.red()).arg(accentColor.green()).arg(accentColor.blue());\n \n outlineSidebar->setStyleSheet(QString(R\"(\n QWidget {\n background-color: %1;\n border-right: 1px solid %2;\n }\n QLabel {\n color: %3;\n background: transparent;\n }\n )\").arg(bgColor).arg(borderColor).arg(textColor));\n \n outlineTree->setStyleSheet(QString(R\"(\n QTreeWidget {\n background-color: %1;\n border: none;\n color: %2;\n outline: none;\n }\n QTreeWidget::item {\n padding: 4px;\n border: none;\n }\n QTreeWidget::item:hover {\n background-color: %3;\n }\n QTreeWidget::item:selected {\n background-color: %4;\n color: %2;\n }\n QTreeWidget::branch {\n background: transparent;\n }\n QTreeWidget::branch:has-children:!has-siblings:closed,\n QTreeWidget::branch:closed:has-children:has-siblings {\n border-image: none;\n image: url(:/resources/icons/down_arrow.png);\n }\n QTreeWidget::branch:open:has-children:!has-siblings,\n QTreeWidget::branch:open:has-children:has-siblings {\n border-image: none;\n image: url(:/resources/icons/up_arrow.png);\n }\n QScrollBar:vertical {\n background: rgba(200, 200, 200, 80);\n border: none;\n margin: 0px;\n width: 16px !important;\n max-width: 16px !important;\n }\n QScrollBar:vertical:hover {\n background: rgba(200, 200, 200, 120);\n }\n QScrollBar::handle:vertical {\n background: rgba(100, 100, 100, 150);\n border-radius: 2px;\n min-height: 120px;\n }\n QScrollBar::handle:vertical:hover {\n background: rgba(80, 80, 80, 210);\n }\n QScrollBar::add-line:vertical, \n QScrollBar::sub-line:vertical {\n width: 0px;\n height: 0px;\n background: none;\n border: none;\n }\n QScrollBar::add-page:vertical, \n QScrollBar::sub-page:vertical {\n background: transparent;\n }\n )\").arg(bgColor).arg(textColor).arg(hoverColor).arg(selectedColor));\n \n // Apply same styling to bookmarks tree\n bookmarksTree->setStyleSheet(QString(R\"(\n QTreeWidget {\n background-color: %1;\n border: none;\n color: %2;\n outline: none;\n }\n QTreeWidget::item {\n padding: 2px;\n border: none;\n min-height: 26px;\n }\n QTreeWidget::item:hover {\n background-color: %3;\n }\n QTreeWidget::item:selected {\n background-color: %4;\n color: %2;\n }\n QScrollBar:vertical {\n background: rgba(200, 200, 200, 80);\n border: none;\n margin: 0px;\n width: 16px !important;\n max-width: 16px !important;\n }\n QScrollBar:vertical:hover {\n background: rgba(200, 200, 200, 120);\n }\n QScrollBar::handle:vertical {\n background: rgba(100, 100, 100, 150);\n border-radius: 2px;\n min-height: 120px;\n }\n QScrollBar::handle:vertical:hover {\n background: rgba(80, 80, 80, 210);\n }\n QScrollBar::add-line:vertical, \n QScrollBar::sub-line:vertical {\n width: 0px;\n height: 0px;\n background: none;\n border: none;\n }\n QScrollBar::add-page:vertical, \n QScrollBar::sub-page:vertical {\n background: transparent;\n }\n )\").arg(bgColor).arg(textColor).arg(hoverColor).arg(selectedColor));\n }\n \n // Update horizontal tab bar styling with accent color\n if (tabList) {\n bool darkMode = isDarkMode();\n QString bgColor = darkMode ? \"rgba(60, 60, 60, 255)\" : \"rgba(240, 240, 240, 255)\";\n QString itemBgColor = darkMode ? \"rgba(80, 80, 80, 255)\" : \"rgba(220, 220, 220, 255)\";\n QString selectedBgColor = darkMode ? \"rgba(45, 45, 45, 255)\" : \"white\";\n QString borderColor = darkMode ? \"rgba(100, 100, 100, 255)\" : \"rgba(180, 180, 180, 255)\";\n QString hoverBgColor = darkMode ? \"rgba(90, 90, 90, 255)\" : \"rgba(230, 230, 230, 255)\";\n \n tabList->setStyleSheet(QString(R\"(\n QListWidget {\n background-color: %1;\n border: none;\n border-bottom: 2px solid %2;\n outline: none;\n }\n QListWidget::item {\n background-color: %3;\n border: 1px solid %4;\n border-bottom: none;\n margin-right: 1px;\n margin-top: 2px;\n padding: 0px;\n min-width: 80px;\n max-width: 120px;\n }\n QListWidget::item:selected {\n background-color: %5;\n border: 1px solid %4;\n border-bottom: 2px solid %2;\n margin-top: 1px;\n }\n QListWidget::item:hover:!selected {\n background-color: %6;\n }\n QScrollBar:horizontal {\n background: %1;\n height: 8px;\n border: none;\n margin: 0px;\n border-top: 1px solid %4;\n }\n QScrollBar::handle:horizontal {\n background: rgba(150, 150, 150, 120);\n border-radius: 4px;\n min-width: 20px;\n margin: 1px;\n }\n QScrollBar::handle:horizontal:hover {\n background: rgba(120, 120, 120, 200);\n }\n QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal {\n width: 0px;\n height: 0px;\n background: none;\n border: none;\n }\n QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {\n background: transparent;\n }\n )\").arg(bgColor)\n .arg(accentColor.name())\n .arg(itemBgColor)\n .arg(borderColor)\n .arg(selectedBgColor)\n .arg(hoverBgColor));\n }\n \n\n \n // Force icon reload for all buttons that use themed icons\n if (loadPdfButton) loadPdfButton->setIcon(loadThemedIcon(\"pdf\"));\n if (clearPdfButton) clearPdfButton->setIcon(loadThemedIcon(\"pdfdelete\"));\n if (pdfTextSelectButton) pdfTextSelectButton->setIcon(loadThemedIcon(\"ibeam\"));\n if (exportNotebookButton) exportNotebookButton->setIcon(loadThemedIcon(\"export\"));\n if (importNotebookButton) importNotebookButton->setIcon(loadThemedIcon(\"import\"));\n if (benchmarkButton) benchmarkButton->setIcon(loadThemedIcon(\"benchmark\"));\n if (toggleTabBarButton) toggleTabBarButton->setIcon(loadThemedIcon(\"tabs\"));\n if (toggleOutlineButton) toggleOutlineButton->setIcon(loadThemedIcon(\"outline\"));\n if (toggleBookmarksButton) toggleBookmarksButton->setIcon(loadThemedIcon(\"bookmark\"));\n if (toggleBookmarkButton) toggleBookmarkButton->setIcon(loadThemedIcon(\"star\"));\n if (selectFolderButton) selectFolderButton->setIcon(loadThemedIcon(\"folder\"));\n if (saveButton) saveButton->setIcon(loadThemedIcon(\"save\"));\n if (saveAnnotatedButton) saveAnnotatedButton->setIcon(loadThemedIcon(\"saveannotated\"));\n if (fullscreenButton) fullscreenButton->setIcon(loadThemedIcon(\"fullscreen\"));\n if (backgroundButton) backgroundButton->setIcon(loadThemedIcon(\"background\"));\n if (straightLineToggleButton) straightLineToggleButton->setIcon(loadThemedIcon(\"straightLine\"));\n if (ropeToolButton) ropeToolButton->setIcon(loadThemedIcon(\"rope\"));\n if (markdownButton) markdownButton->setIcon(loadThemedIcon(\"markdown\"));\n if (deletePageButton) deletePageButton->setIcon(loadThemedIcon(\"trash\"));\n if (zoomButton) zoomButton->setIcon(loadThemedIcon(\"zoom\"));\n if (dialToggleButton) dialToggleButton->setIcon(loadThemedIcon(\"dial\"));\n if (fastForwardButton) fastForwardButton->setIcon(loadThemedIcon(\"fastforward\"));\n if (jumpToPageButton) jumpToPageButton->setIcon(loadThemedIcon(\"bookpage\"));\n if (thicknessButton) thicknessButton->setIcon(loadThemedIcon(\"thickness\"));\n if (btnPageSwitch) btnPageSwitch->setIcon(loadThemedIcon(\"bookpage\"));\n if (btnZoom) btnZoom->setIcon(loadThemedIcon(\"zoom\"));\n if (btnThickness) btnThickness->setIcon(loadThemedIcon(\"thickness\"));\n if (btnTool) btnTool->setIcon(loadThemedIcon(\"pen\"));\n if (btnPresets) btnPresets->setIcon(loadThemedIcon(\"preset\"));\n if (btnPannScroll) btnPannScroll->setIcon(loadThemedIcon(\"scroll\"));\n if (addPresetButton) addPresetButton->setIcon(loadThemedIcon(\"savepreset\"));\n if (openControlPanelButton) openControlPanelButton->setIcon(loadThemedIcon(\"settings\"));\n if (openRecentNotebooksButton) openRecentNotebooksButton->setIcon(loadThemedIcon(\"recent\"));\n if (penToolButton) penToolButton->setIcon(loadThemedIcon(\"pen\"));\n if (markerToolButton) markerToolButton->setIcon(loadThemedIcon(\"marker\"));\n if (eraserToolButton) eraserToolButton->setIcon(loadThemedIcon(\"eraser\"));\n \n // Update button styles with new theme\n bool darkMode = isDarkMode();\n QString newButtonStyle = createButtonStyle(darkMode);\n \n // Update all buttons that use the buttonStyle\n if (loadPdfButton) loadPdfButton->setStyleSheet(newButtonStyle);\n if (clearPdfButton) clearPdfButton->setStyleSheet(newButtonStyle);\n if (pdfTextSelectButton) pdfTextSelectButton->setStyleSheet(newButtonStyle);\n if (exportNotebookButton) exportNotebookButton->setStyleSheet(newButtonStyle);\n if (importNotebookButton) importNotebookButton->setStyleSheet(newButtonStyle);\n if (benchmarkButton) benchmarkButton->setStyleSheet(newButtonStyle);\n if (toggleTabBarButton) toggleTabBarButton->setStyleSheet(newButtonStyle);\n if (toggleOutlineButton) toggleOutlineButton->setStyleSheet(newButtonStyle);\n if (toggleBookmarksButton) toggleBookmarksButton->setStyleSheet(newButtonStyle);\n if (toggleBookmarkButton) toggleBookmarkButton->setStyleSheet(newButtonStyle);\n if (selectFolderButton) selectFolderButton->setStyleSheet(newButtonStyle);\n if (saveButton) saveButton->setStyleSheet(newButtonStyle);\n if (saveAnnotatedButton) saveAnnotatedButton->setStyleSheet(newButtonStyle);\n if (fullscreenButton) fullscreenButton->setStyleSheet(newButtonStyle);\n if (redButton) redButton->setStyleSheet(newButtonStyle);\n if (blueButton) blueButton->setStyleSheet(newButtonStyle);\n if (yellowButton) yellowButton->setStyleSheet(newButtonStyle);\n if (greenButton) greenButton->setStyleSheet(newButtonStyle);\n if (blackButton) blackButton->setStyleSheet(newButtonStyle);\n if (whiteButton) whiteButton->setStyleSheet(newButtonStyle);\n if (thicknessButton) thicknessButton->setStyleSheet(newButtonStyle);\n if (penToolButton) penToolButton->setStyleSheet(newButtonStyle);\n if (markerToolButton) markerToolButton->setStyleSheet(newButtonStyle);\n if (eraserToolButton) eraserToolButton->setStyleSheet(newButtonStyle);\n if (backgroundButton) backgroundButton->setStyleSheet(newButtonStyle);\n if (straightLineToggleButton) straightLineToggleButton->setStyleSheet(newButtonStyle);\n if (ropeToolButton) ropeToolButton->setStyleSheet(newButtonStyle);\n if (markdownButton) markdownButton->setStyleSheet(newButtonStyle);\n if (deletePageButton) deletePageButton->setStyleSheet(newButtonStyle);\n if (zoomButton) zoomButton->setStyleSheet(newButtonStyle);\n if (dialToggleButton) dialToggleButton->setStyleSheet(newButtonStyle);\n if (fastForwardButton) fastForwardButton->setStyleSheet(newButtonStyle);\n if (jumpToPageButton) jumpToPageButton->setStyleSheet(newButtonStyle);\n if (btnPageSwitch) btnPageSwitch->setStyleSheet(newButtonStyle);\n if (btnZoom) btnZoom->setStyleSheet(newButtonStyle);\n if (btnThickness) btnThickness->setStyleSheet(newButtonStyle);\n if (btnTool) btnTool->setStyleSheet(newButtonStyle);\n if (btnPresets) btnPresets->setStyleSheet(newButtonStyle);\n if (btnPannScroll) btnPannScroll->setStyleSheet(newButtonStyle);\n if (addPresetButton) addPresetButton->setStyleSheet(newButtonStyle);\n if (openControlPanelButton) openControlPanelButton->setStyleSheet(newButtonStyle);\n if (openRecentNotebooksButton) openRecentNotebooksButton->setStyleSheet(newButtonStyle);\n if (zoom50Button) zoom50Button->setStyleSheet(newButtonStyle);\n if (dezoomButton) dezoomButton->setStyleSheet(newButtonStyle);\n if (zoom200Button) zoom200Button->setStyleSheet(newButtonStyle);\n if (prevPageButton) prevPageButton->setStyleSheet(newButtonStyle);\n if (nextPageButton) nextPageButton->setStyleSheet(newButtonStyle);\n \n // Update color buttons with palette-based icons\n if (redButton) {\n QString redIconPath = useBrighterPalette ? \":/resources/icons/pen_light_red.png\" : \":/resources/icons/pen_dark_red.png\";\n redButton->setIcon(QIcon(redIconPath));\n }\n if (blueButton) {\n QString blueIconPath = useBrighterPalette ? \":/resources/icons/pen_light_blue.png\" : \":/resources/icons/pen_dark_blue.png\";\n blueButton->setIcon(QIcon(blueIconPath));\n }\n if (yellowButton) {\n QString yellowIconPath = useBrighterPalette ? \":/resources/icons/pen_light_yellow.png\" : \":/resources/icons/pen_dark_yellow.png\";\n yellowButton->setIcon(QIcon(yellowIconPath));\n }\n if (greenButton) {\n QString greenIconPath = useBrighterPalette ? \":/resources/icons/pen_light_green.png\" : \":/resources/icons/pen_dark_green.png\";\n greenButton->setIcon(QIcon(greenIconPath));\n }\n if (blackButton) {\n QString blackIconPath = darkMode ? \":/resources/icons/pen_light_black.png\" : \":/resources/icons/pen_dark_black.png\";\n blackButton->setIcon(QIcon(blackIconPath));\n }\n if (whiteButton) {\n QString whiteIconPath = darkMode ? \":/resources/icons/pen_light_white.png\" : \":/resources/icons/pen_dark_white.png\";\n whiteButton->setIcon(QIcon(whiteIconPath));\n }\n \n // Update tab close button icons and label styling\n if (tabList) {\n bool darkMode = isDarkMode();\n QString labelColor = darkMode ? \"#E0E0E0\" : \"#333\";\n \n for (int i = 0; i < tabList->count(); ++i) {\n QListWidgetItem *item = tabList->item(i);\n if (item) {\n QWidget *tabWidget = tabList->itemWidget(item);\n if (tabWidget) {\n QPushButton *closeButton = tabWidget->findChild();\n if (closeButton) {\n closeButton->setIcon(loadThemedIcon(\"cross\"));\n }\n \n QLabel *tabLabel = tabWidget->findChild(\"tabLabel\");\n if (tabLabel) {\n tabLabel->setStyleSheet(QString(\"color: %1; font-weight: 500; padding: 2px; text-align: left;\").arg(labelColor));\n }\n }\n }\n }\n }\n \n // Update dial display\n updateDialDisplay();\n}\n void migrateOldButtonMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n \n // Check if migration is needed by looking for old format strings\n settings.beginGroup(\"ButtonHoldMappings\");\n QStringList holdKeys = settings.allKeys();\n bool needsMigration = false;\n \n for (const QString &key : holdKeys) {\n QString value = settings.value(key).toString();\n // If we find old English strings, we need to migrate\n if (value == \"PageSwitching\" || value == \"ZoomControl\" || value == \"ThicknessControl\" ||\n value == \"ToolSwitching\" || value == \"PresetSelection\" ||\n value == \"PanAndPageScroll\") {\n needsMigration = true;\n break;\n }\n }\n settings.endGroup();\n \n if (!needsMigration) {\n settings.beginGroup(\"ButtonPressMappings\");\n QStringList pressKeys = settings.allKeys();\n for (const QString &key : pressKeys) {\n QString value = settings.value(key).toString();\n // Check for old English action strings\n if (value == \"Toggle Fullscreen\" || value == \"Toggle Dial\" || value == \"Zoom 50%\" ||\n value == \"Add Preset\" || value == \"Delete Page\" || value == \"Fast Forward\" ||\n value == \"Open Control Panel\" || value == \"Custom Color\") {\n needsMigration = true;\n break;\n }\n }\n settings.endGroup();\n }\n \n if (!needsMigration) return;\n \n // Perform migration\n // qDebug() << \"Migrating old button mappings to new format...\";\n \n // Migrate hold mappings\n settings.beginGroup(\"ButtonHoldMappings\");\n holdKeys = settings.allKeys();\n for (const QString &key : holdKeys) {\n QString oldValue = settings.value(key).toString();\n QString newValue = migrateOldDialModeString(oldValue);\n if (newValue != oldValue) {\n settings.setValue(key, newValue);\n }\n }\n settings.endGroup();\n \n // Migrate press mappings\n settings.beginGroup(\"ButtonPressMappings\");\n QStringList pressKeys = settings.allKeys();\n for (const QString &key : pressKeys) {\n QString oldValue = settings.value(key).toString();\n QString newValue = migrateOldActionString(oldValue);\n if (newValue != oldValue) {\n settings.setValue(key, newValue);\n }\n }\n settings.endGroup();\n \n // qDebug() << \"Button mapping migration completed.\";\n}\n QString migrateOldDialModeString(const QString &oldString) {\n // Convert old English strings to new internal keys\n if (oldString == \"None\") return \"none\";\n if (oldString == \"PageSwitching\") return \"page_switching\";\n if (oldString == \"ZoomControl\") return \"zoom_control\";\n if (oldString == \"ThicknessControl\") return \"thickness_control\";\n\n if (oldString == \"ToolSwitching\") return \"tool_switching\";\n if (oldString == \"PresetSelection\") return \"preset_selection\";\n if (oldString == \"PanAndPageScroll\") return \"pan_and_page_scroll\";\n return oldString; // Return as-is if not found (might already be new format)\n}\n QString migrateOldActionString(const QString &oldString) {\n // Convert old English strings to new internal keys\n if (oldString == \"None\") return \"none\";\n if (oldString == \"Toggle Fullscreen\") return \"toggle_fullscreen\";\n if (oldString == \"Toggle Dial\") return \"toggle_dial\";\n if (oldString == \"Zoom 50%\") return \"zoom_50\";\n if (oldString == \"Zoom Out\") return \"zoom_out\";\n if (oldString == \"Zoom 200%\") return \"zoom_200\";\n if (oldString == \"Add Preset\") return \"add_preset\";\n if (oldString == \"Delete Page\") return \"delete_page\";\n if (oldString == \"Fast Forward\") return \"fast_forward\";\n if (oldString == \"Open Control Panel\") return \"open_control_panel\";\n if (oldString == \"Red\") return \"red_color\";\n if (oldString == \"Blue\") return \"blue_color\";\n if (oldString == \"Yellow\") return \"yellow_color\";\n if (oldString == \"Green\") return \"green_color\";\n if (oldString == \"Black\") return \"black_color\";\n if (oldString == \"White\") return \"white_color\";\n if (oldString == \"Custom Color\") return \"custom_color\";\n if (oldString == \"Toggle Sidebar\") return \"toggle_sidebar\";\n if (oldString == \"Save\") return \"save\";\n if (oldString == \"Straight Line Tool\") return \"straight_line_tool\";\n if (oldString == \"Rope Tool\") return \"rope_tool\";\n if (oldString == \"Set Pen Tool\") return \"set_pen_tool\";\n if (oldString == \"Set Marker Tool\") return \"set_marker_tool\";\n if (oldString == \"Set Eraser Tool\") return \"set_eraser_tool\";\n if (oldString == \"Toggle PDF Text Selection\") return \"toggle_pdf_text_selection\";\n return oldString; // Return as-is if not found (might already be new format)\n}\n InkCanvas* currentCanvas();\n void saveCurrentPage() {\n currentCanvas()->saveToFile(getCurrentPageForCanvas(currentCanvas()));\n}\n void saveCurrentPageConcurrent() {\n InkCanvas *canvas = currentCanvas();\n if (!canvas || !canvas->isEdited()) return;\n \n int pageNumber = getCurrentPageForCanvas(canvas);\n QString saveFolder = canvas->getSaveFolder();\n \n if (saveFolder.isEmpty()) return;\n \n // Create a copy of the buffer for concurrent saving\n QPixmap bufferCopy = canvas->getBuffer();\n \n // Save markdown windows for this page (this must be done on the main thread)\n if (canvas->getMarkdownManager()) {\n canvas->getMarkdownManager()->saveWindowsForPage(pageNumber);\n }\n \n // Run the save operation concurrently\n QFuture future = QtConcurrent::run([saveFolder, pageNumber, bufferCopy]() {\n // Get notebook ID from the save folder (similar to how InkCanvas does it)\n QString notebookId = \"notebook\"; // Default fallback\n QString idFile = saveFolder + \"/.notebook_id.txt\";\n if (QFile::exists(idFile)) {\n QFile file(idFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n notebookId = in.readLine().trimmed();\n file.close();\n }\n }\n \n QString filePath = saveFolder + QString(\"/%1_%2.png\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n \n QImage image(bufferCopy.size(), QImage::Format_ARGB32);\n image.fill(Qt::transparent);\n QPainter painter(&image);\n painter.drawPixmap(0, 0, bufferCopy);\n image.save(filePath, \"PNG\");\n });\n \n // Mark as not edited since we're saving\n canvas->setEdited(false);\n}\n void switchPage(int pageNumber) {\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n\n if (currentCanvas()->isEdited()){\n saveCurrentPageConcurrent(); // Use concurrent saving for smoother page flipping\n }\n\n int oldPage = getCurrentPageForCanvas(currentCanvas()) + 1; // Convert to 1-based for comparison\n int newPage = pageNumber - 1;\n pageMap[canvas] = newPage; // ✅ Save the page for this tab\n\n if (canvas->isPdfLoadedFunc() && pageNumber - 1 < canvas->getTotalPdfPages()) {\n canvas->loadPdfPage(newPage);\n } else {\n canvas->loadPage(newPage);\n }\n\n canvas->setLastActivePage(newPage);\n updateZoom();\n // It seems panXSlider and panYSlider can be null here during startup.\n if(panXSlider && panYSlider){\n canvas->setLastPanX(panXSlider->maximum());\n canvas->setLastPanY(panYSlider->maximum());\n \n // ✅ Enhanced scroll-on-top functionality\n if (scrollOnTopEnabled && panYSlider->maximum() > 0) {\n if (pageNumber > oldPage) {\n // Forward page switching → scroll to top\n panYSlider->setValue(0);\n } else if (pageNumber < oldPage) {\n // Backward page switching → scroll to bottom\n panYSlider->setValue(panYSlider->maximum());\n }\n }\n }\n updateDialDisplay();\n updateBookmarkButtonState(); // Update bookmark button state when switching pages\n}\n void switchPageWithDirection(int pageNumber, int direction) {\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n\n if (currentCanvas()->isEdited()){\n saveCurrentPageConcurrent(); // Use concurrent saving for smoother page flipping\n }\n\n int newPage = pageNumber - 1;\n pageMap[canvas] = newPage; // ✅ Save the page for this tab\n\n if (canvas->isPdfLoadedFunc() && pageNumber - 1 < canvas->getTotalPdfPages()) {\n canvas->loadPdfPage(newPage);\n } else {\n canvas->loadPage(newPage);\n }\n\n canvas->setLastActivePage(newPage);\n updateZoom();\n // It seems panXSlider and panYSlider can be null here during startup.\n if(panXSlider && panYSlider){\n canvas->setLastPanX(panXSlider->maximum());\n canvas->setLastPanY(panYSlider->maximum());\n \n // ✅ Enhanced scroll-on-top functionality with explicit direction\n if (scrollOnTopEnabled && panYSlider->maximum() > 0) {\n if (direction > 0) {\n // Forward page switching → scroll to top\n panYSlider->setValue(0);\n } else if (direction < 0) {\n // Backward page switching → scroll to bottom\n panYSlider->setValue(panYSlider->maximum());\n }\n }\n }\n updateDialDisplay();\n updateBookmarkButtonState(); // Update bookmark button state when switching pages\n}\n void updateTabLabel() {\n int index = tabList->currentRow();\n if (index < 0) return;\n\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n\n QString folderPath = canvas->getSaveFolder(); // ✅ Get save folder\n if (folderPath.isEmpty()) return;\n\n QString tabName;\n\n // ✅ Check if there is an assigned PDF\n QString metadataFile = folderPath + \"/.pdf_path.txt\";\n if (QFile::exists(metadataFile)) {\n QFile file(metadataFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString pdfPath = in.readLine().trimmed();\n file.close();\n\n // ✅ Extract just the PDF filename (not full path)\n QFileInfo pdfInfo(pdfPath);\n if (pdfInfo.exists()) {\n tabName = elideTabText(pdfInfo.fileName(), 90); // e.g., \"mydocument.pdf\" (elided)\n }\n }\n }\n\n // ✅ If no PDF, use the folder name\n if (tabName.isEmpty()) {\n QFileInfo folderInfo(folderPath);\n tabName = elideTabText(folderInfo.fileName(), 90); // e.g., \"MyNotebook\" (elided)\n }\n\n QListWidgetItem *tabItem = tabList->item(index);\n if (tabItem) {\n QWidget *tabWidget = tabList->itemWidget(tabItem); // Get the tab's custom widget\n if (tabWidget) {\n QLabel *tabLabel = tabWidget->findChild(); // Get the QLabel inside\n if (tabLabel) {\n tabLabel->setText(tabName); // ✅ Update tab label\n tabLabel->setWordWrap(false); // No wrapping for horizontal tabs\n }\n }\n }\n}\n QSpinBox *pageInput;\n QPushButton *prevPageButton;\n QPushButton *nextPageButton;\n void addKeyboardMapping(const QString &keySequence, const QString &action) {\n // List of IME-related shortcuts that should not be intercepted\n QStringList imeShortcuts = {\n \"Ctrl+Space\", // Primary IME toggle\n \"Ctrl+Shift\", // Language switching\n \"Ctrl+Alt\", // IME functions\n \"Shift+Alt\", // Alternative language switching\n \"Alt+Shift\" // Alternative language switching (reversed)\n };\n \n // Don't allow mapping of IME-related shortcuts\n if (imeShortcuts.contains(keySequence)) {\n qWarning() << \"Cannot map IME-related shortcut:\" << keySequence;\n return;\n }\n \n keyboardMappings[keySequence] = action;\n keyboardActionMapping[keySequence] = stringToAction(action);\n saveKeyboardMappings();\n}\n void removeKeyboardMapping(const QString &keySequence) {\n keyboardMappings.remove(keySequence);\n keyboardActionMapping.remove(keySequence);\n saveKeyboardMappings();\n}\n QMap getKeyboardMappings() const {\n return keyboardMappings;\n}\n void reconnectControllerSignals() {\n if (!controllerManager || !pageDial) {\n return;\n }\n \n // Reset internal dial state\n tracking = false;\n accumulatedRotation = 0;\n grossTotalClicks = 0;\n tempClicks = 0;\n lastAngle = 0;\n startAngle = 0;\n pendingPageFlip = 0;\n accumulatedRotationAfterLimit = 0;\n \n // Disconnect all existing connections to avoid duplicates\n disconnect(controllerManager, nullptr, this, nullptr);\n disconnect(controllerManager, nullptr, pageDial, nullptr);\n \n // Reconnect all controller signals\n connect(controllerManager, &SDLControllerManager::buttonHeld, this, &MainWindow::handleButtonHeld);\n connect(controllerManager, &SDLControllerManager::buttonReleased, this, &MainWindow::handleButtonReleased);\n connect(controllerManager, &SDLControllerManager::leftStickAngleChanged, pageDial, &QDial::setValue);\n connect(controllerManager, &SDLControllerManager::leftStickReleased, pageDial, &QDial::sliderReleased);\n connect(controllerManager, &SDLControllerManager::buttonSinglePress, this, &MainWindow::handleControllerButton);\n \n // Re-establish dial mode connections by changing to current mode\n DialMode currentMode = currentDialMode;\n changeDialMode(currentMode);\n \n // Update dial display to reflect current state\n updateDialDisplay();\n \n // qDebug() << \"Controller signals reconnected successfully\";\n}\n void updateDialButtonState() {\n // Check if dial is visible\n bool isDialVisible = dialContainer && dialContainer->isVisible();\n \n if (dialToggleButton) {\n dialToggleButton->setProperty(\"selected\", isDialVisible);\n \n // Force style update\n dialToggleButton->style()->unpolish(dialToggleButton);\n dialToggleButton->style()->polish(dialToggleButton);\n }\n}\n void updateFastForwardButtonState() {\n if (fastForwardButton) {\n fastForwardButton->setProperty(\"selected\", fastForwardMode);\n \n // Force style update\n fastForwardButton->style()->unpolish(fastForwardButton);\n fastForwardButton->style()->polish(fastForwardButton);\n }\n}\n void updateToolButtonStates() {\n if (!currentCanvas()) return;\n \n // Reset all tool buttons\n penToolButton->setProperty(\"selected\", false);\n markerToolButton->setProperty(\"selected\", false);\n eraserToolButton->setProperty(\"selected\", false);\n \n // Set the selected property for the current tool\n ToolType currentTool = currentCanvas()->getCurrentTool();\n switch (currentTool) {\n case ToolType::Pen:\n penToolButton->setProperty(\"selected\", true);\n break;\n case ToolType::Marker:\n markerToolButton->setProperty(\"selected\", true);\n break;\n case ToolType::Eraser:\n eraserToolButton->setProperty(\"selected\", true);\n break;\n }\n \n // Force style update\n penToolButton->style()->unpolish(penToolButton);\n penToolButton->style()->polish(penToolButton);\n markerToolButton->style()->unpolish(markerToolButton);\n markerToolButton->style()->polish(markerToolButton);\n eraserToolButton->style()->unpolish(eraserToolButton);\n eraserToolButton->style()->polish(eraserToolButton);\n}\n void handleColorButtonClick() {\n if (!currentCanvas()) return;\n \n ToolType currentTool = currentCanvas()->getCurrentTool();\n \n // If in eraser mode, switch back to pen mode\n if (currentTool == ToolType::Eraser) {\n currentCanvas()->setTool(ToolType::Pen);\n updateToolButtonStates();\n updateThicknessSliderForCurrentTool();\n }\n \n // If rope tool is enabled, turn it off\n if (currentCanvas()->isRopeToolMode()) {\n currentCanvas()->setRopeToolMode(false);\n updateRopeToolButtonState();\n }\n \n // For marker and straight line mode, leave them as they are\n // No special handling needed - they can work with color changes\n}\n void updateThicknessSliderForCurrentTool() {\n if (!currentCanvas() || !thicknessSlider) return;\n \n // Block signals to prevent recursive calls\n thicknessSlider->blockSignals(true);\n \n // Update slider to reflect current tool's thickness\n qreal currentThickness = currentCanvas()->getPenThickness();\n \n // Convert thickness back to slider value (reverse of updateThickness calculation)\n qreal visualThickness = currentThickness * (currentCanvas()->getZoom() / 100.0);\n int sliderValue = qBound(1, static_cast(qRound(visualThickness)), 50);\n \n thicknessSlider->setValue(sliderValue);\n thicknessSlider->blockSignals(false);\n}\n void updatePdfTextSelectButtonState() {\n // Check if PDF text selection is enabled\n bool isEnabled = currentCanvas() && currentCanvas()->isPdfTextSelectionEnabled();\n \n if (pdfTextSelectButton) {\n pdfTextSelectButton->setProperty(\"selected\", isEnabled);\n \n // Force style update (uses the same buttonStyle as other toggle buttons)\n pdfTextSelectButton->style()->unpolish(pdfTextSelectButton);\n pdfTextSelectButton->style()->polish(pdfTextSelectButton);\n }\n}\n private:\n void toggleBenchmark() {\n benchmarking = !benchmarking;\n if (benchmarking) {\n currentCanvas()->startBenchmark();\n benchmarkTimer->start(1000); // Update every second\n } else {\n currentCanvas()->stopBenchmark();\n benchmarkTimer->stop();\n benchmarkLabel->setText(tr(\"PR:N/A\"));\n }\n}\n void updateBenchmarkDisplay() {\n int sampleRate = currentCanvas()->getProcessedRate();\n benchmarkLabel->setText(QString(tr(\"PR:%1 Hz\")).arg(sampleRate));\n}\n void applyCustomColor() {\n QString colorCode = customColorInput->text();\n if (!colorCode.startsWith(\"#\")) {\n colorCode.prepend(\"#\");\n }\n currentCanvas()->setPenColor(QColor(colorCode));\n updateDialDisplay(); \n}\n void updateThickness(int value) {\n // Calculate thickness based on the slider value at 100% zoom\n // The slider value represents the desired visual thickness\n qreal visualThickness = value; // Scale slider value to reasonable thickness\n \n // Apply zoom scaling to maintain visual consistency\n qreal actualThickness = visualThickness * (100.0 / currentCanvas()->getZoom()); \n \n currentCanvas()->setPenThickness(actualThickness);\n}\n void adjustThicknessForZoom(int oldZoom, int newZoom) {\n // Adjust all tool thicknesses to maintain visual consistency when zoom changes\n if (oldZoom == newZoom || oldZoom <= 0 || newZoom <= 0) return;\n \n InkCanvas* canvas = currentCanvas();\n if (!canvas) return;\n \n qreal zoomRatio = qreal(oldZoom) / qreal(newZoom);\n ToolType currentTool = canvas->getCurrentTool();\n \n // Adjust thickness for all tools, not just the current one\n canvas->adjustAllToolThicknesses(zoomRatio);\n \n // Update the thickness slider to reflect the current tool's new thickness\n updateThicknessSliderForCurrentTool();\n \n // ✅ FIXED: Update dial display to show new thickness immediately during zoom changes\n updateDialDisplay();\n}\n void changeTool(int index) {\n if (index == 0) {\n currentCanvas()->setTool(ToolType::Pen);\n } else if (index == 1) {\n currentCanvas()->setTool(ToolType::Marker);\n } else if (index == 2) {\n currentCanvas()->setTool(ToolType::Eraser);\n }\n updateToolButtonStates();\n updateThicknessSliderForCurrentTool();\n updateDialDisplay();\n}\n void selectFolder() {\n QString folder = QFileDialog::getExistingDirectory(this, tr(\"Select Save Folder\"));\n if (!folder.isEmpty()) {\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n if (canvas->isEdited()){\n saveCurrentPage();\n }\n canvas->setSaveFolder(folder);\n switchPageWithDirection(1, 1); // Going to page 1 is forward direction\n pageInput->setValue(1);\n updateTabLabel();\n recentNotebooksManager->addRecentNotebook(folder, canvas); // Track when folder is selected\n }\n }\n}\n void saveCanvas() {\n currentCanvas()->saveToFile(getCurrentPageForCanvas(currentCanvas()));\n}\n void saveAnnotated() {\n currentCanvas()->saveAnnotated(getCurrentPageForCanvas(currentCanvas()));\n}\n void deleteCurrentPage() {\n currentCanvas()->deletePage(getCurrentPageForCanvas(currentCanvas()));\n}\n void loadPdf() {\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n\n QString saveFolder = canvas->getSaveFolder();\n QString tempDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\";\n \n // Check if no save folder is set or if it's the temporary directory\n if (saveFolder.isEmpty() || saveFolder == tempDir) {\n QMessageBox::warning(this, tr(\"Cannot Load PDF\"), \n tr(\"Please select a permanent save folder before loading a PDF.\\n\\nClick the folder icon to choose a location for your notebook.\"));\n return;\n }\n\n QString filePath = QFileDialog::getOpenFileName(this, tr(\"Select PDF\"), \"\", \"PDF Files (*.pdf)\");\n if (!filePath.isEmpty()) {\n currentCanvas()->loadPdf(filePath);\n updateTabLabel(); // ✅ Update the tab name after assigning a PDF\n updateZoom(); // ✅ Update zoom and pan range after PDF is loaded\n \n // Refresh PDF outline if sidebar is visible\n if (outlineSidebarVisible) {\n loadPdfOutline();\n }\n }\n}\n void clearPdf() {\n InkCanvas *canvas = currentCanvas();\n if (!canvas) return;\n \n canvas->clearPdf();\n updateZoom(); // ✅ Update zoom and pan range after PDF is cleared\n}\n void updateZoom() {\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n canvas->setZoom(zoomSlider->value());\n canvas->setLastZoomLevel(zoomSlider->value()); // ✅ Store zoom level per tab\n updatePanRange();\n // updateThickness(thicknessSlider->value()); // ✅ REMOVED: This was resetting thickness on page switch\n // updateDialDisplay();\n }\n}\n void onZoomSliderChanged(int value) {\n // This handles manual zoom slider changes and preserves thickness\n int oldZoom = currentCanvas() ? currentCanvas()->getZoom() : 100;\n int newZoom = value;\n \n updateZoom();\n adjustThicknessForZoom(oldZoom, newZoom); // Maintain visual thickness consistency\n}\n void applyZoom() {\n bool ok;\n int zoomValue = zoomInput->text().toInt(&ok);\n if (ok && zoomValue > 0) {\n currentCanvas()->setZoom(zoomValue);\n updatePanRange(); // Update slider range after zoom change\n }\n}\n void updatePanRange() {\n int zoom = currentCanvas()->getZoom();\n\n QSize canvasSize = currentCanvas()->getCanvasSize();\n QSize viewportSize = QGuiApplication::primaryScreen()->size() * QGuiApplication::primaryScreen()->devicePixelRatio();\n qreal dpr = initialDpr;\n \n // Get the actual widget size instead of screen size for more accurate calculation\n QSize actualViewportSize = size();\n \n // Adjust viewport size for toolbar and tab bar layout\n QSize effectiveViewportSize = actualViewportSize;\n int toolbarHeight = isToolbarTwoRows ? 80 : 50; // Toolbar height\n int tabBarHeight = (tabBarContainer && tabBarContainer->isVisible()) ? 38 : 0; // Tab bar height\n effectiveViewportSize.setHeight(actualViewportSize.height() - toolbarHeight - tabBarHeight);\n \n // Calculate scaled canvas size using proper DPR scaling\n int scaledCanvasWidth = canvasSize.width() * zoom / 100;\n int scaledCanvasHeight = canvasSize.height() * zoom / 100;\n \n // Calculate max pan values - if canvas is smaller than viewport, pan should be 0\n int maxPanX = qMax(0, scaledCanvasWidth - effectiveViewportSize.width());\n int maxPanY = qMax(0, scaledCanvasHeight - effectiveViewportSize.height());\n\n // Scale the pan range properly\n int maxPanX_scaled = maxPanX * 100 / zoom;\n int maxPanY_scaled = maxPanY * 100 / zoom;\n\n // Set range to 0 when canvas is smaller than viewport (centered)\n if (scaledCanvasWidth <= effectiveViewportSize.width()) {\n panXSlider->setRange(0, 0);\n panXSlider->setValue(0);\n // No need for horizontal scrollbar\n panXSlider->setVisible(false);\n } else {\n panXSlider->setRange(0, maxPanX_scaled);\n // Show scrollbar only if mouse is near and timeout hasn't occurred\n if (scrollbarsVisible && !scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->start();\n }\n }\n \n if (scaledCanvasHeight <= effectiveViewportSize.height()) {\n panYSlider->setRange(0, 0);\n panYSlider->setValue(0);\n // No need for vertical scrollbar\n panYSlider->setVisible(false);\n } else {\n panYSlider->setRange(0, maxPanY_scaled);\n // Show scrollbar only if mouse is near and timeout hasn't occurred\n if (scrollbarsVisible && !scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->start();\n }\n }\n}\n void updatePanX(int value) {\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n canvas->setPanX(value);\n canvas->setLastPanX(value); // ✅ Store panX per tab\n \n // Show horizontal scrollbar temporarily\n if (panXSlider->maximum() > 0) {\n panXSlider->setVisible(true);\n scrollbarsVisible = true;\n \n // Make sure scrollbar position matches the canvas position\n if (panXSlider->value() != value) {\n panXSlider->blockSignals(true);\n panXSlider->setValue(value);\n panXSlider->blockSignals(false);\n }\n \n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n scrollbarHideTimer->start();\n }\n }\n}\n void updatePanY(int value) {\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n canvas->setPanY(value);\n canvas->setLastPanY(value); // ✅ Store panY per tab\n \n // Show vertical scrollbar temporarily\n if (panYSlider->maximum() > 0) {\n panYSlider->setVisible(true);\n scrollbarsVisible = true;\n \n // Make sure scrollbar position matches the canvas position\n if (panYSlider->value() != value) {\n panYSlider->blockSignals(true);\n panYSlider->setValue(value);\n panYSlider->blockSignals(false);\n }\n \n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n scrollbarHideTimer->start();\n }\n }\n}\n void selectBackground() {\n QString filePath = QFileDialog::getOpenFileName(this, tr(\"Select Background Image\"), \"\", \"Images (*.png *.jpg *.jpeg)\");\n if (!filePath.isEmpty()) {\n currentCanvas()->setBackground(filePath, getCurrentPageForCanvas(currentCanvas()));\n updateZoom(); // ✅ Update zoom and pan range after background is set\n }\n}\n void forceUIRefresh() {\n setWindowState(Qt::WindowNoState); // Restore first\n setWindowState(Qt::WindowMaximized); // Maximize again\n}\n void switchTab(int index) {\n if (!canvasStack || !tabList || !pageInput || !zoomSlider || !panXSlider || !panYSlider) {\n // qDebug() << \"Error: switchTab() called before UI was fully initialized!\";\n return;\n }\n\n if (index >= 0 && index < canvasStack->count()) {\n canvasStack->setCurrentIndex(index);\n \n // Ensure the tab list selection is properly set and styled\n if (tabList->currentRow() != index) {\n tabList->setCurrentRow(index);\n }\n \n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n int savedPage = canvas->getLastActivePage();\n \n // ✅ Only call blockSignals if pageInput is valid\n if (pageInput) { \n pageInput->blockSignals(true);\n pageInput->setValue(savedPage + 1);\n pageInput->blockSignals(false);\n }\n\n // ✅ Ensure zoomSlider exists before calling methods\n if (zoomSlider) {\n zoomSlider->blockSignals(true);\n zoomSlider->setValue(canvas->getLastZoomLevel());\n zoomSlider->blockSignals(false);\n canvas->setZoom(canvas->getLastZoomLevel());\n }\n\n // ✅ Ensure pan sliders exist before modifying values\n if (panXSlider && panYSlider) {\n panXSlider->blockSignals(true);\n panYSlider->blockSignals(true);\n panXSlider->setValue(canvas->getLastPanX());\n panYSlider->setValue(canvas->getLastPanY());\n panXSlider->blockSignals(false);\n panYSlider->blockSignals(false);\n updatePanRange();\n }\n updateDialDisplay();\n updateColorButtonStates(); // Update button states when switching tabs\n updateStraightLineButtonState(); // Update straight line button state when switching tabs\n updateRopeToolButtonState(); // Update rope tool button state when switching tabs\n updateMarkdownButtonState(); // Update markdown button state when switching tabs\n updatePdfTextSelectButtonState(); // Update PDF text selection button state when switching tabs\n updateBookmarkButtonState(); // Update bookmark button state when switching tabs\n updateDialButtonState(); // Update dial button state when switching tabs\n updateFastForwardButtonState(); // Update fast forward button state when switching tabs\n updateToolButtonStates(); // Update tool button states when switching tabs\n updateThicknessSliderForCurrentTool(); // Update thickness slider for current tool when switching tabs\n \n // Refresh PDF outline if sidebar is visible\n if (outlineSidebarVisible) {\n loadPdfOutline();\n }\n }\n }\n}\n void addNewTab() {\n if (!tabList || !canvasStack) return; // Ensure tabList and canvasStack exist\n\n int newTabIndex = tabList->count(); // New tab index\n QWidget *tabWidget = new QWidget(); // Custom tab container\n tabWidget->setObjectName(\"tabWidget\"); // Name the widget for easy retrieval later\n QHBoxLayout *tabLayout = new QHBoxLayout(tabWidget);\n tabLayout->setContentsMargins(5, 2, 5, 2);\n\n // ✅ Create the label (Tab Name) - optimized for horizontal layout\n QLabel *tabLabel = new QLabel(QString(\"Tab %1\").arg(newTabIndex + 1), tabWidget); \n tabLabel->setObjectName(\"tabLabel\"); // ✅ Name the label for easy retrieval later\n tabLabel->setWordWrap(false); // ✅ No wrapping for horizontal tabs\n tabLabel->setFixedWidth(115); // ✅ Narrower width for compact layout\n tabLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);\n tabLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter); // Left-align to show filename start\n tabLabel->setTextFormat(Qt::PlainText); // Ensure plain text for proper eliding\n // Tab label styling will be updated by theme\n\n // ✅ Create the close button (❌) - styled for browser-like tabs\n QPushButton *closeButton = new QPushButton(tabWidget);\n closeButton->setFixedSize(14, 14); // Smaller to fit narrower tabs\n closeButton->setIcon(loadThemedIcon(\"cross\")); // Set themed icon\n closeButton->setStyleSheet(R\"(\n QPushButton { \n border: none; \n background: transparent; \n border-radius: 6px;\n padding: 1px;\n }\n QPushButton:hover { \n background: rgba(255, 100, 100, 150); \n border-radius: 6px;\n }\n QPushButton:pressed { \n background: rgba(255, 50, 50, 200); \n border-radius: 6px;\n }\n )\"); // Themed styling with hover and press effects\n \n // ✅ Create new InkCanvas instance EARLIER so it can be captured by the lambda\n InkCanvas *newCanvas = new InkCanvas(this);\n \n // ✅ Handle tab closing when the button is clicked\n connect(closeButton, &QPushButton::clicked, this, [=]() { // newCanvas is now captured\n\n // Prevent closing if it's the last remaining tab\n if (tabList->count() <= 1) {\n // Optional: show a message or do nothing silently\n QMessageBox::information(this, tr(\"Notice\"), tr(\"At least one tab must remain open.\"));\n\n return;\n }\n\n // Find the index of the tab associated with this button's parent (tabWidget)\n int indexToRemove = -1;\n // newCanvas is captured by the lambda, representing the canvas of the tab being closed.\n // tabWidget is also captured.\n for (int i = 0; i < tabList->count(); ++i) {\n if (tabList->itemWidget(tabList->item(i)) == tabWidget) {\n indexToRemove = i;\n break;\n }\n }\n\n if (indexToRemove == -1) {\n qWarning() << \"Could not find tab to remove based on tabWidget.\";\n // Fallback or error handling if needed, though this shouldn't happen if tabWidget is valid.\n // As a fallback, try to find the index based on newCanvas if lists are in sync.\n for (int i = 0; i < canvasStack->count(); ++i) {\n if (canvasStack->widget(i) == newCanvas) {\n indexToRemove = i;\n break;\n }\n }\n if (indexToRemove == -1) {\n qWarning() << \"Could not find tab to remove based on newCanvas either.\";\n return; // Critical error, cannot proceed.\n }\n }\n \n // At this point, newCanvas is the InkCanvas instance for the tab being closed.\n // And indexToRemove is its index in tabList and canvasStack.\n\n // 1. Ensure the notebook has a unique save folder if it's temporary/edited\n ensureTabHasUniqueSaveFolder(newCanvas); // Pass the specific canvas\n\n // 2. Get the final save folder path\n QString folderPath = newCanvas->getSaveFolder();\n QString tempDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\";\n\n // 3. Update cover preview and recent list if it's a permanent notebook\n if (!folderPath.isEmpty() && folderPath != tempDir && recentNotebooksManager) {\n recentNotebooksManager->generateAndSaveCoverPreview(folderPath, newCanvas);\n // Add/update in recent list. This also moves it to the top.\n recentNotebooksManager->addRecentNotebook(folderPath, newCanvas);\n }\n \n // 4. Update the tab's label directly as folderPath might have changed\n QLabel *label = tabWidget->findChild(\"tabLabel\");\n if (label) {\n QString tabNameText;\n if (!folderPath.isEmpty() && folderPath != tempDir) { // Only for permanent notebooks\n QString metadataFile = folderPath + \"/.pdf_path.txt\";\n if (QFile::exists(metadataFile)) {\n QFile file(metadataFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString pdfPath = in.readLine().trimmed();\n file.close();\n if (QFile::exists(pdfPath)) { // Check if PDF file actually exists\n tabNameText = elideTabText(QFileInfo(pdfPath).fileName(), 90); // Elide to fit tab width\n }\n }\n }\n // Fallback to folder name if no PDF or PDF path invalid\n if (tabNameText.isEmpty()) {\n tabNameText = elideTabText(QFileInfo(folderPath).fileName(), 90); // Elide to fit tab width\n }\n }\n // Only update the label if a new valid name was determined.\n // If it's still a temp folder, the original \"Tab X\" label remains appropriate.\n if (!tabNameText.isEmpty()) {\n label->setText(tabNameText);\n }\n }\n\n // 5. Remove the tab\n removeTabAt(indexToRemove);\n });\n\n\n // ✅ Add widgets to the tab layout\n tabLayout->addWidget(tabLabel);\n tabLayout->addWidget(closeButton);\n tabLayout->setStretch(0, 1);\n tabLayout->setStretch(1, 0);\n \n // ✅ Create the tab item and set widget (horizontal layout)\n QListWidgetItem *tabItem = new QListWidgetItem();\n tabItem->setSizeHint(QSize(135, 22)); // ✅ Narrower and thinner for compact layout\n tabList->addItem(tabItem);\n tabList->setItemWidget(tabItem, tabWidget); // Attach tab layout\n\n canvasStack->addWidget(newCanvas);\n\n // ✅ Connect touch gesture signals\n connect(newCanvas, &InkCanvas::zoomChanged, this, &MainWindow::handleTouchZoomChange);\n connect(newCanvas, &InkCanvas::panChanged, this, &MainWindow::handleTouchPanChange);\n connect(newCanvas, &InkCanvas::touchGestureEnded, this, &MainWindow::handleTouchGestureEnd);\n connect(newCanvas, &InkCanvas::ropeSelectionCompleted, this, &MainWindow::showRopeSelectionMenu);\n connect(newCanvas, &InkCanvas::pdfLinkClicked, this, [this](int targetPage) {\n // Navigate to the target page when a PDF link is clicked\n if (targetPage >= 0 && targetPage < 9999) {\n switchPageWithDirection(targetPage + 1, (targetPage + 1 > getCurrentPageForCanvas(currentCanvas()) + 1) ? 1 : -1);\n pageInput->setValue(targetPage + 1);\n }\n });\n connect(newCanvas, &InkCanvas::pdfLoaded, this, [this]() {\n // Refresh PDF outline if sidebar is visible\n if (outlineSidebarVisible) {\n loadPdfOutline();\n }\n });\n connect(newCanvas, &InkCanvas::markdownSelectionModeChanged, this, &MainWindow::updateMarkdownButtonState);\n \n // Install event filter to detect mouse movement for scrollbar visibility\n newCanvas->setMouseTracking(true);\n newCanvas->installEventFilter(this);\n \n // Disable tablet tracking for canvases for now to prevent crashes\n // TODO: Find a safer way to implement hover tooltips without tablet tracking\n // QTimer::singleShot(50, this, [newCanvas]() {\n // try {\n // if (newCanvas && newCanvas->window() && newCanvas->window()->windowHandle()) {\n // newCanvas->setAttribute(Qt::WA_TabletTracking, true);\n // }\n // } catch (...) {\n // // Silently ignore tablet tracking errors\n // }\n // });\n \n // ✅ Apply touch gesture setting\n newCanvas->setTouchGesturesEnabled(touchGesturesEnabled);\n\n pageMap[newCanvas] = 0;\n\n // ✅ Select the new tab\n tabList->setCurrentItem(tabItem);\n canvasStack->setCurrentWidget(newCanvas);\n\n zoomSlider->setValue(100 / initialDpr); // Set initial zoom level based on DPR\n updateDialDisplay();\n updateStraightLineButtonState(); // Initialize straight line button state for the new tab\n updateRopeToolButtonState(); // Initialize rope tool button state for the new tab\n updatePdfTextSelectButtonState(); // Initialize PDF text selection button state for the new tab\n updateBookmarkButtonState(); // Initialize bookmark button state for the new tab\n updateMarkdownButtonState(); // Initialize markdown button state for the new tab\n updateDialButtonState(); // Initialize dial button state for the new tab\n updateFastForwardButtonState(); // Initialize fast forward button state for the new tab\n updateToolButtonStates(); // Initialize tool button states for the new tab\n\n QString tempDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\";\n newCanvas->setSaveFolder(tempDir);\n \n // Load persistent background settings\n BackgroundStyle defaultStyle;\n QColor defaultColor;\n int defaultDensity;\n loadDefaultBackgroundSettings(defaultStyle, defaultColor, defaultDensity);\n \n newCanvas->setBackgroundStyle(defaultStyle);\n newCanvas->setBackgroundColor(defaultColor);\n newCanvas->setBackgroundDensity(defaultDensity);\n newCanvas->setPDFRenderDPI(getPdfDPI());\n \n // Update color button states for the new tab\n updateColorButtonStates();\n}\n void removeTabAt(int index) {\n if (!tabList || !canvasStack) return; // Ensure UI elements exist\n if (index < 0 || index >= canvasStack->count()) return;\n\n // ✅ Remove tab entry\n QListWidgetItem *item = tabList->takeItem(index);\n delete item;\n\n // ✅ Remove and delete the canvas safely\n QWidget *canvasWidget = canvasStack->widget(index); // Get widget before removal\n // ensureTabHasUniqueSaveFolder(currentCanvas()); // Moved to the close button lambda\n\n if (canvasWidget) {\n canvasStack->removeWidget(canvasWidget); // Remove from stack\n // InkCanvas *canvasInstance = qobject_cast(canvasWidget);\n // if (canvasInstance) {\n // QString folderPath = canvasInstance->getSaveFolder();\n // QString tempDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\";\n // if (!folderPath.isEmpty() && folderPath != tempDir && recentNotebooksManager) {\n // recentNotebooksManager->addRecentNotebook(folderPath, canvasInstance); // Moved to close button lambda\n // }\n // }\n delete canvasWidget; // Now delete the widget (and its InkCanvas)\n }\n\n // ✅ Select the previous tab (or first tab if none left)\n if (tabList->count() > 0) {\n int newIndex = qMax(0, index - 1);\n tabList->setCurrentRow(newIndex);\n canvasStack->setCurrentWidget(canvasStack->widget(newIndex));\n }\n\n // QWidget *canvasWidget = canvasStack->widget(index); // Redeclaration - remove this block\n // InkCanvas *canvasInstance = qobject_cast(canvasWidget);\n //\n // if (canvasInstance) {\n // QString folderPath = canvasInstance->getSaveFolder();\n // if (!folderPath.isEmpty() && folderPath != QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\") {\n // // recentNotebooksManager->addRecentNotebook(folderPath, canvasInstance); // Moved to close button lambda\n // }\n // }\n}\n void toggleZoomSlider() {\n if (zoomFrame->isVisible()) {\n zoomFrame->hide();\n return;\n }\n\n // ✅ Set as a standalone pop-up window so it can receive events\n zoomFrame->setWindowFlags(Qt::Popup);\n\n // ✅ Position it right below the button\n QPoint buttonPos = zoomButton->mapToGlobal(QPoint(0, zoomButton->height()));\n zoomFrame->move(buttonPos.x(), buttonPos.y() + 5);\n zoomFrame->show();\n}\n void toggleThicknessSlider() {\n if (thicknessFrame->isVisible()) {\n thicknessFrame->hide();\n return;\n }\n\n // ✅ Set as a standalone pop-up window so it can receive events\n thicknessFrame->setWindowFlags(Qt::Popup);\n\n // ✅ Position it right below the button\n QPoint buttonPos = thicknessButton->mapToGlobal(QPoint(0, thicknessButton->height()));\n thicknessFrame->move(buttonPos.x(), buttonPos.y() + 5);\n\n thicknessFrame->show();\n}\n void toggleFullscreen() {\n if (isFullScreen()) {\n showNormal(); // Exit fullscreen mode\n } else {\n showFullScreen(); // Enter fullscreen mode\n }\n}\n void showJumpToPageDialog() {\n bool ok;\n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1; // ✅ Convert zero-based to one-based\n int newPage = QInputDialog::getInt(this, \"Jump to Page\", \"Enter Page Number:\", \n currentPage, 1, 9999, 1, &ok);\n if (ok) {\n // ✅ Use direction-aware page switching for jump-to-page\n int direction = (newPage > currentPage) ? 1 : (newPage < currentPage) ? -1 : 0;\n if (direction != 0) {\n switchPageWithDirection(newPage, direction);\n } else {\n switchPage(newPage); // Same page, no direction needed\n }\n pageInput->setValue(newPage);\n }\n}\n void goToPreviousPage() {\n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1; // Convert to 1-based\n if (currentPage > 1) {\n int newPage = currentPage - 1;\n switchPageWithDirection(newPage, -1); // -1 indicates backward\n pageInput->setValue(newPage);\n }\n}\n void goToNextPage() {\n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1; // Convert to 1-based\n int newPage = currentPage + 1;\n switchPageWithDirection(newPage, 1); // 1 indicates forward\n pageInput->setValue(newPage);\n}\n void onPageInputChanged(int newPage) {\n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1; // Convert to 1-based\n \n // ✅ Use direction-aware page switching for spinbox\n int direction = (newPage > currentPage) ? 1 : (newPage < currentPage) ? -1 : 0;\n if (direction != 0) {\n switchPageWithDirection(newPage, direction);\n } else {\n switchPage(newPage); // Same page, no direction needed\n }\n}\n void toggleDial() {\n if (!dialContainer) { \n // ✅ Create floating container for the dial\n dialContainer = new QWidget(this);\n dialContainer->setObjectName(\"dialContainer\");\n dialContainer->setFixedSize(140, 140);\n dialContainer->setAttribute(Qt::WA_TranslucentBackground);\n dialContainer->setAttribute(Qt::WA_NoSystemBackground);\n dialContainer->setAttribute(Qt::WA_OpaquePaintEvent);\n dialContainer->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);\n dialContainer->setStyleSheet(\"background: transparent; border-radius: 100px;\"); // ✅ More transparent\n\n // ✅ Create dial\n pageDial = new QDial(dialContainer);\n pageDial->setFixedSize(140, 140);\n pageDial->setMinimum(0);\n pageDial->setMaximum(360);\n pageDial->setWrapping(true); // ✅ Allow full-circle rotation\n \n // Apply theme color immediately when dial is created\n QColor accentColor = getAccentColor();\n pageDial->setStyleSheet(QString(R\"(\n QDial {\n background-color: %1;\n }\n )\").arg(accentColor.name()));\n\n /*\n\n modeDial = new QDial(dialContainer);\n modeDial->setFixedSize(150, 150);\n modeDial->setMinimum(0);\n modeDial->setMaximum(300); // 6 modes, 60° each\n modeDial->setSingleStep(60);\n modeDial->setWrapping(true);\n modeDial->setStyleSheet(\"background:rgb(0, 76, 147);\");\n modeDial->move(25, 25);\n \n */\n \n\n dialColorPreview = new QFrame(dialContainer);\n dialColorPreview->setFixedSize(30, 30);\n dialColorPreview->setStyleSheet(\"border-radius: 15px; border: 1px solid black;\");\n dialColorPreview->move(55, 35); // Center of dial\n\n dialIconView = new QLabel(dialContainer);\n dialIconView->setFixedSize(30, 30);\n dialIconView->setStyleSheet(\"border-radius: 1px; border: 1px solid black;\");\n dialIconView->move(55, 35); // Center of dial\n\n // ✅ Position dial near top-right corner initially\n positionDialContainer();\n\n dialDisplay = new QLabel(dialContainer);\n dialDisplay->setAlignment(Qt::AlignCenter);\n dialDisplay->setFixedSize(80, 80);\n dialDisplay->move(30, 30); // Center position inside the dial\n \n\n int fontId = QFontDatabase::addApplicationFont(\":/resources/fonts/Jersey20-Regular.ttf\");\n // int chnFontId = QFontDatabase::addApplicationFont(\":/resources/fonts/NotoSansSC-Medium.ttf\");\n QStringList fontFamilies = QFontDatabase::applicationFontFamilies(fontId);\n\n if (!fontFamilies.isEmpty()) {\n QFont pixelFont(fontFamilies.at(0), 11);\n dialDisplay->setFont(pixelFont);\n }\n\n dialDisplay->setStyleSheet(\"background-color: black; color: white; font-size: 14px; border-radius: 4px;\");\n\n dialHiddenButton = new QPushButton(dialContainer);\n dialHiddenButton->setFixedSize(80, 80);\n dialHiddenButton->move(30, 30); // Same position as dialDisplay\n dialHiddenButton->setStyleSheet(\"background: transparent; border: none;\"); // ✅ Fully invisible\n dialHiddenButton->setFocusPolicy(Qt::NoFocus); // ✅ Prevents accidental focus issues\n dialHiddenButton->setEnabled(false); // ✅ Disabled by default\n\n // ✅ Connection will be set in changeDialMode() based on current mode\n\n dialColorPreview->raise(); // ✅ Ensure it's on top\n dialIconView->raise();\n // ✅ Connect dial input and release\n // connect(pageDial, &QDial::valueChanged, this, &MainWindow::handleDialInput);\n // connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onDialReleased);\n\n // connect(modeDial, &QDial::valueChanged, this, &MainWindow::handleModeSelection);\n changeDialMode(currentDialMode); // ✅ Set initial mode\n\n // ✅ Enable drag detection\n dialContainer->installEventFilter(this);\n }\n\n // ✅ Ensure that `dialContainer` is always initialized before setting visibility\n if (dialContainer) {\n dialContainer->setVisible(!dialContainer->isVisible());\n }\n\n initializeDialSound(); // ✅ Ensure sound is loaded\n\n // Inside toggleDial():\n \n if (!dialDisplay) {\n dialDisplay = new QLabel(dialContainer);\n }\n updateDialDisplay(); // ✅ Ensure it's updated before showing\n\n if (controllerManager) {\n connect(controllerManager, &SDLControllerManager::buttonHeld, this, &MainWindow::handleButtonHeld);\n connect(controllerManager, &SDLControllerManager::buttonReleased, this, &MainWindow::handleButtonReleased);\n connect(controllerManager, &SDLControllerManager::leftStickAngleChanged, pageDial, &QDial::setValue);\n connect(controllerManager, &SDLControllerManager::leftStickReleased, pageDial, &QDial::sliderReleased);\n connect(controllerManager, &SDLControllerManager::buttonSinglePress, this, &MainWindow::handleControllerButton);\n }\n\n loadButtonMappings(); // ✅ Load button mappings for the controller\n\n // Update button state to reflect dial visibility\n updateDialButtonState();\n}\n void positionDialContainer() {\n if (!dialContainer) return;\n \n // Get window dimensions\n int windowWidth = width();\n int windowHeight = height();\n \n // Get dial dimensions\n int dialWidth = dialContainer->width(); // 140px\n int dialHeight = dialContainer->height(); // 140px\n \n // Calculate toolbar height based on current layout\n int toolbarHeight = isToolbarTwoRows ? 80 : 50; // Approximate heights\n \n // Add tab bar height if visible\n int tabBarHeight = (tabBarContainer && tabBarContainer->isVisible()) ? 38 : 0;\n \n // Define margins from edges\n int rightMargin = 20; // Distance from right edge\n int topMargin = 20; // Distance from top edge (below toolbar and tabs)\n \n // Calculate ideal position (top-right corner with margins)\n int idealX = windowWidth - dialWidth - rightMargin;\n int idealY = toolbarHeight + tabBarHeight + topMargin;\n \n // Ensure dial stays within window bounds with minimum margins\n int minMargin = 10;\n int maxX = windowWidth - dialWidth - minMargin;\n int maxY = windowHeight - dialHeight - minMargin;\n \n // Clamp position to stay within bounds\n int finalX = qBound(minMargin, idealX, maxX);\n int finalY = qBound(toolbarHeight + tabBarHeight + minMargin, idealY, maxY);\n \n // Move the dial to the calculated position\n dialContainer->move(finalX, finalY);\n}\n void handleDialInput(int angle) {\n if (!tracking) {\n startAngle = angle; // ✅ Set initial position\n accumulatedRotation = 0; // ✅ Reset tracking\n tracking = true;\n lastAngle = angle;\n return;\n }\n\n int delta = angle - lastAngle;\n\n // ✅ Handle 360-degree wrapping\n if (delta > 180) delta -= 360; // Example: 350° → 10° should be -20° instead of +340°\n if (delta < -180) delta += 360; // Example: 10° → 350° should be +20° instead of -340°\n\n accumulatedRotation += delta; // ✅ Accumulate movement\n\n // ✅ Detect crossing a 45-degree boundary\n int currentClicks = accumulatedRotation / 45; // Total number of \"clicks\" crossed\n int previousClicks = (accumulatedRotation - delta) / 45; // Previous click count\n\n if (currentClicks != previousClicks) { // ✅ Play sound if a new boundary is crossed\n \n if (dialClickSound) {\n dialClickSound->play();\n \n // ✅ Vibrate controller\n SDL_Joystick *joystick = controllerManager->getJoystick();\n if (joystick) {\n // Note: SDL_JoystickRumble requires SDL 2.0.9+\n // For older versions, this will be a no-op\n #if SDL_VERSION_ATLEAST(2, 0, 9)\n SDL_JoystickRumble(joystick, 0xA000, 0xF000, 10); // Vibrate shortly\n #endif\n }\n \n grossTotalClicks += 1;\n tempClicks = currentClicks;\n updateDialDisplay();\n \n if (isLowResPreviewEnabled()) {\n int previewPage = qBound(1, getCurrentPageForCanvas(currentCanvas()) + currentClicks, 99999);\n currentCanvas()->loadPdfPreviewAsync(previewPage);\n }\n }\n }\n\n lastAngle = angle; // ✅ Store last position\n}\n void onDialReleased() {\n if (!tracking) return; // ✅ Ignore if no tracking\n\n int pagesToAdvance = fastForwardMode ? 8 : 1;\n int totalClicks = accumulatedRotation / 45; // ✅ Convert degrees to pages\n\n /*\n int leftOver = accumulatedRotation % 45; // ✅ Track remaining rotation\n if (leftOver > 22 && totalClicks >= 0) {\n totalClicks += 1; // ✅ Round up if more than halfway\n } \n else if (leftOver <= -22 && totalClicks >= 0) {\n totalClicks -= 1; // ✅ Round down if more than halfway\n }\n */\n \n\n if (totalClicks != 0 || grossTotalClicks != 0) { // ✅ Only switch pages if movement happened\n // Use concurrent autosave for smoother dial operation\n if (currentCanvas()->isEdited()) {\n saveCurrentPageConcurrent();\n }\n\n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1;\n int newPage = qBound(1, currentPage + totalClicks * pagesToAdvance, 99999);\n \n // ✅ Use direction-aware page switching for dial\n int direction = (totalClicks * pagesToAdvance > 0) ? 1 : -1;\n switchPageWithDirection(newPage, direction);\n pageInput->setValue(newPage);\n tempClicks = 0;\n updateDialDisplay(); \n /*\n if (dialClickSound) {\n dialClickSound->play();\n }\n */\n }\n\n accumulatedRotation = 0; // ✅ Reset tracking\n grossTotalClicks = 0;\n tracking = false;\n}\n void initializeDialSound() {\n if (!dialClickSound) {\n dialClickSound = new QSoundEffect(this);\n dialClickSound->setSource(QUrl::fromLocalFile(\":/resources/sounds/dial_click.wav\")); // ✅ Path to the sound file\n dialClickSound->setVolume(0.8); // ✅ Set volume (0.0 - 1.0)\n }\n}\n void changeDialMode(DialMode mode) {\n\n if (!dialContainer) return; // ✅ Ensure dial container exists\n currentDialMode = mode; // ✅ Set new mode\n updateDialDisplay();\n\n // ✅ Enable dialHiddenButton for PanAndPageScroll and ZoomControl modes\n dialHiddenButton->setEnabled(currentDialMode == PanAndPageScroll || currentDialMode == ZoomControl);\n\n // ✅ Disconnect previous slots\n disconnect(pageDial, &QDial::valueChanged, nullptr, nullptr);\n disconnect(pageDial, &QDial::sliderReleased, nullptr, nullptr);\n \n // ✅ Disconnect dialHiddenButton to reconnect with appropriate function\n disconnect(dialHiddenButton, &QPushButton::clicked, nullptr, nullptr);\n \n // ✅ Connect dialHiddenButton to appropriate function based on mode\n if (currentDialMode == PanAndPageScroll) {\n connect(dialHiddenButton, &QPushButton::clicked, this, &MainWindow::toggleControlBar);\n } else if (currentDialMode == ZoomControl) {\n connect(dialHiddenButton, &QPushButton::clicked, this, &MainWindow::cycleZoomLevels);\n }\n\n dialColorPreview->hide();\n dialDisplay->setStyleSheet(\"background-color: black; color: white; font-size: 14px; border-radius: 40px;\");\n\n // ✅ Connect the correct function set for the current mode\n switch (currentDialMode) {\n case PageSwitching:\n connect(pageDial, &QDial::valueChanged, this, &MainWindow::handleDialInput);\n connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onDialReleased);\n break;\n case ZoomControl:\n connect(pageDial, &QDial::valueChanged, this, &MainWindow::handleDialZoom);\n connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onZoomReleased);\n break;\n case ThicknessControl:\n connect(pageDial, &QDial::valueChanged, this, &MainWindow::handleDialThickness);\n connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onThicknessReleased);\n break;\n\n case ToolSwitching:\n connect(pageDial, &QDial::valueChanged, this, &MainWindow::handleToolSelection);\n connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onToolReleased);\n break;\n case PresetSelection:\n connect(pageDial, &QDial::valueChanged, this, &MainWindow::handlePresetSelection);\n connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onPresetReleased);\n break;\n case PanAndPageScroll:\n connect(pageDial, &QDial::valueChanged, this, &MainWindow::handleDialPanScroll);\n connect(pageDial, &QDial::sliderReleased, this, &MainWindow::onPanScrollReleased);\n break;\n \n }\n}\n void handleDialZoom(int angle) {\n if (!tracking) {\n startAngle = angle; \n accumulatedRotation = 0; \n tracking = true;\n lastAngle = angle;\n return;\n }\n\n int delta = angle - lastAngle;\n\n // ✅ Handle 360-degree wrapping\n if (delta > 180) delta -= 360;\n if (delta < -180) delta += 360;\n\n accumulatedRotation += delta;\n\n if (abs(delta) < 4) { \n return; \n }\n\n // ✅ Apply zoom dynamically (instead of waiting for release)\n int oldZoom = zoomSlider->value();\n int newZoom = qBound(10, oldZoom + (delta / 4), 400); \n zoomSlider->setValue(newZoom);\n updateZoom(); // ✅ Ensure zoom updates immediately\n updateDialDisplay(); \n\n lastAngle = angle;\n}\n void handleDialThickness(int angle) {\n if (!tracking) {\n startAngle = angle;\n tracking = true;\n lastAngle = angle;\n return;\n }\n\n int delta = angle - lastAngle;\n if (delta > 180) delta -= 360;\n if (delta < -180) delta += 360;\n\n int thicknessStep = fastForwardMode ? 5 : 1;\n currentCanvas()->setPenThickness(qBound(1.0, currentCanvas()->getPenThickness() + (delta / 10.0) * thicknessStep, 50.0));\n\n updateDialDisplay();\n lastAngle = angle;\n}\n void onZoomReleased() {\n accumulatedRotation = 0;\n tracking = false;\n}\n void onThicknessReleased() {\n accumulatedRotation = 0;\n tracking = false;\n}\n void updateDialDisplay() {\n if (!dialDisplay) return;\n if (!dialColorPreview) return;\n if (!dialIconView) return;\n dialIconView->show();\n qreal dpr = initialDpr;\n QColor currentColor = currentCanvas()->getPenColor();\n switch (currentDialMode) {\n case DialMode::PageSwitching:\n if (fastForwardMode){\n dialDisplay->setText(QString(tr(\"\\n\\nPage\\n%1\").arg(getCurrentPageForCanvas(currentCanvas()) + 1 + tempClicks * 8)));\n }\n else {\n dialDisplay->setText(QString(tr(\"\\n\\nPage\\n%1\").arg(getCurrentPageForCanvas(currentCanvas()) + 1 + tempClicks)));\n }\n dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/bookpage_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n break;\n case DialMode::ThicknessControl:\n {\n QString toolName;\n switch (currentCanvas()->getCurrentTool()) {\n case ToolType::Pen:\n toolName = tr(\"Pen\");\n break;\n case ToolType::Marker:\n toolName = tr(\"Marker\");\n break;\n case ToolType::Eraser:\n toolName = tr(\"Eraser\");\n break;\n }\n dialDisplay->setText(QString(tr(\"\\n\\n%1\\n%2\").arg(toolName).arg(QString::number(currentCanvas()->getPenThickness(), 'f', 1))));\n dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/thickness_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n }\n break;\n case DialMode::ZoomControl:\n dialDisplay->setText(QString(tr(\"\\n\\nZoom\\n%1%\").arg(currentCanvas() ? currentCanvas()->getZoom() * initialDpr : zoomSlider->value() * initialDpr)));\n dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/zoom_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n break;\n \n case DialMode::ToolSwitching:\n // ✅ Convert ToolType to QString for display\n switch (currentCanvas()->getCurrentTool()) {\n case ToolType::Pen:\n dialDisplay->setText(tr(\"\\n\\n\\nPen\"));\n dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/pen_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n break;\n case ToolType::Marker:\n dialDisplay->setText(tr(\"\\n\\n\\nMarker\"));\n dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/marker_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n break;\n case ToolType::Eraser:\n dialDisplay->setText(tr(\"\\n\\n\\nEraser\"));\n dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/eraser_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n break;\n }\n break;\n case PresetSelection:\n dialColorPreview->show();\n dialIconView->hide();\n dialColorPreview->setStyleSheet(QString(\"background-color: %1; border-radius: 15px; border: 1px solid black;\")\n .arg(colorPresets[currentPresetIndex].name()));\n dialDisplay->setText(QString(tr(\"\\n\\nPreset %1\\n#%2\"))\n .arg(currentPresetIndex + 1) // ✅ Display preset index (1-based)\n .arg(colorPresets[currentPresetIndex].name().remove(\"#\"))); // ✅ Display hex color\n // dialIconView->setPixmap(QPixmap(\":/resources/reversed_icons/preset_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n break;\n case DialMode::PanAndPageScroll:\n dialIconView->setPixmap(QPixmap(\":/resources/icons/scroll_reversed.png\").scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation));\n QString fullscreenStatus = controlBarVisible ? tr(\"Etr\") : tr(\"Exit\");\n dialDisplay->setText(QString(tr(\"\\n\\nPage %1\\n%2 FulScr\")).arg(getCurrentPageForCanvas(currentCanvas()) + 1).arg(fullscreenStatus));\n break;\n }\n}\n void handleToolSelection(int angle) {\n static int lastToolIndex = -1; // ✅ Track last tool index\n\n // ✅ Snap to closest fixed 120° step\n int snappedAngle = (angle + 60) / 120 * 120; // Round to nearest 120°\n int toolIndex = snappedAngle / 120; // Convert to tool index (0, 1, 2)\n\n if (toolIndex >= 3) toolIndex = 0; // ✅ Wrap around at 360° → Back to Pen (0)\n\n if (toolIndex != lastToolIndex) { // ✅ Only switch if tool actually changes\n toolSelector->setCurrentIndex(toolIndex); // ✅ Change tool\n lastToolIndex = toolIndex; // ✅ Update last selected tool\n\n // ✅ Play click sound when tool changes\n if (dialClickSound) {\n dialClickSound->play();\n }\n\n SDL_Joystick *joystick = controllerManager->getJoystick();\n\n if (joystick) {\n #if SDL_VERSION_ATLEAST(2, 0, 9)\n SDL_JoystickRumble(joystick, 0xA000, 0xF000, 20); // ✅ Vibrate controller\n #endif\n }\n\n updateToolButtonStates(); // ✅ Update tool button states\n updateDialDisplay(); // ✅ Update dial display]\n }\n}\n void onToolReleased() {\n \n}\n void handlePresetSelection(int angle) {\n static int lastAngle = angle;\n int delta = angle - lastAngle;\n\n // ✅ Handle 360-degree wrapping\n if (delta > 180) delta -= 360;\n if (delta < -180) delta += 360;\n\n if (abs(delta) >= 60) { // ✅ Change preset every 60° (6 presets)\n lastAngle = angle;\n currentPresetIndex = (currentPresetIndex + (delta > 0 ? 1 : -1) + colorPresets.size()) % colorPresets.size();\n \n QColor selectedColor = colorPresets[currentPresetIndex];\n currentCanvas()->setPenColor(selectedColor);\n updateCustomColorButtonStyle(selectedColor);\n updateDialDisplay();\n updateColorButtonStates(); // Update button states when preset is selected\n \n if (dialClickSound) dialClickSound->play(); // ✅ Provide feedback\n SDL_Joystick *joystick = controllerManager->getJoystick();\n if (joystick) {\n #if SDL_VERSION_ATLEAST(2, 0, 9)\n SDL_JoystickRumble(joystick, 0xA000, 0xF000, 25); // Vibrate shortly\n #endif\n }\n }\n}\n void onPresetReleased() {\n accumulatedRotation = 0;\n tracking = false;\n}\n void addColorPreset() {\n QColor currentColor = currentCanvas()->getPenColor();\n\n // ✅ Prevent duplicates\n if (!colorPresets.contains(currentColor)) {\n if (colorPresets.size() >= 6) {\n colorPresets.dequeue(); // ✅ Remove oldest color\n }\n colorPresets.enqueue(currentColor);\n }\n}\n void updateColorPalette() {\n // Clear existing presets\n colorPresets.clear();\n currentPresetIndex = 0;\n \n // Add default pen color (theme-aware)\n colorPresets.enqueue(getDefaultPenColor());\n \n // Add palette colors\n colorPresets.enqueue(getPaletteColor(\"red\"));\n colorPresets.enqueue(getPaletteColor(\"yellow\"));\n colorPresets.enqueue(getPaletteColor(\"blue\"));\n colorPresets.enqueue(getPaletteColor(\"green\"));\n colorPresets.enqueue(QColor(\"#000000\")); // Black (always same)\n colorPresets.enqueue(QColor(\"#FFFFFF\")); // White (always same)\n \n // Only update UI elements if they exist\n if (redButton && blueButton && yellowButton && greenButton) {\n bool darkMode = isDarkMode();\n \n // Update color button icons based on current palette (not theme)\n QString redIconPath = useBrighterPalette ? \":/resources/icons/pen_light_red.png\" : \":/resources/icons/pen_dark_red.png\";\n QString blueIconPath = useBrighterPalette ? \":/resources/icons/pen_light_blue.png\" : \":/resources/icons/pen_dark_blue.png\";\n QString yellowIconPath = useBrighterPalette ? \":/resources/icons/pen_light_yellow.png\" : \":/resources/icons/pen_dark_yellow.png\";\n QString greenIconPath = useBrighterPalette ? \":/resources/icons/pen_light_green.png\" : \":/resources/icons/pen_dark_green.png\";\n \n redButton->setIcon(QIcon(redIconPath));\n blueButton->setIcon(QIcon(blueIconPath));\n yellowButton->setIcon(QIcon(yellowIconPath));\n greenButton->setIcon(QIcon(greenIconPath));\n \n // Update color button states\n updateColorButtonStates();\n }\n}\n QColor getPaletteColor(const QString &colorName) {\n if (useBrighterPalette) {\n // Brighter colors (good for dark backgrounds)\n if (colorName == \"red\") return QColor(\"#FF7755\");\n if (colorName == \"yellow\") return QColor(\"#EECC00\");\n if (colorName == \"blue\") return QColor(\"#66CCFF\");\n if (colorName == \"green\") return QColor(\"#55FF77\");\n } else {\n // Darker colors (good for light backgrounds)\n if (colorName == \"red\") return QColor(\"#AA0000\");\n if (colorName == \"yellow\") return QColor(\"#997700\");\n if (colorName == \"blue\") return QColor(\"#0000AA\");\n if (colorName == \"green\") return QColor(\"#007700\");\n }\n \n // Fallback colors\n if (colorName == \"black\") return QColor(\"#000000\");\n if (colorName == \"white\") return QColor(\"#FFFFFF\");\n \n return QColor(\"#000000\"); // Default fallback\n}\n qreal getDevicePixelRatio() {\n QScreen *screen = QGuiApplication::primaryScreen();\n qreal devicePixelRatio = screen ? screen->devicePixelRatio() : 1.0; // Default to 1.0 if null\n return devicePixelRatio;\n}\n bool isDarkMode() {\n QColor bg = palette().color(QPalette::Window);\n return bg.lightness() < 128; // Lightness scale: 0 (black) - 255 (white)\n}\n QIcon loadThemedIcon(const QString& baseName) {\n QString path = isDarkMode()\n ? QString(\":/resources/icons/%1_reversed.png\").arg(baseName)\n : QString(\":/resources/icons/%1.png\").arg(baseName);\n return QIcon(path);\n}\n QString createButtonStyle(bool darkMode) {\n if (darkMode) {\n // Dark mode: Keep current white highlights (good contrast)\n return R\"(\n QPushButton {\n background: transparent;\n border: none;\n padding: 6px;\n }\n QPushButton:hover {\n background: rgba(255, 255, 255, 50);\n }\n QPushButton:pressed {\n background: rgba(0, 0, 0, 50);\n }\n QPushButton[selected=\"true\"] {\n background: rgba(255, 255, 255, 100);\n border: 2px solid rgba(255, 255, 255, 150);\n padding: 4px;\n border-radius: 4px;\n }\n QPushButton[selected=\"true\"]:hover {\n background: rgba(255, 255, 255, 120);\n }\n QPushButton[selected=\"true\"]:pressed {\n background: rgba(0, 0, 0, 50);\n }\n )\";\n } else {\n // Light mode: Use darker colors for better visibility\n return R\"(\n QPushButton {\n background: transparent;\n border: none;\n padding: 6px;\n }\n QPushButton:hover {\n background: rgba(0, 0, 0, 30);\n }\n QPushButton:pressed {\n background: rgba(0, 0, 0, 60);\n }\n QPushButton[selected=\"true\"] {\n background: rgba(0, 0, 0, 80);\n border: 2px solid rgba(0, 0, 0, 120);\n padding: 4px;\n border-radius: 4px;\n }\n QPushButton[selected=\"true\"]:hover {\n background: rgba(0, 0, 0, 100);\n }\n QPushButton[selected=\"true\"]:pressed {\n background: rgba(0, 0, 0, 140);\n }\n )\";\n }\n}\n void handleDialPanScroll(int angle) {\n if (!tracking) {\n startAngle = angle;\n accumulatedRotation = 0;\n accumulatedRotationAfterLimit = 0;\n tracking = true;\n lastAngle = angle;\n pendingPageFlip = 0;\n return;\n }\n\n int delta = angle - lastAngle;\n\n // Handle 360 wrap\n if (delta > 180) delta -= 360;\n if (delta < -180) delta += 360;\n\n accumulatedRotation += delta;\n\n // Pan scroll\n int panDelta = delta * 4; // Adjust scroll sensitivity here\n int currentPan = panYSlider->value();\n int newPan = currentPan + panDelta;\n\n // Clamp pan slider\n newPan = qBound(panYSlider->minimum(), newPan, panYSlider->maximum());\n panYSlider->setValue(newPan);\n\n // ✅ NEW → if slider reached top/bottom, accumulate AFTER LIMIT\n if (newPan == panYSlider->maximum()) {\n accumulatedRotationAfterLimit += delta;\n\n if (accumulatedRotationAfterLimit >= 120) {\n pendingPageFlip = +1; // Flip next when released\n }\n } \n else if (newPan == panYSlider->minimum()) {\n accumulatedRotationAfterLimit += delta;\n\n if (accumulatedRotationAfterLimit <= -120) {\n pendingPageFlip = -1; // Flip previous when released\n }\n } \n else {\n // Reset after limit accumulator when not at limit\n accumulatedRotationAfterLimit = 0;\n pendingPageFlip = 0;\n }\n\n lastAngle = angle;\n}\n void onPanScrollReleased() {\n // ✅ Perform page flip only when dial released and flip is pending\n if (pendingPageFlip != 0) {\n // Use concurrent saving for smooth dial operation\n if (currentCanvas()->isEdited()) {\n saveCurrentPageConcurrent();\n }\n\n int currentPage = getCurrentPageForCanvas(currentCanvas());\n int newPage = qBound(1, currentPage + pendingPageFlip + 1, 99999);\n \n // ✅ Use direction-aware page switching for pan-and-scroll dial\n switchPageWithDirection(newPage, pendingPageFlip);\n pageInput->setValue(newPage);\n updateDialDisplay();\n\n SDL_Joystick *joystick = controllerManager->getJoystick();\n if (joystick) {\n #if SDL_VERSION_ATLEAST(2, 0, 9)\n SDL_JoystickRumble(joystick, 0xA000, 0xF000, 25); // Vibrate shortly\n #endif\n }\n }\n\n // Reset states\n pendingPageFlip = 0;\n accumulatedRotation = 0;\n accumulatedRotationAfterLimit = 0;\n tracking = false;\n}\n void handleTouchZoomChange(int newZoom) {\n // Update zoom slider without triggering updateZoom again\n zoomSlider->blockSignals(true);\n int oldZoom = zoomSlider->value(); // Get the old zoom value before updating the slider\n zoomSlider->setValue(newZoom);\n zoomSlider->blockSignals(false);\n \n // Show both scrollbars during gesture\n if (panXSlider->maximum() > 0) {\n panXSlider->setVisible(true);\n }\n if (panYSlider->maximum() > 0) {\n panYSlider->setVisible(true);\n }\n scrollbarsVisible = true;\n \n // Update canvas zoom directly\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n // The canvas zoom has already been set by the gesture processing in InkCanvas::event()\n // So we don't need to set it again, just update the last zoom level\n canvas->setLastZoomLevel(newZoom);\n updatePanRange();\n \n // ✅ FIXED: Add thickness adjustment for pinch-to-zoom gestures to maintain visual consistency\n adjustThicknessForZoom(oldZoom, newZoom);\n \n updateDialDisplay();\n }\n}\n void handleTouchPanChange(int panX, int panY) {\n // Clamp values to valid ranges\n panX = qBound(panXSlider->minimum(), panX, panXSlider->maximum());\n panY = qBound(panYSlider->minimum(), panY, panYSlider->maximum());\n \n // Show both scrollbars during gesture\n if (panXSlider->maximum() > 0) {\n panXSlider->setVisible(true);\n }\n if (panYSlider->maximum() > 0) {\n panYSlider->setVisible(true);\n }\n scrollbarsVisible = true;\n \n // Update sliders without triggering their valueChanged signals\n panXSlider->blockSignals(true);\n panYSlider->blockSignals(true);\n panXSlider->setValue(panX);\n panYSlider->setValue(panY);\n panXSlider->blockSignals(false);\n panYSlider->blockSignals(false);\n \n // Update canvas pan directly\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n canvas->setPanX(panX);\n canvas->setPanY(panY);\n canvas->setLastPanX(panX);\n canvas->setLastPanY(panY);\n }\n}\n void handleTouchGestureEnd() {\n // Hide scrollbars immediately when touch gesture ends\n panXSlider->setVisible(false);\n panYSlider->setVisible(false);\n scrollbarsVisible = false;\n}\n void updateColorButtonStates() {\n // Check if there's a current canvas\n if (!currentCanvas()) return;\n \n // Get current pen color\n QColor currentColor = currentCanvas()->getPenColor();\n \n // Determine if we're in dark mode to match the correct colors\n bool darkMode = isDarkMode();\n \n // Reset all color buttons to original style\n redButton->setProperty(\"selected\", false);\n blueButton->setProperty(\"selected\", false);\n yellowButton->setProperty(\"selected\", false);\n greenButton->setProperty(\"selected\", false);\n blackButton->setProperty(\"selected\", false);\n whiteButton->setProperty(\"selected\", false);\n \n // Set the selected property for the matching color button based on current palette\n QColor redColor = getPaletteColor(\"red\");\n QColor blueColor = getPaletteColor(\"blue\");\n QColor yellowColor = getPaletteColor(\"yellow\");\n QColor greenColor = getPaletteColor(\"green\");\n \n if (currentColor == redColor) {\n redButton->setProperty(\"selected\", true);\n } else if (currentColor == blueColor) {\n blueButton->setProperty(\"selected\", true);\n } else if (currentColor == yellowColor) {\n yellowButton->setProperty(\"selected\", true);\n } else if (currentColor == greenColor) {\n greenButton->setProperty(\"selected\", true);\n } else if (currentColor == QColor(\"#000000\")) {\n blackButton->setProperty(\"selected\", true);\n } else if (currentColor == QColor(\"#FFFFFF\")) {\n whiteButton->setProperty(\"selected\", true);\n }\n \n // Force style update\n redButton->style()->unpolish(redButton);\n redButton->style()->polish(redButton);\n blueButton->style()->unpolish(blueButton);\n blueButton->style()->polish(blueButton);\n yellowButton->style()->unpolish(yellowButton);\n yellowButton->style()->polish(yellowButton);\n greenButton->style()->unpolish(greenButton);\n greenButton->style()->polish(greenButton);\n blackButton->style()->unpolish(blackButton);\n blackButton->style()->polish(blackButton);\n whiteButton->style()->unpolish(whiteButton);\n whiteButton->style()->polish(whiteButton);\n}\n void selectColorButton(QPushButton* selectedButton) {\n updateColorButtonStates();\n}\n void updateStraightLineButtonState() {\n // Check if there's a current canvas\n if (!currentCanvas()) return;\n \n // Update the button state to match the canvas straight line mode\n bool isEnabled = currentCanvas()->isStraightLineMode();\n \n // Set visual indicator that the button is active/inactive\n if (straightLineToggleButton) {\n straightLineToggleButton->setProperty(\"selected\", isEnabled);\n \n // Force style update\n straightLineToggleButton->style()->unpolish(straightLineToggleButton);\n straightLineToggleButton->style()->polish(straightLineToggleButton);\n }\n}\n void updateRopeToolButtonState() {\n // Check if there's a current canvas\n if (!currentCanvas()) return;\n\n // Update the button state to match the canvas rope tool mode\n bool isEnabled = currentCanvas()->isRopeToolMode();\n\n // Set visual indicator that the button is active/inactive\n if (ropeToolButton) {\n ropeToolButton->setProperty(\"selected\", isEnabled);\n\n // Force style update\n ropeToolButton->style()->unpolish(ropeToolButton);\n ropeToolButton->style()->polish(ropeToolButton);\n }\n}\n void updateMarkdownButtonState() {\n // Check if there's a current canvas\n if (!currentCanvas()) return;\n\n // Update the button state to match the canvas markdown selection mode\n bool isEnabled = currentCanvas()->isMarkdownSelectionMode();\n\n // Set visual indicator that the button is active/inactive\n if (markdownButton) {\n markdownButton->setProperty(\"selected\", isEnabled);\n\n // Force style update\n markdownButton->style()->unpolish(markdownButton);\n markdownButton->style()->polish(markdownButton);\n }\n}\n void setPenTool() {\n if (!currentCanvas()) return;\n currentCanvas()->setTool(ToolType::Pen);\n updateToolButtonStates();\n updateThicknessSliderForCurrentTool();\n updateDialDisplay();\n}\n void setMarkerTool() {\n if (!currentCanvas()) return;\n currentCanvas()->setTool(ToolType::Marker);\n updateToolButtonStates();\n updateThicknessSliderForCurrentTool();\n updateDialDisplay();\n}\n void setEraserTool() {\n if (!currentCanvas()) return;\n currentCanvas()->setTool(ToolType::Eraser);\n updateToolButtonStates();\n updateThicknessSliderForCurrentTool();\n updateDialDisplay();\n}\n QColor getContrastingTextColor(const QColor &backgroundColor) {\n // Calculate relative luminance using the formula from WCAG 2.0\n double r = backgroundColor.redF();\n double g = backgroundColor.greenF();\n double b = backgroundColor.blueF();\n \n // Gamma correction\n r = (r <= 0.03928) ? r/12.92 : pow((r + 0.055)/1.055, 2.4);\n g = (g <= 0.03928) ? g/12.92 : pow((g + 0.055)/1.055, 2.4);\n b = (b <= 0.03928) ? b/12.92 : pow((b + 0.055)/1.055, 2.4);\n \n // Calculate luminance\n double luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;\n \n // Use white text for darker backgrounds\n return (luminance < 0.5) ? Qt::white : Qt::black;\n}\n void updateCustomColorButtonStyle(const QColor &color) {\n QColor textColor = getContrastingTextColor(color);\n customColorButton->setStyleSheet(QString(\"background-color: %1; color: %2\")\n .arg(color.name())\n .arg(textColor.name()));\n customColorButton->setText(QString(\"%1\").arg(color.name()).toUpper());\n}\n void openRecentNotebooksDialog() {\n RecentNotebooksDialog dialog(this, recentNotebooksManager, this);\n dialog.exec();\n}\n void showPendingTooltip() {\n // This function is now unused since we disabled tablet tracking\n // Tooltips will work through normal mouse hover events instead\n // Keeping the function for potential future use\n}\n void showRopeSelectionMenu(const QPoint &position) {\n // Create context menu for rope tool selection\n QMenu *contextMenu = new QMenu(this);\n contextMenu->setAttribute(Qt::WA_DeleteOnClose);\n \n // Add Copy action\n QAction *copyAction = contextMenu->addAction(tr(\"Copy\"));\n copyAction->setIcon(loadThemedIcon(\"copy\"));\n connect(copyAction, &QAction::triggered, this, [this]() {\n if (currentCanvas()) {\n currentCanvas()->copyRopeSelection();\n }\n });\n \n // Add Delete action\n QAction *deleteAction = contextMenu->addAction(tr(\"Delete\"));\n deleteAction->setIcon(loadThemedIcon(\"trash\"));\n connect(deleteAction, &QAction::triggered, this, [this]() {\n if (currentCanvas()) {\n currentCanvas()->deleteRopeSelection();\n }\n });\n \n // Add Cancel action\n QAction *cancelAction = contextMenu->addAction(tr(\"Cancel\"));\n cancelAction->setIcon(loadThemedIcon(\"cross\"));\n connect(cancelAction, &QAction::triggered, this, [this]() {\n if (currentCanvas()) {\n currentCanvas()->cancelRopeSelection();\n }\n });\n \n // Convert position from canvas coordinates to global coordinates\n QPoint globalPos = currentCanvas()->mapToGlobal(position);\n \n // Show the menu at the specified position\n contextMenu->popup(globalPos);\n}\n void toggleOutlineSidebar() {\n outlineSidebarVisible = !outlineSidebarVisible;\n \n // Hide bookmarks sidebar if it's visible when opening outline\n if (outlineSidebarVisible && bookmarksSidebar && bookmarksSidebar->isVisible()) {\n bookmarksSidebar->setVisible(false);\n bookmarksSidebarVisible = false;\n // Update bookmarks button state\n if (toggleBookmarksButton) {\n toggleBookmarksButton->setProperty(\"selected\", false);\n toggleBookmarksButton->style()->unpolish(toggleBookmarksButton);\n toggleBookmarksButton->style()->polish(toggleBookmarksButton);\n }\n }\n \n outlineSidebar->setVisible(outlineSidebarVisible);\n \n // Update button toggle state\n if (toggleOutlineButton) {\n toggleOutlineButton->setProperty(\"selected\", outlineSidebarVisible);\n toggleOutlineButton->style()->unpolish(toggleOutlineButton);\n toggleOutlineButton->style()->polish(toggleOutlineButton);\n }\n \n // Load PDF outline when showing sidebar for the first time\n if (outlineSidebarVisible) {\n loadPdfOutline();\n }\n}\n void onOutlineItemClicked(QTreeWidgetItem *item, int column) {\n Q_UNUSED(column);\n \n if (!item) return;\n \n // Get the page number stored in the item data\n QVariant pageData = item->data(0, Qt::UserRole);\n if (pageData.isValid()) {\n int pageNumber = pageData.toInt();\n if (pageNumber >= 0) {\n // Switch to the selected page (convert from 0-based to 1-based)\n switchPage(pageNumber + 1);\n pageInput->setValue(pageNumber + 1);\n }\n }\n}\n void loadPdfOutline() {\n if (!outlineTree) return;\n \n outlineTree->clear();\n \n // Get current PDF document\n Poppler::Document* pdfDoc = getPdfDocument();\n if (!pdfDoc) return;\n \n // Get the outline from the PDF document\n QVector outlineItems = pdfDoc->outline();\n \n if (outlineItems.isEmpty()) {\n // If no outline exists, show page numbers as fallback\n int pageCount = pdfDoc->numPages();\n for (int i = 0; i < pageCount; ++i) {\n QTreeWidgetItem* item = new QTreeWidgetItem(outlineTree);\n item->setText(0, QString(tr(\"Page %1\")).arg(i + 1));\n item->setData(0, Qt::UserRole, i); // Store 0-based page index\n }\n } else {\n // Process the actual PDF outline\n for (const Poppler::OutlineItem& outlineItem : outlineItems) {\n addOutlineItem(outlineItem, nullptr);\n }\n }\n \n // Expand the first level by default\n outlineTree->expandToDepth(0);\n}\n void addOutlineItem(const Poppler::OutlineItem& outlineItem, QTreeWidgetItem* parentItem) {\n if (outlineItem.isNull()) return;\n \n QTreeWidgetItem* item;\n if (parentItem) {\n item = new QTreeWidgetItem(parentItem);\n } else {\n item = new QTreeWidgetItem(outlineTree);\n }\n \n // Set the title\n item->setText(0, outlineItem.name());\n \n // Try to get the page number from the destination\n int pageNumber = -1;\n auto destination = outlineItem.destination();\n if (destination) {\n pageNumber = destination->pageNumber();\n }\n \n // Store the page number (1-based) in the item data\n if (pageNumber >= 0) {\n item->setData(0, Qt::UserRole, pageNumber + 1); // Convert to 1-based\n }\n \n // Add child items recursively\n if (outlineItem.hasChildren()) {\n QVector children = outlineItem.children();\n for (const Poppler::OutlineItem& child : children) {\n addOutlineItem(child, item);\n }\n }\n}\n Poppler::Document* getPdfDocument();\n void toggleBookmarksSidebar() {\n if (!bookmarksSidebar) return;\n \n bool isVisible = bookmarksSidebar->isVisible();\n \n // Hide outline sidebar if it's visible\n if (!isVisible && outlineSidebar && outlineSidebar->isVisible()) {\n outlineSidebar->setVisible(false);\n outlineSidebarVisible = false;\n // Update outline button state\n if (toggleOutlineButton) {\n toggleOutlineButton->setProperty(\"selected\", false);\n toggleOutlineButton->style()->unpolish(toggleOutlineButton);\n toggleOutlineButton->style()->polish(toggleOutlineButton);\n }\n }\n \n bookmarksSidebar->setVisible(!isVisible);\n bookmarksSidebarVisible = !isVisible;\n \n // Update button toggle state\n if (toggleBookmarksButton) {\n toggleBookmarksButton->setProperty(\"selected\", bookmarksSidebarVisible);\n toggleBookmarksButton->style()->unpolish(toggleBookmarksButton);\n toggleBookmarksButton->style()->polish(toggleBookmarksButton);\n }\n \n if (bookmarksSidebarVisible) {\n loadBookmarks(); // Refresh bookmarks when opening\n }\n}\n void onBookmarkItemClicked(QTreeWidgetItem *item, int column) {\n Q_UNUSED(column);\n if (!item) return;\n \n // Get the page number from the item data\n bool ok;\n int pageNumber = item->data(0, Qt::UserRole).toInt(&ok);\n if (ok && pageNumber > 0) {\n // Navigate to the bookmarked page\n switchPageWithDirection(pageNumber, (pageNumber > getCurrentPageForCanvas(currentCanvas()) + 1) ? 1 : -1);\n pageInput->setValue(pageNumber);\n }\n}\n void loadBookmarks() {\n if (!bookmarksTree || !currentCanvas()) return;\n \n bookmarksTree->clear();\n \n // Get the current notebook's save folder\n QString saveFolder = currentCanvas()->getSaveFolder();\n if (saveFolder.isEmpty()) return;\n \n QString bookmarksFile = saveFolder + \"/.bookmarks.txt\";\n QFile file(bookmarksFile);\n \n bookmarks.clear();\n \n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n while (!in.atEnd()) {\n QString line = in.readLine().trimmed();\n if (line.isEmpty()) continue;\n \n QStringList parts = line.split('\\t', Qt::KeepEmptyParts);\n if (parts.size() >= 2) {\n bool ok;\n int pageNum = parts[0].toInt(&ok);\n if (ok) {\n QString title = parts[1];\n bookmarks[pageNum] = title;\n }\n }\n }\n file.close();\n }\n \n // Populate the tree widget\n for (auto it = bookmarks.begin(); it != bookmarks.end(); ++it) {\n QTreeWidgetItem *item = new QTreeWidgetItem(bookmarksTree);\n \n // Create a custom widget for each bookmark item\n QWidget *itemWidget = new QWidget();\n QHBoxLayout *itemLayout = new QHBoxLayout(itemWidget);\n itemLayout->setContentsMargins(5, 2, 5, 2);\n itemLayout->setSpacing(5);\n \n // Page number label (fixed width)\n QLabel *pageLabel = new QLabel(QString(tr(\"Page %1\")).arg(it.key()));\n pageLabel->setFixedWidth(60);\n pageLabel->setStyleSheet(\"font-weight: bold; color: #666;\");\n itemLayout->addWidget(pageLabel);\n \n // Editable title (supports Windows handwriting if available)\n QLineEdit *titleEdit = new QLineEdit(it.value());\n titleEdit->setPlaceholderText(\"Enter bookmark title...\");\n titleEdit->setProperty(\"pageNumber\", it.key()); // Store page number for saving\n \n // Enable IME support for multi-language input\n titleEdit->setAttribute(Qt::WA_InputMethodEnabled, true);\n titleEdit->setInputMethodHints(Qt::ImhNone); // Allow all input methods\n titleEdit->installEventFilter(this); // Install event filter for IME handling\n \n // Connect to save when editing is finished\n connect(titleEdit, &QLineEdit::editingFinished, this, [this, titleEdit]() {\n int pageNum = titleEdit->property(\"pageNumber\").toInt();\n QString newTitle = titleEdit->text().trimmed();\n \n if (newTitle.isEmpty()) {\n // Remove bookmark if title is empty\n bookmarks.remove(pageNum);\n } else {\n // Update bookmark title\n bookmarks[pageNum] = newTitle;\n }\n saveBookmarks();\n updateBookmarkButtonState(); // Update button state\n });\n \n itemLayout->addWidget(titleEdit, 1);\n \n // Store page number in item data for navigation\n item->setData(0, Qt::UserRole, it.key());\n \n // Set the custom widget\n bookmarksTree->setItemWidget(item, 0, itemWidget);\n \n // Set item height\n item->setSizeHint(0, QSize(0, 30));\n }\n \n updateBookmarkButtonState(); // Update button state after loading\n}\n void saveBookmarks() {\n if (!currentCanvas()) return;\n \n QString saveFolder = currentCanvas()->getSaveFolder();\n if (saveFolder.isEmpty()) return;\n \n QString bookmarksFile = saveFolder + \"/.bookmarks.txt\";\n QFile file(bookmarksFile);\n \n if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {\n QTextStream out(&file);\n \n // Sort bookmarks by page number\n QList sortedPages = bookmarks.keys();\n std::sort(sortedPages.begin(), sortedPages.end());\n \n for (int pageNum : sortedPages) {\n out << pageNum << '\\t' << bookmarks[pageNum] << '\\n';\n }\n \n file.close();\n }\n}\n void toggleCurrentPageBookmark() {\n if (!currentCanvas()) return;\n \n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1; // Convert to 1-based\n \n if (bookmarks.contains(currentPage)) {\n // Remove bookmark\n bookmarks.remove(currentPage);\n } else {\n // Add bookmark with default title\n QString defaultTitle = QString(tr(\"Bookmark %1\")).arg(currentPage);\n bookmarks[currentPage] = defaultTitle;\n }\n \n saveBookmarks();\n updateBookmarkButtonState();\n \n // Refresh bookmarks view if visible\n if (bookmarksSidebarVisible) {\n loadBookmarks();\n }\n}\n void updateBookmarkButtonState() {\n if (!toggleBookmarkButton || !currentCanvas()) return;\n \n int currentPage = getCurrentPageForCanvas(currentCanvas()) + 1; // Convert to 1-based\n bool isBookmarked = bookmarks.contains(currentPage);\n \n toggleBookmarkButton->setProperty(\"selected\", isBookmarked);\n \n // Update tooltip\n if (isBookmarked) {\n toggleBookmarkButton->setToolTip(tr(\"Remove Bookmark\"));\n } else {\n toggleBookmarkButton->setToolTip(tr(\"Add Bookmark\"));\n }\n \n // Force style update\n toggleBookmarkButton->style()->unpolish(toggleBookmarkButton);\n toggleBookmarkButton->style()->polish(toggleBookmarkButton);\n}\n private:\n InkCanvas *canvas;\n QPushButton *benchmarkButton;\n QLabel *benchmarkLabel;\n QTimer *benchmarkTimer;\n bool benchmarking;\n QPushButton *exportNotebookButton;\n QPushButton *importNotebookButton;\n QPushButton *redButton;\n QPushButton *blueButton;\n QPushButton *yellowButton;\n QPushButton *greenButton;\n QPushButton *blackButton;\n QPushButton *whiteButton;\n QLineEdit *customColorInput;\n QPushButton *customColorButton;\n QPushButton *thicknessButton;\n QSlider *thicknessSlider;\n QFrame *thicknessFrame;\n QComboBox *toolSelector;\n QPushButton *penToolButton;\n QPushButton *markerToolButton;\n QPushButton *eraserToolButton;\n QPushButton *deletePageButton;\n QPushButton *selectFolderButton;\n QPushButton *saveButton;\n QPushButton *saveAnnotatedButton;\n QPushButton *fullscreenButton;\n QPushButton *openControlPanelButton;\n QPushButton *openRecentNotebooksButton;\n QPushButton *loadPdfButton;\n QPushButton *clearPdfButton;\n QPushButton *pdfTextSelectButton;\n QPushButton *toggleTabBarButton;\n QMap pageMap;\n QPushButton *backgroundButton;\n QPushButton *straightLineToggleButton;\n QPushButton *ropeToolButton;\n QPushButton *markdownButton;\n QSlider *zoomSlider;\n QPushButton *zoomButton;\n QFrame *zoomFrame;\n QPushButton *dezoomButton;\n QPushButton *zoom50Button;\n QPushButton *zoom200Button;\n QWidget *zoomContainer;\n QLineEdit *zoomInput;\n QScrollBar *panXSlider;\n QScrollBar *panYSlider;\n QListWidget *tabList;\n QStackedWidget *canvasStack;\n QPushButton *addTabButton;\n QWidget *tabBarContainer;\n QWidget *outlineSidebar;\n QTreeWidget *outlineTree;\n QPushButton *toggleOutlineButton;\n bool outlineSidebarVisible = false;\n QWidget *bookmarksSidebar;\n QTreeWidget *bookmarksTree;\n QPushButton *toggleBookmarksButton;\n QPushButton *toggleBookmarkButton;\n QPushButton *touchGesturesButton;\n bool bookmarksSidebarVisible = false;\n QMap bookmarks;\n QPushButton *jumpToPageButton;\n QWidget *dialContainer = nullptr;\n QDial *pageDial = nullptr;\n QDial *modeDial = nullptr;\n QPushButton *dialToggleButton;\n bool fastForwardMode = false;\n QPushButton *fastForwardButton;\n int lastAngle = 0;\n int startAngle = 0;\n bool tracking = false;\n int accumulatedRotation = 0;\n QSoundEffect *dialClickSound = nullptr;\n int grossTotalClicks = 0;\n DialMode currentDialMode = PanAndPageScroll;\n DialMode temporaryDialMode = None;\n QComboBox *dialModeSelector;\n QPushButton *colorPreview;\n QLabel *dialDisplay = nullptr;\n QFrame *dialColorPreview;\n QLabel *dialIconView;\n QFont pixelFont;\n QPushButton *btnPageSwitch;\n QPushButton *btnZoom;\n QPushButton *btnThickness;\n QPushButton *btnTool;\n QPushButton *btnPresets;\n QPushButton *btnPannScroll;\n int tempClicks = 0;\n QPushButton *dialHiddenButton;\n QQueue colorPresets;\n QPushButton *addPresetButton;\n int currentPresetIndex = 0;\n bool useBrighterPalette = false;\n qreal initialDpr = 1.0;\n QWidget *sidebarContainer;\n QWidget *controlBar;\n void setTemporaryDialMode(DialMode mode) {\n if (temporaryDialMode == None) {\n temporaryDialMode = currentDialMode;\n }\n changeDialMode(mode);\n}\n void clearTemporaryDialMode() {\n if (temporaryDialMode != None) {\n changeDialMode(temporaryDialMode);\n temporaryDialMode = None;\n }\n}\n bool controlBarVisible = true;\n void toggleControlBar() {\n // Proper fullscreen toggle: handle both sidebar and control bar\n \n if (controlBarVisible) {\n // Going into fullscreen mode\n \n // First, remember current tab bar state\n sidebarWasVisibleBeforeFullscreen = tabBarContainer->isVisible();\n \n // Hide tab bar if it's visible\n if (tabBarContainer->isVisible()) {\n tabBarContainer->setVisible(false);\n }\n \n // Hide control bar\n controlBarVisible = false;\n controlBar->setVisible(false);\n \n // Hide floating popup widgets when control bar is hidden to prevent stacking\n if (zoomFrame && zoomFrame->isVisible()) zoomFrame->hide();\n if (thicknessFrame && thicknessFrame->isVisible()) thicknessFrame->hide();\n \n // Hide orphaned widgets that are not added to any layout\n if (colorPreview) colorPreview->hide();\n if (thicknessButton) thicknessButton->hide();\n if (jumpToPageButton) jumpToPageButton->hide();\n\n if (toolSelector) toolSelector->hide();\n if (zoomButton) zoomButton->hide();\n if (customColorInput) customColorInput->hide();\n \n // Find and hide local widgets that might be orphaned\n QList comboBoxes = findChildren();\n for (QComboBox* combo : comboBoxes) {\n if (combo->parent() == this && !combo->isVisible()) {\n // Already hidden, keep it hidden\n } else if (combo->parent() == this) {\n // This might be the orphaned dialModeSelector or similar\n combo->hide();\n }\n }\n } else {\n // Coming out of fullscreen mode\n \n // Restore control bar\n controlBarVisible = true;\n controlBar->setVisible(true);\n \n // Restore tab bar to its previous state\n tabBarContainer->setVisible(sidebarWasVisibleBeforeFullscreen);\n \n // Show orphaned widgets when control bar is visible\n // Note: These are kept hidden normally since they're not in the layout\n // Only show them if they were specifically intended to be visible\n }\n \n // Update dial display to reflect new status\n updateDialDisplay();\n \n // Force layout update to recalculate space\n if (auto *canvas = currentCanvas()) {\n QTimer::singleShot(0, this, [this, canvas]() {\n canvas->setMaximumSize(canvas->getCanvasSize());\n });\n }\n}\n void cycleZoomLevels() {\n if (!zoomSlider) return;\n \n int currentZoom = zoomSlider->value();\n int targetZoom;\n \n // Calculate the scaled zoom levels based on initial DPR\n int zoom50 = 50 / initialDpr;\n int zoom100 = 100 / initialDpr;\n int zoom200 = 200 / initialDpr;\n \n // Cycle through 0.5x -> 1x -> 2x -> 0.5x...\n if (currentZoom <= zoom50 + 5) { // Close to 0.5x (with small tolerance)\n targetZoom = zoom100; // Go to 1x\n } else if (currentZoom <= zoom100 + 5) { // Close to 1x\n targetZoom = zoom200; // Go to 2x\n } else { // Any other zoom level or close to 2x\n targetZoom = zoom50; // Go to 0.5x\n }\n \n zoomSlider->setValue(targetZoom);\n updateZoom();\n updateDialDisplay();\n}\n bool sidebarWasVisibleBeforeFullscreen = true;\n int accumulatedRotationAfterLimit = 0;\n int pendingPageFlip = 0;\n QMap buttonHoldMapping;\n QMap buttonPressMapping;\n QMap buttonPressActionMapping;\n QMap keyboardMappings;\n QMap keyboardActionMapping;\n QTimer *tooltipTimer;\n QWidget *lastHoveredWidget;\n QPoint pendingTooltipPos;\n void handleButtonHeld(const QString &buttonName) {\n QString mode = buttonHoldMapping.value(buttonName, \"None\");\n if (mode != \"None\") {\n setTemporaryDialMode(dialModeFromString(mode));\n return;\n }\n}\n void handleButtonReleased(const QString &buttonName) {\n QString mode = buttonHoldMapping.value(buttonName, \"None\");\n if (mode != \"None\") {\n clearTemporaryDialMode();\n }\n}\n void handleControllerButton(const QString &buttonName) { // This is for single press functions\n ControllerAction action = buttonPressActionMapping.value(buttonName, ControllerAction::None);\n\n switch (action) {\n case ControllerAction::ToggleFullscreen:\n fullscreenButton->click();\n break;\n case ControllerAction::ToggleDial:\n toggleDial();\n break;\n case ControllerAction::Zoom50:\n zoom50Button->click();\n break;\n case ControllerAction::ZoomOut:\n dezoomButton->click();\n break;\n case ControllerAction::Zoom200:\n zoom200Button->click();\n break;\n case ControllerAction::AddPreset:\n addPresetButton->click();\n break;\n case ControllerAction::DeletePage:\n deletePageButton->click(); // assuming you have this\n break;\n case ControllerAction::FastForward:\n fastForwardButton->click(); // assuming you have this\n break;\n case ControllerAction::OpenControlPanel:\n openControlPanelButton->click();\n break;\n case ControllerAction::RedColor:\n redButton->click();\n break;\n case ControllerAction::BlueColor:\n blueButton->click();\n break;\n case ControllerAction::YellowColor:\n yellowButton->click();\n break;\n case ControllerAction::GreenColor:\n greenButton->click();\n break;\n case ControllerAction::BlackColor:\n blackButton->click();\n break;\n case ControllerAction::WhiteColor:\n whiteButton->click();\n break;\n case ControllerAction::CustomColor:\n customColorButton->click();\n break;\n case ControllerAction::ToggleSidebar:\n toggleTabBarButton->click();\n break;\n case ControllerAction::Save:\n saveButton->click();\n break;\n case ControllerAction::StraightLineTool:\n straightLineToggleButton->click();\n break;\n case ControllerAction::RopeTool:\n ropeToolButton->click();\n break;\n case ControllerAction::SetPenTool:\n setPenTool();\n break;\n case ControllerAction::SetMarkerTool:\n setMarkerTool();\n break;\n case ControllerAction::SetEraserTool:\n setEraserTool();\n break;\n case ControllerAction::TogglePdfTextSelection:\n pdfTextSelectButton->click();\n break;\n case ControllerAction::ToggleOutline:\n toggleOutlineButton->click();\n break;\n case ControllerAction::ToggleBookmarks:\n toggleBookmarksButton->click();\n break;\n case ControllerAction::AddBookmark:\n toggleBookmarkButton->click();\n break;\n case ControllerAction::ToggleTouchGestures:\n touchGesturesButton->click();\n break;\n default:\n break;\n }\n}\n void handleKeyboardShortcut(const QString &keySequence) {\n ControllerAction action = keyboardActionMapping.value(keySequence, ControllerAction::None);\n \n // Use the same handler as Joy-Con buttons\n switch (action) {\n case ControllerAction::ToggleFullscreen:\n fullscreenButton->click();\n break;\n case ControllerAction::ToggleDial:\n toggleDial();\n break;\n case ControllerAction::Zoom50:\n zoom50Button->click();\n break;\n case ControllerAction::ZoomOut:\n dezoomButton->click();\n break;\n case ControllerAction::Zoom200:\n zoom200Button->click();\n break;\n case ControllerAction::AddPreset:\n addPresetButton->click();\n break;\n case ControllerAction::DeletePage:\n deletePageButton->click();\n break;\n case ControllerAction::FastForward:\n fastForwardButton->click();\n break;\n case ControllerAction::OpenControlPanel:\n openControlPanelButton->click();\n break;\n case ControllerAction::RedColor:\n redButton->click();\n break;\n case ControllerAction::BlueColor:\n blueButton->click();\n break;\n case ControllerAction::YellowColor:\n yellowButton->click();\n break;\n case ControllerAction::GreenColor:\n greenButton->click();\n break;\n case ControllerAction::BlackColor:\n blackButton->click();\n break;\n case ControllerAction::WhiteColor:\n whiteButton->click();\n break;\n case ControllerAction::CustomColor:\n customColorButton->click();\n break;\n case ControllerAction::ToggleSidebar:\n toggleTabBarButton->click();\n break;\n case ControllerAction::Save:\n saveButton->click();\n break;\n case ControllerAction::StraightLineTool:\n straightLineToggleButton->click();\n break;\n case ControllerAction::RopeTool:\n ropeToolButton->click();\n break;\n case ControllerAction::SetPenTool:\n setPenTool();\n break;\n case ControllerAction::SetMarkerTool:\n setMarkerTool();\n break;\n case ControllerAction::SetEraserTool:\n setEraserTool();\n break;\n case ControllerAction::TogglePdfTextSelection:\n pdfTextSelectButton->click();\n break;\n case ControllerAction::ToggleOutline:\n toggleOutlineButton->click();\n break;\n case ControllerAction::ToggleBookmarks:\n toggleBookmarksButton->click();\n break;\n case ControllerAction::AddBookmark:\n toggleBookmarkButton->click();\n break;\n case ControllerAction::ToggleTouchGestures:\n touchGesturesButton->click();\n break;\n default:\n break;\n }\n}\n void saveKeyboardMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.beginGroup(\"KeyboardMappings\");\n for (auto it = keyboardMappings.begin(); it != keyboardMappings.end(); ++it) {\n settings.setValue(it.key(), it.value());\n }\n settings.endGroup();\n}\n void loadKeyboardMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.beginGroup(\"KeyboardMappings\");\n QStringList keys = settings.allKeys();\n \n // List of IME-related shortcuts that should not be intercepted\n QStringList imeShortcuts = {\n \"Ctrl+Space\", // Primary IME toggle\n \"Ctrl+Shift\", // Language switching\n \"Ctrl+Alt\", // IME functions\n \"Shift+Alt\", // Alternative language switching\n \"Alt+Shift\" // Alternative language switching (reversed)\n };\n \n for (const QString &key : keys) {\n // Skip IME-related shortcuts\n if (imeShortcuts.contains(key)) {\n // Remove from settings if it exists\n settings.remove(key);\n continue;\n }\n \n QString value = settings.value(key).toString();\n keyboardMappings[key] = value;\n keyboardActionMapping[key] = stringToAction(value);\n }\n settings.endGroup();\n \n // Save settings to persist the removal of IME shortcuts\n settings.sync();\n}\n void ensureTabHasUniqueSaveFolder(InkCanvas* canvas) {\n if (!canvas) return;\n\n if (canvasStack->count() == 0) return;\n\n QString currentFolder = canvas->getSaveFolder();\n QString tempFolder = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\";\n\n if (currentFolder.isEmpty() || currentFolder == tempFolder) {\n\n QDir sourceDir(tempFolder);\n QStringList pageFiles = sourceDir.entryList(QStringList() << \"*.png\", QDir::Files);\n\n // No pages to save → skip prompting\n if (pageFiles.isEmpty()) {\n return;\n }\n\n QMessageBox::warning(this, tr(\"Unsaved Notebook\"),\n tr(\"This notebook is still using a temporary session folder.\\nPlease select a permanent folder to avoid data loss.\"));\n\n QString selectedFolder = QFileDialog::getExistingDirectory(this, tr(\"Select Save Folder\"));\n if (selectedFolder.isEmpty()) return;\n\n QDir destDir(selectedFolder);\n if (!destDir.exists()) {\n QDir().mkpath(selectedFolder);\n }\n\n // Copy contents from temp to selected folder\n for (const QString &file : sourceDir.entryList(QDir::Files)) {\n QString srcFilePath = tempFolder + \"/\" + file;\n QString dstFilePath = selectedFolder + \"/\" + file;\n\n // If file already exists at destination, remove it to avoid rename failure\n if (QFile::exists(dstFilePath)) {\n QFile::remove(dstFilePath);\n }\n\n QFile::rename(srcFilePath, dstFilePath); // This moves the file\n }\n\n canvas->setSaveFolder(selectedFolder);\n // updateTabLabel(); // No longer needed here, handled by the close button lambda\n }\n\n return;\n}\n RecentNotebooksManager *recentNotebooksManager;\n int pdfRenderDPI = 192;\n void setupUi() {\n \n // Ensure IME is properly enabled for the application\n QInputMethod *inputMethod = QGuiApplication::inputMethod();\n if (inputMethod) {\n inputMethod->show();\n inputMethod->reset();\n }\n \n // Create theme-aware button style\n bool darkMode = isDarkMode();\n QString buttonStyle = createButtonStyle(darkMode);\n\n\n loadPdfButton = new QPushButton(this);\n clearPdfButton = new QPushButton(this);\n loadPdfButton->setFixedSize(26, 30);\n clearPdfButton->setFixedSize(26, 30);\n QIcon pdfIcon(loadThemedIcon(\"pdf\")); // Path to your icon in resources\n QIcon pdfDeleteIcon(loadThemedIcon(\"pdfdelete\")); // Path to your icon in resources\n loadPdfButton->setIcon(pdfIcon);\n clearPdfButton->setIcon(pdfDeleteIcon);\n loadPdfButton->setStyleSheet(buttonStyle);\n clearPdfButton->setStyleSheet(buttonStyle);\n loadPdfButton->setToolTip(tr(\"Load PDF\"));\n clearPdfButton->setToolTip(tr(\"Clear PDF\"));\n connect(loadPdfButton, &QPushButton::clicked, this, &MainWindow::loadPdf);\n connect(clearPdfButton, &QPushButton::clicked, this, &MainWindow::clearPdf);\n\n pdfTextSelectButton = new QPushButton(this);\n pdfTextSelectButton->setFixedSize(26, 30);\n QIcon pdfTextIcon(loadThemedIcon(\"ibeam\"));\n pdfTextSelectButton->setIcon(pdfTextIcon);\n pdfTextSelectButton->setStyleSheet(buttonStyle);\n pdfTextSelectButton->setToolTip(tr(\"Toggle PDF Text Selection\"));\n connect(pdfTextSelectButton, &QPushButton::clicked, this, [this]() {\n if (!currentCanvas()) return;\n \n bool newMode = !currentCanvas()->isPdfTextSelectionEnabled();\n currentCanvas()->setPdfTextSelectionEnabled(newMode);\n updatePdfTextSelectButtonState();\n updateBookmarkButtonState();\n \n // Clear any existing selection when toggling\n if (!newMode) {\n currentCanvas()->clearPdfTextSelection();\n }\n });\n\n exportNotebookButton = new QPushButton(this);\n exportNotebookButton->setFixedSize(26, 30);\n QIcon exportIcon(loadThemedIcon(\"export\")); // Path to your icon in resources\n exportNotebookButton->setIcon(exportIcon);\n exportNotebookButton->setStyleSheet(buttonStyle);\n exportNotebookButton->setToolTip(tr(\"Export Notebook Into .SNPKG File\"));\n importNotebookButton = new QPushButton(this);\n importNotebookButton->setFixedSize(26, 30);\n QIcon importIcon(loadThemedIcon(\"import\")); // Path to your icon in resources\n importNotebookButton->setIcon(importIcon);\n importNotebookButton->setStyleSheet(buttonStyle);\n importNotebookButton->setToolTip(tr(\"Import Notebook From .SNPKG File\"));\n\n connect(exportNotebookButton, &QPushButton::clicked, this, [=]() {\n QString filename = QFileDialog::getSaveFileName(this, tr(\"Export Notebook\"), \"\", \"SpeedyNote Package (*.snpkg)\");\n if (!filename.isEmpty()) {\n if (!filename.endsWith(\".snpkg\")) filename += \".snpkg\";\n currentCanvas()->exportNotebook(filename);\n }\n });\n \n connect(importNotebookButton, &QPushButton::clicked, this, [=]() {\n QString filename = QFileDialog::getOpenFileName(this, tr(\"Import Notebook\"), \"\", \"SpeedyNote Package (*.snpkg)\");\n if (!filename.isEmpty()) {\n currentCanvas()->importNotebook(filename);\n }\n });\n\n benchmarkButton = new QPushButton(this);\n QIcon benchmarkIcon(loadThemedIcon(\"benchmark\")); // Path to your icon in resources\n benchmarkButton->setIcon(benchmarkIcon);\n benchmarkButton->setFixedSize(26, 30); // Make the benchmark button smaller\n benchmarkButton->setStyleSheet(buttonStyle);\n benchmarkButton->setToolTip(tr(\"Toggle Benchmark\"));\n benchmarkLabel = new QLabel(\"PR:N/A\", this);\n benchmarkLabel->setFixedHeight(30); // Make the benchmark bar smaller\n\n toggleTabBarButton = new QPushButton(this);\n toggleTabBarButton->setIcon(loadThemedIcon(\"tabs\")); // You can design separate icons for \"show\" and \"hide\"\n toggleTabBarButton->setToolTip(tr(\"Show/Hide Tab Bar\"));\n toggleTabBarButton->setFixedSize(26, 30);\n toggleTabBarButton->setStyleSheet(buttonStyle);\n toggleTabBarButton->setProperty(\"selected\", true); // Initially visible\n \n // PDF Outline Toggle Button\n toggleOutlineButton = new QPushButton(this);\n toggleOutlineButton->setIcon(loadThemedIcon(\"outline\")); // Icon to be added later\n toggleOutlineButton->setToolTip(tr(\"Show/Hide PDF Outline\"));\n toggleOutlineButton->setFixedSize(26, 30);\n toggleOutlineButton->setStyleSheet(buttonStyle);\n toggleOutlineButton->setProperty(\"selected\", false); // Initially hidden\n \n // Bookmarks Toggle Button\n toggleBookmarksButton = new QPushButton(this);\n toggleBookmarksButton->setIcon(loadThemedIcon(\"bookmark\")); // Using bookpage icon for bookmarks\n toggleBookmarksButton->setToolTip(tr(\"Show/Hide Bookmarks\"));\n toggleBookmarksButton->setFixedSize(26, 30);\n toggleBookmarksButton->setStyleSheet(buttonStyle);\n toggleBookmarksButton->setProperty(\"selected\", false); // Initially hidden\n \n // Add/Remove Bookmark Toggle Button\n toggleBookmarkButton = new QPushButton(this);\n toggleBookmarkButton->setIcon(loadThemedIcon(\"star\"));\n toggleBookmarkButton->setToolTip(tr(\"Add/Remove Bookmark\"));\n toggleBookmarkButton->setFixedSize(26, 30);\n toggleBookmarkButton->setStyleSheet(buttonStyle);\n toggleBookmarkButton->setProperty(\"selected\", false); // For toggle state styling\n\n // Touch Gestures Toggle Button\n touchGesturesButton = new QPushButton(this);\n touchGesturesButton->setIcon(loadThemedIcon(\"hand\")); // Using hand icon for touch/gesture\n touchGesturesButton->setToolTip(tr(\"Toggle Touch Gestures\"));\n touchGesturesButton->setFixedSize(26, 30);\n touchGesturesButton->setStyleSheet(buttonStyle);\n touchGesturesButton->setProperty(\"selected\", touchGesturesEnabled); // For toggle state styling\n\n selectFolderButton = new QPushButton(this);\n selectFolderButton->setFixedSize(26, 30);\n QIcon folderIcon(loadThemedIcon(\"folder\")); // Path to your icon in resources\n selectFolderButton->setIcon(folderIcon);\n selectFolderButton->setStyleSheet(buttonStyle);\n selectFolderButton->setToolTip(tr(\"Select Save Folder\"));\n connect(selectFolderButton, &QPushButton::clicked, this, &MainWindow::selectFolder);\n \n \n saveButton = new QPushButton(this);\n saveButton->setFixedSize(26, 30);\n QIcon saveIcon(loadThemedIcon(\"save\")); // Path to your icon in resources\n saveButton->setIcon(saveIcon);\n saveButton->setStyleSheet(buttonStyle);\n saveButton->setToolTip(tr(\"Save Current Page\"));\n connect(saveButton, &QPushButton::clicked, this, &MainWindow::saveCurrentPage);\n \n saveAnnotatedButton = new QPushButton(this);\n saveAnnotatedButton->setFixedSize(26, 30);\n QIcon saveAnnotatedIcon(loadThemedIcon(\"saveannotated\")); // Path to your icon in resources\n saveAnnotatedButton->setIcon(saveAnnotatedIcon);\n saveAnnotatedButton->setStyleSheet(buttonStyle);\n saveAnnotatedButton->setToolTip(tr(\"Save Page with Background\"));\n connect(saveAnnotatedButton, &QPushButton::clicked, this, &MainWindow::saveAnnotated);\n\n fullscreenButton = new QPushButton(this);\n fullscreenButton->setIcon(loadThemedIcon(\"fullscreen\")); // Load from resources\n fullscreenButton->setFixedSize(26, 30);\n fullscreenButton->setToolTip(tr(\"Toggle Fullscreen\"));\n fullscreenButton->setStyleSheet(buttonStyle);\n\n // ✅ Connect button click to toggleFullscreen() function\n connect(fullscreenButton, &QPushButton::clicked, this, &MainWindow::toggleFullscreen);\n\n // Use the darkMode variable already declared at the beginning of setupUi()\n\n redButton = new QPushButton(this);\n redButton->setFixedSize(18, 30); // Half width\n QString redIconPath = darkMode ? \":/resources/icons/pen_light_red.png\" : \":/resources/icons/pen_dark_red.png\";\n QIcon redIcon(redIconPath);\n redButton->setIcon(redIcon);\n redButton->setStyleSheet(buttonStyle);\n connect(redButton, &QPushButton::clicked, [this]() { \n handleColorButtonClick();\n currentCanvas()->setPenColor(getPaletteColor(\"red\")); \n updateDialDisplay(); \n updateColorButtonStates();\n });\n \n blueButton = new QPushButton(this);\n blueButton->setFixedSize(18, 30); // Half width\n QString blueIconPath = darkMode ? \":/resources/icons/pen_light_blue.png\" : \":/resources/icons/pen_dark_blue.png\";\n QIcon blueIcon(blueIconPath);\n blueButton->setIcon(blueIcon);\n blueButton->setStyleSheet(buttonStyle);\n connect(blueButton, &QPushButton::clicked, [this]() { \n handleColorButtonClick();\n currentCanvas()->setPenColor(getPaletteColor(\"blue\")); \n updateDialDisplay(); \n updateColorButtonStates();\n });\n\n yellowButton = new QPushButton(this);\n yellowButton->setFixedSize(18, 30); // Half width\n QString yellowIconPath = darkMode ? \":/resources/icons/pen_light_yellow.png\" : \":/resources/icons/pen_dark_yellow.png\";\n QIcon yellowIcon(yellowIconPath);\n yellowButton->setIcon(yellowIcon);\n yellowButton->setStyleSheet(buttonStyle);\n connect(yellowButton, &QPushButton::clicked, [this]() { \n handleColorButtonClick();\n currentCanvas()->setPenColor(getPaletteColor(\"yellow\")); \n updateDialDisplay(); \n updateColorButtonStates();\n });\n\n greenButton = new QPushButton(this);\n greenButton->setFixedSize(18, 30); // Half width\n QString greenIconPath = darkMode ? \":/resources/icons/pen_light_green.png\" : \":/resources/icons/pen_dark_green.png\";\n QIcon greenIcon(greenIconPath);\n greenButton->setIcon(greenIcon);\n greenButton->setStyleSheet(buttonStyle);\n connect(greenButton, &QPushButton::clicked, [this]() { \n handleColorButtonClick();\n currentCanvas()->setPenColor(getPaletteColor(\"green\")); \n updateDialDisplay(); \n updateColorButtonStates();\n });\n\n blackButton = new QPushButton(this);\n blackButton->setFixedSize(18, 30); // Half width\n QString blackIconPath = darkMode ? \":/resources/icons/pen_light_black.png\" : \":/resources/icons/pen_dark_black.png\";\n QIcon blackIcon(blackIconPath);\n blackButton->setIcon(blackIcon);\n blackButton->setStyleSheet(buttonStyle);\n connect(blackButton, &QPushButton::clicked, [this]() { \n handleColorButtonClick();\n currentCanvas()->setPenColor(QColor(\"#000000\")); \n updateDialDisplay(); \n updateColorButtonStates();\n });\n\n whiteButton = new QPushButton(this);\n whiteButton->setFixedSize(18, 30); // Half width\n QString whiteIconPath = darkMode ? \":/resources/icons/pen_light_white.png\" : \":/resources/icons/pen_dark_white.png\";\n QIcon whiteIcon(whiteIconPath);\n whiteButton->setIcon(whiteIcon);\n whiteButton->setStyleSheet(buttonStyle);\n connect(whiteButton, &QPushButton::clicked, [this]() { \n handleColorButtonClick();\n currentCanvas()->setPenColor(QColor(\"#FFFFFF\")); \n updateDialDisplay(); \n updateColorButtonStates();\n });\n \n customColorInput = new QLineEdit(this);\n customColorInput->setPlaceholderText(\"Custom HEX\");\n customColorInput->setFixedSize(85, 30);\n \n // Enable IME support for multi-language input\n customColorInput->setAttribute(Qt::WA_InputMethodEnabled, true);\n customColorInput->setInputMethodHints(Qt::ImhNone); // Allow all input methods\n customColorInput->installEventFilter(this); // Install event filter for IME handling\n \n connect(customColorInput, &QLineEdit::returnPressed, this, &MainWindow::applyCustomColor);\n\n \n thicknessButton = new QPushButton(this);\n thicknessButton->setIcon(loadThemedIcon(\"thickness\"));\n thicknessButton->setFixedSize(26, 30);\n thicknessButton->setStyleSheet(buttonStyle);\n connect(thicknessButton, &QPushButton::clicked, this, &MainWindow::toggleThicknessSlider);\n\n thicknessFrame = new QFrame(this);\n thicknessFrame->setFrameShape(QFrame::StyledPanel);\n thicknessFrame->setStyleSheet(R\"(\n background-color: black;\n border: 1px solid black;\n padding: 5px;\n )\");\n thicknessFrame->setVisible(false);\n thicknessFrame->setFixedSize(220, 40); // Adjust width/height as needed\n\n thicknessSlider = new QSlider(Qt::Horizontal, this);\n thicknessSlider->setRange(1, 50);\n thicknessSlider->setValue(5);\n thicknessSlider->setMaximumWidth(200);\n\n\n connect(thicknessSlider, &QSlider::valueChanged, this, &MainWindow::updateThickness);\n\n QVBoxLayout *popupLayoutThickness = new QVBoxLayout();\n popupLayoutThickness->setContentsMargins(10, 5, 10, 5);\n popupLayoutThickness->addWidget(thicknessSlider);\n thicknessFrame->setLayout(popupLayoutThickness);\n\n\n toolSelector = new QComboBox(this);\n toolSelector->addItem(loadThemedIcon(\"pen\"), \"\");\n toolSelector->addItem(loadThemedIcon(\"marker\"), \"\");\n toolSelector->addItem(loadThemedIcon(\"eraser\"), \"\");\n toolSelector->setFixedWidth(43);\n toolSelector->setFixedHeight(30);\n connect(toolSelector, QOverload::of(&QComboBox::currentIndexChanged), this, &MainWindow::changeTool);\n\n // ✅ Individual tool buttons\n penToolButton = new QPushButton(this);\n penToolButton->setFixedSize(26, 30);\n penToolButton->setIcon(loadThemedIcon(\"pen\"));\n penToolButton->setStyleSheet(buttonStyle);\n penToolButton->setToolTip(tr(\"Pen Tool\"));\n connect(penToolButton, &QPushButton::clicked, this, &MainWindow::setPenTool);\n\n markerToolButton = new QPushButton(this);\n markerToolButton->setFixedSize(26, 30);\n markerToolButton->setIcon(loadThemedIcon(\"marker\"));\n markerToolButton->setStyleSheet(buttonStyle);\n markerToolButton->setToolTip(tr(\"Marker Tool\"));\n connect(markerToolButton, &QPushButton::clicked, this, &MainWindow::setMarkerTool);\n\n eraserToolButton = new QPushButton(this);\n eraserToolButton->setFixedSize(26, 30);\n eraserToolButton->setIcon(loadThemedIcon(\"eraser\"));\n eraserToolButton->setStyleSheet(buttonStyle);\n eraserToolButton->setToolTip(tr(\"Eraser Tool\"));\n connect(eraserToolButton, &QPushButton::clicked, this, &MainWindow::setEraserTool);\n\n backgroundButton = new QPushButton(this);\n backgroundButton->setFixedSize(26, 30);\n QIcon bgIcon(loadThemedIcon(\"background\")); // Path to your icon in resources\n backgroundButton->setIcon(bgIcon);\n backgroundButton->setStyleSheet(buttonStyle);\n backgroundButton->setToolTip(tr(\"Set Background Pic\"));\n connect(backgroundButton, &QPushButton::clicked, this, &MainWindow::selectBackground);\n\n // Initialize straight line toggle button\n straightLineToggleButton = new QPushButton(this);\n straightLineToggleButton->setFixedSize(26, 30);\n QIcon straightLineIcon(loadThemedIcon(\"straightLine\")); // Make sure this icon exists or use a different one\n straightLineToggleButton->setIcon(straightLineIcon);\n straightLineToggleButton->setStyleSheet(buttonStyle);\n straightLineToggleButton->setToolTip(tr(\"Toggle Straight Line Mode\"));\n connect(straightLineToggleButton, &QPushButton::clicked, this, [this]() {\n if (!currentCanvas()) return;\n \n // If we're turning on straight line mode, first disable rope tool\n if (!currentCanvas()->isStraightLineMode()) {\n currentCanvas()->setRopeToolMode(false);\n updateRopeToolButtonState();\n }\n \n bool newMode = !currentCanvas()->isStraightLineMode();\n currentCanvas()->setStraightLineMode(newMode);\n updateStraightLineButtonState();\n });\n \n ropeToolButton = new QPushButton(this);\n ropeToolButton->setFixedSize(26, 30);\n QIcon ropeToolIcon(loadThemedIcon(\"rope\")); // Make sure this icon exists\n ropeToolButton->setIcon(ropeToolIcon);\n ropeToolButton->setStyleSheet(buttonStyle);\n ropeToolButton->setToolTip(tr(\"Toggle Rope Tool Mode\"));\n connect(ropeToolButton, &QPushButton::clicked, this, [this]() {\n if (!currentCanvas()) return;\n \n // If we're turning on rope tool mode, first disable straight line\n if (!currentCanvas()->isRopeToolMode()) {\n currentCanvas()->setStraightLineMode(false);\n updateStraightLineButtonState();\n }\n \n bool newMode = !currentCanvas()->isRopeToolMode();\n currentCanvas()->setRopeToolMode(newMode);\n updateRopeToolButtonState();\n });\n \n markdownButton = new QPushButton(this);\n markdownButton->setFixedSize(26, 30);\n QIcon markdownIcon(loadThemedIcon(\"markdown\")); // Using text icon for markdown\n markdownButton->setIcon(markdownIcon);\n markdownButton->setStyleSheet(buttonStyle);\n markdownButton->setToolTip(tr(\"Add Markdown Window\"));\n connect(markdownButton, &QPushButton::clicked, this, [this]() {\n if (!currentCanvas()) return;\n \n // Toggle markdown selection mode\n bool newMode = !currentCanvas()->isMarkdownSelectionMode();\n currentCanvas()->setMarkdownSelectionMode(newMode);\n updateMarkdownButtonState();\n });\n \n deletePageButton = new QPushButton(this);\n deletePageButton->setFixedSize(26, 30);\n QIcon trashIcon(loadThemedIcon(\"trash\")); // Path to your icon in resources\n deletePageButton->setIcon(trashIcon);\n deletePageButton->setStyleSheet(buttonStyle);\n deletePageButton->setToolTip(tr(\"Delete Current Page\"));\n connect(deletePageButton, &QPushButton::clicked, this, &MainWindow::deleteCurrentPage);\n\n zoomButton = new QPushButton(this);\n zoomButton->setIcon(loadThemedIcon(\"zoom\"));\n zoomButton->setFixedSize(26, 30);\n zoomButton->setStyleSheet(buttonStyle);\n connect(zoomButton, &QPushButton::clicked, this, &MainWindow::toggleZoomSlider);\n\n // ✅ Create the floating frame (Initially Hidden)\n zoomFrame = new QFrame(this);\n zoomFrame->setFrameShape(QFrame::StyledPanel);\n zoomFrame->setStyleSheet(R\"(\n background-color: black;\n border: 1px solid black;\n padding: 5px;\n )\");\n zoomFrame->setVisible(false);\n zoomFrame->setFixedSize(440, 40); // Adjust width/height as needed\n\n zoomSlider = new QSlider(Qt::Horizontal, this);\n zoomSlider->setRange(10, 400);\n zoomSlider->setValue(100);\n zoomSlider->setMaximumWidth(405);\n\n connect(zoomSlider, &QSlider::valueChanged, this, &MainWindow::onZoomSliderChanged);\n\n QVBoxLayout *popupLayout = new QVBoxLayout();\n popupLayout->setContentsMargins(10, 5, 10, 5);\n popupLayout->addWidget(zoomSlider);\n zoomFrame->setLayout(popupLayout);\n \n\n zoom50Button = new QPushButton(\"0.5x\", this);\n zoom50Button->setFixedSize(35, 30);\n zoom50Button->setStyleSheet(buttonStyle);\n zoom50Button->setToolTip(tr(\"Set Zoom to 50%\"));\n connect(zoom50Button, &QPushButton::clicked, [this]() { zoomSlider->setValue(50 / initialDpr); updateDialDisplay(); });\n\n dezoomButton = new QPushButton(\"1x\", this);\n dezoomButton->setFixedSize(26, 30);\n dezoomButton->setStyleSheet(buttonStyle);\n dezoomButton->setToolTip(tr(\"Set Zoom to 100%\"));\n connect(dezoomButton, &QPushButton::clicked, [this]() { zoomSlider->setValue(100 / initialDpr); updateDialDisplay(); });\n\n zoom200Button = new QPushButton(\"2x\", this);\n zoom200Button->setFixedSize(31, 30);\n zoom200Button->setStyleSheet(buttonStyle);\n zoom200Button->setToolTip(tr(\"Set Zoom to 200%\"));\n connect(zoom200Button, &QPushButton::clicked, [this]() { zoomSlider->setValue(200 / initialDpr); updateDialDisplay(); });\n\n panXSlider = new QScrollBar(Qt::Horizontal, this);\n panYSlider = new QScrollBar(Qt::Vertical, this);\n panYSlider->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);\n \n // Set scrollbar styling\n QString scrollBarStyle = R\"(\n QScrollBar {\n background: rgba(200, 200, 200, 80);\n border: none;\n margin: 0px;\n }\n QScrollBar:hover {\n background: rgba(200, 200, 200, 120);\n }\n QScrollBar:horizontal {\n height: 16px !important; /* Force narrow height */\n max-height: 16px !important;\n }\n QScrollBar:vertical {\n width: 16px !important; /* Force narrow width */\n max-width: 16px !important;\n }\n QScrollBar::handle {\n background: rgba(100, 100, 100, 150);\n border-radius: 2px;\n min-height: 120px; /* Longer handle for vertical scrollbar */\n min-width: 120px; /* Longer handle for horizontal scrollbar */\n }\n QScrollBar::handle:hover {\n background: rgba(80, 80, 80, 210);\n }\n /* Hide scroll buttons */\n QScrollBar::add-line, \n QScrollBar::sub-line {\n width: 0px;\n height: 0px;\n background: none;\n border: none;\n }\n /* Disable scroll page buttons */\n QScrollBar::add-page, \n QScrollBar::sub-page {\n background: transparent;\n }\n )\";\n \n panXSlider->setStyleSheet(scrollBarStyle);\n panYSlider->setStyleSheet(scrollBarStyle);\n \n // Force fixed dimensions programmatically\n panXSlider->setFixedHeight(16);\n panYSlider->setFixedWidth(16);\n \n // Set up auto-hiding\n panXSlider->setMouseTracking(true);\n panYSlider->setMouseTracking(true);\n panXSlider->installEventFilter(this);\n panYSlider->installEventFilter(this);\n panXSlider->setVisible(false);\n panYSlider->setVisible(false);\n \n // Create timer for auto-hiding\n scrollbarHideTimer = new QTimer(this);\n scrollbarHideTimer->setSingleShot(true);\n scrollbarHideTimer->setInterval(200); // Hide after 0.2 seconds\n connect(scrollbarHideTimer, &QTimer::timeout, this, [this]() {\n panXSlider->setVisible(false);\n panYSlider->setVisible(false);\n scrollbarsVisible = false;\n });\n \n // panXSlider->setFixedHeight(30);\n // panYSlider->setFixedWidth(30);\n\n connect(panXSlider, &QScrollBar::valueChanged, this, &MainWindow::updatePanX);\n \n connect(panYSlider, &QScrollBar::valueChanged, this, &MainWindow::updatePanY);\n\n\n\n\n // 🌟 PDF Outline Sidebar\n outlineSidebar = new QWidget(this);\n outlineSidebar->setFixedWidth(250);\n outlineSidebar->setVisible(false); // Hidden by default\n \n QVBoxLayout *outlineLayout = new QVBoxLayout(outlineSidebar);\n outlineLayout->setContentsMargins(5, 5, 5, 5);\n \n QLabel *outlineLabel = new QLabel(tr(\"PDF Outline\"), outlineSidebar);\n outlineLabel->setStyleSheet(\"font-weight: bold; padding: 5px;\");\n outlineLayout->addWidget(outlineLabel);\n \n outlineTree = new QTreeWidget(outlineSidebar);\n outlineTree->setHeaderHidden(true);\n outlineTree->setRootIsDecorated(true);\n outlineTree->setIndentation(15);\n outlineLayout->addWidget(outlineTree);\n \n // Connect outline tree item clicks\n connect(outlineTree, &QTreeWidget::itemClicked, this, &MainWindow::onOutlineItemClicked);\n \n // 🌟 Bookmarks Sidebar\n bookmarksSidebar = new QWidget(this);\n bookmarksSidebar->setFixedWidth(250);\n bookmarksSidebar->setVisible(false); // Hidden by default\n \n QVBoxLayout *bookmarksLayout = new QVBoxLayout(bookmarksSidebar);\n bookmarksLayout->setContentsMargins(5, 5, 5, 5);\n \n QLabel *bookmarksLabel = new QLabel(tr(\"Bookmarks\"), bookmarksSidebar);\n bookmarksLabel->setStyleSheet(\"font-weight: bold; padding: 5px;\");\n bookmarksLayout->addWidget(bookmarksLabel);\n \n bookmarksTree = new QTreeWidget(bookmarksSidebar);\n bookmarksTree->setHeaderHidden(true);\n bookmarksTree->setRootIsDecorated(false);\n bookmarksTree->setIndentation(0);\n bookmarksLayout->addWidget(bookmarksTree);\n \n // Connect bookmarks tree item clicks\n connect(bookmarksTree, &QTreeWidget::itemClicked, this, &MainWindow::onBookmarkItemClicked);\n\n // 🌟 Horizontal Tab Bar (like modern web browsers)\n tabList = new QListWidget(this);\n tabList->setFlow(QListView::LeftToRight); // Make it horizontal\n tabList->setFixedHeight(32); // Increased to accommodate scrollbar below tabs\n tabList->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);\n tabList->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n tabList->setSelectionMode(QAbstractItemView::SingleSelection);\n\n // Style the tab bar like a modern browser with transparent scrollbar\n tabList->setStyleSheet(R\"(\n QListWidget {\n background-color: rgba(240, 240, 240, 255);\n border: none;\n border-bottom: 1px solid rgba(200, 200, 200, 255);\n outline: none;\n }\n QListWidget::item {\n background-color: rgba(220, 220, 220, 255);\n border: 1px solid rgba(180, 180, 180, 255);\n border-bottom: none;\n margin-right: 1px;\n margin-top: 2px;\n padding: 0px;\n min-width: 80px;\n max-width: 120px;\n }\n QListWidget::item:selected {\n background-color: white;\n border: 1px solid rgba(180, 180, 180, 255);\n border-bottom: 1px solid white;\n margin-top: 1px;\n }\n QListWidget::item:hover:!selected {\n background-color: rgba(230, 230, 230, 255);\n }\n QScrollBar:horizontal {\n background: rgba(240, 240, 240, 255);\n height: 8px;\n border: none;\n margin: 0px;\n border-top: 1px solid rgba(200, 200, 200, 255);\n }\n QScrollBar::handle:horizontal {\n background: rgba(150, 150, 150, 120);\n border-radius: 4px;\n min-width: 20px;\n margin: 1px;\n }\n QScrollBar::handle:horizontal:hover {\n background: rgba(120, 120, 120, 200);\n }\n QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal {\n width: 0px;\n height: 0px;\n background: none;\n border: none;\n }\n QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {\n background: transparent;\n }\n )\");\n\n // 🌟 Add Button for New Tab (styled like browser + button)\n addTabButton = new QPushButton(this);\n QIcon addTab(loadThemedIcon(\"addtab\")); // Path to your icon in resources\n addTabButton->setIcon(addTab);\n addTabButton->setFixedSize(30, 30); // Even smaller to match thinner layout\n addTabButton->setStyleSheet(R\"(\n QPushButton {\n background-color: rgba(220, 220, 220, 255);\n border: 1px solid rgba(180, 180, 180, 255);\n border-radius: 15px;\n margin: 2px;\n }\n QPushButton:hover {\n background-color: rgba(200, 200, 200, 255);\n }\n QPushButton:pressed {\n background-color: rgba(180, 180, 180, 255);\n }\n )\");\n addTabButton->setToolTip(tr(\"Add New Tab\"));\n connect(addTabButton, &QPushButton::clicked, this, &MainWindow::addNewTab);\n\n if (!canvasStack) {\n canvasStack = new QStackedWidget(this);\n }\n\n connect(tabList, &QListWidget::currentRowChanged, this, &MainWindow::switchTab);\n\n // Create horizontal tab container\n tabBarContainer = new QWidget(this);\n tabBarContainer->setObjectName(\"tabBarContainer\");\n tabBarContainer->setFixedHeight(38); // Increased to accommodate scrollbar below tabs\n \n QHBoxLayout *tabBarLayout = new QHBoxLayout(tabBarContainer);\n tabBarLayout->setContentsMargins(5, 5, 5, 5);\n tabBarLayout->setSpacing(5);\n tabBarLayout->addWidget(tabList, 1); // Tab list takes most space\n tabBarLayout->addWidget(addTabButton, 0); // Add button stays at the end\n\n connect(toggleTabBarButton, &QPushButton::clicked, this, [=]() {\n bool isVisible = tabBarContainer->isVisible();\n tabBarContainer->setVisible(!isVisible);\n \n // Update button toggle state\n toggleTabBarButton->setProperty(\"selected\", !isVisible);\n toggleTabBarButton->style()->unpolish(toggleTabBarButton);\n toggleTabBarButton->style()->polish(toggleTabBarButton);\n\n QTimer::singleShot(0, this, [this]() {\n if (auto *canvas = currentCanvas()) {\n canvas->setMaximumSize(canvas->getCanvasSize());\n }\n });\n });\n \n connect(toggleOutlineButton, &QPushButton::clicked, this, &MainWindow::toggleOutlineSidebar);\n connect(toggleBookmarksButton, &QPushButton::clicked, this, &MainWindow::toggleBookmarksSidebar);\n connect(toggleBookmarkButton, &QPushButton::clicked, this, &MainWindow::toggleCurrentPageBookmark);\n connect(touchGesturesButton, &QPushButton::clicked, this, [this]() {\n setTouchGesturesEnabled(!touchGesturesEnabled);\n touchGesturesButton->setProperty(\"selected\", touchGesturesEnabled);\n touchGesturesButton->style()->unpolish(touchGesturesButton);\n touchGesturesButton->style()->polish(touchGesturesButton);\n });\n\n \n\n\n // Previous page button\n prevPageButton = new QPushButton(this);\n prevPageButton->setFixedSize(26, 30);\n prevPageButton->setText(\"◀\");\n prevPageButton->setStyleSheet(buttonStyle);\n prevPageButton->setToolTip(tr(\"Previous Page\"));\n connect(prevPageButton, &QPushButton::clicked, this, &MainWindow::goToPreviousPage);\n\n pageInput = new QSpinBox(this);\n pageInput->setFixedSize(42, 30);\n pageInput->setMinimum(1);\n pageInput->setMaximum(9999);\n pageInput->setValue(1);\n pageInput->setMaximumWidth(100);\n connect(pageInput, QOverload::of(&QSpinBox::valueChanged), this, &MainWindow::onPageInputChanged);\n\n // Next page button\n nextPageButton = new QPushButton(this);\n nextPageButton->setFixedSize(26, 30);\n nextPageButton->setText(\"▶\");\n nextPageButton->setStyleSheet(buttonStyle);\n nextPageButton->setToolTip(tr(\"Next Page\"));\n connect(nextPageButton, &QPushButton::clicked, this, &MainWindow::goToNextPage);\n\n jumpToPageButton = new QPushButton(this);\n // QIcon jumpIcon(\":/resources/icons/bookpage.png\"); // Path to your icon in resources\n jumpToPageButton->setFixedSize(26, 30);\n jumpToPageButton->setStyleSheet(buttonStyle);\n jumpToPageButton->setIcon(loadThemedIcon(\"bookpage\"));\n connect(jumpToPageButton, &QPushButton::clicked, this, &MainWindow::showJumpToPageDialog);\n\n // ✅ Dial Toggle Button\n dialToggleButton = new QPushButton(this);\n dialToggleButton->setIcon(loadThemedIcon(\"dial\")); // Icon for dial\n dialToggleButton->setFixedSize(26, 30);\n dialToggleButton->setToolTip(tr(\"Toggle Magic Dial\"));\n dialToggleButton->setStyleSheet(buttonStyle);\n\n // ✅ Connect to toggle function\n connect(dialToggleButton, &QPushButton::clicked, this, &MainWindow::toggleDial);\n\n // toggleDial();\n\n \n\n fastForwardButton = new QPushButton(this);\n fastForwardButton->setFixedSize(26, 30);\n // QIcon ffIcon(\":/resources/icons/fastforward.png\"); // Path to your icon in resources\n fastForwardButton->setIcon(loadThemedIcon(\"fastforward\"));\n fastForwardButton->setToolTip(tr(\"Toggle Fast Forward 8x\"));\n fastForwardButton->setStyleSheet(buttonStyle);\n\n // ✅ Toggle fast-forward mode\n connect(fastForwardButton, &QPushButton::clicked, [this]() {\n fastForwardMode = !fastForwardMode;\n updateFastForwardButtonState();\n });\n\n QComboBox *dialModeSelector = new QComboBox(this);\n dialModeSelector->addItem(\"Page Switch\", PageSwitching);\n dialModeSelector->addItem(\"Zoom\", ZoomControl);\n dialModeSelector->addItem(\"Thickness\", ThicknessControl);\n\n dialModeSelector->addItem(\"Tool Switch\", ToolSwitching);\n dialModeSelector->setFixedWidth(120);\n\n connect(dialModeSelector, QOverload::of(&QComboBox::currentIndexChanged), this,\n [this](int index) { changeDialMode(static_cast(index)); });\n\n\n\n colorPreview = new QPushButton(this);\n colorPreview->setFixedSize(26, 30);\n colorPreview->setStyleSheet(\"border-radius: 15px; border: 1px solid gray;\");\n colorPreview->setEnabled(false); // ✅ Prevents it from being clicked\n\n btnPageSwitch = new QPushButton(loadThemedIcon(\"bookpage\"), \"\", this);\n btnPageSwitch->setStyleSheet(buttonStyle);\n btnPageSwitch->setFixedSize(26, 30);\n btnPageSwitch->setToolTip(tr(\"Set Dial Mode to Page Switching\"));\n btnZoom = new QPushButton(loadThemedIcon(\"zoom\"), \"\", this);\n btnZoom->setStyleSheet(buttonStyle);\n btnZoom->setFixedSize(26, 30);\n btnZoom->setToolTip(tr(\"Set Dial Mode to Zoom Ctrl\"));\n btnThickness = new QPushButton(loadThemedIcon(\"thickness\"), \"\", this);\n btnThickness->setStyleSheet(buttonStyle);\n btnThickness->setFixedSize(26, 30);\n btnThickness->setToolTip(tr(\"Set Dial Mode to Pen Tip Thickness Ctrl\"));\n\n btnTool = new QPushButton(loadThemedIcon(\"pen\"), \"\", this);\n btnTool->setStyleSheet(buttonStyle);\n btnTool->setFixedSize(26, 30);\n btnTool->setToolTip(tr(\"Set Dial Mode to Tool Switching\"));\n btnPresets = new QPushButton(loadThemedIcon(\"preset\"), \"\", this);\n btnPresets->setStyleSheet(buttonStyle);\n btnPresets->setFixedSize(26, 30);\n btnPresets->setToolTip(tr(\"Set Dial Mode to Color Preset Selection\"));\n btnPannScroll = new QPushButton(loadThemedIcon(\"scroll\"), \"\", this);\n btnPannScroll->setStyleSheet(buttonStyle);\n btnPannScroll->setFixedSize(26, 30);\n btnPannScroll->setToolTip(tr(\"Slide and turn pages with the dial\"));\n\n connect(btnPageSwitch, &QPushButton::clicked, this, [this]() { changeDialMode(PageSwitching); });\n connect(btnZoom, &QPushButton::clicked, this, [this]() { changeDialMode(ZoomControl); });\n connect(btnThickness, &QPushButton::clicked, this, [this]() { changeDialMode(ThicknessControl); });\n\n connect(btnTool, &QPushButton::clicked, this, [this]() { changeDialMode(ToolSwitching); });\n connect(btnPresets, &QPushButton::clicked, this, [this]() { changeDialMode(PresetSelection); }); \n connect(btnPannScroll, &QPushButton::clicked, this, [this]() { changeDialMode(PanAndPageScroll); });\n\n\n // ✅ Initialize color presets based on palette mode (will be updated after UI setup)\n colorPresets.enqueue(getDefaultPenColor());\n colorPresets.enqueue(QColor(\"#AA0000\")); // Temporary - will be updated later\n colorPresets.enqueue(QColor(\"#997700\"));\n colorPresets.enqueue(QColor(\"#0000AA\"));\n colorPresets.enqueue(QColor(\"#007700\"));\n colorPresets.enqueue(QColor(\"#000000\"));\n colorPresets.enqueue(QColor(\"#FFFFFF\"));\n\n // ✅ Button to add current color to presets\n addPresetButton = new QPushButton(loadThemedIcon(\"savepreset\"), \"\", this);\n addPresetButton->setStyleSheet(buttonStyle);\n addPresetButton->setToolTip(tr(\"Add Current Color to Presets\"));\n addPresetButton->setFixedSize(26, 30);\n connect(addPresetButton, &QPushButton::clicked, this, &MainWindow::addColorPreset);\n\n\n\n\n openControlPanelButton = new QPushButton(this);\n openControlPanelButton->setIcon(loadThemedIcon(\"settings\")); // Replace with your actual settings icon\n openControlPanelButton->setStyleSheet(buttonStyle);\n openControlPanelButton->setToolTip(tr(\"Open Control Panel\"));\n openControlPanelButton->setFixedSize(26, 30); // Adjust to match your other buttons\n\n connect(openControlPanelButton, &QPushButton::clicked, this, [=]() {\n InkCanvas *canvas = currentCanvas();\n if (canvas) {\n ControlPanelDialog dialog(this, canvas, this);\n dialog.exec(); // Modal\n }\n });\n\n openRecentNotebooksButton = new QPushButton(this); // Create button\n openRecentNotebooksButton->setIcon(loadThemedIcon(\"recent\")); // Replace with actual icon if available\n openRecentNotebooksButton->setStyleSheet(buttonStyle);\n openRecentNotebooksButton->setToolTip(tr(\"Open Recent Notebooks\"));\n openRecentNotebooksButton->setFixedSize(26, 30);\n connect(openRecentNotebooksButton, &QPushButton::clicked, this, &MainWindow::openRecentNotebooksDialog);\n\n customColorButton = new QPushButton(this);\n customColorButton->setFixedSize(62, 30);\n QColor initialColor = getDefaultPenColor(); // Theme-aware default color\n customColorButton->setText(initialColor.name().toUpper());\n\n if (currentCanvas()) {\n initialColor = currentCanvas()->getPenColor();\n }\n\n updateCustomColorButtonStyle(initialColor);\n\n QTimer::singleShot(0, this, [=]() {\n connect(customColorButton, &QPushButton::clicked, this, [=]() {\n if (!currentCanvas()) return;\n \n handleColorButtonClick();\n \n // Get the current custom color from the button text\n QString buttonText = customColorButton->text();\n QColor customColor(buttonText);\n \n // Check if the custom color is already the current pen color\n if (currentCanvas()->getPenColor() == customColor) {\n // Second click - show color picker dialog\n QColor chosen = QColorDialog::getColor(currentCanvas()->getPenColor(), this, \"Select Pen Color\");\n if (chosen.isValid()) {\n currentCanvas()->setPenColor(chosen);\n updateCustomColorButtonStyle(chosen);\n updateDialDisplay();\n updateColorButtonStates();\n }\n } else {\n // First click - apply the custom color\n currentCanvas()->setPenColor(customColor);\n updateDialDisplay();\n updateColorButtonStates();\n }\n });\n });\n\n QHBoxLayout *controlLayout = new QHBoxLayout;\n \n controlLayout->addWidget(toggleOutlineButton);\n controlLayout->addWidget(toggleBookmarksButton);\n controlLayout->addWidget(toggleBookmarkButton);\n controlLayout->addWidget(touchGesturesButton);\n controlLayout->addWidget(toggleTabBarButton);\n controlLayout->addWidget(selectFolderButton);\n\n controlLayout->addWidget(exportNotebookButton);\n controlLayout->addWidget(importNotebookButton);\n controlLayout->addWidget(loadPdfButton);\n controlLayout->addWidget(clearPdfButton);\n controlLayout->addWidget(pdfTextSelectButton);\n controlLayout->addWidget(backgroundButton);\n controlLayout->addWidget(saveButton);\n controlLayout->addWidget(saveAnnotatedButton);\n controlLayout->addWidget(openControlPanelButton);\n controlLayout->addWidget(openRecentNotebooksButton); // Add button to layout\n controlLayout->addWidget(redButton);\n controlLayout->addWidget(blueButton);\n controlLayout->addWidget(yellowButton);\n controlLayout->addWidget(greenButton);\n controlLayout->addWidget(blackButton);\n controlLayout->addWidget(whiteButton);\n controlLayout->addWidget(customColorButton);\n controlLayout->addWidget(straightLineToggleButton);\n controlLayout->addWidget(ropeToolButton); // Add rope tool button to layout\n controlLayout->addWidget(markdownButton); // Add markdown button to layout\n // controlLayout->addWidget(colorPreview);\n // controlLayout->addWidget(thicknessButton);\n // controlLayout->addWidget(jumpToPageButton);\n controlLayout->addWidget(dialToggleButton);\n controlLayout->addWidget(fastForwardButton);\n // controlLayout->addWidget(channelSelector);\n controlLayout->addWidget(btnPageSwitch);\n controlLayout->addWidget(btnPannScroll);\n controlLayout->addWidget(btnZoom);\n controlLayout->addWidget(btnThickness);\n\n controlLayout->addWidget(btnTool);\n controlLayout->addWidget(btnPresets);\n controlLayout->addWidget(addPresetButton);\n // controlLayout->addWidget(dialModeSelector);\n // controlLayout->addStretch();\n \n // controlLayout->addWidget(toolSelector);\n controlLayout->addWidget(fullscreenButton);\n // controlLayout->addWidget(zoomButton);\n controlLayout->addWidget(zoom50Button);\n controlLayout->addWidget(dezoomButton);\n controlLayout->addWidget(zoom200Button);\n controlLayout->addStretch();\n \n \n controlLayout->addWidget(prevPageButton);\n controlLayout->addWidget(pageInput);\n controlLayout->addWidget(nextPageButton);\n controlLayout->addWidget(benchmarkButton);\n controlLayout->addWidget(benchmarkLabel);\n controlLayout->addWidget(deletePageButton);\n \n \n \n controlBar = new QWidget; // Use member variable instead of local\n controlBar->setObjectName(\"controlBar\");\n // controlBar->setLayout(controlLayout); // Commented out - responsive layout will handle this\n controlBar->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);\n\n // Theme will be applied later in loadUserSettings -> updateTheme()\n controlBar->setStyleSheet(\"\");\n\n \n \n\n canvasStack = new QStackedWidget();\n canvasStack->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);\n\n // Create a container for the canvas and scrollbars with relative positioning\n QWidget *canvasContainer = new QWidget;\n QVBoxLayout *canvasLayout = new QVBoxLayout(canvasContainer);\n canvasLayout->setContentsMargins(0, 0, 0, 0);\n canvasLayout->addWidget(canvasStack);\n\n // Enable context menu for the workaround\n canvasContainer->setContextMenuPolicy(Qt::CustomContextMenu);\n \n // Set up the scrollbars to overlay the canvas\n panXSlider->setParent(canvasContainer);\n panYSlider->setParent(canvasContainer);\n \n // Raise scrollbars to ensure they're visible above the canvas\n panXSlider->raise();\n panYSlider->raise();\n \n // Handle scrollbar intersection\n connect(canvasContainer, &QWidget::customContextMenuRequested, this, [this]() {\n // This connection is just to make sure the container exists\n // and can receive signals - a workaround for some Qt versions\n });\n \n // Position the scrollbars at the bottom and right edges\n canvasContainer->installEventFilter(this);\n \n // Update scrollbar positions initially\n QTimer::singleShot(0, this, [this, canvasContainer]() {\n updateScrollbarPositions();\n });\n\n // Main layout: toolbar -> tab bar -> canvas (vertical stack)\n QWidget *container = new QWidget;\n container->setObjectName(\"container\");\n QVBoxLayout *mainLayout = new QVBoxLayout(container);\n mainLayout->setContentsMargins(0, 0, 0, 0); // ✅ Remove extra margins\n mainLayout->setSpacing(0); // ✅ Remove spacing between components\n \n // Add components in vertical order\n mainLayout->addWidget(controlBar); // Toolbar at top\n mainLayout->addWidget(tabBarContainer); // Tab bar below toolbar\n \n // Content area with sidebars and canvas\n QHBoxLayout *contentLayout = new QHBoxLayout;\n contentLayout->setContentsMargins(0, 0, 0, 0);\n contentLayout->setSpacing(0);\n contentLayout->addWidget(outlineSidebar, 0); // Fixed width outline sidebar\n contentLayout->addWidget(bookmarksSidebar, 0); // Fixed width bookmarks sidebar\n contentLayout->addWidget(canvasContainer, 1); // Canvas takes remaining space\n \n QWidget *contentWidget = new QWidget;\n contentWidget->setLayout(contentLayout);\n mainLayout->addWidget(contentWidget, 1);\n\n setCentralWidget(container);\n\n benchmarkTimer = new QTimer(this);\n connect(benchmarkButton, &QPushButton::clicked, this, &MainWindow::toggleBenchmark);\n connect(benchmarkTimer, &QTimer::timeout, this, &MainWindow::updateBenchmarkDisplay);\n\n QString tempDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/temp_session\";\n QDir dir(tempDir);\n\n // Remove all contents (but keep the directory itself)\n if (dir.exists()) {\n dir.removeRecursively(); // Careful: this wipes everything inside\n }\n QDir().mkpath(tempDir); // Recreate clean directory\n\n addNewTab();\n\n // Initialize responsive toolbar layout\n createSingleRowLayout(); // Start with single row layout\n \n // Now that all UI components are created, update the color palette\n updateColorPalette();\n\n}\n void loadUserSettings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n\n // Load low-res toggle\n lowResPreviewEnabled = settings.value(\"lowResPreviewEnabled\", true).toBool();\n setLowResPreviewEnabled(lowResPreviewEnabled);\n\n \n zoomButtonsVisible = settings.value(\"zoomButtonsVisible\", true).toBool();\n setZoomButtonsVisible(zoomButtonsVisible);\n\n scrollOnTopEnabled = settings.value(\"scrollOnTopEnabled\", true).toBool();\n setScrollOnTopEnabled(scrollOnTopEnabled);\n\n touchGesturesEnabled = settings.value(\"touchGesturesEnabled\", true).toBool();\n setTouchGesturesEnabled(touchGesturesEnabled);\n \n // Update button visual state to match loaded setting\n touchGesturesButton->setProperty(\"selected\", touchGesturesEnabled);\n touchGesturesButton->style()->unpolish(touchGesturesButton);\n touchGesturesButton->style()->polish(touchGesturesButton);\n \n // Initialize default background settings if they don't exist\n if (!settings.contains(\"defaultBackgroundStyle\")) {\n saveDefaultBackgroundSettings(BackgroundStyle::Grid, Qt::white, 30);\n }\n \n // Load keyboard mappings\n loadKeyboardMappings();\n \n // Load theme settings\n loadThemeSettings();\n}\n bool scrollbarsVisible = false;\n QTimer *scrollbarHideTimer = nullptr;\n bool eventFilter(QObject *obj, QEvent *event) override {\n static bool dragging = false;\n static QPoint lastMousePos;\n static QTimer *longPressTimer = nullptr;\n\n // Handle IME focus events for text input widgets\n QLineEdit *lineEdit = qobject_cast(obj);\n if (lineEdit) {\n if (event->type() == QEvent::FocusIn) {\n // Ensure IME is enabled when text field gets focus\n lineEdit->setAttribute(Qt::WA_InputMethodEnabled, true);\n QInputMethod *inputMethod = QGuiApplication::inputMethod();\n if (inputMethod) {\n inputMethod->show();\n }\n }\n else if (event->type() == QEvent::FocusOut) {\n // Keep IME available but reset state\n QInputMethod *inputMethod = QGuiApplication::inputMethod();\n if (inputMethod) {\n inputMethod->reset();\n }\n }\n }\n\n // Handle resize events for canvas container\n QWidget *container = canvasStack ? canvasStack->parentWidget() : nullptr;\n if (obj == container && event->type() == QEvent::Resize) {\n updateScrollbarPositions();\n return false; // Let the event propagate\n }\n\n // Handle scrollbar visibility\n if (obj == panXSlider || obj == panYSlider) {\n if (event->type() == QEvent::Enter) {\n // Mouse entered scrollbar area\n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n return false;\n } \n else if (event->type() == QEvent::Leave) {\n // Mouse left scrollbar area - start timer to hide\n if (!scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->start();\n }\n return false;\n }\n }\n\n // Check if this is a canvas event for scrollbar handling\n InkCanvas* canvas = qobject_cast(obj);\n if (canvas) {\n // Handle mouse movement for scrollbar visibility\n if (event->type() == QEvent::MouseMove) {\n QMouseEvent* mouseEvent = static_cast(event);\n handleEdgeProximity(canvas, mouseEvent->pos());\n }\n // Handle tablet events for stylus hover (safely)\n else if (event->type() == QEvent::TabletMove) {\n try {\n QTabletEvent* tabletEvent = static_cast(event);\n handleEdgeProximity(canvas, tabletEvent->position().toPoint());\n } catch (...) {\n // Ignore tablet event errors to prevent crashes\n }\n }\n // Handle mouse button press events for forward/backward navigation\n else if (event->type() == QEvent::MouseButtonPress) {\n QMouseEvent* mouseEvent = static_cast(event);\n \n // Mouse button 4 (Back button) - Previous page\n if (mouseEvent->button() == Qt::BackButton) {\n if (prevPageButton) {\n prevPageButton->click();\n }\n return true; // Consume the event\n }\n // Mouse button 5 (Forward button) - Next page\n else if (mouseEvent->button() == Qt::ForwardButton) {\n if (nextPageButton) {\n nextPageButton->click();\n }\n return true; // Consume the event\n }\n }\n // Handle wheel events for scrolling\n else if (event->type() == QEvent::Wheel) {\n QWheelEvent* wheelEvent = static_cast(event);\n \n // Check if we need scrolling\n bool needHorizontalScroll = panXSlider->maximum() > 0;\n bool needVerticalScroll = panYSlider->maximum() > 0;\n \n // Handle vertical scrolling (Y axis)\n if (wheelEvent->angleDelta().y() != 0 && needVerticalScroll) {\n // Calculate scroll amount (negative because wheel up should scroll up)\n int scrollDelta = -wheelEvent->angleDelta().y() / 8; // Convert from 1/8 degree units\n scrollDelta = scrollDelta / 15; // Convert to steps (typical wheel step is 15 degrees)\n \n // Much faster base scroll speed - aim for ~3-5 scrolls to reach bottom\n int baseScrollAmount = panYSlider->maximum() / 8; // 1/8 of total range per scroll\n scrollDelta = scrollDelta * qMax(baseScrollAmount, 50); // Minimum 50 units per scroll\n \n // Apply the scroll\n int currentPan = panYSlider->value();\n int newPan = qBound(panYSlider->minimum(), currentPan + scrollDelta, panYSlider->maximum());\n panYSlider->setValue(newPan);\n \n // Show scrollbar temporarily\n panYSlider->setVisible(true);\n scrollbarsVisible = true;\n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n scrollbarHideTimer->start();\n \n // Consume the event\n return true;\n }\n \n // Handle horizontal scrolling (X axis) - for completeness\n if (wheelEvent->angleDelta().x() != 0 && needHorizontalScroll) {\n // Calculate scroll amount\n int scrollDelta = wheelEvent->angleDelta().x() / 8; // Convert from 1/8 degree units\n scrollDelta = scrollDelta / 15; // Convert to steps\n \n // Much faster base scroll speed - same logic as vertical\n int baseScrollAmount = panXSlider->maximum() / 8; // 1/8 of total range per scroll\n scrollDelta = scrollDelta * qMax(baseScrollAmount, 50); // Minimum 50 units per scroll\n \n // Apply the scroll\n int currentPan = panXSlider->value();\n int newPan = qBound(panXSlider->minimum(), currentPan + scrollDelta, panXSlider->maximum());\n panXSlider->setValue(newPan);\n \n // Show scrollbar temporarily\n panXSlider->setVisible(true);\n scrollbarsVisible = true;\n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n scrollbarHideTimer->start();\n \n // Consume the event\n return true;\n }\n \n // If no scrolling was needed, let the event propagate\n return false;\n }\n }\n\n // Handle dial container drag events\n if (obj == dialContainer) {\n if (event->type() == QEvent::MouseButtonPress) {\n QMouseEvent *mouseEvent = static_cast(event);\n lastMousePos = mouseEvent->globalPos();\n dragging = false;\n\n if (!longPressTimer) {\n longPressTimer = new QTimer(this);\n longPressTimer->setSingleShot(true);\n connect(longPressTimer, &QTimer::timeout, [this]() {\n dragging = true; // ✅ Allow movement after long press\n });\n }\n longPressTimer->start(1500); // ✅ Start long press timer (500ms)\n return true;\n }\n\n if (event->type() == QEvent::MouseMove && dragging) {\n QMouseEvent *mouseEvent = static_cast(event);\n QPoint delta = mouseEvent->globalPos() - lastMousePos;\n dialContainer->move(dialContainer->pos() + delta);\n lastMousePos = mouseEvent->globalPos();\n return true;\n }\n\n if (event->type() == QEvent::MouseButtonRelease) {\n if (longPressTimer) longPressTimer->stop();\n dragging = false; // ✅ Stop dragging on release\n return true;\n }\n }\n\n return QObject::eventFilter(obj, event);\n}\n void updateScrollbarPositions() {\n QWidget *container = canvasStack->parentWidget();\n if (!container || !panXSlider || !panYSlider) return;\n \n // Add small margins for better visibility\n const int margin = 3;\n \n // Get scrollbar dimensions\n const int scrollbarWidth = panYSlider->width();\n const int scrollbarHeight = panXSlider->height();\n \n // Calculate sizes based on container\n int containerWidth = container->width();\n int containerHeight = container->height();\n \n // Leave a bit of space for the corner\n int cornerOffset = 15;\n \n // Position horizontal scrollbar at top\n panXSlider->setGeometry(\n cornerOffset + margin, // Leave space at left corner\n margin,\n containerWidth - cornerOffset - margin*2, // Full width minus corner and right margin\n scrollbarHeight\n );\n \n // Position vertical scrollbar at left\n panYSlider->setGeometry(\n margin,\n cornerOffset + margin, // Leave space at top corner\n scrollbarWidth,\n containerHeight - cornerOffset - margin*2 // Full height minus corner and bottom margin\n );\n}\n void handleEdgeProximity(InkCanvas* canvas, const QPoint& pos) {\n if (!canvas) return;\n \n // Get canvas dimensions\n int canvasWidth = canvas->width();\n int canvasHeight = canvas->height();\n \n // Edge detection zones - show scrollbars when pointer is within 50px of edges\n bool nearLeftEdge = pos.x() < 25; // For vertical scrollbar\n bool nearTopEdge = pos.y() < 25; // For horizontal scrollbar - entire top edge\n \n // Only show scrollbars if canvas is larger than viewport\n bool needHorizontalScroll = panXSlider->maximum() > 0;\n bool needVerticalScroll = panYSlider->maximum() > 0;\n \n // Show/hide scrollbars based on pointer position\n if (nearLeftEdge && needVerticalScroll) {\n panYSlider->setVisible(true);\n scrollbarsVisible = true;\n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n scrollbarHideTimer->start();\n }\n \n if (nearTopEdge && needHorizontalScroll) {\n panXSlider->setVisible(true);\n scrollbarsVisible = true;\n if (scrollbarHideTimer->isActive()) {\n scrollbarHideTimer->stop();\n }\n scrollbarHideTimer->start();\n }\n}\n bool isToolbarTwoRows = false;\n QVBoxLayout *controlLayoutVertical = nullptr;\n QHBoxLayout *controlLayoutSingle = nullptr;\n QHBoxLayout *controlLayoutFirstRow = nullptr;\n QHBoxLayout *controlLayoutSecondRow = nullptr;\n void updateToolbarLayout() {\n // Calculate scaled width using device pixel ratio\n QScreen *screen = QGuiApplication::primaryScreen();\n // qreal dpr = screen ? screen->devicePixelRatio() : 1.0;\n int scaledWidth = width();\n \n // Dynamic threshold based on zoom button visibility\n int threshold = areZoomButtonsVisible() ? 1548 : 1438;\n \n // Debug output to understand what's happening\n // qDebug() << \"Window width:\" << scaledWidth << \"Threshold:\" << threshold << \"Zoom buttons visible:\" << areZoomButtonsVisible();\n \n bool shouldBeTwoRows = scaledWidth <= threshold;\n \n // qDebug() << \"Should be two rows:\" << shouldBeTwoRows << \"Currently is two rows:\" << isToolbarTwoRows;\n \n if (shouldBeTwoRows != isToolbarTwoRows) {\n isToolbarTwoRows = shouldBeTwoRows;\n \n // qDebug() << \"Switching to\" << (isToolbarTwoRows ? \"two rows\" : \"single row\");\n \n if (isToolbarTwoRows) {\n createTwoRowLayout();\n } else {\n createSingleRowLayout();\n }\n }\n}\n void createSingleRowLayout() {\n // Delete separator line if it exists (from previous 2-row layout)\n if (separatorLine) {\n delete separatorLine;\n separatorLine = nullptr;\n }\n \n // Create new single row layout first\n QHBoxLayout *newLayout = new QHBoxLayout;\n \n // Add all widgets to single row (same order as before)\n newLayout->addWidget(toggleTabBarButton);\n newLayout->addWidget(toggleOutlineButton);\n newLayout->addWidget(toggleBookmarksButton);\n newLayout->addWidget(toggleBookmarkButton);\n newLayout->addWidget(touchGesturesButton);\n newLayout->addWidget(selectFolderButton);\n newLayout->addWidget(exportNotebookButton);\n newLayout->addWidget(importNotebookButton);\n newLayout->addWidget(loadPdfButton);\n newLayout->addWidget(clearPdfButton);\n newLayout->addWidget(pdfTextSelectButton);\n newLayout->addWidget(backgroundButton);\n newLayout->addWidget(saveButton);\n newLayout->addWidget(saveAnnotatedButton);\n newLayout->addWidget(openControlPanelButton);\n newLayout->addWidget(openRecentNotebooksButton);\n newLayout->addWidget(redButton);\n newLayout->addWidget(blueButton);\n newLayout->addWidget(yellowButton);\n newLayout->addWidget(greenButton);\n newLayout->addWidget(blackButton);\n newLayout->addWidget(whiteButton);\n newLayout->addWidget(customColorButton);\n newLayout->addWidget(penToolButton);\n newLayout->addWidget(markerToolButton);\n newLayout->addWidget(eraserToolButton);\n newLayout->addWidget(straightLineToggleButton);\n newLayout->addWidget(ropeToolButton);\n newLayout->addWidget(markdownButton);\n newLayout->addWidget(dialToggleButton);\n newLayout->addWidget(fastForwardButton);\n newLayout->addWidget(btnPageSwitch);\n newLayout->addWidget(btnPannScroll);\n newLayout->addWidget(btnZoom);\n newLayout->addWidget(btnThickness);\n\n newLayout->addWidget(btnTool);\n newLayout->addWidget(btnPresets);\n newLayout->addWidget(addPresetButton);\n newLayout->addWidget(fullscreenButton);\n \n // Only add zoom buttons if they're visible\n if (areZoomButtonsVisible()) {\n newLayout->addWidget(zoom50Button);\n newLayout->addWidget(dezoomButton);\n newLayout->addWidget(zoom200Button);\n }\n \n newLayout->addStretch();\n newLayout->addWidget(prevPageButton);\n newLayout->addWidget(pageInput);\n newLayout->addWidget(nextPageButton);\n newLayout->addWidget(benchmarkButton);\n newLayout->addWidget(benchmarkLabel);\n newLayout->addWidget(deletePageButton);\n \n // Safely replace the layout\n QLayout* oldLayout = controlBar->layout();\n if (oldLayout) {\n // Remove all items from old layout (but don't delete widgets)\n QLayoutItem* item;\n while ((item = oldLayout->takeAt(0)) != nullptr) {\n // Just removing, not deleting widgets\n }\n delete oldLayout;\n }\n \n // Set the new layout\n controlBar->setLayout(newLayout);\n controlLayoutSingle = newLayout;\n \n // Clean up other layout pointers\n controlLayoutVertical = nullptr;\n controlLayoutFirstRow = nullptr;\n controlLayoutSecondRow = nullptr;\n \n // Update pan range after layout change\n updatePanRange();\n}\n void createTwoRowLayout() {\n // Create new layouts first\n QVBoxLayout *newVerticalLayout = new QVBoxLayout;\n QHBoxLayout *newFirstRowLayout = new QHBoxLayout;\n QHBoxLayout *newSecondRowLayout = new QHBoxLayout;\n \n // Add comfortable spacing and margins for 2-row layout\n newFirstRowLayout->setContentsMargins(8, 8, 8, 6); // More generous margins\n newFirstRowLayout->setSpacing(3); // Add spacing between buttons for less cramped feel\n newSecondRowLayout->setContentsMargins(8, 6, 8, 8); // More generous margins\n newSecondRowLayout->setSpacing(3); // Add spacing between buttons for less cramped feel\n \n // First row: up to customColorButton\n newFirstRowLayout->addWidget(toggleTabBarButton);\n newFirstRowLayout->addWidget(toggleOutlineButton);\n newFirstRowLayout->addWidget(toggleBookmarksButton);\n newFirstRowLayout->addWidget(toggleBookmarkButton);\n newFirstRowLayout->addWidget(touchGesturesButton);\n newFirstRowLayout->addWidget(selectFolderButton);\n newFirstRowLayout->addWidget(exportNotebookButton);\n newFirstRowLayout->addWidget(importNotebookButton);\n newFirstRowLayout->addWidget(loadPdfButton);\n newFirstRowLayout->addWidget(clearPdfButton);\n newFirstRowLayout->addWidget(pdfTextSelectButton);\n newFirstRowLayout->addWidget(backgroundButton);\n newFirstRowLayout->addWidget(saveButton);\n newFirstRowLayout->addWidget(saveAnnotatedButton);\n newFirstRowLayout->addWidget(openControlPanelButton);\n newFirstRowLayout->addWidget(openRecentNotebooksButton);\n newFirstRowLayout->addWidget(redButton);\n newFirstRowLayout->addWidget(blueButton);\n newFirstRowLayout->addWidget(yellowButton);\n newFirstRowLayout->addWidget(greenButton);\n newFirstRowLayout->addWidget(blackButton);\n newFirstRowLayout->addWidget(whiteButton);\n newFirstRowLayout->addWidget(customColorButton);\n newFirstRowLayout->addWidget(penToolButton);\n newFirstRowLayout->addWidget(markerToolButton);\n newFirstRowLayout->addWidget(eraserToolButton);\n newFirstRowLayout->addStretch();\n \n // Create a separator line\n if (!separatorLine) {\n separatorLine = new QFrame();\n separatorLine->setFrameShape(QFrame::HLine);\n separatorLine->setFrameShadow(QFrame::Sunken);\n separatorLine->setLineWidth(1);\n separatorLine->setStyleSheet(\"QFrame { color: rgba(255, 255, 255, 255); }\");\n }\n \n // Second row: everything after customColorButton\n newSecondRowLayout->addWidget(straightLineToggleButton);\n newSecondRowLayout->addWidget(ropeToolButton);\n newSecondRowLayout->addWidget(markdownButton);\n newSecondRowLayout->addWidget(dialToggleButton);\n newSecondRowLayout->addWidget(fastForwardButton);\n newSecondRowLayout->addWidget(btnPageSwitch);\n newSecondRowLayout->addWidget(btnPannScroll);\n newSecondRowLayout->addWidget(btnZoom);\n newSecondRowLayout->addWidget(btnThickness);\n\n newSecondRowLayout->addWidget(btnTool);\n newSecondRowLayout->addWidget(btnPresets);\n newSecondRowLayout->addWidget(addPresetButton);\n newSecondRowLayout->addWidget(fullscreenButton);\n \n // Only add zoom buttons if they're visible\n if (areZoomButtonsVisible()) {\n newSecondRowLayout->addWidget(zoom50Button);\n newSecondRowLayout->addWidget(dezoomButton);\n newSecondRowLayout->addWidget(zoom200Button);\n }\n \n newSecondRowLayout->addStretch();\n newSecondRowLayout->addWidget(prevPageButton);\n newSecondRowLayout->addWidget(pageInput);\n newSecondRowLayout->addWidget(nextPageButton);\n newSecondRowLayout->addWidget(benchmarkButton);\n newSecondRowLayout->addWidget(benchmarkLabel);\n newSecondRowLayout->addWidget(deletePageButton);\n \n // Add layouts to vertical layout with separator\n newVerticalLayout->addLayout(newFirstRowLayout);\n newVerticalLayout->addWidget(separatorLine);\n newVerticalLayout->addLayout(newSecondRowLayout);\n newVerticalLayout->setContentsMargins(0, 0, 0, 0);\n newVerticalLayout->setSpacing(0); // No spacing since we have our own separator\n \n // Safely replace the layout\n QLayout* oldLayout = controlBar->layout();\n if (oldLayout) {\n // Remove all items from old layout (but don't delete widgets)\n QLayoutItem* item;\n while ((item = oldLayout->takeAt(0)) != nullptr) {\n // Just removing, not deleting widgets\n }\n delete oldLayout;\n }\n \n // Set the new layout\n controlBar->setLayout(newVerticalLayout);\n controlLayoutVertical = newVerticalLayout;\n controlLayoutFirstRow = newFirstRowLayout;\n controlLayoutSecondRow = newSecondRowLayout;\n \n // Clean up other layout pointer\n controlLayoutSingle = nullptr;\n \n // Update pan range after layout change\n updatePanRange();\n}\n QString elideTabText(const QString &text, int maxWidth) {\n // Create a font metrics object using the default font\n QFontMetrics fontMetrics(QApplication::font());\n \n // Elide the text from the right (showing the beginning)\n return fontMetrics.elidedText(text, Qt::ElideRight, maxWidth);\n}\n QTimer *layoutUpdateTimer = nullptr;\n QFrame *separatorLine = nullptr;\n protected:\n void resizeEvent(QResizeEvent *event) override {\n QMainWindow::resizeEvent(event);\n \n // Use a timer to delay layout updates during resize to prevent excessive switching\n if (!layoutUpdateTimer) {\n layoutUpdateTimer = new QTimer(this);\n layoutUpdateTimer->setSingleShot(true);\n connect(layoutUpdateTimer, &QTimer::timeout, this, [this]() {\n updateToolbarLayout();\n // Also reposition dial after resize finishes\n if (dialContainer && dialContainer->isVisible()) {\n positionDialContainer();\n }\n });\n }\n \n layoutUpdateTimer->stop();\n layoutUpdateTimer->start(100); // Wait 100ms after resize stops\n}\n void keyPressEvent(QKeyEvent *event) override {\n // Don't intercept keyboard events when text input widgets have focus\n // This prevents conflicts with Windows TextInputFramework\n QWidget *focusWidget = QApplication::focusWidget();\n if (focusWidget) {\n bool isTextInputWidget = qobject_cast(focusWidget) || \n qobject_cast(focusWidget) || \n qobject_cast(focusWidget) ||\n qobject_cast(focusWidget) ||\n qobject_cast(focusWidget);\n \n if (isTextInputWidget) {\n // Let text input widgets handle their own keyboard events\n QMainWindow::keyPressEvent(event);\n return;\n }\n }\n \n // Don't intercept IME-related keyboard shortcuts\n // These are reserved for Windows Input Method Editor\n if (event->modifiers() & Qt::ControlModifier) {\n if (event->key() == Qt::Key_Space || // Ctrl+Space (IME toggle)\n event->key() == Qt::Key_Shift || // Ctrl+Shift (language switch)\n event->key() == Qt::Key_Alt) { // Ctrl+Alt (IME functions)\n // Let Windows handle IME shortcuts\n QMainWindow::keyPressEvent(event);\n return;\n }\n }\n \n // Don't intercept Shift+Alt (another common IME shortcut)\n if ((event->modifiers() & Qt::ShiftModifier) && (event->modifiers() & Qt::AltModifier)) {\n QMainWindow::keyPressEvent(event);\n return;\n }\n \n // Build key sequence string\n QStringList modifiers;\n \n if (event->modifiers() & Qt::ControlModifier) modifiers << \"Ctrl\";\n if (event->modifiers() & Qt::ShiftModifier) modifiers << \"Shift\";\n if (event->modifiers() & Qt::AltModifier) modifiers << \"Alt\";\n if (event->modifiers() & Qt::MetaModifier) modifiers << \"Meta\";\n \n QString keyString = QKeySequence(event->key()).toString();\n \n QString fullSequence;\n if (!modifiers.isEmpty()) {\n fullSequence = modifiers.join(\"+\") + \"+\" + keyString;\n } else {\n fullSequence = keyString;\n }\n \n // Check if this sequence is mapped\n if (keyboardMappings.contains(fullSequence)) {\n handleKeyboardShortcut(fullSequence);\n event->accept();\n return;\n }\n \n // If not handled, pass to parent\n QMainWindow::keyPressEvent(event);\n}\n void tabletEvent(QTabletEvent *event) override {\n // Since tablet tracking is disabled to prevent crashes, we now only handle\n // basic tablet events that come through when stylus is touching the surface\n if (!event) {\n return;\n }\n \n // Just pass tablet events to parent safely without custom hover handling\n // (hover tooltips will work through normal mouse events instead)\n try {\n QMainWindow::tabletEvent(event);\n } catch (...) {\n // Catch any exceptions and just accept the event\n event->accept();\n }\n}\n void inputMethodEvent(QInputMethodEvent *event) override {\n // Forward IME events to the focused widget\n QWidget *focusWidget = QApplication::focusWidget();\n if (focusWidget && focusWidget != this) {\n QApplication::sendEvent(focusWidget, event);\n event->accept();\n return;\n }\n \n // Default handling\n QMainWindow::inputMethodEvent(event);\n}\n QVariant inputMethodQuery(Qt::InputMethodQuery query) const override {\n // Forward IME queries to the focused widget\n QWidget *focusWidget = QApplication::focusWidget();\n if (focusWidget && focusWidget != this) {\n return focusWidget->inputMethodQuery(query);\n }\n \n // Default handling\n return QMainWindow::inputMethodQuery(query);\n}\n};"], ["/SpeedyNote/markdown/qmarkdowntextedit.h", "class LineNumArea {\n Q_OBJECT\n Q_PROPERTY(\n bool highlighting READ highlightingEnabled WRITE setHighlightingEnabled);\n friend class LineNumArea;\n public:\n enum AutoTextOption {\n None = 0x0000,\n\n // inserts closing characters for brackets and Markdown characters\n BracketClosing = 0x0001,\n\n // removes matching brackets and Markdown characters\n BracketRemoval = 0x0002\n };\n Q_DECLARE_FLAGS(AutoTextOptions, AutoTextOption);\n explicit QMarkdownTextEdit(QWidget *parent = nullptr,\n bool initHighlighter = true) {\n installEventFilter(this);\n viewport()->installEventFilter(this);\n _autoTextOptions = AutoTextOption::BracketClosing;\n\n _lineNumArea = new LineNumArea(this);\n updateLineNumberAreaWidth(0);\n\n // Markdown highlighting is enabled by default\n _highlightingEnabled = initHighlighter;\n if (initHighlighter) {\n _highlighter = new MarkdownHighlighter(document());\n }\n\n QFont font = this->font();\n\n // set the tab stop to the width of 4 spaces in the editor\n constexpr int tabStop = 4;\n QFontMetrics metrics(font);\n\n#if QT_VERSION < QT_VERSION_CHECK(5, 11, 0)\n setTabStopWidth(tabStop * metrics.width(' '));\n#else\n setTabStopDistance(tabStop * metrics.horizontalAdvance(QLatin1Char(' ')));\n#endif\n\n // add shortcuts for duplicating text\n // new QShortcut( QKeySequence( \"Ctrl+D\" ), this, SLOT( duplicateText() )\n // ); new QShortcut( QKeySequence( \"Ctrl+Alt+Down\" ), this, SLOT(\n // duplicateText() ) );\n\n // add a layout to the widget\n auto *layout = new QVBoxLayout(this);\n layout->setContentsMargins(0, 0, 0, 0);\n layout->addStretch();\n this->setLayout(layout);\n\n // add the hidden search widget\n _searchWidget = new QPlainTextEditSearchWidget(this);\n this->layout()->addWidget(_searchWidget);\n\n connect(this, &QPlainTextEdit::textChanged, this,\n &QMarkdownTextEdit::adjustRightMargin);\n connect(this, &QPlainTextEdit::cursorPositionChanged, this,\n &QMarkdownTextEdit::centerTheCursor);\n connect(verticalScrollBar(), &QScrollBar::valueChanged, this,\n [this](int) { _lineNumArea->update(); });\n connect(this, &QPlainTextEdit::cursorPositionChanged, this, [this]() {\n _lineNumArea->update();\n\n auto oldArea = blockBoundingGeometry(_textCursor.block())\n .translated(contentOffset());\n _textCursor = textCursor();\n auto newArea = blockBoundingGeometry(_textCursor.block())\n .translated(contentOffset());\n auto areaToUpdate = oldArea | newArea;\n viewport()->update(areaToUpdate.toRect());\n });\n connect(document(), &QTextDocument::blockCountChanged, this,\n &QMarkdownTextEdit::updateLineNumberAreaWidth);\n connect(this, &QPlainTextEdit::updateRequest, this,\n &QMarkdownTextEdit::updateLineNumberArea);\n\n updateSettings();\n\n // workaround for disabled signals up initialization\n QTimer::singleShot(300, this, &QMarkdownTextEdit::adjustRightMargin);\n}\n MarkdownHighlighter *highlighter();\n QPlainTextEditSearchWidget *searchWidget();\n void setIgnoredClickUrlSchemata(QStringList ignoredUrlSchemata) {\n _ignoredClickUrlSchemata = std::move(ignoredUrlSchemata);\n}\n virtual void openUrl(const QString &urlString) {\n qDebug() << \"QMarkdownTextEdit \" << __func__\n << \" - 'urlString': \" << urlString;\n\n QDesktopServices::openUrl(QUrl(urlString));\n}\n QString getMarkdownUrlAtPosition(const QString &text, int position) {\n QString url;\n\n // get a map of parsed Markdown urls with their link texts as key\n const QMap urlMap = parseMarkdownUrlsFromText(text);\n QMap::const_iterator i = urlMap.constBegin();\n for (; i != urlMap.constEnd(); ++i) {\n const QString &linkText = i.key();\n const QString &urlString = i.value();\n\n const int foundPositionStart = text.indexOf(linkText);\n\n if (foundPositionStart >= 0) {\n // calculate end position of found linkText\n const int foundPositionEnd = foundPositionStart + linkText.size();\n\n // check if position is in found string range\n if ((position >= foundPositionStart) &&\n (position <= foundPositionEnd)) {\n url = urlString;\n break;\n }\n }\n }\n\n return url;\n}\n void initSearchFrame(QWidget *searchFrame, bool darkMode = false) {\n _searchFrame = searchFrame;\n\n // remove the search widget from our layout\n layout()->removeWidget(_searchWidget);\n\n QLayout *layout = _searchFrame->layout();\n\n // create a grid layout for the frame and add the search widget to it\n if (layout == nullptr) {\n layout = new QVBoxLayout(_searchFrame);\n layout->setSpacing(0);\n layout->setContentsMargins(0, 0, 0, 0);\n }\n\n _searchWidget->setDarkMode(darkMode);\n layout->addWidget(_searchWidget);\n _searchFrame->setLayout(layout);\n}\n void setAutoTextOptions(AutoTextOptions options) {\n _autoTextOptions = options;\n}\n static bool isValidUrl(const QString &urlString) {\n static QRegularExpression regex(R\"(^\\w+:\\/\\/.+)\");\n const QRegularExpressionMatch match = regex.match(urlString);\n return match.hasMatch();\n}\n void resetMouseCursor() const {\n QWidget *viewPort = viewport();\n viewPort->setCursor(Qt::IBeamCursor);\n}\n void setReadOnly(bool ro) {\n QPlainTextEdit::setReadOnly(ro);\n\n // attempted to fix a problem with Chinese and Japanese input methods\n // @see https://github.com/pbek/QOwnNotes/issues/976\n setAttribute(Qt::WA_InputMethodEnabled, !isReadOnly());\n}\n void doSearch(QString &searchText,\n QPlainTextEditSearchWidget::SearchMode searchMode =\n QPlainTextEditSearchWidget::SearchMode::PlainTextMode) {\n _searchWidget->setSearchText(searchText);\n _searchWidget->setSearchMode(searchMode);\n _searchWidget->doSearchCount();\n _searchWidget->activate(false);\n}\n void hideSearchWidget(bool reset) {\n _searchWidget->deactivate();\n\n if (reset) {\n _searchWidget->reset();\n }\n}\n void updateSettings() {\n // if true: centers the screen if cursor reaches bottom (but not top)\n searchWidget()->setDebounceDelay(_debounceDelay);\n setCenterOnScroll(_centerCursor);\n}\n void setLineNumbersCurrentLineColor(QColor color) {\n _lineNumArea->setCurrentLineColor(std::move(color));\n}\n void setLineNumbersOtherLineColor(QColor color) {\n _lineNumArea->setOtherLineColor(std::move(color));\n}\n void setSearchWidgetDebounceDelay(uint debounceDelay) {\n _debounceDelay = debounceDelay;\n searchWidget()->setDebounceDelay(_debounceDelay);\n}\n void setHighlightingEnabled(bool enabled) {\n if (_highlightingEnabled == enabled || _highlighter == nullptr) {\n return;\n }\n\n _highlightingEnabled = enabled;\n _highlighter->setDocument(enabled ? document() : Q_NULLPTR);\n\n if (enabled) {\n _highlighter->rehighlight();\n }\n}\n [[nodiscard]] bool highlightingEnabled() const {\n return _highlightingEnabled && _highlighter != nullptr;\n}\n void setHighlightCurrentLine(bool set) {\n _highlightCurrentLine = set;\n}\n bool highlightCurrentLine() { return _highlightCurrentLine; }\n void setCurrentLineHighlightColor(const QColor &c) {\n _currentLineHighlightColor = color;\n}\n QColor currentLineHighlightColor() {\n return _currentLineHighlightColor;\n}\n public:\n void duplicateText() {\n if (isReadOnly()) {\n return;\n }\n\n QTextCursor cursor = this->textCursor();\n QString selectedText = cursor.selectedText();\n\n // duplicate line if no text was selected\n if (selectedText.isEmpty()) {\n const int position = cursor.position();\n\n // select the whole line\n cursor.movePosition(QTextCursor::StartOfBlock);\n cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);\n\n const int positionDiff = cursor.position() - position;\n selectedText = \"\\n\" + cursor.selectedText();\n\n // insert text with new line at end of the selected line\n cursor.setPosition(cursor.selectionEnd());\n cursor.insertText(selectedText);\n\n // set the position to same position it was in the duplicated line\n cursor.setPosition(cursor.position() - positionDiff);\n } else {\n // duplicate selected text\n cursor.setPosition(cursor.selectionEnd());\n const int selectionStart = cursor.position();\n\n // insert selected text\n cursor.insertText(selectedText);\n const int selectionEnd = cursor.position();\n\n // select the inserted text\n cursor.setPosition(selectionStart);\n cursor.setPosition(selectionEnd, QTextCursor::KeepAnchor);\n }\n\n this->setTextCursor(cursor);\n}\n void setText(const QString &text) { setPlainText(text); }\n void setPlainText(const QString &text) {\n // clear the dirty blocks vector to increase performance and prevent\n // a possible crash in QSyntaxHighlighter::rehighlightBlock\n if (_highlighter) _highlighter->clearDirtyBlocks();\n\n QPlainTextEdit::setPlainText(text);\n adjustRightMargin();\n}\n void adjustRightMargin() {\n QMargins margins = layout()->contentsMargins();\n const int rightMargin =\n document()->size().height() > viewport()->size().height() ? 24 : 0;\n margins.setRight(rightMargin);\n layout()->setContentsMargins(margins);\n}\n void hide() {\n _searchWidget->hide();\n QWidget::hide();\n}\n bool openLinkAtCursorPosition() {\n QTextCursor cursor = this->textCursor();\n const int clickedPosition = cursor.position();\n\n // select the text in the clicked block and find out on\n // which position we clicked\n cursor.movePosition(QTextCursor::StartOfBlock);\n const int positionFromStart = clickedPosition - cursor.position();\n cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);\n\n const QString selectedText = cursor.selectedText();\n\n // find out which url in the selected text was clicked\n const QString urlString =\n getMarkdownUrlAtPosition(selectedText, positionFromStart);\n const QUrl url = QUrl(urlString);\n const bool isRelativeFileUrl =\n urlString.startsWith(QLatin1String(\"file://..\"));\n const bool isLegacyAttachmentUrl =\n urlString.startsWith(QLatin1String(\"file://attachments\"));\n\n qDebug() << __func__ << \" - 'emit urlClicked( urlString )': \" << urlString;\n\n Q_EMIT urlClicked(urlString);\n\n if ((url.isValid() && isValidUrl(urlString)) || isRelativeFileUrl ||\n isLegacyAttachmentUrl) {\n // ignore some schemata\n if (!(_ignoredClickUrlSchemata.contains(url.scheme()) ||\n isRelativeFileUrl || isLegacyAttachmentUrl)) {\n // open the url\n openUrl(urlString);\n }\n\n return true;\n }\n\n return false;\n}\n bool handleBackspaceEntered() {\n if (!(_autoTextOptions & AutoTextOption::BracketRemoval) || isReadOnly()) {\n return false;\n }\n\n QTextCursor cursor = textCursor();\n\n // return if some text was selected\n if (!cursor.selectedText().isEmpty()) {\n return false;\n }\n\n int position = cursor.position();\n const int positionInBlock = cursor.positionInBlock();\n int block = cursor.block().blockNumber();\n\n if (_highlighter)\n if (_highlighter->isPosInACodeSpan(block, positionInBlock - 1))\n return false;\n\n // return if backspace was pressed at the beginning of a block\n if (positionInBlock == 0) {\n return false;\n }\n\n // get the current text from the block\n const QString text = cursor.block().text();\n\n char charToRemove{};\n\n // current char\n const char charInFront = text.at(positionInBlock - 1).toLatin1();\n\n if (charInFront == '*')\n return handleCharRemoval(MarkdownHighlighter::RangeType::Emphasis,\n block, positionInBlock - 1);\n else if (charInFront == '`')\n return handleCharRemoval(MarkdownHighlighter::RangeType::CodeSpan,\n block, positionInBlock - 1);\n\n // handle removal of \", ', and brackets\n\n // is it opener?\n int pos = _openingCharacters.indexOf(charInFront);\n // for \" and '\n bool isOpener = false;\n bool isCloser = false;\n if (pos == 5 || pos == 6) {\n isOpener = isQuotOpener(positionInBlock - 1, text);\n } else {\n isOpener = pos != -1;\n }\n if (isOpener) {\n charToRemove = _closingCharacters.at(pos);\n } else {\n // is it closer?\n pos = _closingCharacters.indexOf(charInFront);\n if (pos == 5 || pos == 6)\n isCloser = isQuotCloser(positionInBlock - 1, text);\n else\n isCloser = pos != -1;\n if (isCloser)\n charToRemove = _openingCharacters.at(pos);\n else\n return false;\n }\n\n int charToRemoveIndex = -1;\n if (isOpener) {\n bool closer = true;\n charToRemoveIndex = text.indexOf(charToRemove, positionInBlock);\n if (charToRemoveIndex == -1) return false;\n if (pos == 5 || pos == 6)\n closer = isQuotCloser(charToRemoveIndex, text);\n if (!closer) return false;\n cursor.setPosition(position + (charToRemoveIndex - positionInBlock));\n cursor.deleteChar();\n } else if (isCloser) {\n charToRemoveIndex = text.lastIndexOf(charToRemove, positionInBlock - 2);\n if (charToRemoveIndex == -1) return false;\n bool opener = true;\n if (pos == 5 || pos == 6)\n opener = isQuotOpener(charToRemoveIndex, text);\n if (!opener) return false;\n const int pos = position - (positionInBlock - charToRemoveIndex);\n cursor.setPosition(pos);\n cursor.deleteChar();\n position -= 1;\n } else {\n charToRemoveIndex = text.lastIndexOf(charToRemove, positionInBlock - 2);\n if (charToRemoveIndex == -1) return false;\n const int pos = position - (positionInBlock - charToRemoveIndex);\n cursor.setPosition(pos);\n cursor.deleteChar();\n position -= 1;\n }\n\n // moving the cursor back to the old position so the previous character\n // can be removed\n cursor.setPosition(position);\n setTextCursor(cursor);\n return false;\n}\n void centerTheCursor() {\n if (_mouseButtonDown || !_centerCursor) {\n return;\n }\n\n // Centers the cursor every time, but not on the top and bottom,\n // bottom is done by setCenterOnScroll() in updateSettings()\n centerCursor();\n\n /*\n QRect cursor = cursorRect();\n QRect vp = viewport()->rect();\n\n qDebug() << __func__ << \" - 'cursor.top': \" << cursor.top();\n qDebug() << __func__ << \" - 'cursor.bottom': \" << cursor.bottom();\n qDebug() << __func__ << \" - 'vp': \" << vp.bottom();\n\n int bottom = 0;\n int top = 0;\n\n qDebug() << __func__ << \" - 'viewportMargins().top()': \"\n << viewportMargins().top();\n\n qDebug() << __func__ << \" - 'viewportMargins().bottom()': \"\n << viewportMargins().bottom();\n\n int vpBottom = viewportMargins().top() + viewportMargins().bottom() +\n vp.bottom(); int vpCenter = vpBottom / 2; int cBottom = cursor.bottom() +\n viewportMargins().top();\n\n qDebug() << __func__ << \" - 'vpBottom': \" << vpBottom;\n qDebug() << __func__ << \" - 'vpCenter': \" << vpCenter;\n qDebug() << __func__ << \" - 'cBottom': \" << cBottom;\n\n\n if (cBottom >= vpCenter) {\n bottom = cBottom + viewportMargins().top() / 2 +\n viewportMargins().bottom() / 2 - (vp.bottom() / 2);\n // bottom = cBottom - (vp.bottom() / 2);\n // bottom *= 1.5;\n }\n\n // setStyleSheet(QString(\"QPlainTextEdit {padding-bottom:\n %1px;}\").arg(QString::number(bottom)));\n\n // if (cursor.top() < (vp.bottom() / 2)) {\n // top = (vp.bottom() / 2) - cursor.top() + viewportMargins().top() /\n 2 + viewportMargins().bottom() / 2;\n //// top *= -1;\n //// bottom *= 1.5;\n // }\n qDebug() << __func__ << \" - 'top': \" << top;\n qDebug() << __func__ << \" - 'bottom': \" << bottom;\n setViewportMargins(0,top,0, bottom);\n\n\n // QScrollBar* scrollbar = verticalScrollBar();\n //\n // qDebug() << __func__ << \" - 'scrollbar->value();': \" <<\n scrollbar->value();;\n // qDebug() << __func__ << \" - 'scrollbar->maximum();': \"\n // << scrollbar->maximum();;\n\n\n // scrollbar->setValue(scrollbar->value() - offset.y());\n //\n // setViewportMargins\n\n // setViewportMargins(0, 0, 0, bottom);\n */\n}\n void undo() {\n if (isReadOnly()) {\n return;\n }\n\n QTextCursor cursor = textCursor();\n // if no text selected, call undo\n if (!cursor.hasSelection()) {\n QPlainTextEdit::undo();\n return;\n }\n\n // if text is selected and bracket closing was used\n // we retain our selection\n if (_handleBracketClosingUsed) {\n // get the selection\n int selectionEnd = cursor.selectionEnd();\n int selectionStart = cursor.selectionStart();\n // call undo\n QPlainTextEdit::undo();\n // select again\n cursor.setPosition(selectionStart - 1);\n cursor.setPosition(selectionEnd - 1, QTextCursor::KeepAnchor);\n this->setTextCursor(cursor);\n _handleBracketClosingUsed = false;\n } else {\n // if text was selected but bracket closing wasn't used\n // do normal undo\n QPlainTextEdit::undo();\n return;\n }\n}\n void moveTextUpDown(bool up) {\n if (isReadOnly()) {\n return;\n }\n\n QTextCursor cursor = textCursor();\n QTextCursor move = cursor;\n\n move.setVisualNavigation(false);\n\n move.beginEditBlock(); // open an edit block to keep undo operations sane\n bool hasSelection = cursor.hasSelection();\n\n if (hasSelection) {\n // if there's a selection inside the block, we select the whole block\n move.setPosition(cursor.selectionStart());\n move.movePosition(QTextCursor::StartOfBlock);\n move.setPosition(cursor.selectionEnd(), QTextCursor::KeepAnchor);\n move.movePosition(\n move.atBlockStart() ? QTextCursor::Left : QTextCursor::EndOfBlock,\n QTextCursor::KeepAnchor);\n } else {\n move.movePosition(QTextCursor::StartOfBlock);\n move.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);\n }\n\n // get the text of the current block\n QString text = move.selectedText();\n\n move.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor);\n move.removeSelectedText();\n\n if (up) { // up key\n move.movePosition(QTextCursor::PreviousBlock);\n move.insertBlock();\n move.movePosition(QTextCursor::Left);\n } else { // down key\n move.movePosition(QTextCursor::EndOfBlock);\n if (move.atBlockStart()) { // empty block\n move.movePosition(QTextCursor::NextBlock);\n move.insertBlock();\n move.movePosition(QTextCursor::Left);\n } else {\n move.insertBlock();\n }\n }\n\n int start = move.position();\n move.clearSelection();\n move.insertText(text);\n int end = move.position();\n\n // reselect\n if (hasSelection) {\n move.setPosition(end);\n move.setPosition(start, QTextCursor::KeepAnchor);\n } else {\n move.setPosition(start);\n }\n\n move.endEditBlock();\n\n setTextCursor(move);\n}\n void setLineNumberEnabled(bool enabled) {\n _lineNumArea->setLineNumAreaEnabled(enabled);\n updateLineNumberAreaWidth(0);\n}\n protected:\n QTextCursor _textCursor;\n MarkdownHighlighter *_highlighter = nullptr;\n bool _highlightingEnabled;\n QStringList _ignoredClickUrlSchemata;\n QPlainTextEditSearchWidget *_searchWidget;\n QWidget *_searchFrame;\n AutoTextOptions _autoTextOptions;\n bool _mouseButtonDown = false;\n bool _centerCursor = false;\n bool _highlightCurrentLine = false;\n QColor _currentLineHighlightColor = QColor();\n uint _debounceDelay = 0;\n bool eventFilter(QObject *obj, QEvent *event) override {\n // qDebug() << event->type();\n if (event->type() == QEvent::HoverMove) {\n auto *mouseEvent = static_cast(event);\n\n QWidget *viewPort = this->viewport();\n // toggle cursor when control key has been pressed or released\n viewPort->setCursor(\n mouseEvent->modifiers().testFlag(Qt::ControlModifier)\n ? Qt::PointingHandCursor\n : Qt::IBeamCursor);\n } else if (event->type() == QEvent::KeyPress) {\n auto *keyEvent = static_cast(event);\n\n // set cursor to pointing hand if control key was pressed\n if (keyEvent->modifiers().testFlag(Qt::ControlModifier)) {\n QWidget *viewPort = this->viewport();\n viewPort->setCursor(Qt::PointingHandCursor);\n }\n\n // disallow keys if text edit hasn't focus\n if (!this->hasFocus()) {\n return true;\n }\n\n if ((keyEvent->key() == Qt::Key_Escape) && _searchWidget->isVisible()) {\n _searchWidget->deactivate();\n return true;\n } else if (keyEvent->key() == Qt::Key_Insert &&\n keyEvent->modifiers().testFlag(Qt::NoModifier)) {\n setOverwriteMode(!overwriteMode());\n\n // This solves a UI glitch if the visual cursor was not properly\n // updated when characters have different widths\n QTextCursor cursor = this->textCursor();\n cursor.movePosition(QTextCursor::Right);\n setTextCursor(cursor);\n cursor.movePosition(QTextCursor::Left);\n setTextCursor(cursor);\n\n return false;\n } else if ((keyEvent->key() == Qt::Key_Tab) ||\n (keyEvent->key() == Qt::Key_Backtab)) {\n // handle entered tab and reverse tab keys\n return handleTabEntered(keyEvent->key() == Qt::Key_Backtab);\n } else if ((keyEvent->key() == Qt::Key_F) &&\n keyEvent->modifiers().testFlag(Qt::ControlModifier)) {\n _searchWidget->activate();\n return true;\n } else if ((keyEvent->key() == Qt::Key_R) &&\n keyEvent->modifiers().testFlag(Qt::ControlModifier)) {\n _searchWidget->activateReplace();\n return true;\n // } else if (keyEvent->key() == Qt::Key_Delete) {\n } else if (keyEvent->key() == Qt::Key_Backspace) {\n return handleBackspaceEntered();\n } else if (keyEvent->key() == Qt::Key_Asterisk) {\n return handleBracketClosing(QLatin1Char('*'));\n } else if (keyEvent->key() == Qt::Key_QuoteDbl) {\n return quotationMarkCheck(QLatin1Char('\"'));\n // apostrophe bracket closing is temporary disabled because\n // apostrophes are used in different contexts\n // } else if (keyEvent->key() == Qt::Key_Apostrophe) {\n // return handleBracketClosing(\"'\");\n // underline bracket closing is temporary disabled because\n // underlines are used in different contexts\n // } else if (keyEvent->key() == Qt::Key_Underscore) {\n // return handleBracketClosing(\"_\");\n } else if (keyEvent->key() == Qt::Key_QuoteLeft) {\n return quotationMarkCheck(QLatin1Char('`'));\n } else if (keyEvent->key() == Qt::Key_AsciiTilde) {\n return handleBracketClosing(QLatin1Char('~'));\n#ifdef Q_OS_MAC\n } else if (keyEvent->modifiers().testFlag(Qt::AltModifier) &&\n keyEvent->key() == Qt::Key_ParenLeft) {\n // bracket closing for US keyboard on macOS\n return handleBracketClosing(QLatin1Char('{'), QLatin1Char('}'));\n#endif\n } else if (keyEvent->key() == Qt::Key_ParenLeft) {\n return handleBracketClosing(QLatin1Char('('), QLatin1Char(')'));\n } else if (keyEvent->key() == Qt::Key_BraceLeft) {\n return handleBracketClosing(QLatin1Char('{'), QLatin1Char('}'));\n } else if (keyEvent->key() == Qt::Key_BracketLeft) {\n return handleBracketClosing(QLatin1Char('['), QLatin1Char(']'));\n } else if (keyEvent->key() == Qt::Key_Less) {\n return handleBracketClosing(QLatin1Char('<'), QLatin1Char('>'));\n#ifdef Q_OS_MAC\n } else if (keyEvent->modifiers().testFlag(Qt::AltModifier) &&\n keyEvent->key() == Qt::Key_ParenRight) {\n // bracket closing for US keyboard on macOS\n return bracketClosingCheck(QLatin1Char('{'), QLatin1Char('}'));\n#endif\n } else if (keyEvent->key() == Qt::Key_ParenRight) {\n return bracketClosingCheck(QLatin1Char('('), QLatin1Char(')'));\n } else if (keyEvent->key() == Qt::Key_BraceRight) {\n return bracketClosingCheck(QLatin1Char('{'), QLatin1Char('}'));\n } else if (keyEvent->key() == Qt::Key_BracketRight) {\n return bracketClosingCheck(QLatin1Char('['), QLatin1Char(']'));\n } else if (keyEvent->key() == Qt::Key_Greater) {\n return bracketClosingCheck(QLatin1Char('<'), QLatin1Char('>'));\n } else if ((keyEvent->key() == Qt::Key_Return ||\n keyEvent->key() == Qt::Key_Enter) &&\n !isReadOnly() &&\n keyEvent->modifiers().testFlag(Qt::ShiftModifier)) {\n QTextCursor cursor = this->textCursor();\n cursor.insertText(\" \\n\");\n return true;\n } else if ((keyEvent->key() == Qt::Key_Return ||\n keyEvent->key() == Qt::Key_Enter) &&\n !isReadOnly() &&\n keyEvent->modifiers().testFlag(Qt::ControlModifier)) {\n QTextCursor cursor = this->textCursor();\n cursor.movePosition(QTextCursor::EndOfBlock);\n cursor.insertText(QStringLiteral(\"\\n\"));\n setTextCursor(cursor);\n return true;\n } else if (keyEvent == QKeySequence::Copy ||\n keyEvent == QKeySequence::Cut) {\n QTextCursor cursor = this->textCursor();\n if (!cursor.hasSelection()) {\n QString text;\n if (cursor.block().length() <= 1) // no content\n text = \"\\n\";\n else {\n // cursor.select(QTextCursor::BlockUnderCursor); //\n // negative, it will include the previous paragraph\n // separator\n cursor.movePosition(QTextCursor::StartOfBlock);\n cursor.movePosition(QTextCursor::EndOfBlock,\n QTextCursor::KeepAnchor);\n text = cursor.selectedText();\n if (!cursor.atEnd()) {\n text += \"\\n\";\n // this is the paragraph separator\n cursor.movePosition(QTextCursor::NextCharacter,\n QTextCursor::KeepAnchor, 1);\n }\n }\n if (keyEvent == QKeySequence::Cut) {\n if (!cursor.atEnd() && text == \"\\n\")\n cursor.deletePreviousChar();\n else\n cursor.removeSelectedText();\n cursor.movePosition(QTextCursor::StartOfBlock);\n setTextCursor(cursor);\n }\n qApp->clipboard()->setText(text);\n return true;\n }\n } else if ((keyEvent->key() == Qt::Key_Down) &&\n keyEvent->modifiers().testFlag(Qt::ControlModifier) &&\n keyEvent->modifiers().testFlag(Qt::AltModifier)) {\n // duplicate text with `Ctrl + Alt + Down`\n duplicateText();\n return true;\n#ifndef Q_OS_MAC\n } else if ((keyEvent->key() == Qt::Key_Down) &&\n keyEvent->modifiers().testFlag(Qt::ControlModifier) &&\n !keyEvent->modifiers().testFlag(Qt::ShiftModifier)) {\n // scroll the page down\n auto *scrollBar = verticalScrollBar();\n scrollBar->setSliderPosition(scrollBar->sliderPosition() + 1);\n return true;\n } else if ((keyEvent->key() == Qt::Key_Up) &&\n keyEvent->modifiers().testFlag(Qt::ControlModifier) &&\n !keyEvent->modifiers().testFlag(Qt::ShiftModifier)) {\n // scroll the page up\n auto *scrollBar = verticalScrollBar();\n scrollBar->setSliderPosition(scrollBar->sliderPosition() - 1);\n return true;\n#endif\n } else if ((keyEvent->key() == Qt::Key_Down) &&\n keyEvent->modifiers().testFlag(Qt::NoModifier)) {\n // if you are in the last line and press cursor down the cursor will\n // jump to the end of the line\n QTextCursor cursor = textCursor();\n if (cursor.position() >= document()->lastBlock().position()) {\n cursor.movePosition(QTextCursor::EndOfLine);\n\n // check if we are really in the last line, not only in\n // the last block\n if (cursor.atBlockEnd()) {\n setTextCursor(cursor);\n }\n }\n return QPlainTextEdit::eventFilter(obj, event);\n } else if ((keyEvent->key() == Qt::Key_Up) &&\n keyEvent->modifiers().testFlag(Qt::NoModifier)) {\n // if you are in the first line and press cursor up the cursor will\n // jump to the start of the line\n QTextCursor cursor = textCursor();\n QTextBlock block = document()->firstBlock();\n int endOfFirstLinePos = block.position() + block.length();\n\n if (cursor.position() <= endOfFirstLinePos) {\n cursor.movePosition(QTextCursor::StartOfLine);\n\n // check if we are really in the first line, not only in\n // the first block\n if (cursor.atBlockStart()) {\n setTextCursor(cursor);\n }\n }\n return QPlainTextEdit::eventFilter(obj, event);\n } else if (keyEvent->key() == Qt::Key_Return ||\n keyEvent->key() == Qt::Key_Enter) {\n return handleReturnEntered();\n } else if ((keyEvent->key() == Qt::Key_F3)) {\n _searchWidget->doSearch(\n !keyEvent->modifiers().testFlag(Qt::ShiftModifier));\n return true;\n } else if ((keyEvent->key() == Qt::Key_Z) &&\n (keyEvent->modifiers().testFlag(Qt::ControlModifier)) &&\n !(keyEvent->modifiers().testFlag(Qt::ShiftModifier))) {\n undo();\n return true;\n } else if ((keyEvent->key() == Qt::Key_Down) &&\n (keyEvent->modifiers().testFlag(Qt::ControlModifier)) &&\n (keyEvent->modifiers().testFlag(Qt::ShiftModifier))) {\n moveTextUpDown(false);\n return true;\n } else if ((keyEvent->key() == Qt::Key_Up) &&\n (keyEvent->modifiers().testFlag(Qt::ControlModifier)) &&\n (keyEvent->modifiers().testFlag(Qt::ShiftModifier))) {\n moveTextUpDown(true);\n return true;\n#ifdef Q_OS_MAC\n // https://github.com/pbek/QOwnNotes/issues/1593\n // https://github.com/pbek/QOwnNotes/issues/2643\n } else if (keyEvent->key() == Qt::Key_Home) {\n QTextCursor cursor = textCursor();\n // Meta is Control on macOS\n cursor.movePosition(\n keyEvent->modifiers().testFlag(Qt::MetaModifier)\n ? QTextCursor::Start\n : QTextCursor::StartOfLine,\n keyEvent->modifiers().testFlag(Qt::ShiftModifier)\n ? QTextCursor::KeepAnchor\n : QTextCursor::MoveAnchor);\n this->setTextCursor(cursor);\n return true;\n } else if (keyEvent->key() == Qt::Key_End) {\n QTextCursor cursor = textCursor();\n // Meta is Control on macOS\n cursor.movePosition(\n keyEvent->modifiers().testFlag(Qt::MetaModifier)\n ? QTextCursor::End\n : QTextCursor::EndOfLine,\n keyEvent->modifiers().testFlag(Qt::ShiftModifier)\n ? QTextCursor::KeepAnchor\n : QTextCursor::MoveAnchor);\n this->setTextCursor(cursor);\n return true;\n#endif\n }\n\n return QPlainTextEdit::eventFilter(obj, event);\n } else if (event->type() == QEvent::KeyRelease) {\n auto *keyEvent = static_cast(event);\n\n // reset cursor if control key was released\n if (keyEvent->key() == Qt::Key_Control) {\n resetMouseCursor();\n }\n\n return QPlainTextEdit::eventFilter(obj, event);\n } else if (event->type() == QEvent::MouseButtonRelease) {\n _mouseButtonDown = false;\n auto *mouseEvent = static_cast(event);\n\n // track `Ctrl + Click` in the text edit\n if ((obj == this->viewport()) &&\n (mouseEvent->button() == Qt::LeftButton) &&\n (QGuiApplication::keyboardModifiers() == Qt::ExtraButton24)) {\n // open the link (if any) at the current position\n // in the noteTextEdit\n openLinkAtCursorPosition();\n return true;\n }\n } else if (event->type() == QEvent::MouseButtonPress) {\n _mouseButtonDown = true;\n } else if (event->type() == QEvent::MouseButtonDblClick) {\n _mouseButtonDown = true;\n } else if (event->type() == QEvent::Wheel) {\n auto *wheel = dynamic_cast(event);\n\n // emit zoom signals\n if (wheel->modifiers() == Qt::ControlModifier) {\n if (wheel->angleDelta().y() > 0) {\n Q_EMIT zoomIn();\n } else {\n Q_EMIT zoomOut();\n }\n\n return true;\n }\n }\n\n return QPlainTextEdit::eventFilter(obj, event);\n}\n QMargins viewportMargins() {\n return QPlainTextEdit::viewportMargins();\n}\n bool increaseSelectedTextIndention(\n bool reverse,\n const QString &indentCharacters = QChar::fromLatin1('\\t')) {\n QTextCursor cursor = this->textCursor();\n QString selectedText = cursor.selectedText();\n\n if (!selectedText.isEmpty()) {\n // Start the selection at start of the first block of the selection\n int end = cursor.selectionEnd();\n cursor.setPosition(cursor.selectionStart());\n cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor);\n cursor.setPosition(end, QTextCursor::KeepAnchor);\n this->setTextCursor(cursor);\n selectedText = cursor.selectedText();\n\n // we need this strange newline character we are getting in the\n // selected text for newlines\n const QString newLine =\n QString::fromUtf8(QByteArray::fromHex(QByteArrayLiteral(\"e280a9\")));\n QString newText;\n\n if (reverse) {\n // un-indent text\n\n const int indentSize = indentCharacters == QStringLiteral(\"\\t\")\n ? 4\n : indentCharacters.length();\n\n // remove leading \\t or spaces in following lines\n newText = selectedText.replace(\n QRegularExpression(newLine + QStringLiteral(\"(\\\\t| {1,\") +\n QString::number(indentSize) +\n QStringLiteral(\"})\")),\n QStringLiteral(\"\\n\"));\n\n // remove leading \\t or spaces in first line\n newText.remove(QRegularExpression(QStringLiteral(\"^(\\\\t| {1,\") +\n QString::number(indentSize) +\n QStringLiteral(\"})\")));\n } else {\n // replace trailing new line to prevent an indent of the line after\n // the selection\n newText = selectedText.replace(\n QRegularExpression(QRegularExpression::escape(newLine) +\n QStringLiteral(\"$\")),\n QStringLiteral(\"\\n\"));\n\n // indent text\n newText.replace(newLine, QStringLiteral(\"\\n\") + indentCharacters)\n .prepend(indentCharacters);\n\n // remove trailing \\t\n static QRegularExpression regex1(QStringLiteral(\"\\\\t$\"));\n newText.remove(regex1);\n }\n\n // insert the new text\n cursor.insertText(newText);\n\n // update the selection to the new text\n cursor.setPosition(cursor.position() - newText.size(),\n QTextCursor::KeepAnchor);\n this->setTextCursor(cursor);\n\n return true;\n } else if (reverse) {\n const int indentSize = indentCharacters.length();\n\n // do the check as often as we have characters to un-indent\n for (int i = 1; i <= indentSize; i++) {\n // if nothing was selected but we want to reverse the indention\n // check if there is a \\t in front or after the cursor and remove it\n // if so\n const int position = cursor.position();\n\n if (!cursor.atStart()) {\n // get character in front of cursor\n cursor.setPosition(position - 1, QTextCursor::KeepAnchor);\n }\n\n // check for \\t or space in front of cursor\n static QRegularExpression regex1(QStringLiteral(\"[\\\\t ]\"));\n QRegularExpressionMatch match = regex1.match(cursor.selectedText());\n\n if (!match.hasMatch()) {\n // (select to) check for \\t or space after the cursor\n cursor.setPosition(position);\n\n if (!cursor.atEnd()) {\n cursor.setPosition(position + 1, QTextCursor::KeepAnchor);\n }\n }\n\n match = regex1.match(cursor.selectedText());\n\n if (match.hasMatch()) {\n cursor.removeSelectedText();\n }\n\n cursor = this->textCursor();\n }\n\n return true;\n }\n\n // else just insert indentCharacters\n cursor.insertText(indentCharacters);\n\n return true;\n}\n bool handleTabEntered(bool reverse, const QString &indentCharacters =\n QChar::fromLatin1('\\t')) {\n if (isReadOnly()) {\n return true;\n }\n\n QTextCursor cursor = this->textCursor();\n\n // only check for lists if we haven't a text selected\n if (cursor.selectedText().isEmpty()) {\n cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);\n const QString currentLineText = cursor.selectedText();\n\n // check if we want to indent or un-indent an ordered list\n // Valid listCharacters: '+ ', '-' , '* ', '+ [ ] ', '+ [x] ', '- [ ] ',\n // '- [x] ', '- [-] ', '* [ ] ', '* [x] '.\n static QRegularExpression regex1(\n R\"(^(\\s*)([+|\\-|\\*] \\[(x|-| )\\]|[+\\-\\*])(\\s+)$)\");\n QRegularExpressionMatchIterator i = regex1.globalMatch(currentLineText);\n\n if (i.hasNext()) {\n QRegularExpressionMatch match = i.next();\n QString whitespaces = match.captured(1);\n const QString listCharacter = match.captured(2);\n const QString whitespaceCharacter = match.captured(4);\n\n // add or remove one tabulator key\n if (reverse) {\n // remove one set of indentCharacters or a tabulator\n whitespaces.remove(QRegularExpression(\n QStringLiteral(\"^(\\\\t|\") +\n QRegularExpression::escape(indentCharacters) +\n QStringLiteral(\")\")));\n\n } else {\n whitespaces += indentCharacters;\n }\n\n cursor.insertText(whitespaces + listCharacter +\n whitespaceCharacter);\n return true;\n }\n\n // check if we want to indent or un-indent an ordered list\n static QRegularExpression regex2(R\"(^(\\s*)(\\d+)([\\.|\\)])(\\s+)$)\");\n i = regex2.globalMatch(currentLineText);\n\n if (i.hasNext()) {\n const QRegularExpressionMatch match = i.next();\n QString whitespaces = match.captured(1);\n const QString listCharacter = match.captured(2);\n const QString listMarker = match.captured(3);\n const QString whitespaceCharacter = match.captured(4);\n\n // add or remove one tabulator key\n if (reverse) {\n whitespaces.chop(1);\n } else {\n whitespaces += indentCharacters;\n }\n\n cursor.insertText(whitespaces + listCharacter + listMarker +\n whitespaceCharacter);\n return true;\n }\n }\n\n // check if we want to indent the whole text\n return increaseSelectedTextIndention(reverse, indentCharacters);\n}\n QMap parseMarkdownUrlsFromText(const QString &text) {\n QMap urlMap;\n QRegularExpressionMatchIterator iterator;\n\n // match urls like this: \n // re = QRegularExpression(\"(<(.+?:\\\\/\\\\/.+?)>)\");\n static QRegularExpression regex1(QStringLiteral(\"(<(.+?)>)\"));\n iterator = regex1.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString linkText = match.captured(1);\n QString url = match.captured(2);\n urlMap[linkText] = url;\n }\n\n // match urls like this: [this url](http://mylink)\n // QRegularExpression re(\"(\\\\[.*?\\\\]\\\\((.+?:\\\\/\\\\/.+?)\\\\))\");\n static QRegularExpression regex2(R\"((\\[.*?\\]\\((.+?)\\)))\");\n iterator = regex2.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString linkText = match.captured(1);\n QString url = match.captured(2);\n urlMap[linkText] = url;\n }\n\n // match urls like this: http://mylink\n static QRegularExpression regex3(R\"(\\b\\w+?:\\/\\/[^\\s]+[^\\s>\\)])\");\n iterator = regex3.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString url = match.captured(0);\n urlMap[url] = url;\n }\n\n // match urls like this: www.github.com\n static QRegularExpression regex4(R\"(\\bwww\\.[^\\s]+\\.[^\\s]+\\b)\");\n iterator = regex4.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString url = match.captured(0);\n urlMap[url] = QStringLiteral(\"http://\") + url;\n }\n\n // match reference urls like this: [this url][1] with this later:\n // [1]: http://domain\n static QRegularExpression regex5(R\"((\\[.*?\\]\\[(.+?)\\]))\");\n iterator = regex5.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString linkText = match.captured(1);\n QString referenceId = match.captured(2);\n\n // search for the referenced url in the whole text edit\n // QRegularExpression refRegExp(\n // \"\\\\[\" + QRegularExpression::escape(referenceId) +\n // \"\\\\]: (.+?:\\\\/\\\\/.+)\");\n QRegularExpression refRegExp(QStringLiteral(\"\\\\[\") +\n QRegularExpression::escape(referenceId) +\n QStringLiteral(\"\\\\]: (.+)\"));\n QRegularExpressionMatch urlMatch = refRegExp.match(toPlainText());\n\n if (urlMatch.hasMatch()) {\n QString url = urlMatch.captured(1);\n urlMap[linkText] = url;\n }\n }\n\n return urlMap;\n}\n bool handleReturnEntered() {\n if (isReadOnly()) {\n return true;\n }\n\n // This will be the main cursor to add or remove text\n QTextCursor cursor = this->textCursor();\n\n // We need a 2nd cursor to get the text of the current block without moving\n // the main cursor that is used to remove the selected text\n QTextCursor cursor2 = this->textCursor();\n cursor2.select(QTextCursor::BlockUnderCursor);\n const QString currentLineText = cursor2.selectedText().trimmed();\n\n const int position = cursor.position();\n const bool cursorAtBlockStart = cursor.atBlockStart();\n cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);\n const QString currentLinePartialText = cursor.selectedText();\n\n // if return is pressed and there is just an unordered list symbol then we\n // want to remove the list symbol Valid listCharacters: '+ ', '-' , '* ', '+\n // [ ] ', '+ [x] ', '- [ ] ', '- [-] ', '- [x] ', '* [ ] ', '* [x] '.\n static QRegularExpression regex1(\n R\"(^(\\s*)([+|\\-|\\*] \\[(x|-| |)\\]|[+\\-\\*])(\\s+)$)\");\n QRegularExpressionMatchIterator iterator =\n regex1.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n cursor.removeSelectedText();\n return true;\n }\n\n // if return is pressed and there is just an ordered list symbol then we\n // want to remove the list symbol\n static QRegularExpression regex2(R\"(^(\\s*)(\\d+[\\.|\\)])(\\s+)$)\");\n iterator = regex2.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n qDebug() << cursor.selectedText();\n cursor.removeSelectedText();\n return true;\n }\n\n // Check if we are in an unordered list.\n // We are in a list when we have '* ', '- ' or '+ ', possibly with preceding\n // whitespace. If e.g. user has entered '**text**' and pressed enter - we\n // don't want to do more list-stuff.\n QString currentLine = currentLinePartialText.trimmed();\n QChar char0;\n QChar char1;\n if (currentLine.length() >= 1) char0 = currentLine.at(0);\n if (currentLine.length() >= 2) char1 = currentLine.at(1);\n const bool inList =\n ((char0 == QLatin1Char('*') || char0 == QLatin1Char('-') ||\n char0 == QLatin1Char('+')) &&\n char1 == QLatin1Char(' '));\n\n if (inList) {\n // if the current line starts with a list character (possibly after\n // whitespaces) add the whitespaces at the next line too\n // Valid listCharacters: '+ ', '-' , '* ', '+ [ ] ', '+ [x] ', '- [ ] ',\n // '- [x] ', '- [-] ', '* [ ] ', '* [x] '.\n static QRegularExpression regex3(\n R\"(^(\\s*)([+|\\-|\\*] \\[(x|-| |)\\]|[+\\-\\*])(\\s+))\");\n iterator = regex3.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n const QString whitespaces = match.captured(1);\n QString listCharacter = match.captured(2);\n const QString whitespaceCharacter = match.captured(4);\n\n static QRegularExpression regex4(R\"(^([+|\\-|\\*]) \\[(x| |\\-|)\\])\");\n // start new checkbox list item with an unchecked checkbox\n iterator = regex4.globalMatch(listCharacter);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match1 = iterator.next();\n const QString realListCharacter = match1.captured(1);\n listCharacter = realListCharacter + QStringLiteral(\" [ ]\");\n }\n\n cursor.setPosition(position);\n cursor.insertText(\"\\n\" + whitespaces + listCharacter +\n whitespaceCharacter);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n }\n\n // check for ordered lists and increment the list number in the next line\n static QRegularExpression regex5(R\"(^(\\s*)(\\d+)([\\.|\\)])(\\s+))\");\n iterator = regex5.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n const QString whitespaces = match.captured(1);\n const uint listNumber = match.captured(2).toUInt();\n const QString listMarker = match.captured(3);\n const QString whitespaceCharacter = match.captured(4);\n\n cursor.setPosition(position);\n cursor.insertText(\"\\n\" + whitespaces + QString::number(listNumber + 1) +\n listMarker + whitespaceCharacter);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n\n // intent next line with same whitespaces as in current line\n static QRegularExpression regex6(R\"(^(\\s+))\");\n iterator = regex6.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n const QString whitespaces = match.captured(1);\n\n cursor.setPosition(position);\n cursor.insertText(\"\\n\" + whitespaces);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n\n // Add new list item above current line if we are at the start the line of a\n // list item\n if (cursorAtBlockStart) {\n static QRegularExpression regex7(\n R\"(^([+|\\-|\\*] \\[(x|-| |)\\]|[+\\-\\*])(\\s+))\");\n iterator = regex7.globalMatch(currentLineText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n QString listCharacter = match.captured(1);\n const QString whitespaceCharacter = match.captured(3);\n\n static QRegularExpression regex8(R\"(^([+|\\-|\\*]) \\[(x| |\\-|)\\])\");\n // start new checkbox list item with an unchecked checkbox\n iterator = regex8.globalMatch(listCharacter);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match1 = iterator.next();\n const QString realListCharacter = match1.captured(1);\n listCharacter = realListCharacter + QStringLiteral(\" [ ]\");\n }\n\n cursor.setPosition(position);\n // Enter new list item above current line\n cursor.insertText(listCharacter + whitespaceCharacter + \"\\n\");\n // Move the cursor at the end of the new list item\n cursor.movePosition(QTextCursor::Left);\n setTextCursor(cursor);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n }\n\n return false;\n}\n bool handleBracketClosing(const QChar openingCharacter,\n QChar closingCharacter = QChar()) {\n // check if bracket closing or read-only are enabled\n if (!(_autoTextOptions & AutoTextOption::BracketClosing) || isReadOnly()) {\n return false;\n }\n\n QTextCursor cursor = textCursor();\n\n if (closingCharacter.isNull()) {\n closingCharacter = openingCharacter;\n }\n\n const QString selectedText = cursor.selectedText();\n\n // When user currently has text selected, we prepend the openingCharacter\n // and append the closingCharacter. E.g. 'text' -> '(text)'. We keep the\n // current selectedText selected.\n if (!selectedText.isEmpty()) {\n // Insert. The selectedText is overwritten.\n const QString newText =\n openingCharacter + selectedText + closingCharacter;\n cursor.insertText(newText);\n\n // Re-select the selectedText.\n const int selectionEnd = cursor.position() - 1;\n const int selectionStart = selectionEnd - selectedText.length();\n\n cursor.setPosition(selectionStart);\n cursor.setPosition(selectionEnd, QTextCursor::KeepAnchor);\n this->setTextCursor(cursor);\n _handleBracketClosingUsed = true;\n return true;\n }\n\n // get the current text from the block (inserted character not included)\n // Remove whitespace at start of string (e.g. in multilevel-lists).\n static QRegularExpression regex1(\"^\\\\s+\");\n const QString text = cursor.block().text().remove(regex1);\n\n const int pib = cursor.positionInBlock();\n bool isPreviousAsterisk =\n pib > 0 && pib < text.length() && text.at(pib - 1) == '*';\n bool isNextAsterisk = pib < text.length() && text.at(pib) == '*';\n bool isMaybeBold = isPreviousAsterisk && isNextAsterisk;\n if (pib < text.length() && !isMaybeBold && !text.at(pib).isSpace()) {\n return false;\n }\n\n // Default positions to move the cursor back.\n int cursorSubtract = 1;\n // Special handling for `*` opening character, as this could be:\n // - start of a list (or sublist);\n // - start of a bold text;\n if (openingCharacter == QLatin1Char('*')) {\n // don't auto complete in code block\n bool isInCode =\n MarkdownHighlighter::isCodeBlock(cursor.block().userState());\n // we only do auto completion if there is a space before the cursor pos\n bool hasSpaceOrAsteriskBefore = !text.isEmpty() && pib > 0 &&\n (text.at(pib - 1).isSpace() ||\n text.at(pib - 1) == QLatin1Char('*'));\n // This could be the start of a list, don't autocomplete.\n bool isEmpty = text.isEmpty();\n\n if (isInCode || !hasSpaceOrAsteriskBefore || isEmpty) {\n return false;\n }\n\n // bold\n if (isPreviousAsterisk && isNextAsterisk) {\n cursorSubtract = 1;\n }\n\n // User wants: '**'.\n // Not the start of a list, probably bold text. We autocomplete with\n // extra closingCharacter and cursorSubtract to 'catchup'.\n if (text == QLatin1String(\"*\")) {\n cursor.insertText(QStringLiteral(\"*\"));\n cursorSubtract = 2;\n }\n }\n\n // Auto-completion for ``` pair\n if (openingCharacter == QLatin1Char('`')) {\n#if QT_VERSION < QT_VERSION_CHECK(5, 12, 0)\n if (QRegExp(QStringLiteral(\"[^`]*``\")).exactMatch(text)) {\n#else\n if (QRegularExpression(\n QRegularExpression::anchoredPattern(QStringLiteral(\"[^`]*``\")))\n .match(text)\n .hasMatch()) {\n#endif\n cursor.insertText(QStringLiteral(\"``\"));\n cursorSubtract = 3;\n }\n }\n\n // don't auto complete in code block\n if (openingCharacter == QLatin1Char('<') &&\n MarkdownHighlighter::isCodeBlock(cursor.block().userState())) {\n return false;\n }\n\n cursor.beginEditBlock();\n cursor.insertText(openingCharacter);\n cursor.insertText(closingCharacter);\n cursor.setPosition(cursor.position() - cursorSubtract);\n cursor.endEditBlock();\n\n setTextCursor(cursor);\n return true;\n}\n\n/**\n * Checks if the closing character should be output or not\n *\n * @param openingCharacter\n * @param closingCharacter\n * @return\n */\nbool QMarkdownTextEdit::bracketClosingCheck(const QChar openingCharacter,\n QChar closingCharacter) {\n // check if bracket closing or read-only are enabled\n if (!(_autoTextOptions & AutoTextOption::BracketClosing) || isReadOnly()) {\n return false;\n }\n\n if (closingCharacter.isNull()) {\n closingCharacter = openingCharacter;\n }\n\n QTextCursor cursor = textCursor();\n const int positionInBlock = cursor.positionInBlock();\n\n // get the current text from the block\n const QString text = cursor.block().text();\n const int textLength = text.length();\n\n // if we are at the end of the line we just want to enter the character\n if (positionInBlock >= textLength) {\n return false;\n }\n\n const QChar currentChar = text.at(positionInBlock);\n\n // if (closingCharacter == openingCharacter) {\n\n // }\n\n qDebug() << __func__ << \" - 'currentChar': \" << currentChar;\n\n // if the current character is not the closing character we just want to\n // enter the character\n if (currentChar != closingCharacter) {\n return false;\n }\n\n const QString leftText = text.left(positionInBlock);\n const int openingCharacterCount = leftText.count(openingCharacter);\n const int closingCharacterCount = leftText.count(closingCharacter);\n\n // if there were enough opening characters just enter the character\n if (openingCharacterCount < (closingCharacterCount + 1)) {\n return false;\n }\n\n // move the cursor to the right and don't enter the character\n cursor.movePosition(QTextCursor::Right);\n setTextCursor(cursor);\n return true;\n}\n\n/**\n * Checks if the closing character should be output or not or if a closing\n * character after an opening character if needed\n *\n * @param quotationCharacter\n * @return\n */\nbool QMarkdownTextEdit::quotationMarkCheck(const QChar quotationCharacter) {\n // check if bracket closing or read-only are enabled\n if (!(_autoTextOptions & AutoTextOption::BracketClosing) || isReadOnly()) {\n return false;\n }\n\n QTextCursor cursor = textCursor();\n const int positionInBlock = cursor.positionInBlock();\n\n // get the current text from the block\n const QString text = cursor.block().text();\n const int textLength = text.length();\n\n // if last char is not space, we are at word end, no autocompletion\n const bool isBacktick = quotationCharacter == '`';\n if (!isBacktick && positionInBlock != 0 &&\n !text.at(positionInBlock - 1).isSpace()) {\n return false;\n }\n\n // if we are at the end of the line we just want to enter the character\n if (positionInBlock >= textLength) {\n return handleBracketClosing(quotationCharacter);\n }\n\n const QChar currentChar = text.at(positionInBlock);\n\n // if the current character is not the quotation character we just want to\n // enter the character\n if (currentChar != quotationCharacter) {\n return handleBracketClosing(quotationCharacter);\n }\n\n // move the cursor to the right and don't enter the character\n cursor.movePosition(QTextCursor::Right);\n setTextCursor(cursor);\n return true;\n}\n\n/***********************************\n * helper methods for char removal\n * Rules for (') and (\"):\n * if [sp]\" -> opener (sp = space)\n * if \"[sp] -> closer\n ***********************************/\nbool isQuotOpener(int position, const QString &text) {\n if (position == 0) return true;\n const int prevCharPos = position - 1;\n return text.at(prevCharPos).isSpace();\n}\nbool isQuotCloser(int position, const QString &text) {\n const int nextCharPos = position + 1;\n if (nextCharPos >= text.length()) return true;\n return text.at(nextCharPos).isSpace();\n}\n\n/**\n * Handles removing of matching brackets and other Markdown characters\n * Only works with backspace to remove text\n *\n * @return\n */\nbool QMarkdownTextEdit::handleBackspaceEntered() {\n if (!(_autoTextOptions & AutoTextOption::BracketRemoval) || isReadOnly()) {\n return false;\n }\n\n QTextCursor cursor = textCursor();\n\n // return if some text was selected\n if (!cursor.selectedText().isEmpty()) {\n return false;\n }\n\n int position = cursor.position();\n const int positionInBlock = cursor.positionInBlock();\n int block = cursor.block().blockNumber();\n\n if (_highlighter)\n if (_highlighter->isPosInACodeSpan(block, positionInBlock - 1))\n return false;\n\n // return if backspace was pressed at the beginning of a block\n if (positionInBlock == 0) {\n return false;\n }\n\n // get the current text from the block\n const QString text = cursor.block().text();\n\n char charToRemove{};\n\n // current char\n const char charInFront = text.at(positionInBlock - 1).toLatin1();\n\n if (charInFront == '*')\n return handleCharRemoval(MarkdownHighlighter::RangeType::Emphasis,\n block, positionInBlock - 1);\n else if (charInFront == '`')\n return handleCharRemoval(MarkdownHighlighter::RangeType::CodeSpan,\n block, positionInBlock - 1);\n\n // handle removal of \", ', and brackets\n\n // is it opener?\n int pos = _openingCharacters.indexOf(charInFront);\n // for \" and '\n bool isOpener = false;\n bool isCloser = false;\n if (pos == 5 || pos == 6) {\n isOpener = isQuotOpener(positionInBlock - 1, text);\n } else {\n isOpener = pos != -1;\n }\n if (isOpener) {\n charToRemove = _closingCharacters.at(pos);\n } else {\n // is it closer?\n pos = _closingCharacters.indexOf(charInFront);\n if (pos == 5 || pos == 6)\n isCloser = isQuotCloser(positionInBlock - 1, text);\n else\n isCloser = pos != -1;\n if (isCloser)\n charToRemove = _openingCharacters.at(pos);\n else\n return false;\n }\n\n int charToRemoveIndex = -1;\n if (isOpener) {\n bool closer = true;\n charToRemoveIndex = text.indexOf(charToRemove, positionInBlock);\n if (charToRemoveIndex == -1) return false;\n if (pos == 5 || pos == 6)\n closer = isQuotCloser(charToRemoveIndex, text);\n if (!closer) return false;\n cursor.setPosition(position + (charToRemoveIndex - positionInBlock));\n cursor.deleteChar();\n } else if (isCloser) {\n charToRemoveIndex = text.lastIndexOf(charToRemove, positionInBlock - 2);\n if (charToRemoveIndex == -1) return false;\n bool opener = true;\n if (pos == 5 || pos == 6)\n opener = isQuotOpener(charToRemoveIndex, text);\n if (!opener) return false;\n const int pos = position - (positionInBlock - charToRemoveIndex);\n cursor.setPosition(pos);\n cursor.deleteChar();\n position -= 1;\n } else {\n charToRemoveIndex = text.lastIndexOf(charToRemove, positionInBlock - 2);\n if (charToRemoveIndex == -1) return false;\n const int pos = position - (positionInBlock - charToRemoveIndex);\n cursor.setPosition(pos);\n cursor.deleteChar();\n position -= 1;\n }\n\n // moving the cursor back to the old position so the previous character\n // can be removed\n cursor.setPosition(position);\n setTextCursor(cursor);\n return false;\n}\n\nbool QMarkdownTextEdit::handleCharRemoval(MarkdownHighlighter::RangeType type,\n int block, int position) {\n if (!_highlighter) return false;\n\n auto range = _highlighter->findPositionInRanges(type, block, position);\n if (range == QPair{-1, -1}) return false;\n\n int charToRemovePos = range.first;\n if (position == range.first) charToRemovePos = range.second;\n\n QTextCursor cursor = textCursor();\n auto gpos = cursor.position();\n\n if (charToRemovePos > position) {\n cursor.setPosition(gpos + (charToRemovePos - (position + 1)));\n } else {\n cursor.setPosition(gpos - (position - charToRemovePos + 1));\n gpos--;\n }\n\n cursor.deleteChar();\n cursor.setPosition(gpos);\n setTextCursor(cursor);\n return false;\n}\n\nvoid QMarkdownTextEdit::updateLineNumAreaGeometry() {\n const auto contentsRect = this->contentsRect();\n const QRect newGeometry = {contentsRect.left(), contentsRect.top(),\n _lineNumArea->sizeHint().width(),\n contentsRect.height()};\n auto oldGeometry = _lineNumArea->geometry();\n if (newGeometry != oldGeometry) {\n _lineNumArea->setGeometry(newGeometry);\n }\n}\n\nvoid QMarkdownTextEdit::resizeEvent(QResizeEvent *event) {\n QPlainTextEdit::resizeEvent(event);\n updateLineNumAreaGeometry();\n}\n\n/**\n * Increases (or decreases) the indention of the selected text\n * (if there is a text selected) in the noteTextEdit\n * @return\n */\nbool QMarkdownTextEdit::increaseSelectedTextIndention(\n bool reverse, const QString &indentCharacters) {\n QTextCursor cursor = this->textCursor();\n QString selectedText = cursor.selectedText();\n\n if (!selectedText.isEmpty()) {\n // Start the selection at start of the first block of the selection\n int end = cursor.selectionEnd();\n cursor.setPosition(cursor.selectionStart());\n cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor);\n cursor.setPosition(end, QTextCursor::KeepAnchor);\n this->setTextCursor(cursor);\n selectedText = cursor.selectedText();\n\n // we need this strange newline character we are getting in the\n // selected text for newlines\n const QString newLine =\n QString::fromUtf8(QByteArray::fromHex(QByteArrayLiteral(\"e280a9\")));\n QString newText;\n\n if (reverse) {\n // un-indent text\n\n const int indentSize = indentCharacters == QStringLiteral(\"\\t\")\n ? 4\n : indentCharacters.length();\n\n // remove leading \\t or spaces in following lines\n newText = selectedText.replace(\n QRegularExpression(newLine + QStringLiteral(\"(\\\\t| {1,\") +\n QString::number(indentSize) +\n QStringLiteral(\"})\")),\n QStringLiteral(\"\\n\"));\n\n // remove leading \\t or spaces in first line\n newText.remove(QRegularExpression(QStringLiteral(\"^(\\\\t| {1,\") +\n QString::number(indentSize) +\n QStringLiteral(\"})\")));\n } else {\n // replace trailing new line to prevent an indent of the line after\n // the selection\n newText = selectedText.replace(\n QRegularExpression(QRegularExpression::escape(newLine) +\n QStringLiteral(\"$\")),\n QStringLiteral(\"\\n\"));\n\n // indent text\n newText.replace(newLine, QStringLiteral(\"\\n\") + indentCharacters)\n .prepend(indentCharacters);\n\n // remove trailing \\t\n static QRegularExpression regex1(QStringLiteral(\"\\\\t$\"));\n newText.remove(regex1);\n }\n\n // insert the new text\n cursor.insertText(newText);\n\n // update the selection to the new text\n cursor.setPosition(cursor.position() - newText.size(),\n QTextCursor::KeepAnchor);\n this->setTextCursor(cursor);\n\n return true;\n } else if (reverse) {\n const int indentSize = indentCharacters.length();\n\n // do the check as often as we have characters to un-indent\n for (int i = 1; i <= indentSize; i++) {\n // if nothing was selected but we want to reverse the indention\n // check if there is a \\t in front or after the cursor and remove it\n // if so\n const int position = cursor.position();\n\n if (!cursor.atStart()) {\n // get character in front of cursor\n cursor.setPosition(position - 1, QTextCursor::KeepAnchor);\n }\n\n // check for \\t or space in front of cursor\n static QRegularExpression regex1(QStringLiteral(\"[\\\\t ]\"));\n QRegularExpressionMatch match = regex1.match(cursor.selectedText());\n\n if (!match.hasMatch()) {\n // (select to) check for \\t or space after the cursor\n cursor.setPosition(position);\n\n if (!cursor.atEnd()) {\n cursor.setPosition(position + 1, QTextCursor::KeepAnchor);\n }\n }\n\n match = regex1.match(cursor.selectedText());\n\n if (match.hasMatch()) {\n cursor.removeSelectedText();\n }\n\n cursor = this->textCursor();\n }\n\n return true;\n }\n\n // else just insert indentCharacters\n cursor.insertText(indentCharacters);\n\n return true;\n}\n\n/**\n * @brief Opens the link (if any) at the current cursor position\n */\nbool QMarkdownTextEdit::openLinkAtCursorPosition() {\n QTextCursor cursor = this->textCursor();\n const int clickedPosition = cursor.position();\n\n // select the text in the clicked block and find out on\n // which position we clicked\n cursor.movePosition(QTextCursor::StartOfBlock);\n const int positionFromStart = clickedPosition - cursor.position();\n cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);\n\n const QString selectedText = cursor.selectedText();\n\n // find out which url in the selected text was clicked\n const QString urlString =\n getMarkdownUrlAtPosition(selectedText, positionFromStart);\n const QUrl url = QUrl(urlString);\n const bool isRelativeFileUrl =\n urlString.startsWith(QLatin1String(\"file://..\"));\n const bool isLegacyAttachmentUrl =\n urlString.startsWith(QLatin1String(\"file://attachments\"));\n\n qDebug() << __func__ << \" - 'emit urlClicked( urlString )': \" << urlString;\n\n Q_EMIT urlClicked(urlString);\n\n if ((url.isValid() && isValidUrl(urlString)) || isRelativeFileUrl ||\n isLegacyAttachmentUrl) {\n // ignore some schemata\n if (!(_ignoredClickUrlSchemata.contains(url.scheme()) ||\n isRelativeFileUrl || isLegacyAttachmentUrl)) {\n // open the url\n openUrl(urlString);\n }\n\n return true;\n }\n\n return false;\n}\n\n/**\n * Checks if urlString is a valid url\n *\n * @param urlString\n * @return\n */\nbool QMarkdownTextEdit::isValidUrl(const QString &urlString) {\n static QRegularExpression regex(R\"(^\\w+:\\/\\/.+)\");\n const QRegularExpressionMatch match = regex.match(urlString);\n return match.hasMatch();\n}\n\n/**\n * Handles clicked urls\n *\n * examples:\n * - opens the webpage\n * - opens the file\n * \"/path/to/my/file/QOwnNotes.pdf\" if the operating system supports that\n * handler\n */\nvoid QMarkdownTextEdit::openUrl(const QString &urlString) {\n qDebug() << \"QMarkdownTextEdit \" << __func__\n << \" - 'urlString': \" << urlString;\n\n QDesktopServices::openUrl(QUrl(urlString));\n}\n\n/**\n * @brief Returns the highlighter instance\n * @return\n */\nMarkdownHighlighter *QMarkdownTextEdit::highlighter() { return _highlighter; }\n\n/**\n * @brief Returns the searchWidget instance\n * @return\n */\nQPlainTextEditSearchWidget *QMarkdownTextEdit::searchWidget() {\n return _searchWidget;\n}\n\n/**\n * @brief Sets url schemata that will be ignored when clicked on\n * @param urlSchemes\n */\nvoid QMarkdownTextEdit::setIgnoredClickUrlSchemata(\n QStringList ignoredUrlSchemata) {\n _ignoredClickUrlSchemata = std::move(ignoredUrlSchemata);\n}\n\n/**\n * @brief Returns a map of parsed Markdown urls with their link texts as key\n *\n * @param text\n * @return parsed urls\n */\nQMap QMarkdownTextEdit::parseMarkdownUrlsFromText(\n const QString &text) {\n QMap urlMap;\n QRegularExpressionMatchIterator iterator;\n\n // match urls like this: \n // re = QRegularExpression(\"(<(.+?:\\\\/\\\\/.+?)>)\");\n static QRegularExpression regex1(QStringLiteral(\"(<(.+?)>)\"));\n iterator = regex1.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString linkText = match.captured(1);\n QString url = match.captured(2);\n urlMap[linkText] = url;\n }\n\n // match urls like this: [this url](http://mylink)\n // QRegularExpression re(\"(\\\\[.*?\\\\]\\\\((.+?:\\\\/\\\\/.+?)\\\\))\");\n static QRegularExpression regex2(R\"((\\[.*?\\]\\((.+?)\\)))\");\n iterator = regex2.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString linkText = match.captured(1);\n QString url = match.captured(2);\n urlMap[linkText] = url;\n }\n\n // match urls like this: http://mylink\n static QRegularExpression regex3(R\"(\\b\\w+?:\\/\\/[^\\s]+[^\\s>\\)])\");\n iterator = regex3.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString url = match.captured(0);\n urlMap[url] = url;\n }\n\n // match urls like this: www.github.com\n static QRegularExpression regex4(R\"(\\bwww\\.[^\\s]+\\.[^\\s]+\\b)\");\n iterator = regex4.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString url = match.captured(0);\n urlMap[url] = QStringLiteral(\"http://\") + url;\n }\n\n // match reference urls like this: [this url][1] with this later:\n // [1]: http://domain\n static QRegularExpression regex5(R\"((\\[.*?\\]\\[(.+?)\\]))\");\n iterator = regex5.globalMatch(text);\n while (iterator.hasNext()) {\n QRegularExpressionMatch match = iterator.next();\n QString linkText = match.captured(1);\n QString referenceId = match.captured(2);\n\n // search for the referenced url in the whole text edit\n // QRegularExpression refRegExp(\n // \"\\\\[\" + QRegularExpression::escape(referenceId) +\n // \"\\\\]: (.+?:\\\\/\\\\/.+)\");\n QRegularExpression refRegExp(QStringLiteral(\"\\\\[\") +\n QRegularExpression::escape(referenceId) +\n QStringLiteral(\"\\\\]: (.+)\"));\n QRegularExpressionMatch urlMatch = refRegExp.match(toPlainText());\n\n if (urlMatch.hasMatch()) {\n QString url = urlMatch.captured(1);\n urlMap[linkText] = url;\n }\n }\n\n return urlMap;\n}\n\n/**\n * @brief Returns the Markdown url at position\n * @param text\n * @param position\n * @return url string\n */\nQString QMarkdownTextEdit::getMarkdownUrlAtPosition(const QString &text,\n int position) {\n QString url;\n\n // get a map of parsed Markdown urls with their link texts as key\n const QMap urlMap = parseMarkdownUrlsFromText(text);\n QMap::const_iterator i = urlMap.constBegin();\n for (; i != urlMap.constEnd(); ++i) {\n const QString &linkText = i.key();\n const QString &urlString = i.value();\n\n const int foundPositionStart = text.indexOf(linkText);\n\n if (foundPositionStart >= 0) {\n // calculate end position of found linkText\n const int foundPositionEnd = foundPositionStart + linkText.size();\n\n // check if position is in found string range\n if ((position >= foundPositionStart) &&\n (position <= foundPositionEnd)) {\n url = urlString;\n break;\n }\n }\n }\n\n return url;\n}\n\n/**\n * @brief Duplicates the text in the text edit\n */\nvoid QMarkdownTextEdit::duplicateText() {\n if (isReadOnly()) {\n return;\n }\n\n QTextCursor cursor = this->textCursor();\n QString selectedText = cursor.selectedText();\n\n // duplicate line if no text was selected\n if (selectedText.isEmpty()) {\n const int position = cursor.position();\n\n // select the whole line\n cursor.movePosition(QTextCursor::StartOfBlock);\n cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);\n\n const int positionDiff = cursor.position() - position;\n selectedText = \"\\n\" + cursor.selectedText();\n\n // insert text with new line at end of the selected line\n cursor.setPosition(cursor.selectionEnd());\n cursor.insertText(selectedText);\n\n // set the position to same position it was in the duplicated line\n cursor.setPosition(cursor.position() - positionDiff);\n } else {\n // duplicate selected text\n cursor.setPosition(cursor.selectionEnd());\n const int selectionStart = cursor.position();\n\n // insert selected text\n cursor.insertText(selectedText);\n const int selectionEnd = cursor.position();\n\n // select the inserted text\n cursor.setPosition(selectionStart);\n cursor.setPosition(selectionEnd, QTextCursor::KeepAnchor);\n }\n\n this->setTextCursor(cursor);\n}\n\nvoid QMarkdownTextEdit::setText(const QString &text) { setPlainText(text); }\n\nvoid QMarkdownTextEdit::setPlainText(const QString &text) {\n // clear the dirty blocks vector to increase performance and prevent\n // a possible crash in QSyntaxHighlighter::rehighlightBlock\n if (_highlighter) _highlighter->clearDirtyBlocks();\n\n QPlainTextEdit::setPlainText(text);\n adjustRightMargin();\n}\n\n/**\n * Uses another widget as parent for the search widget\n */\nvoid QMarkdownTextEdit::initSearchFrame(QWidget *searchFrame, bool darkMode) {\n _searchFrame = searchFrame;\n\n // remove the search widget from our layout\n layout()->removeWidget(_searchWidget);\n\n QLayout *layout = _searchFrame->layout();\n\n // create a grid layout for the frame and add the search widget to it\n if (layout == nullptr) {\n layout = new QVBoxLayout(_searchFrame);\n layout->setSpacing(0);\n layout->setContentsMargins(0, 0, 0, 0);\n }\n\n _searchWidget->setDarkMode(darkMode);\n layout->addWidget(_searchWidget);\n _searchFrame->setLayout(layout);\n}\n\n/**\n * Hides the text edit and the search widget\n */\nvoid QMarkdownTextEdit::hide() {\n _searchWidget->hide();\n QWidget::hide();\n}\n\n/**\n * Handles an entered return key\n */\nbool QMarkdownTextEdit::handleReturnEntered() {\n if (isReadOnly()) {\n return true;\n }\n\n // This will be the main cursor to add or remove text\n QTextCursor cursor = this->textCursor();\n\n // We need a 2nd cursor to get the text of the current block without moving\n // the main cursor that is used to remove the selected text\n QTextCursor cursor2 = this->textCursor();\n cursor2.select(QTextCursor::BlockUnderCursor);\n const QString currentLineText = cursor2.selectedText().trimmed();\n\n const int position = cursor.position();\n const bool cursorAtBlockStart = cursor.atBlockStart();\n cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);\n const QString currentLinePartialText = cursor.selectedText();\n\n // if return is pressed and there is just an unordered list symbol then we\n // want to remove the list symbol Valid listCharacters: '+ ', '-' , '* ', '+\n // [ ] ', '+ [x] ', '- [ ] ', '- [-] ', '- [x] ', '* [ ] ', '* [x] '.\n static QRegularExpression regex1(\n R\"(^(\\s*)([+|\\-|\\*] \\[(x|-| |)\\]|[+\\-\\*])(\\s+)$)\");\n QRegularExpressionMatchIterator iterator =\n regex1.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n cursor.removeSelectedText();\n return true;\n }\n\n // if return is pressed and there is just an ordered list symbol then we\n // want to remove the list symbol\n static QRegularExpression regex2(R\"(^(\\s*)(\\d+[\\.|\\)])(\\s+)$)\");\n iterator = regex2.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n qDebug() << cursor.selectedText();\n cursor.removeSelectedText();\n return true;\n }\n\n // Check if we are in an unordered list.\n // We are in a list when we have '* ', '- ' or '+ ', possibly with preceding\n // whitespace. If e.g. user has entered '**text**' and pressed enter - we\n // don't want to do more list-stuff.\n QString currentLine = currentLinePartialText.trimmed();\n QChar char0;\n QChar char1;\n if (currentLine.length() >= 1) char0 = currentLine.at(0);\n if (currentLine.length() >= 2) char1 = currentLine.at(1);\n const bool inList =\n ((char0 == QLatin1Char('*') || char0 == QLatin1Char('-') ||\n char0 == QLatin1Char('+')) &&\n char1 == QLatin1Char(' '));\n\n if (inList) {\n // if the current line starts with a list character (possibly after\n // whitespaces) add the whitespaces at the next line too\n // Valid listCharacters: '+ ', '-' , '* ', '+ [ ] ', '+ [x] ', '- [ ] ',\n // '- [x] ', '- [-] ', '* [ ] ', '* [x] '.\n static QRegularExpression regex3(\n R\"(^(\\s*)([+|\\-|\\*] \\[(x|-| |)\\]|[+\\-\\*])(\\s+))\");\n iterator = regex3.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n const QString whitespaces = match.captured(1);\n QString listCharacter = match.captured(2);\n const QString whitespaceCharacter = match.captured(4);\n\n static QRegularExpression regex4(R\"(^([+|\\-|\\*]) \\[(x| |\\-|)\\])\");\n // start new checkbox list item with an unchecked checkbox\n iterator = regex4.globalMatch(listCharacter);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match1 = iterator.next();\n const QString realListCharacter = match1.captured(1);\n listCharacter = realListCharacter + QStringLiteral(\" [ ]\");\n }\n\n cursor.setPosition(position);\n cursor.insertText(\"\\n\" + whitespaces + listCharacter +\n whitespaceCharacter);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n }\n\n // check for ordered lists and increment the list number in the next line\n static QRegularExpression regex5(R\"(^(\\s*)(\\d+)([\\.|\\)])(\\s+))\");\n iterator = regex5.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n const QString whitespaces = match.captured(1);\n const uint listNumber = match.captured(2).toUInt();\n const QString listMarker = match.captured(3);\n const QString whitespaceCharacter = match.captured(4);\n\n cursor.setPosition(position);\n cursor.insertText(\"\\n\" + whitespaces + QString::number(listNumber + 1) +\n listMarker + whitespaceCharacter);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n\n // intent next line with same whitespaces as in current line\n static QRegularExpression regex6(R\"(^(\\s+))\");\n iterator = regex6.globalMatch(currentLinePartialText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n const QString whitespaces = match.captured(1);\n\n cursor.setPosition(position);\n cursor.insertText(\"\\n\" + whitespaces);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n\n // Add new list item above current line if we are at the start the line of a\n // list item\n if (cursorAtBlockStart) {\n static QRegularExpression regex7(\n R\"(^([+|\\-|\\*] \\[(x|-| |)\\]|[+\\-\\*])(\\s+))\");\n iterator = regex7.globalMatch(currentLineText);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match = iterator.next();\n QString listCharacter = match.captured(1);\n const QString whitespaceCharacter = match.captured(3);\n\n static QRegularExpression regex8(R\"(^([+|\\-|\\*]) \\[(x| |\\-|)\\])\");\n // start new checkbox list item with an unchecked checkbox\n iterator = regex8.globalMatch(listCharacter);\n if (iterator.hasNext()) {\n const QRegularExpressionMatch match1 = iterator.next();\n const QString realListCharacter = match1.captured(1);\n listCharacter = realListCharacter + QStringLiteral(\" [ ]\");\n }\n\n cursor.setPosition(position);\n // Enter new list item above current line\n cursor.insertText(listCharacter + whitespaceCharacter + \"\\n\");\n // Move the cursor at the end of the new list item\n cursor.movePosition(QTextCursor::Left);\n setTextCursor(cursor);\n\n // scroll to the cursor if we are at the bottom of the document\n ensureCursorVisible();\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Handles entered tab or reverse tab keys\n */\nbool QMarkdownTextEdit::handleTabEntered(bool reverse,\n const QString &indentCharacters) {\n if (isReadOnly()) {\n return true;\n }\n\n QTextCursor cursor = this->textCursor();\n\n // only check for lists if we haven't a text selected\n if (cursor.selectedText().isEmpty()) {\n cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);\n const QString currentLineText = cursor.selectedText();\n\n // check if we want to indent or un-indent an ordered list\n // Valid listCharacters: '+ ', '-' , '* ', '+ [ ] ', '+ [x] ', '- [ ] ',\n // '- [x] ', '- [-] ', '* [ ] ', '* [x] '.\n static QRegularExpression regex1(\n R\"(^(\\s*)([+|\\-|\\*] \\[(x|-| )\\]|[+\\-\\*])(\\s+)$)\");\n QRegularExpressionMatchIterator i = regex1.globalMatch(currentLineText);\n\n if (i.hasNext()) {\n QRegularExpressionMatch match = i.next();\n QString whitespaces = match.captured(1);\n const QString listCharacter = match.captured(2);\n const QString whitespaceCharacter = match.captured(4);\n\n // add or remove one tabulator key\n if (reverse) {\n // remove one set of indentCharacters or a tabulator\n whitespaces.remove(QRegularExpression(\n QStringLiteral(\"^(\\\\t|\") +\n QRegularExpression::escape(indentCharacters) +\n QStringLiteral(\")\")));\n\n } else {\n whitespaces += indentCharacters;\n }\n\n cursor.insertText(whitespaces + listCharacter +\n whitespaceCharacter);\n return true;\n }\n\n // check if we want to indent or un-indent an ordered list\n static QRegularExpression regex2(R\"(^(\\s*)(\\d+)([\\.|\\)])(\\s+)$)\");\n i = regex2.globalMatch(currentLineText);\n\n if (i.hasNext()) {\n const QRegularExpressionMatch match = i.next();\n QString whitespaces = match.captured(1);\n const QString listCharacter = match.captured(2);\n const QString listMarker = match.captured(3);\n const QString whitespaceCharacter = match.captured(4);\n\n // add or remove one tabulator key\n if (reverse) {\n whitespaces.chop(1);\n } else {\n whitespaces += indentCharacters;\n }\n\n cursor.insertText(whitespaces + listCharacter + listMarker +\n whitespaceCharacter);\n return true;\n }\n }\n\n // check if we want to indent the whole text\n return increaseSelectedTextIndention(reverse, indentCharacters);\n}\n\n/**\n * Sets the auto text options\n */\nvoid QMarkdownTextEdit::setAutoTextOptions(AutoTextOptions options) {\n _autoTextOptions = options;\n}\n\nvoid QMarkdownTextEdit::updateLineNumberArea(const QRect rect, int dy) {\n if (dy)\n _lineNumArea->scroll(0, dy);\n else\n _lineNumArea->update(0, rect.y(), _lineNumArea->sizeHint().width(),\n rect.height());\n\n updateLineNumAreaGeometry();\n\n if (rect.contains(viewport()->rect())) {\n updateLineNumberAreaWidth(0);\n }\n}\n\nvoid QMarkdownTextEdit::updateLineNumberAreaWidth(int) {\n QSignalBlocker blocker(this);\n const auto oldMargins = viewportMargins();\n const int width =\n _lineNumArea->isLineNumAreaEnabled()\n ? _lineNumArea->sizeHint().width() + _lineNumberLeftMarginOffset\n : oldMargins.left();\n const auto newMargins = QMargins{width, oldMargins.top(),\n oldMargins.right(), oldMargins.bottom()};\n\n if (newMargins != oldMargins) {\n setViewportMargins(newMargins);\n }\n\n // Grow lineNumArea font-size with the font size of the editor\n const int pointSize = this->font().pointSize();\n if (pointSize > 0) {\n QFont font = _lineNumArea->font();\n font.setPointSize(pointSize);\n _lineNumArea->setFont(font);\n }\n}\n\n/**\n * @param e\n * @details This does two things\n * 1. Overrides QPlainTextEdit::paintEvent to fix the RTL bug of QPlainTextEdit\n * 2. Paints a rectangle around code block fences [Code taken from\n * ghostwriter(which in turn is based on QPlaintextEdit::paintEvent() with\n * modifications and minor improvements for our use\n */\nvoid QMarkdownTextEdit::paintEvent(QPaintEvent *e) {\n QTextBlock block = firstVisibleBlock();\n\n QPainter painter(viewport());\n const QRect viewportRect = viewport()->rect();\n // painter.fillRect(viewportRect, Qt::transparent);\n bool firstVisible = true;\n QPointF offset(contentOffset());\n QRectF blockAreaRect; // Code or block quote rect.\n bool inBlockArea = false;\n\n bool clipTop = false;\n bool drawBlock = false;\n qreal dy = 0.0;\n bool done = false;\n\n const QColor &color = MarkdownHighlighter::codeBlockBackgroundColor();\n const int cornerRadius = 5;\n\n while (block.isValid() && !done) {\n const QRectF r = blockBoundingRect(block).translated(offset);\n const int state = block.userState();\n\n if (!inBlockArea && MarkdownHighlighter::isCodeBlock(state)) {\n // skip the backticks\n if (!block.text().startsWith(QLatin1String(\"```\")) &&\n !block.text().startsWith(QLatin1String(\"~~~\"))) {\n blockAreaRect = r;\n dy = 0.0;\n inBlockArea = true;\n }\n\n // If this is the first visible block within the viewport\n // and if the previous block is part of the text block area,\n // then the rectangle to draw for the block area will have\n // its top clipped by the viewport and will need to be\n // drawn specially.\n const int prevBlockState = block.previous().userState();\n if (firstVisible &&\n MarkdownHighlighter::isCodeBlock(prevBlockState)) {\n clipTop = true;\n }\n }\n // Else if the block ends a text block area...\n else if (inBlockArea && MarkdownHighlighter::isCodeBlockEnd(state)) {\n drawBlock = true;\n inBlockArea = false;\n blockAreaRect.setHeight(dy);\n }\n // If the block is at the end of the document and ends a text\n // block area...\n //\n if (inBlockArea && block == this->document()->lastBlock()) {\n drawBlock = true;\n inBlockArea = false;\n dy += r.height();\n blockAreaRect.setHeight(dy);\n }\n offset.ry() += r.height();\n dy += r.height();\n\n // If this is the last text block visible within the viewport...\n if (offset.y() > viewportRect.height()) {\n if (inBlockArea) {\n blockAreaRect.setHeight(dy);\n drawBlock = true;\n }\n\n // Finished drawing.\n done = true;\n }\n // If this is the last text block visible within the viewport...\n if (offset.y() > viewportRect.height()) {\n if (inBlockArea) {\n blockAreaRect.setHeight(dy);\n drawBlock = true;\n }\n // Finished drawing.\n done = true;\n }\n\n if (drawBlock) {\n painter.setCompositionMode(QPainter::CompositionMode_SourceOver);\n painter.setPen(Qt::NoPen);\n painter.setBrush(QBrush(color));\n\n // If the first visible block is \"clipped\" such that the previous\n // block is part of the text block area, then only draw a rectangle\n // with the bottom corners rounded, and with the top corners square\n // to reflect that the first visible block is part of a larger block\n // of text.\n //\n if (clipTop) {\n QPainterPath path;\n path.setFillRule(Qt::WindingFill);\n path.addRoundedRect(blockAreaRect, cornerRadius, cornerRadius);\n qreal adjustedHeight = blockAreaRect.height() / 2;\n path.addRect(blockAreaRect.adjusted(0, 0, 0, -adjustedHeight));\n painter.drawPath(path.simplified());\n clipTop = false;\n }\n // Else draw the entire rectangle with all corners rounded.\n else {\n painter.drawRoundedRect(blockAreaRect, cornerRadius,\n cornerRadius);\n }\n\n drawBlock = false;\n }\n\n // this fixes the RTL bug of QPlainTextEdit\n // https://bugreports.qt.io/browse/QTBUG-7516\n if (block.text().isRightToLeft()) {\n QTextLayout *layout = block.layout();\n // opt = document()->defaultTextOption();\n QTextOption opt = QTextOption(Qt::AlignRight);\n opt.setTextDirection(Qt::RightToLeft);\n layout->setTextOption(opt);\n }\n\n // Current line highlight\n QTextCursor cursor = textCursor();\n if (highlightCurrentLine() && cursor.block() == block) {\n QTextLine line =\n block.layout()->lineForTextPosition(cursor.positionInBlock());\n QRectF lineRect = line.rect();\n lineRect.moveTop(lineRect.top() + r.top());\n lineRect.setLeft(0.);\n lineRect.setRight(viewportRect.width());\n painter.fillRect(lineRect.toAlignedRect(),\n currentLineHighlightColor());\n }\n\n block = block.next();\n firstVisible = false;\n }\n\n painter.end();\n QPlainTextEdit::paintEvent(e);\n}\n\n/**\n * Overrides QPlainTextEdit::setReadOnly to fix a problem with Chinese and\n * Japanese input methods\n *\n * @param ro\n */\nvoid QMarkdownTextEdit::setReadOnly(bool ro) {\n QPlainTextEdit::setReadOnly(ro);\n\n // attempted to fix a problem with Chinese and Japanese input methods\n // @see https://github.com/pbek/QOwnNotes/issues/976\n setAttribute(Qt::WA_InputMethodEnabled, !isReadOnly());\n}\n\nvoid QMarkdownTextEdit::doSearch(\n QString &searchText, QPlainTextEditSearchWidget::SearchMode searchMode) {\n _searchWidget->setSearchText(searchText);\n _searchWidget->setSearchMode(searchMode);\n _searchWidget->doSearchCount();\n _searchWidget->activate(false);\n}\n\nvoid QMarkdownTextEdit::hideSearchWidget(bool reset) {\n _searchWidget->deactivate();\n\n if (reset) {\n _searchWidget->reset();\n }\n}\n\nvoid QMarkdownTextEdit::updateSettings() {\n // if true: centers the screen if cursor reaches bottom (but not top)\n searchWidget()->setDebounceDelay(_debounceDelay);\n setCenterOnScroll(_centerCursor);\n}\n\nvoid QMarkdownTextEdit::setLineNumberLeftMarginOffset(int offset) {\n _lineNumberLeftMarginOffset = offset;\n}\n\nQMargins QMarkdownTextEdit::viewportMargins() {\n return QPlainTextEdit::viewportMargins();\n}\n bool bracketClosingCheck(const QChar openingCharacter,\n QChar closingCharacter) {\n // check if bracket closing or read-only are enabled\n if (!(_autoTextOptions & AutoTextOption::BracketClosing) || isReadOnly()) {\n return false;\n }\n\n if (closingCharacter.isNull()) {\n closingCharacter = openingCharacter;\n }\n\n QTextCursor cursor = textCursor();\n const int positionInBlock = cursor.positionInBlock();\n\n // get the current text from the block\n const QString text = cursor.block().text();\n const int textLength = text.length();\n\n // if we are at the end of the line we just want to enter the character\n if (positionInBlock >= textLength) {\n return false;\n }\n\n const QChar currentChar = text.at(positionInBlock);\n\n // if (closingCharacter == openingCharacter) {\n\n // }\n\n qDebug() << __func__ << \" - 'currentChar': \" << currentChar;\n\n // if the current character is not the closing character we just want to\n // enter the character\n if (currentChar != closingCharacter) {\n return false;\n }\n\n const QString leftText = text.left(positionInBlock);\n const int openingCharacterCount = leftText.count(openingCharacter);\n const int closingCharacterCount = leftText.count(closingCharacter);\n\n // if there were enough opening characters just enter the character\n if (openingCharacterCount < (closingCharacterCount + 1)) {\n return false;\n }\n\n // move the cursor to the right and don't enter the character\n cursor.movePosition(QTextCursor::Right);\n setTextCursor(cursor);\n return true;\n}\n bool quotationMarkCheck(const QChar quotationCharacter) {\n // check if bracket closing or read-only are enabled\n if (!(_autoTextOptions & AutoTextOption::BracketClosing) || isReadOnly()) {\n return false;\n }\n\n QTextCursor cursor = textCursor();\n const int positionInBlock = cursor.positionInBlock();\n\n // get the current text from the block\n const QString text = cursor.block().text();\n const int textLength = text.length();\n\n // if last char is not space, we are at word end, no autocompletion\n const bool isBacktick = quotationCharacter == '`';\n if (!isBacktick && positionInBlock != 0 &&\n !text.at(positionInBlock - 1).isSpace()) {\n return false;\n }\n\n // if we are at the end of the line we just want to enter the character\n if (positionInBlock >= textLength) {\n return handleBracketClosing(quotationCharacter);\n }\n\n const QChar currentChar = text.at(positionInBlock);\n\n // if the current character is not the quotation character we just want to\n // enter the character\n if (currentChar != quotationCharacter) {\n return handleBracketClosing(quotationCharacter);\n }\n\n // move the cursor to the right and don't enter the character\n cursor.movePosition(QTextCursor::Right);\n setTextCursor(cursor);\n return true;\n}\n void focusOutEvent(QFocusEvent *event) override {\n resetMouseCursor();\n QPlainTextEdit::focusOutEvent(event);\n}\n void paintEvent(QPaintEvent *e) override {\n QTextBlock block = firstVisibleBlock();\n\n QPainter painter(viewport());\n const QRect viewportRect = viewport()->rect();\n // painter.fillRect(viewportRect, Qt::transparent);\n bool firstVisible = true;\n QPointF offset(contentOffset());\n QRectF blockAreaRect; // Code or block quote rect.\n bool inBlockArea = false;\n\n bool clipTop = false;\n bool drawBlock = false;\n qreal dy = 0.0;\n bool done = false;\n\n const QColor &color = MarkdownHighlighter::codeBlockBackgroundColor();\n const int cornerRadius = 5;\n\n while (block.isValid() && !done) {\n const QRectF r = blockBoundingRect(block).translated(offset);\n const int state = block.userState();\n\n if (!inBlockArea && MarkdownHighlighter::isCodeBlock(state)) {\n // skip the backticks\n if (!block.text().startsWith(QLatin1String(\"```\")) &&\n !block.text().startsWith(QLatin1String(\"~~~\"))) {\n blockAreaRect = r;\n dy = 0.0;\n inBlockArea = true;\n }\n\n // If this is the first visible block within the viewport\n // and if the previous block is part of the text block area,\n // then the rectangle to draw for the block area will have\n // its top clipped by the viewport and will need to be\n // drawn specially.\n const int prevBlockState = block.previous().userState();\n if (firstVisible &&\n MarkdownHighlighter::isCodeBlock(prevBlockState)) {\n clipTop = true;\n }\n }\n // Else if the block ends a text block area...\n else if (inBlockArea && MarkdownHighlighter::isCodeBlockEnd(state)) {\n drawBlock = true;\n inBlockArea = false;\n blockAreaRect.setHeight(dy);\n }\n // If the block is at the end of the document and ends a text\n // block area...\n //\n if (inBlockArea && block == this->document()->lastBlock()) {\n drawBlock = true;\n inBlockArea = false;\n dy += r.height();\n blockAreaRect.setHeight(dy);\n }\n offset.ry() += r.height();\n dy += r.height();\n\n // If this is the last text block visible within the viewport...\n if (offset.y() > viewportRect.height()) {\n if (inBlockArea) {\n blockAreaRect.setHeight(dy);\n drawBlock = true;\n }\n\n // Finished drawing.\n done = true;\n }\n // If this is the last text block visible within the viewport...\n if (offset.y() > viewportRect.height()) {\n if (inBlockArea) {\n blockAreaRect.setHeight(dy);\n drawBlock = true;\n }\n // Finished drawing.\n done = true;\n }\n\n if (drawBlock) {\n painter.setCompositionMode(QPainter::CompositionMode_SourceOver);\n painter.setPen(Qt::NoPen);\n painter.setBrush(QBrush(color));\n\n // If the first visible block is \"clipped\" such that the previous\n // block is part of the text block area, then only draw a rectangle\n // with the bottom corners rounded, and with the top corners square\n // to reflect that the first visible block is part of a larger block\n // of text.\n //\n if (clipTop) {\n QPainterPath path;\n path.setFillRule(Qt::WindingFill);\n path.addRoundedRect(blockAreaRect, cornerRadius, cornerRadius);\n qreal adjustedHeight = blockAreaRect.height() / 2;\n path.addRect(blockAreaRect.adjusted(0, 0, 0, -adjustedHeight));\n painter.drawPath(path.simplified());\n clipTop = false;\n }\n // Else draw the entire rectangle with all corners rounded.\n else {\n painter.drawRoundedRect(blockAreaRect, cornerRadius,\n cornerRadius);\n }\n\n drawBlock = false;\n }\n\n // this fixes the RTL bug of QPlainTextEdit\n // https://bugreports.qt.io/browse/QTBUG-7516\n if (block.text().isRightToLeft()) {\n QTextLayout *layout = block.layout();\n // opt = document()->defaultTextOption();\n QTextOption opt = QTextOption(Qt::AlignRight);\n opt.setTextDirection(Qt::RightToLeft);\n layout->setTextOption(opt);\n }\n\n // Current line highlight\n QTextCursor cursor = textCursor();\n if (highlightCurrentLine() && cursor.block() == block) {\n QTextLine line =\n block.layout()->lineForTextPosition(cursor.positionInBlock());\n QRectF lineRect = line.rect();\n lineRect.moveTop(lineRect.top() + r.top());\n lineRect.setLeft(0.);\n lineRect.setRight(viewportRect.width());\n painter.fillRect(lineRect.toAlignedRect(),\n currentLineHighlightColor());\n }\n\n block = block.next();\n firstVisible = false;\n }\n\n painter.end();\n QPlainTextEdit::paintEvent(e);\n}\n bool handleCharRemoval(MarkdownHighlighter::RangeType type, int block,\n int position) {\n if (!_highlighter) return false;\n\n auto range = _highlighter->findPositionInRanges(type, block, position);\n if (range == QPair{-1, -1}) return false;\n\n int charToRemovePos = range.first;\n if (position == range.first) charToRemovePos = range.second;\n\n QTextCursor cursor = textCursor();\n auto gpos = cursor.position();\n\n if (charToRemovePos > position) {\n cursor.setPosition(gpos + (charToRemovePos - (position + 1)));\n } else {\n cursor.setPosition(gpos - (position - charToRemovePos + 1));\n gpos--;\n }\n\n cursor.deleteChar();\n cursor.setPosition(gpos);\n setTextCursor(cursor);\n return false;\n}\n void resizeEvent(QResizeEvent *event) override {\n QPlainTextEdit::resizeEvent(event);\n updateLineNumAreaGeometry();\n}\n void setLineNumberLeftMarginOffset(int offset) {\n _lineNumberLeftMarginOffset = offset;\n}\n int _lineNumberLeftMarginOffset = 0;\n void updateLineNumAreaGeometry() {\n const auto contentsRect = this->contentsRect();\n const QRect newGeometry = {contentsRect.left(), contentsRect.top(),\n _lineNumArea->sizeHint().width(),\n contentsRect.height()};\n auto oldGeometry = _lineNumArea->geometry();\n if (newGeometry != oldGeometry) {\n _lineNumArea->setGeometry(newGeometry);\n }\n}\n void updateLineNumberArea(const QRect rect, int dy) {\n if (dy)\n _lineNumArea->scroll(0, dy);\n else\n _lineNumArea->update(0, rect.y(), _lineNumArea->sizeHint().width(),\n rect.height());\n\n updateLineNumAreaGeometry();\n\n if (rect.contains(viewport()->rect())) {\n updateLineNumberAreaWidth(0);\n }\n}\n Q_SLOT void updateLineNumberAreaWidth(int) {\n QSignalBlocker blocker(this);\n const auto oldMargins = viewportMargins();\n const int width =\n _lineNumArea->isLineNumAreaEnabled()\n ? _lineNumArea->sizeHint().width() + _lineNumberLeftMarginOffset\n : oldMargins.left();\n const auto newMargins = QMargins{width, oldMargins.top(),\n oldMargins.right(), oldMargins.bottom()};\n\n if (newMargins != oldMargins) {\n setViewportMargins(newMargins);\n }\n\n // Grow lineNumArea font-size with the font size of the editor\n const int pointSize = this->font().pointSize();\n if (pointSize > 0) {\n QFont font = _lineNumArea->font();\n font.setPointSize(pointSize);\n _lineNumArea->setFont(font);\n }\n}\n bool _handleBracketClosingUsed;\n LineNumArea *_lineNumArea;\n void urlClicked(QString url);\n void zoomIn();\n void zoomOut();\n};"], ["/SpeedyNote/source/ControlPanelDialog.h", "class ControlPanelDialog {\n Q_OBJECT\n\npublic:\n explicit ControlPanelDialog(MainWindow *mainWindow, InkCanvas *targetCanvas, QWidget *parent = nullptr);\n private:\n void applyChanges() {\n if (!canvas) return;\n\n BackgroundStyle style = static_cast(\n styleCombo->currentData().toInt()\n );\n\n canvas->setBackgroundStyle(style);\n canvas->setBackgroundColor(selectedColor);\n canvas->setBackgroundDensity(densitySpin->value());\n canvas->update();\n canvas->saveBackgroundMetadata();\n\n // ✅ Save these settings as defaults for new tabs\n if (mainWindowRef) {\n mainWindowRef->saveDefaultBackgroundSettings(style, selectedColor, densitySpin->value());\n }\n\n // ✅ Apply button mappings back to MainWindow with internal keys\n if (mainWindowRef) {\n for (const QString &buttonKey : holdMappingCombos.keys()) {\n QString displayString = holdMappingCombos[buttonKey]->currentText();\n QString internalKey = ButtonMappingHelper::displayToInternalKey(displayString, true); // true = isDialMode\n mainWindowRef->setHoldMapping(buttonKey, internalKey);\n }\n for (const QString &buttonKey : pressMappingCombos.keys()) {\n QString displayString = pressMappingCombos[buttonKey]->currentText();\n QString internalKey = ButtonMappingHelper::displayToInternalKey(displayString, false); // false = isAction\n mainWindowRef->setPressMapping(buttonKey, internalKey);\n }\n\n // ✅ Save to persistent settings\n mainWindowRef->saveButtonMappings();\n \n // ✅ Apply theme settings\n mainWindowRef->setUseCustomAccentColor(useCustomAccentCheckbox->isChecked());\n if (selectedAccentColor.isValid()) {\n mainWindowRef->setCustomAccentColor(selectedAccentColor);\n }\n \n // ✅ Apply color palette setting\n mainWindowRef->setUseBrighterPalette(useBrighterPaletteCheckbox->isChecked());\n }\n}\n void chooseColor() {\n QColor chosen = QColorDialog::getColor(selectedColor, this, tr(\"Select Background Color\"));\n if (chosen.isValid()) {\n selectedColor = chosen;\n colorButton->setStyleSheet(QString(\"background-color: %1\").arg(selectedColor.name()));\n }\n}\n void addKeyboardMapping() {\n // Step 1: Capture key sequence\n KeyCaptureDialog captureDialog(this);\n if (captureDialog.exec() != QDialog::Accepted) {\n return;\n }\n \n QString keySequence = captureDialog.getCapturedKeySequence();\n if (keySequence.isEmpty()) {\n return;\n }\n \n // Check if key sequence already exists\n if (mainWindowRef && mainWindowRef->getKeyboardMappings().contains(keySequence)) {\n QMessageBox::warning(this, tr(\"Key Already Mapped\"), \n tr(\"The key sequence '%1' is already mapped. Please choose a different key combination.\").arg(keySequence));\n return;\n }\n \n // Step 2: Choose action\n QStringList actions = ButtonMappingHelper::getTranslatedActions();\n bool ok;\n QString selectedAction = QInputDialog::getItem(this, tr(\"Select Action\"), \n tr(\"Choose the action to perform when '%1' is pressed:\").arg(keySequence), \n actions, 0, false, &ok);\n \n if (!ok || selectedAction.isEmpty()) {\n return;\n }\n \n // Convert display name to internal key\n QString internalKey = ButtonMappingHelper::displayToInternalKey(selectedAction, false);\n \n // Add the mapping\n if (mainWindowRef) {\n mainWindowRef->addKeyboardMapping(keySequence, internalKey);\n \n // Update table\n int row = keyboardTable->rowCount();\n keyboardTable->insertRow(row);\n keyboardTable->setItem(row, 0, new QTableWidgetItem(keySequence));\n keyboardTable->setItem(row, 1, new QTableWidgetItem(selectedAction));\n }\n}\n void removeKeyboardMapping() {\n int currentRow = keyboardTable->currentRow();\n if (currentRow < 0) {\n QMessageBox::information(this, tr(\"No Selection\"), tr(\"Please select a mapping to remove.\"));\n return;\n }\n \n QTableWidgetItem *keyItem = keyboardTable->item(currentRow, 0);\n if (!keyItem) return;\n \n QString keySequence = keyItem->text();\n \n // Confirm removal\n int ret = QMessageBox::question(this, tr(\"Remove Mapping\"), \n tr(\"Are you sure you want to remove the keyboard shortcut '%1'?\").arg(keySequence),\n QMessageBox::Yes | QMessageBox::No, QMessageBox::No);\n \n if (ret == QMessageBox::Yes) {\n // Remove from MainWindow\n if (mainWindowRef) {\n mainWindowRef->removeKeyboardMapping(keySequence);\n }\n \n // Remove from table\n keyboardTable->removeRow(currentRow);\n }\n}\n void openControllerMapping() {\n if (!mainWindowRef) {\n QMessageBox::warning(this, tr(\"Error\"), tr(\"MainWindow reference not available.\"));\n return;\n }\n \n SDLControllerManager *controllerManager = mainWindowRef->getControllerManager();\n if (!controllerManager) {\n QMessageBox::warning(this, tr(\"Controller Not Available\"), \n tr(\"Controller manager is not available. Please ensure a controller is connected and restart the application.\"));\n return;\n }\n \n if (!controllerManager->getJoystick()) {\n QMessageBox::warning(this, tr(\"No Controller Detected\"), \n tr(\"No controller is currently connected. Please connect your controller and restart the application.\"));\n return;\n }\n \n ControllerMappingDialog dialog(controllerManager, this);\n dialog.exec();\n}\n void reconnectController() {\n if (!mainWindowRef) {\n QMessageBox::warning(this, tr(\"Error\"), tr(\"MainWindow reference not available.\"));\n return;\n }\n \n SDLControllerManager *controllerManager = mainWindowRef->getControllerManager();\n if (!controllerManager) {\n QMessageBox::warning(this, tr(\"Controller Not Available\"), \n tr(\"Controller manager is not available.\"));\n return;\n }\n \n // Show reconnecting message\n controllerStatusLabel->setText(tr(\"🔄 Reconnecting...\"));\n controllerStatusLabel->setStyleSheet(\"color: orange;\");\n \n // Force the UI to update immediately\n QApplication::processEvents();\n \n // Attempt to reconnect using thread-safe method\n QMetaObject::invokeMethod(controllerManager, \"reconnect\", Qt::BlockingQueuedConnection);\n \n // Update status after reconnection attempt\n updateControllerStatus();\n \n // Show result message\n if (controllerManager->getJoystick()) {\n // Reconnect the controller signals in MainWindow\n mainWindowRef->reconnectControllerSignals();\n \n QMessageBox::information(this, tr(\"Reconnection Successful\"), \n tr(\"Controller has been successfully reconnected!\"));\n } else {\n QMessageBox::warning(this, tr(\"Reconnection Failed\"), \n tr(\"Failed to reconnect controller. Please ensure your controller is powered on and in pairing mode, then try again.\"));\n }\n}\n private:\n InkCanvas *canvas;\n QTabWidget *tabWidget;\n QWidget *backgroundTab;\n QComboBox *styleCombo;\n QPushButton *colorButton;\n QSpinBox *densitySpin;\n QPushButton *applyButton;\n QPushButton *okButton;\n QPushButton *cancelButton;\n QColor selectedColor;\n void createBackgroundTab() {\n backgroundTab = new QWidget(this);\n\n QLabel *styleLabel = new QLabel(tr(\"Background Style:\"));\n styleCombo = new QComboBox();\n styleCombo->addItem(tr(\"None\"), static_cast(BackgroundStyle::None));\n styleCombo->addItem(tr(\"Grid\"), static_cast(BackgroundStyle::Grid));\n styleCombo->addItem(tr(\"Lines\"), static_cast(BackgroundStyle::Lines));\n\n QLabel *colorLabel = new QLabel(tr(\"Background Color:\"));\n colorButton = new QPushButton();\n connect(colorButton, &QPushButton::clicked, this, &ControlPanelDialog::chooseColor);\n\n QLabel *densityLabel = new QLabel(tr(\"Density:\"));\n densitySpin = new QSpinBox();\n densitySpin->setRange(10, 200);\n densitySpin->setSuffix(\" px\");\n densitySpin->setSingleStep(5);\n\n QGridLayout *layout = new QGridLayout(backgroundTab);\n layout->addWidget(styleLabel, 0, 0);\n layout->addWidget(styleCombo, 0, 1);\n layout->addWidget(colorLabel, 1, 0);\n layout->addWidget(colorButton, 1, 1);\n layout->addWidget(densityLabel, 2, 0);\n layout->addWidget(densitySpin, 2, 1);\n // layout->setColumnStretch(1, 1); // Stretch the second column\n layout->setRowStretch(3, 1); // Stretch the last row\n}\n void loadFromCanvas() {\n styleCombo->setCurrentIndex(static_cast(canvas->getBackgroundStyle()));\n densitySpin->setValue(canvas->getBackgroundDensity());\n selectedColor = canvas->getBackgroundColor();\n\n colorButton->setStyleSheet(QString(\"background-color: %1\").arg(selectedColor.name()));\n\n if (mainWindowRef) {\n for (const QString &buttonKey : holdMappingCombos.keys()) {\n QString internalKey = mainWindowRef->getHoldMapping(buttonKey);\n QString displayString = ButtonMappingHelper::internalKeyToDisplay(internalKey, true); // true = isDialMode\n int index = holdMappingCombos[buttonKey]->findText(displayString);\n if (index >= 0) holdMappingCombos[buttonKey]->setCurrentIndex(index);\n }\n\n for (const QString &buttonKey : pressMappingCombos.keys()) {\n QString internalKey = mainWindowRef->getPressMapping(buttonKey);\n QString displayString = ButtonMappingHelper::internalKeyToDisplay(internalKey, false); // false = isAction\n int index = pressMappingCombos[buttonKey]->findText(displayString);\n if (index >= 0) pressMappingCombos[buttonKey]->setCurrentIndex(index);\n }\n \n // Load theme settings\n useCustomAccentCheckbox->setChecked(mainWindowRef->isUsingCustomAccentColor());\n \n // Get the stored custom accent color\n selectedAccentColor = mainWindowRef->getCustomAccentColor();\n \n accentColorButton->setStyleSheet(QString(\"background-color: %1\").arg(selectedAccentColor.name()));\n accentColorButton->setEnabled(useCustomAccentCheckbox->isChecked());\n \n // Load color palette setting\n useBrighterPaletteCheckbox->setChecked(mainWindowRef->isUsingBrighterPalette());\n }\n}\n MainWindow *mainWindowRef;\n InkCanvas *canvasRef;\n QWidget *performanceTab;\n QWidget *toolbarTab;\n void createToolbarTab() {\n toolbarTab = new QWidget(this);\n QVBoxLayout *toolbarLayout = new QVBoxLayout(toolbarTab);\n\n // ✅ Checkbox to show/hide benchmark controls\n QCheckBox *benchmarkVisibilityCheckbox = new QCheckBox(tr(\"Show Benchmark Controls\"), toolbarTab);\n benchmarkVisibilityCheckbox->setChecked(mainWindowRef->areBenchmarkControlsVisible());\n toolbarLayout->addWidget(benchmarkVisibilityCheckbox);\n QLabel *benchmarkNote = new QLabel(tr(\"This will show/hide the benchmark controls on the toolbar. Press the clock button to start/stop the benchmark.\"));\n benchmarkNote->setWordWrap(true);\n benchmarkNote->setStyleSheet(\"color: gray; font-size: 10px;\");\n toolbarLayout->addWidget(benchmarkNote);\n\n // ✅ Checkbox to show/hide zoom buttons\n QCheckBox *zoomButtonsVisibilityCheckbox = new QCheckBox(tr(\"Show Zoom Buttons\"), toolbarTab);\n zoomButtonsVisibilityCheckbox->setChecked(mainWindowRef->areZoomButtonsVisible());\n toolbarLayout->addWidget(zoomButtonsVisibilityCheckbox);\n QLabel *zoomButtonsNote = new QLabel(tr(\"This will show/hide the 0.5x, 1x, and 2x zoom buttons on the toolbar\"));\n zoomButtonsNote->setWordWrap(true);\n zoomButtonsNote->setStyleSheet(\"color: gray; font-size: 10px;\");\n toolbarLayout->addWidget(zoomButtonsNote);\n\n QCheckBox *scrollOnTopCheckBox = new QCheckBox(tr(\"Scroll on Top after Page Switching\"), toolbarTab);\n scrollOnTopCheckBox->setChecked(mainWindowRef->isScrollOnTopEnabled());\n toolbarLayout->addWidget(scrollOnTopCheckBox);\n QLabel *scrollNote = new QLabel(tr(\"Enabling this will make the page scroll to the top after switching to a new page.\"));\n scrollNote->setWordWrap(true);\n scrollNote->setStyleSheet(\"color: gray; font-size: 10px;\");\n toolbarLayout->addWidget(scrollNote);\n \n toolbarLayout->addStretch();\n toolbarTab->setLayout(toolbarLayout);\n tabWidget->addTab(toolbarTab, tr(\"Features\"));\n\n\n // Connect the checkbox\n connect(benchmarkVisibilityCheckbox, &QCheckBox::toggled, mainWindowRef, &MainWindow::setBenchmarkControlsVisible);\n connect(zoomButtonsVisibilityCheckbox, &QCheckBox::toggled, mainWindowRef, &MainWindow::setZoomButtonsVisible);\n connect(scrollOnTopCheckBox, &QCheckBox::toggled, mainWindowRef, &MainWindow::setScrollOnTopEnabled);\n}\n void createPerformanceTab() {\n performanceTab = new QWidget();\n QVBoxLayout *layout = new QVBoxLayout(performanceTab);\n\n QCheckBox *previewToggle = new QCheckBox(tr(\"Enable Low-Resolution PDF Previews\"));\n previewToggle->setChecked(mainWindowRef->isLowResPreviewEnabled());\n\n connect(previewToggle, &QCheckBox::toggled, mainWindowRef, &MainWindow::setLowResPreviewEnabled);\n\n QLabel *note = new QLabel(tr(\"Disabling this may improve dial smoothness on low-end devices.\"));\n note->setWordWrap(true);\n note->setStyleSheet(\"color: gray; font-size: 10px;\");\n\n QLabel *dpiLabel = new QLabel(tr(\"PDF Rendering DPI:\"));\n QComboBox *dpiSelector = new QComboBox();\n dpiSelector->addItems({\"96\", \"192\", \"288\", \"384\", \"480\"});\n dpiSelector->setCurrentText(QString::number(mainWindowRef->getPdfDPI()));\n\n connect(dpiSelector, &QComboBox::currentTextChanged, this, [=](const QString &value) {\n mainWindowRef->setPdfDPI(value.toInt());\n });\n\n QLabel *notePDF = new QLabel(tr(\"Adjust how the PDF is rendered. Higher DPI means better quality but slower performance. DO NOT CHANGE THIS OPTION WHEN MULTIPLE TABS ARE OPEN. THIS MAY LEAD TO UNDEFINED BEHAVIOR!\"));\n notePDF->setWordWrap(true);\n notePDF->setStyleSheet(\"color: gray; font-size: 10px;\");\n\n\n layout->addWidget(previewToggle);\n layout->addWidget(note);\n layout->addWidget(dpiLabel);\n layout->addWidget(dpiSelector);\n layout->addWidget(notePDF);\n\n layout->addStretch();\n\n // return performanceTab;\n}\n QWidget *controllerMappingTab;\n QPushButton *reconnectButton;\n QLabel *controllerStatusLabel;\n QMap holdMappingCombos;\n QMap pressMappingCombos;\n void createButtonMappingTab() {\n QWidget *buttonTab = new QWidget(this);\n QVBoxLayout *layout = new QVBoxLayout(buttonTab);\n\n QStringList buttonKeys = ButtonMappingHelper::getInternalButtonKeys();\n QStringList buttonDisplayNames = ButtonMappingHelper::getTranslatedButtons();\n QStringList dialModes = ButtonMappingHelper::getTranslatedDialModes();\n QStringList actions = ButtonMappingHelper::getTranslatedActions();\n\n for (int i = 0; i < buttonKeys.size(); ++i) {\n const QString &buttonKey = buttonKeys[i];\n const QString &buttonDisplayName = buttonDisplayNames[i];\n \n QHBoxLayout *h = new QHBoxLayout();\n h->addWidget(new QLabel(buttonDisplayName)); // Use translated button name\n\n QComboBox *holdCombo = new QComboBox();\n holdCombo->addItems(dialModes); // Add translated dial mode names\n holdMappingCombos[buttonKey] = holdCombo;\n h->addWidget(new QLabel(tr(\"Hold:\")));\n h->addWidget(holdCombo);\n\n QComboBox *pressCombo = new QComboBox();\n pressCombo->addItems(actions); // Add translated action names\n pressMappingCombos[buttonKey] = pressCombo;\n h->addWidget(new QLabel(tr(\"Press:\")));\n h->addWidget(pressCombo);\n\n layout->addLayout(h);\n }\n\n layout->addStretch();\n buttonTab->setLayout(layout);\n tabWidget->addTab(buttonTab, tr(\"Button Mapping\"));\n}\n void createControllerMappingTab() {\n controllerMappingTab = new QWidget(this);\n QVBoxLayout *layout = new QVBoxLayout(controllerMappingTab);\n \n // Instructions\n QLabel *instructionLabel = new QLabel(tr(\"Configure physical controller button mappings for your Joy-Con or other controller:\"), controllerMappingTab);\n instructionLabel->setWordWrap(true);\n layout->addWidget(instructionLabel);\n \n QLabel *noteLabel = new QLabel(tr(\"Note: This maps your physical controller buttons to the logical Joy-Con functions used by the application. \"\n \"After setting up the physical mapping, you can configure what actions each logical button performs in the 'Button Mapping' tab.\"), controllerMappingTab);\n noteLabel->setWordWrap(true);\n noteLabel->setStyleSheet(\"color: gray; font-size: 10px; margin-bottom: 10px;\");\n layout->addWidget(noteLabel);\n \n // Button to open controller mapping dialog\n QPushButton *openMappingButton = new QPushButton(tr(\"Configure Controller Mapping\"), controllerMappingTab);\n openMappingButton->setMinimumHeight(40);\n connect(openMappingButton, &QPushButton::clicked, this, &ControlPanelDialog::openControllerMapping);\n layout->addWidget(openMappingButton);\n \n // Button to reconnect controller\n reconnectButton = new QPushButton(tr(\"Reconnect Controller\"), controllerMappingTab);\n reconnectButton->setMinimumHeight(40);\n reconnectButton->setStyleSheet(\"QPushButton { background-color: #4CAF50; color: white; font-weight: bold; }\");\n connect(reconnectButton, &QPushButton::clicked, this, &ControlPanelDialog::reconnectController);\n layout->addWidget(reconnectButton);\n \n // Status information\n QLabel *statusLabel = new QLabel(tr(\"Current controller status:\"), controllerMappingTab);\n statusLabel->setStyleSheet(\"font-weight: bold; margin-top: 20px;\");\n layout->addWidget(statusLabel);\n \n // Dynamic status label\n controllerStatusLabel = new QLabel(controllerMappingTab);\n updateControllerStatus();\n layout->addWidget(controllerStatusLabel);\n \n layout->addStretch();\n \n tabWidget->addTab(controllerMappingTab, tr(\"Controller Mapping\"));\n}\n void createKeyboardMappingTab() {\n keyboardTab = new QWidget(this);\n QVBoxLayout *layout = new QVBoxLayout(keyboardTab);\n \n // Instructions\n QLabel *instructionLabel = new QLabel(tr(\"Configure custom keyboard shortcuts for application actions:\"), keyboardTab);\n instructionLabel->setWordWrap(true);\n layout->addWidget(instructionLabel);\n \n // Table to show current mappings\n keyboardTable = new QTableWidget(0, 2, keyboardTab);\n keyboardTable->setHorizontalHeaderLabels({tr(\"Key Sequence\"), tr(\"Action\")});\n keyboardTable->horizontalHeader()->setStretchLastSection(true);\n keyboardTable->setSelectionBehavior(QAbstractItemView::SelectRows);\n keyboardTable->setEditTriggers(QAbstractItemView::NoEditTriggers);\n layout->addWidget(keyboardTable);\n \n // Buttons\n QHBoxLayout *buttonLayout = new QHBoxLayout();\n addKeyboardMappingButton = new QPushButton(tr(\"Add Mapping\"), keyboardTab);\n removeKeyboardMappingButton = new QPushButton(tr(\"Remove Mapping\"), keyboardTab);\n \n buttonLayout->addWidget(addKeyboardMappingButton);\n buttonLayout->addWidget(removeKeyboardMappingButton);\n buttonLayout->addStretch();\n \n layout->addLayout(buttonLayout);\n \n // Connections\n connect(addKeyboardMappingButton, &QPushButton::clicked, this, &ControlPanelDialog::addKeyboardMapping);\n connect(removeKeyboardMappingButton, &QPushButton::clicked, this, &ControlPanelDialog::removeKeyboardMapping);\n \n // Load current mappings\n if (mainWindowRef) {\n QMap mappings = mainWindowRef->getKeyboardMappings();\n keyboardTable->setRowCount(mappings.size());\n int row = 0;\n for (auto it = mappings.begin(); it != mappings.end(); ++it) {\n keyboardTable->setItem(row, 0, new QTableWidgetItem(it.key()));\n QString displayAction = ButtonMappingHelper::internalKeyToDisplay(it.value(), false);\n keyboardTable->setItem(row, 1, new QTableWidgetItem(displayAction));\n row++;\n }\n }\n \n tabWidget->addTab(keyboardTab, tr(\"Keyboard Shortcuts\"));\n}\n QWidget *keyboardTab;\n QTableWidget *keyboardTable;\n QPushButton *addKeyboardMappingButton;\n QPushButton *removeKeyboardMappingButton;\n QWidget *themeTab;\n QCheckBox *useCustomAccentCheckbox;\n QPushButton *accentColorButton;\n QColor selectedAccentColor;\n QCheckBox *useBrighterPaletteCheckbox;\n void createThemeTab() {\n themeTab = new QWidget(this);\n QVBoxLayout *layout = new QVBoxLayout(themeTab);\n \n // Custom accent color\n useCustomAccentCheckbox = new QCheckBox(tr(\"Use Custom Accent Color\"), themeTab);\n layout->addWidget(useCustomAccentCheckbox);\n \n QLabel *accentColorLabel = new QLabel(tr(\"Accent Color:\"), themeTab);\n accentColorButton = new QPushButton(themeTab);\n accentColorButton->setFixedSize(100, 30);\n connect(accentColorButton, &QPushButton::clicked, this, &ControlPanelDialog::chooseAccentColor);\n \n QHBoxLayout *accentColorLayout = new QHBoxLayout();\n accentColorLayout->addWidget(accentColorLabel);\n accentColorLayout->addWidget(accentColorButton);\n accentColorLayout->addStretch();\n layout->addLayout(accentColorLayout);\n \n QLabel *accentColorNote = new QLabel(tr(\"When enabled, use a custom accent color instead of the system accent color for the toolbar, dial, and tab selection.\"));\n accentColorNote->setWordWrap(true);\n accentColorNote->setStyleSheet(\"color: gray; font-size: 10px;\");\n layout->addWidget(accentColorNote);\n \n // Enable/disable accent color button based on checkbox\n connect(useCustomAccentCheckbox, &QCheckBox::toggled, accentColorButton, &QPushButton::setEnabled);\n connect(useCustomAccentCheckbox, &QCheckBox::toggled, accentColorLabel, &QLabel::setEnabled);\n \n // Color palette preference\n useBrighterPaletteCheckbox = new QCheckBox(tr(\"Use Brighter Color Palette\"), themeTab);\n layout->addWidget(useBrighterPaletteCheckbox);\n \n QLabel *paletteNote = new QLabel(tr(\"When enabled, use brighter colors (good for dark PDF backgrounds). When disabled, use darker colors (good for light PDF backgrounds). This setting is independent of the UI theme.\"));\n paletteNote->setWordWrap(true);\n paletteNote->setStyleSheet(\"color: gray; font-size: 10px;\");\n layout->addWidget(paletteNote);\n \n layout->addStretch();\n \n tabWidget->addTab(themeTab, tr(\"Theme\"));\n}\n void chooseAccentColor() {\n QColor chosen = QColorDialog::getColor(selectedAccentColor, this, tr(\"Select Accent Color\"));\n if (chosen.isValid()) {\n selectedAccentColor = chosen;\n accentColorButton->setStyleSheet(QString(\"background-color: %1\").arg(selectedAccentColor.name()));\n }\n}\n void updateControllerStatus() {\n if (!mainWindowRef || !controllerStatusLabel) return;\n \n SDLControllerManager *controllerManager = mainWindowRef->getControllerManager();\n if (!controllerManager) {\n controllerStatusLabel->setText(tr(\"✗ Controller manager not available\"));\n controllerStatusLabel->setStyleSheet(\"color: red;\");\n return;\n }\n \n if (controllerManager->getJoystick()) {\n controllerStatusLabel->setText(tr(\"✓ Controller connected\"));\n controllerStatusLabel->setStyleSheet(\"color: green; font-weight: bold;\");\n } else {\n controllerStatusLabel->setText(tr(\"✗ No controller detected\"));\n controllerStatusLabel->setStyleSheet(\"color: red; font-weight: bold;\");\n }\n}\n};"], ["/SpeedyNote/source/PdfOpenDialog.h", "class PdfOpenDialog {\n Q_OBJECT\n\npublic:\n enum Result {\n Cancel,\n CreateNewFolder,\n UseExistingFolder\n };\n explicit PdfOpenDialog(const QString &pdfPath, QWidget *parent = nullptr) {\n setWindowTitle(tr(\"Open PDF with SpeedyNote\"));\n setWindowIcon(QIcon(\":/resources/icons/mainicon.png\"));\n setModal(true);\n \n // Remove setFixedSize and use proper size management instead\n // Calculate size based on DPI\n QScreen *screen = QGuiApplication::primaryScreen();\n qreal dpr = screen ? screen->devicePixelRatio() : 1.0;\n \n // Set minimum and maximum sizes instead of fixed size\n int baseWidth = 500;\n int baseHeight = 200;\n \n // Scale sizes appropriately for DPI\n int scaledWidth = static_cast(baseWidth * qMax(1.0, dpr * 0.8));\n int scaledHeight = static_cast(baseHeight * qMax(1.0, dpr * 0.8));\n \n setMinimumSize(scaledWidth, scaledHeight);\n setMaximumSize(scaledWidth + 100, scaledHeight + 50); // Allow some flexibility\n \n // Set size policy to prevent unwanted resizing\n setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);\n \n setupUI();\n \n // Ensure the dialog is properly sized after UI setup\n adjustSize();\n \n // Center the dialog on parent or screen\n if (parent) {\n move(parent->geometry().center() - rect().center());\n } else {\n move(screen->geometry().center() - rect().center());\n }\n}\n static bool hasValidNotebookFolder(const QString &pdfPath, QString &folderPath) {\n QFileInfo fileInfo(pdfPath);\n QString suggestedFolderName = fileInfo.baseName(); // Filename without extension\n QString pdfDir = fileInfo.absolutePath(); // Directory containing the PDF\n QString potentialFolderPath = pdfDir + \"/\" + suggestedFolderName;\n \n if (isValidNotebookFolder(potentialFolderPath, pdfPath)) {\n folderPath = potentialFolderPath;\n return true;\n }\n \n return false;\n}\n protected:\n void resizeEvent(QResizeEvent *event) override {\n // Handle resize events smoothly to prevent jitter during window dragging\n if (event->size() != event->oldSize()) {\n // Only process if size actually changed\n QDialog::resizeEvent(event);\n \n // Ensure the dialog stays within reasonable bounds\n QSize newSize = event->size();\n QSize minSize = minimumSize();\n QSize maxSize = maximumSize();\n \n // Clamp the size to prevent unwanted resizing\n newSize = newSize.expandedTo(minSize).boundedTo(maxSize);\n \n if (newSize != event->size()) {\n // If size needs to be adjusted, do it without triggering another resize event\n resize(newSize);\n }\n } else {\n // If size hasn't changed, just call parent implementation\n QDialog::resizeEvent(event);\n }\n}\n private:\n void onCreateNewFolder() {\n QFileInfo fileInfo(pdfPath);\n QString suggestedFolderName = fileInfo.baseName();\n \n // Get the directory where the PDF is located\n QString pdfDir = fileInfo.absolutePath();\n QString newFolderPath = pdfDir + \"/\" + suggestedFolderName;\n \n // Check if folder already exists\n if (QDir(newFolderPath).exists()) {\n QMessageBox::StandardButton reply = QMessageBox::question(\n this, \n tr(\"Folder Exists\"), \n tr(\"A folder named \\\"%1\\\" already exists in the same directory as the PDF.\\n\\nDo you want to use this existing folder?\").arg(suggestedFolderName),\n QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel\n );\n \n if (reply == QMessageBox::Yes) {\n selectedFolder = newFolderPath;\n result = UseExistingFolder;\n accept();\n return;\n } else if (reply == QMessageBox::Cancel) {\n return; // Stay in dialog\n }\n // If No, continue to create with different name\n \n // Try to create with incremented name\n int counter = 1;\n do {\n newFolderPath = pdfDir + \"/\" + suggestedFolderName + QString(\"_%1\").arg(counter);\n counter++;\n } while (QDir(newFolderPath).exists() && counter < 100);\n \n if (counter >= 100) {\n QMessageBox::warning(this, tr(\"Error\"), tr(\"Could not create a unique folder name.\"));\n return;\n }\n }\n \n // Create the new folder\n QDir dir;\n if (dir.mkpath(newFolderPath)) {\n selectedFolder = newFolderPath;\n result = CreateNewFolder;\n accept();\n } else {\n QMessageBox::warning(this, tr(\"Error\"), tr(\"Failed to create folder: %1\").arg(newFolderPath));\n }\n}\n void onUseExistingFolder() {\n QString folder = QFileDialog::getExistingDirectory(\n this, \n tr(\"Select Existing Notebook Folder\"), \n QFileInfo(pdfPath).absolutePath()\n );\n \n if (!folder.isEmpty()) {\n selectedFolder = folder;\n result = UseExistingFolder;\n accept();\n }\n}\n void onCancel() {\n result = Cancel;\n reject();\n}\n private:\n void setupUI() {\n QVBoxLayout *mainLayout = new QVBoxLayout(this);\n mainLayout->setSpacing(15);\n mainLayout->setContentsMargins(20, 20, 20, 20);\n \n // Set layout size constraint to prevent unwanted resizing\n mainLayout->setSizeConstraint(QLayout::SetMinAndMaxSize);\n \n // Icon and title\n QHBoxLayout *headerLayout = new QHBoxLayout();\n headerLayout->setSpacing(10);\n \n QLabel *iconLabel = new QLabel();\n QPixmap icon = QIcon(\":/resources/icons/mainicon.png\").pixmap(48, 48);\n iconLabel->setPixmap(icon);\n iconLabel->setFixedSize(48, 48);\n iconLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);\n \n QLabel *titleLabel = new QLabel(tr(\"Open PDF with SpeedyNote\"));\n titleLabel->setStyleSheet(\"font-size: 16px; font-weight: bold;\");\n titleLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);\n \n headerLayout->addWidget(iconLabel);\n headerLayout->addWidget(titleLabel);\n headerLayout->addStretch();\n \n mainLayout->addLayout(headerLayout);\n \n // PDF file info\n QFileInfo fileInfo(pdfPath);\n QString fileName = fileInfo.fileName();\n QString folderName = fileInfo.baseName(); // Filename without extension\n \n QLabel *messageLabel = new QLabel(tr(\"PDF File: %1\\n\\nHow would you like to open this PDF?\").arg(fileName));\n messageLabel->setWordWrap(true);\n messageLabel->setStyleSheet(\"font-size: 12px; color: #666;\");\n messageLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);\n \n mainLayout->addWidget(messageLabel);\n \n // Buttons\n QVBoxLayout *buttonLayout = new QVBoxLayout();\n buttonLayout->setSpacing(10);\n \n // Create new folder button\n QPushButton *createFolderBtn = new QPushButton(tr(\"Create New Notebook Folder (\\\"%1\\\")\").arg(folderName));\n createFolderBtn->setIcon(QApplication::style()->standardIcon(QStyle::SP_DirIcon));\n createFolderBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);\n createFolderBtn->setMinimumHeight(40);\n createFolderBtn->setStyleSheet(R\"(\n QPushButton {\n text-align: left;\n padding: 10px;\n border: 1px solid palette(mid);\n border-radius: 5px;\n background: palette(button);\n }\n QPushButton:hover {\n background: palette(light);\n border-color: palette(dark);\n }\n QPushButton:pressed {\n background: palette(midlight);\n }\n )\");\n connect(createFolderBtn, &QPushButton::clicked, this, &PdfOpenDialog::onCreateNewFolder);\n \n // Use existing folder button\n QPushButton *existingFolderBtn = new QPushButton(tr(\"Use Existing Notebook Folder...\"));\n existingFolderBtn->setIcon(QApplication::style()->standardIcon(QStyle::SP_DirOpenIcon));\n existingFolderBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);\n existingFolderBtn->setMinimumHeight(40);\n existingFolderBtn->setStyleSheet(R\"(\n QPushButton {\n text-align: left;\n padding: 10px;\n border: 1px solid palette(mid);\n border-radius: 5px;\n background: palette(button);\n }\n QPushButton:hover {\n background: palette(light);\n border-color: palette(dark);\n }\n QPushButton:pressed {\n background: palette(midlight);\n }\n )\");\n connect(existingFolderBtn, &QPushButton::clicked, this, &PdfOpenDialog::onUseExistingFolder);\n \n buttonLayout->addWidget(createFolderBtn);\n buttonLayout->addWidget(existingFolderBtn);\n \n mainLayout->addLayout(buttonLayout);\n \n // Cancel button\n QHBoxLayout *cancelLayout = new QHBoxLayout();\n cancelLayout->addStretch();\n \n QPushButton *cancelBtn = new QPushButton(tr(\"Cancel\"));\n cancelBtn->setIcon(QApplication::style()->standardIcon(QStyle::SP_DialogCancelButton));\n cancelBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);\n cancelBtn->setMinimumSize(80, 30);\n cancelBtn->setStyleSheet(R\"(\n QPushButton {\n padding: 8px 20px;\n border: 1px solid palette(mid);\n border-radius: 3px;\n background: palette(button);\n }\n QPushButton:hover {\n background: palette(light);\n }\n QPushButton:pressed {\n background: palette(midlight);\n }\n )\");\n connect(cancelBtn, &QPushButton::clicked, this, &PdfOpenDialog::onCancel);\n \n cancelLayout->addWidget(cancelBtn);\n mainLayout->addLayout(cancelLayout);\n}\n static bool isValidNotebookFolder(const QString &folderPath, const QString &pdfPath) {\n QDir folder(folderPath);\n if (!folder.exists()) {\n return false;\n }\n \n // Priority 1: Check for .pdf_path.txt file with matching PDF path\n QString pdfPathFile = folderPath + \"/.pdf_path.txt\";\n if (QFile::exists(pdfPathFile)) {\n QFile file(pdfPathFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString storedPdfPath = in.readLine().trimmed();\n file.close();\n \n if (!storedPdfPath.isEmpty()) {\n // Compare absolute paths to handle relative path differences\n QFileInfo currentPdf(pdfPath);\n QFileInfo storedPdf(storedPdfPath);\n \n // Check if the stored PDF file still exists and matches\n if (storedPdf.exists() && \n currentPdf.absoluteFilePath() == storedPdf.absoluteFilePath()) {\n return true;\n }\n }\n }\n }\n \n // Priority 2: Check for .notebook_id.txt file (SpeedyNote notebook folder)\n QString notebookIdFile = folderPath + \"/.notebook_id.txt\";\n if (QFile::exists(notebookIdFile)) {\n // Additional check: ensure this folder has some notebook content\n QStringList contentFiles = folder.entryList(\n QStringList() << \"*.png\" << \".pdf_path.txt\" << \".bookmarks.txt\" << \".background_config.txt\", \n QDir::Files\n );\n \n // If it has notebook-related files, it's likely a valid SpeedyNote folder\n // but not necessarily for this specific PDF\n if (!contentFiles.isEmpty()) {\n // This is a SpeedyNote notebook, but for a different PDF\n // Return false so the user gets the dialog to choose what to do\n return false;\n }\n }\n \n return false;\n}\n Result result;\n QString selectedFolder;\n QString pdfPath;\n};"], ["/SpeedyNote/source/RecentNotebooksManager.h", "class InkCanvas {\n Q_OBJECT\n\npublic:\n explicit RecentNotebooksManager(QObject *parent = nullptr);\n void addRecentNotebook(const QString& folderPath, InkCanvas* canvasForPreview = nullptr) {\n if (folderPath.isEmpty()) return;\n\n // Remove if already exists to move it to the front\n recentNotebookPaths.removeAll(folderPath);\n recentNotebookPaths.prepend(folderPath);\n\n // Trim the list if it exceeds the maximum size\n while (recentNotebookPaths.size() > MAX_RECENT_NOTEBOOKS) {\n recentNotebookPaths.removeLast();\n }\n\n generateAndSaveCoverPreview(folderPath, canvasForPreview);\n saveRecentNotebooks();\n}\n QStringList getRecentNotebooks() const {\n return recentNotebookPaths;\n}\n QString getCoverImagePathForNotebook(const QString& folderPath) const {\n QString coverDir = getCoverImageDir();\n QString coverFileName = sanitizeFolderName(folderPath) + \"_cover.png\";\n QString coverFilePath = coverDir + coverFileName;\n if (QFile::exists(coverFilePath)) {\n return coverFilePath;\n }\n return \"\"; // Return empty if no cover exists\n}\n QString getNotebookDisplayName(const QString& folderPath) const {\n // Check for PDF metadata first\n QString metadataFile = folderPath + \"/.pdf_path.txt\";\n if (QFile::exists(metadataFile)) {\n QFile file(metadataFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString pdfPath = in.readLine().trimmed();\n file.close();\n if (!pdfPath.isEmpty()) {\n return QFileInfo(pdfPath).fileName();\n }\n }\n }\n // Fallback to folder name\n return QFileInfo(folderPath).fileName();\n}\n void generateAndSaveCoverPreview(const QString& folderPath, InkCanvas* optionalCanvas = nullptr) {\n QString coverDir = getCoverImageDir();\n QString coverFileName = sanitizeFolderName(folderPath) + \"_cover.png\";\n QString coverFilePath = coverDir + coverFileName;\n\n QImage coverImage(400, 300, QImage::Format_ARGB32_Premultiplied);\n coverImage.fill(Qt::white); // Default background\n QPainter painter(&coverImage);\n painter.setRenderHint(QPainter::SmoothPixmapTransform);\n\n if (optionalCanvas && optionalCanvas->width() > 0 && optionalCanvas->height() > 0) {\n int logicalCanvasWidth = optionalCanvas->width();\n int logicalCanvasHeight = optionalCanvas->height();\n\n double targetAspectRatio = 4.0 / 3.0;\n double canvasAspectRatio = (double)logicalCanvasWidth / logicalCanvasHeight;\n\n int grabWidth, grabHeight;\n int xOffset = 0, yOffset = 0;\n\n if (canvasAspectRatio > targetAspectRatio) { // Canvas is wider than target 4:3\n grabHeight = logicalCanvasHeight;\n grabWidth = qRound(logicalCanvasHeight * targetAspectRatio);\n xOffset = (logicalCanvasWidth - grabWidth) / 2;\n } else { // Canvas is taller than or equal to target 4:3\n grabWidth = logicalCanvasWidth;\n grabHeight = qRound(logicalCanvasWidth / targetAspectRatio);\n yOffset = (logicalCanvasHeight - grabHeight) / 2;\n }\n\n if (grabWidth > 0 && grabHeight > 0) {\n QRect grabRect(xOffset, yOffset, grabWidth, grabHeight);\n QPixmap capturedView = optionalCanvas->grab(grabRect);\n painter.drawPixmap(coverImage.rect(), capturedView, capturedView.rect());\n } else {\n // Fallback if calculated grab dimensions are invalid, draw placeholder or fill\n // This case should ideally not be hit if canvas width/height > 0\n painter.fillRect(coverImage.rect(), Qt::lightGray);\n painter.setPen(Qt::black);\n painter.drawText(coverImage.rect(), Qt::AlignCenter, tr(\"Preview Error\"));\n }\n } else {\n // Fallback: check for a saved \"annotated_..._00000.png\" or the first page\n // This part remains the same as it deals with pre-rendered images.\n QString notebookIdStr;\n InkCanvas tempCanvas(nullptr); // Temporary canvas to access potential notebookId property logic if it were there\n // However, notebookId is specific to an instance with a saveFolder.\n // For a generic fallback, we might need a different way or assume a common naming if notebookId is unknown.\n // For now, let's assume a simple naming or improve this fallback if needed.\n \n // Attempt to get notebookId if folderPath is a valid notebook with an ID file\n QFile idFile(folderPath + \"/.notebook_id.txt\");\n if (idFile.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&idFile);\n notebookIdStr = in.readLine().trimmed();\n idFile.close();\n }\n\n QString firstPagePath, firstAnnotatedPagePath;\n if (!notebookIdStr.isEmpty()) {\n firstPagePath = folderPath + QString(\"/%1_00000.png\").arg(notebookIdStr);\n firstAnnotatedPagePath = folderPath + QString(\"/annotated_%1_00000.png\").arg(notebookIdStr);\n } else {\n // Fallback if no ID, try a generic name (less ideal)\n // This situation should be rare if notebooks are managed properly\n // For robustness, one might iterate files or use a known default page name\n // For this example, we'll stick to a pattern that might not always work without an ID\n // Consider that `InkCanvas(nullptr).property(\"notebookId\")` was problematic as `notebookId` is instance specific.\n }\n\n QImage pageImage;\n if (!firstAnnotatedPagePath.isEmpty() && QFile::exists(firstAnnotatedPagePath)) {\n pageImage.load(firstAnnotatedPagePath);\n } else if (!firstPagePath.isEmpty() && QFile::exists(firstPagePath)) {\n pageImage.load(firstPagePath);\n }\n\n if (!pageImage.isNull()) {\n painter.drawImage(coverImage.rect(), pageImage, pageImage.rect());\n } else {\n // If no image found, draw a placeholder\n painter.fillRect(coverImage.rect(), Qt::darkGray);\n painter.setPen(Qt::white);\n painter.drawText(coverImage.rect(), Qt::AlignCenter, tr(\"No Page 0 Preview\"));\n }\n }\n coverImage.save(coverFilePath, \"PNG\");\n}\n private:\n void loadRecentNotebooks() {\n recentNotebookPaths = settings.value(\"recentNotebooks\").toStringList();\n}\n void saveRecentNotebooks() {\n settings.setValue(\"recentNotebooks\", recentNotebookPaths);\n}\n QString getCoverImageDir() const {\n return QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + \"/RecentCovers/\";\n}\n QString sanitizeFolderName(const QString& folderPath) const {\n return QFileInfo(folderPath).baseName().replace(QRegularExpression(\"[^a-zA-Z0-9_]\"), \"_\");\n}\n QStringList recentNotebookPaths;\n const int MAX_RECENT_NOTEBOOKS = 16;\n QSettings settings;\n};"], ["/SpeedyNote/source/RecentNotebooksDialog.h", "class QPushButton {\n Q_OBJECT\n\npublic:\n explicit RecentNotebooksDialog(MainWindow *mainWindow, RecentNotebooksManager *manager, QWidget *parent = nullptr);\n private:\n void onNotebookClicked() {\n QPushButton *button = qobject_cast(sender());\n if (button) {\n QString notebookPath = button->property(\"notebookPath\").toString();\n if (!notebookPath.isEmpty() && mainWindowRef) {\n // This logic is similar to MainWindow::selectFolder but directly sets the folder.\n InkCanvas *canvas = mainWindowRef->currentCanvas(); // Get current canvas from MainWindow\n if (canvas) {\n if (canvas->isEdited()){\n mainWindowRef->saveCurrentPage(); // Use MainWindow's save method\n }\n canvas->setSaveFolder(notebookPath);\n mainWindowRef->switchPageWithDirection(1, 1); // Use MainWindow's direction-aware switchPage method\n mainWindowRef->pageInput->setValue(1); // Update pageInput in MainWindow\n mainWindowRef->updateTabLabel(); // Update tab label in MainWindow\n \n // Update recent notebooks list and refresh cover page\n if (notebookManager) {\n // Generate and save fresh cover preview\n notebookManager->generateAndSaveCoverPreview(notebookPath, canvas);\n // Add/update in recent list (this moves it to the top)\n notebookManager->addRecentNotebook(notebookPath, canvas);\n }\n }\n accept(); // Close the dialog\n }\n }\n}\n private:\n void setupUi() {\n QVBoxLayout *mainLayout = new QVBoxLayout(this);\n QScrollArea *scrollArea = new QScrollArea(this);\n scrollArea->setWidgetResizable(true);\n QWidget *gridContainer = new QWidget();\n gridLayout = new QGridLayout(gridContainer);\n gridLayout->setSpacing(15);\n\n scrollArea->setWidget(gridContainer);\n mainLayout->addWidget(scrollArea);\n setLayout(mainLayout);\n}\n void populateGrid() {\n QStringList recentPaths = notebookManager->getRecentNotebooks();\n int row = 0;\n int col = 0;\n const int numCols = 4;\n\n for (const QString &path : recentPaths) {\n if (path.isEmpty()) continue;\n\n QPushButton *button = new QPushButton(this);\n button->setFixedSize(180, 180); // Larger buttons\n button->setProperty(\"notebookPath\", path); // Store path for slot\n connect(button, &QPushButton::clicked, this, &RecentNotebooksDialog::onNotebookClicked);\n\n QVBoxLayout *buttonLayout = new QVBoxLayout(button);\n buttonLayout->setContentsMargins(5,5,5,5);\n\n QLabel *coverLabel = new QLabel(this);\n coverLabel->setFixedSize(170, 127); // 4:3 aspect ratio for cover\n coverLabel->setAlignment(Qt::AlignCenter);\n QString coverPath = notebookManager->getCoverImagePathForNotebook(path);\n if (!coverPath.isEmpty()) {\n QPixmap coverPixmap(coverPath);\n coverLabel->setPixmap(coverPixmap.scaled(coverLabel->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));\n } else {\n coverLabel->setText(tr(\"No Preview\"));\n }\n coverLabel->setStyleSheet(\"border: 1px solid gray;\");\n\n QLabel *nameLabel = new QLabel(notebookManager->getNotebookDisplayName(path), this);\n nameLabel->setAlignment(Qt::AlignCenter);\n nameLabel->setWordWrap(true);\n nameLabel->setFixedHeight(40); // Fixed height for name label\n\n buttonLayout->addWidget(coverLabel);\n buttonLayout->addWidget(nameLabel);\n button->setLayout(buttonLayout);\n\n gridLayout->addWidget(button, row, col);\n\n col++;\n if (col >= numCols) {\n col = 0;\n row++;\n }\n }\n}\n RecentNotebooksManager *notebookManager;\n QGridLayout *gridLayout;\n MainWindow *mainWindowRef;\n};"], ["/SpeedyNote/source/ControllerMappingDialog.h", "class SDLControllerManager {\n Q_OBJECT\n\npublic:\n explicit ControllerMappingDialog(SDLControllerManager *controllerManager, QWidget *parent = nullptr);\n private:\n void startButtonMapping(const QString &logicalButton) {\n if (!controller) return;\n \n // Disable all mapping buttons during mapping\n for (auto button : mappingButtons) {\n button->setEnabled(false);\n }\n \n // Update the current button being mapped\n currentMappingButton = logicalButton;\n mappingButtons[logicalButton]->setText(tr(\"Press button...\"));\n \n // Start button detection mode\n controller->startButtonDetection();\n \n // Start timeout timer\n mappingTimeoutTimer->start();\n \n // Show status message\n QApplication::setOverrideCursor(Qt::WaitCursor);\n}\n void onRawButtonPressed(int sdlButton, const QString &buttonName) {\n if (currentMappingButton.isEmpty()) return;\n \n // Stop detection and timeout\n controller->stopButtonDetection();\n mappingTimeoutTimer->stop();\n QApplication::restoreOverrideCursor();\n \n // Check if this button is already mapped to another function\n QMap currentMappings = controller->getAllPhysicalMappings();\n QString conflictingButton;\n for (auto it = currentMappings.begin(); it != currentMappings.end(); ++it) {\n if (it.value() == sdlButton && it.key() != currentMappingButton) {\n conflictingButton = it.key();\n break;\n }\n }\n \n if (!conflictingButton.isEmpty()) {\n int ret = QMessageBox::question(this, tr(\"Button Conflict\"), \n tr(\"The button '%1' is already mapped to '%2'.\\n\\nDo you want to reassign it to '%3'?\")\n .arg(buttonName).arg(conflictingButton).arg(currentMappingButton),\n QMessageBox::Yes | QMessageBox::No);\n \n if (ret != QMessageBox::Yes) {\n // Reset UI and return\n mappingButtons[currentMappingButton]->setText(tr(\"Map\"));\n for (auto button : mappingButtons) {\n button->setEnabled(true);\n }\n currentMappingButton.clear();\n return;\n }\n \n // Clear the conflicting mapping\n controller->setPhysicalButtonMapping(conflictingButton, -1);\n currentMappingLabels[conflictingButton]->setText(\"Not mapped\");\n currentMappingLabels[conflictingButton]->setStyleSheet(\"color: gray;\");\n }\n \n // Set the new mapping\n controller->setPhysicalButtonMapping(currentMappingButton, sdlButton);\n \n // Get appropriate text color for current theme\n QString textColor = isDarkMode() ? \"white\" : \"black\";\n \n // Update UI\n currentMappingLabels[currentMappingButton]->setText(buttonName);\n currentMappingLabels[currentMappingButton]->setStyleSheet(QString(\"color: %1; font-weight: bold;\").arg(textColor));\n mappingButtons[currentMappingButton]->setText(tr(\"Map\"));\n \n // Re-enable all buttons\n for (auto button : mappingButtons) {\n button->setEnabled(true);\n }\n \n currentMappingButton.clear();\n \n QMessageBox::information(this, tr(\"Mapping Complete\"), \n tr(\"Button '%1' has been successfully mapped!\").arg(buttonName));\n}\n void resetToDefaults() {\n int ret = QMessageBox::question(this, tr(\"Reset to Defaults\"), \n tr(\"Are you sure you want to reset all button mappings to their default values?\\n\\nThis will overwrite your current configuration.\"),\n QMessageBox::Yes | QMessageBox::No);\n \n if (ret == QMessageBox::Yes) {\n // Get default mappings and apply them\n QMap defaults = controller->getDefaultMappings();\n for (auto it = defaults.begin(); it != defaults.end(); ++it) {\n controller->setPhysicalButtonMapping(it.key(), it.value());\n }\n \n // Update display\n updateMappingDisplay();\n \n QMessageBox::information(this, tr(\"Reset Complete\"), \n tr(\"All button mappings have been reset to their default values.\"));\n }\n}\n void applyMappings() {\n // Mappings are already applied in real-time, just close the dialog\n accept();\n}\n private:\n SDLControllerManager *controller;\n QGridLayout *mappingLayout;\n QMap buttonLabels;\n QMap currentMappingLabels;\n QMap mappingButtons;\n QPushButton *resetButton;\n QPushButton *applyButton;\n QPushButton *cancelButton;\n QString currentMappingButton;\n QTimer *mappingTimeoutTimer;\n void setupUI() {\n QVBoxLayout *mainLayout = new QVBoxLayout(this);\n \n // Instructions\n QLabel *instructionLabel = new QLabel(tr(\"Map your physical controller buttons to Joy-Con functions.\\n\"\n \"Click 'Map' next to each function, then press the corresponding button on your controller.\"), this);\n instructionLabel->setWordWrap(true);\n instructionLabel->setStyleSheet(\"font-weight: bold; margin-bottom: 10px;\");\n mainLayout->addWidget(instructionLabel);\n \n // Mapping grid\n QWidget *mappingWidget = new QWidget(this);\n mappingLayout = new QGridLayout(mappingWidget);\n \n // Headers\n mappingLayout->addWidget(new QLabel(tr(\"Joy-Con Function\"), this), 0, 0);\n mappingLayout->addWidget(new QLabel(tr(\"Description\"), this), 0, 1);\n mappingLayout->addWidget(new QLabel(tr(\"Current Mapping\"), this), 0, 2);\n mappingLayout->addWidget(new QLabel(tr(\"Action\"), this), 0, 3);\n \n // Get logical button descriptions\n QMap descriptions = getLogicalButtonDescriptions();\n \n // Create mapping rows for each logical button\n QStringList logicalButtons = {\"LEFTSHOULDER\", \"RIGHTSHOULDER\", \"PADDLE2\", \"PADDLE4\", \n \"Y\", \"A\", \"B\", \"X\", \"LEFTSTICK\", \"START\", \"GUIDE\"};\n \n int row = 1;\n for (const QString &logicalButton : logicalButtons) {\n // Function name\n QLabel *functionLabel = new QLabel(logicalButton, this);\n functionLabel->setStyleSheet(\"font-weight: bold;\");\n buttonLabels[logicalButton] = functionLabel;\n mappingLayout->addWidget(functionLabel, row, 0);\n \n // Description\n QLabel *descLabel = new QLabel(descriptions.value(logicalButton, \"Unknown\"), this);\n descLabel->setWordWrap(true);\n mappingLayout->addWidget(descLabel, row, 1);\n \n // Current mapping display\n QLabel *currentLabel = new QLabel(\"Not mapped\", this);\n currentLabel->setStyleSheet(\"color: gray;\");\n currentMappingLabels[logicalButton] = currentLabel;\n mappingLayout->addWidget(currentLabel, row, 2);\n \n // Map button\n QPushButton *mapButton = new QPushButton(tr(\"Map\"), this);\n mappingButtons[logicalButton] = mapButton;\n connect(mapButton, &QPushButton::clicked, this, [this, logicalButton]() {\n startButtonMapping(logicalButton);\n });\n mappingLayout->addWidget(mapButton, row, 3);\n \n row++;\n }\n \n mainLayout->addWidget(mappingWidget);\n \n // Buttons\n QHBoxLayout *buttonLayout = new QHBoxLayout();\n \n resetButton = new QPushButton(tr(\"Reset to Defaults\"), this);\n connect(resetButton, &QPushButton::clicked, this, &ControllerMappingDialog::resetToDefaults);\n buttonLayout->addWidget(resetButton);\n \n buttonLayout->addStretch();\n \n applyButton = new QPushButton(tr(\"Apply\"), this);\n connect(applyButton, &QPushButton::clicked, this, &ControllerMappingDialog::applyMappings);\n buttonLayout->addWidget(applyButton);\n \n cancelButton = new QPushButton(tr(\"Cancel\"), this);\n connect(cancelButton, &QPushButton::clicked, this, &QDialog::reject);\n buttonLayout->addWidget(cancelButton);\n \n mainLayout->addLayout(buttonLayout);\n}\n QMap getLogicalButtonDescriptions() const {\n QMap descriptions;\n descriptions[\"LEFTSHOULDER\"] = tr(\"L Button (Left Shoulder)\");\n descriptions[\"RIGHTSHOULDER\"] = tr(\"ZL Button (Left Trigger)\");\n descriptions[\"PADDLE2\"] = tr(\"SL Button (Side Left)\");\n descriptions[\"PADDLE4\"] = tr(\"SR Button (Side Right)\");\n descriptions[\"Y\"] = tr(\"Up Arrow (D-Pad Up)\");\n descriptions[\"A\"] = tr(\"Down Arrow (D-Pad Down)\");\n descriptions[\"B\"] = tr(\"Left Arrow (D-Pad Left)\");\n descriptions[\"X\"] = tr(\"Right Arrow (D-Pad Right)\");\n descriptions[\"LEFTSTICK\"] = tr(\"Analog Stick Press\");\n descriptions[\"START\"] = tr(\"Minus Button (-)\");\n descriptions[\"GUIDE\"] = tr(\"Screenshot Button\");\n return descriptions;\n}\n void loadCurrentMappings() {\n QMap currentMappings = controller->getAllPhysicalMappings();\n \n // Get appropriate text color for current theme\n QString textColor = isDarkMode() ? \"white\" : \"black\";\n \n for (auto it = currentMappings.begin(); it != currentMappings.end(); ++it) {\n const QString &logicalButton = it.key();\n int physicalButton = it.value();\n \n if (currentMappingLabels.contains(logicalButton)) {\n QString physicalName = controller->getPhysicalButtonName(physicalButton);\n currentMappingLabels[logicalButton]->setText(physicalName);\n currentMappingLabels[logicalButton]->setStyleSheet(QString(\"color: %1; font-weight: bold;\").arg(textColor));\n }\n }\n}\n void updateMappingDisplay() {\n loadCurrentMappings();\n}\n bool isDarkMode() const {\n // Same logic as MainWindow::isDarkMode()\n QColor bg = palette().color(QPalette::Window);\n return bg.lightness() < 128; // Lightness scale: 0 (black) - 255 (white)\n}\n};"], ["/SpeedyNote/markdown/qplaintexteditsearchwidget.h", "class QPlainTextEditSearchWidget {\n Q_OBJECT\n\n public:\n enum SearchMode { PlainTextMode, WholeWordsMode, RegularExpressionMode };\n explicit QPlainTextEditSearchWidget(QPlainTextEdit *parent = nullptr) {\n ui->setupUi(this);\n _textEdit = parent;\n _darkMode = false;\n hide();\n ui->searchCountLabel->setStyleSheet(QStringLiteral(\"* {color: grey}\"));\n // hiding will leave a open space in the horizontal layout\n ui->searchCountLabel->setEnabled(false);\n _currentSearchResult = 0;\n _searchResultCount = 0;\n\n connect(ui->closeButton, &QPushButton::clicked, this,\n &QPlainTextEditSearchWidget::deactivate);\n connect(ui->searchLineEdit, &QLineEdit::textChanged, this,\n &QPlainTextEditSearchWidget::searchLineEditTextChanged);\n connect(ui->searchDownButton, &QPushButton::clicked, this,\n &QPlainTextEditSearchWidget::doSearchDown);\n connect(ui->searchUpButton, &QPushButton::clicked, this,\n &QPlainTextEditSearchWidget::doSearchUp);\n connect(ui->replaceToggleButton, &QPushButton::toggled, this,\n &QPlainTextEditSearchWidget::setReplaceMode);\n connect(ui->replaceButton, &QPushButton::clicked, this,\n &QPlainTextEditSearchWidget::doReplace);\n connect(ui->replaceAllButton, &QPushButton::clicked, this,\n &QPlainTextEditSearchWidget::doReplaceAll);\n\n connect(&_debounceTimer, &QTimer::timeout, this,\n &QPlainTextEditSearchWidget::performSearch);\n\n installEventFilter(this);\n ui->searchLineEdit->installEventFilter(this);\n ui->replaceLineEdit->installEventFilter(this);\n\n#ifdef Q_OS_MAC\n // set the spacing to 8 for OS X\n layout()->setSpacing(8);\n ui->buttonFrame->layout()->setSpacing(9);\n\n // set the margin to 0 for the top buttons for OS X\n QString buttonStyle = QStringLiteral(\"QPushButton {margin: 0}\");\n ui->closeButton->setStyleSheet(buttonStyle);\n ui->searchDownButton->setStyleSheet(buttonStyle);\n ui->searchUpButton->setStyleSheet(buttonStyle);\n ui->replaceToggleButton->setStyleSheet(buttonStyle);\n ui->matchCaseSensitiveButton->setStyleSheet(buttonStyle);\n#endif\n}\n bool doSearch(bool searchDown = true, bool allowRestartAtTop = true,\n bool updateUI = true) {\n if (_debounceTimer.isActive()) {\n stopDebounce();\n }\n\n const QString text = ui->searchLineEdit->text();\n\n if (text.isEmpty()) {\n if (updateUI) {\n ui->searchLineEdit->setStyleSheet(QLatin1String(\"\"));\n }\n\n return false;\n }\n\n const int searchMode = ui->modeComboBox->currentIndex();\n const bool caseSensitive = ui->matchCaseSensitiveButton->isChecked();\n\n QFlags options =\n searchDown ? QTextDocument::FindFlag(0) : QTextDocument::FindBackward;\n if (searchMode == WholeWordsMode) {\n options |= QTextDocument::FindWholeWords;\n }\n\n if (caseSensitive) {\n options |= QTextDocument::FindCaseSensitively;\n }\n\n // block signal to reduce too many signals being fired and too many updates\n _textEdit->blockSignals(true);\n\n bool found =\n searchMode == RegularExpressionMode\n ?\n#if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0))\n _textEdit->find(\n QRegularExpression(\n text, caseSensitive\n ? QRegularExpression::NoPatternOption\n : QRegularExpression::CaseInsensitiveOption),\n options)\n :\n#else\n _textEdit->find(QRegExp(text, caseSensitive ? Qt::CaseSensitive\n : Qt::CaseInsensitive),\n options)\n :\n#endif\n _textEdit->find(text, options);\n\n _textEdit->blockSignals(false);\n\n if (found) {\n const int result =\n searchDown ? ++_currentSearchResult : --_currentSearchResult;\n _currentSearchResult = std::min(result, _searchResultCount);\n\n updateSearchCountLabelText();\n }\n\n // start at the top (or bottom) if not found\n if (!found && allowRestartAtTop) {\n _textEdit->moveCursor(searchDown ? QTextCursor::Start\n : QTextCursor::End);\n found =\n searchMode == RegularExpressionMode\n ?\n#if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0))\n _textEdit->find(\n QRegularExpression(\n text, caseSensitive\n ? QRegularExpression::NoPatternOption\n : QRegularExpression::CaseInsensitiveOption),\n options)\n :\n#else\n _textEdit->find(\n QRegExp(text, caseSensitive ? Qt::CaseSensitive\n : Qt::CaseInsensitive),\n options)\n :\n#endif\n _textEdit->find(text, options);\n\n if (found && updateUI) {\n _currentSearchResult = searchDown ? 1 : _searchResultCount;\n updateSearchCountLabelText();\n }\n }\n\n if (updateUI) {\n const QRect rect = _textEdit->cursorRect();\n QMargins margins = _textEdit->layout()->contentsMargins();\n const int searchWidgetHotArea = _textEdit->height() - this->height();\n const int marginBottom =\n (rect.y() > searchWidgetHotArea) ? (this->height() + 10) : 0;\n\n // move the search box a bit up if we would block the search result\n if (margins.bottom() != marginBottom) {\n margins.setBottom(marginBottom);\n _textEdit->layout()->setContentsMargins(margins);\n }\n\n // add a background color according if we found the text or not\n const QString bgColorCode = _darkMode\n ? (found ? QStringLiteral(\"#135a13\")\n : QStringLiteral(\"#8d2b36\"))\n : found ? QStringLiteral(\"#D5FAE2\")\n : QStringLiteral(\"#FAE9EB\");\n const QString fgColorCode =\n _darkMode ? QStringLiteral(\"#cccccc\") : QStringLiteral(\"#404040\");\n\n ui->searchLineEdit->setStyleSheet(\n QStringLiteral(\"* { background: \") + bgColorCode +\n QStringLiteral(\"; color: \") + fgColorCode + QStringLiteral(\"; }\"));\n\n // restore the search extra selections after the find command\n this->setSearchExtraSelections();\n }\n\n return found;\n}\n void setDarkMode(bool enabled) {\n _darkMode = enabled;\n}\n ~QPlainTextEditSearchWidget() { delete ui; }\n void setSearchText(const QString &searchText) {\n ui->searchLineEdit->setText(searchText);\n}\n void setSearchMode(SearchMode searchMode) {\n ui->modeComboBox->setCurrentIndex(searchMode);\n}\n void setDebounceDelay(uint debounceDelay) {\n _debounceTimer.setInterval(static_cast(debounceDelay));\n}\n void activate(bool focus) {\n setReplaceMode(ui->modeComboBox->currentIndex() !=\n SearchMode::PlainTextMode);\n show();\n\n // preset the selected text as search text if there is any and there is no\n // other search text\n const QString selectedText = _textEdit->textCursor().selectedText();\n if (!selectedText.isEmpty() && ui->searchLineEdit->text().isEmpty()) {\n ui->searchLineEdit->setText(selectedText);\n }\n\n if (focus) {\n ui->searchLineEdit->setFocus();\n }\n\n ui->searchLineEdit->selectAll();\n updateSearchExtraSelections();\n doSearchDown();\n}\n void clearSearchExtraSelections() {\n _searchExtraSelections.clear();\n setSearchExtraSelections();\n}\n void updateSearchExtraSelections() {\n _searchExtraSelections.clear();\n const auto textCursor = _textEdit->textCursor();\n _textEdit->moveCursor(QTextCursor::Start);\n const QColor color = selectionColor;\n QTextCharFormat extraFmt;\n extraFmt.setBackground(color);\n int findCounter = 0;\n const int searchMode = ui->modeComboBox->currentIndex();\n\n while (doSearch(true, false, false)) {\n findCounter++;\n\n // prevent infinite loops from regular expression searches like \"$\", \"^\"\n // or \"\\b\"\n if (searchMode == RegularExpressionMode && findCounter >= 10000) {\n break;\n }\n\n QTextEdit::ExtraSelection extra = QTextEdit::ExtraSelection();\n extra.format = extraFmt;\n\n extra.cursor = _textEdit->textCursor();\n _searchExtraSelections.append(extra);\n }\n\n _textEdit->setTextCursor(textCursor);\n this->setSearchExtraSelections();\n}\n private:\n Ui::QPlainTextEditSearchWidget *ui;\n int _searchResultCount;\n int _currentSearchResult;\n QList _searchExtraSelections;\n QColor selectionColor;\n QTimer _debounceTimer;\n QString _searchTerm;\n void setSearchExtraSelections() const {\n this->_textEdit->setExtraSelections(this->_searchExtraSelections);\n}\n void stopDebounce() {\n _debounceTimer.stop();\n ui->searchDownButton->setEnabled(true);\n ui->searchUpButton->setEnabled(true);\n}\n protected:\n QPlainTextEdit *_textEdit;\n bool _darkMode;\n bool eventFilter(QObject *obj, QEvent *event) override {\n if (event->type() == QEvent::KeyPress) {\n auto *keyEvent = static_cast(event);\n\n if (keyEvent->key() == Qt::Key_Escape) {\n deactivate();\n return true;\n } else if ((!_debounceTimer.isActive() &&\n keyEvent->modifiers().testFlag(Qt::ShiftModifier) &&\n (keyEvent->key() == Qt::Key_Return)) ||\n (keyEvent->key() == Qt::Key_Up)) {\n doSearchUp();\n return true;\n } else if (!_debounceTimer.isActive() &&\n ((keyEvent->key() == Qt::Key_Return) ||\n (keyEvent->key() == Qt::Key_Down))) {\n doSearchDown();\n return true;\n } else if (!_debounceTimer.isActive() &&\n keyEvent->key() == Qt::Key_F3) {\n doSearch(!keyEvent->modifiers().testFlag(Qt::ShiftModifier));\n return true;\n }\n\n // if ((obj == ui->replaceLineEdit) && (keyEvent->key() ==\n // Qt::Key_Tab)\n // && ui->replaceToggleButton->isChecked()) {\n // ui->replaceLineEdit->setFocus();\n // }\n\n return false;\n }\n\n return QWidget::eventFilter(obj, event);\n}\n public:\n void activate() {\n setReplaceMode(ui->modeComboBox->currentIndex() !=\n SearchMode::PlainTextMode);\n show();\n\n // preset the selected text as search text if there is any and there is no\n // other search text\n const QString selectedText = _textEdit->textCursor().selectedText();\n if (!selectedText.isEmpty() && ui->searchLineEdit->text().isEmpty()) {\n ui->searchLineEdit->setText(selectedText);\n }\n\n if (focus) {\n ui->searchLineEdit->setFocus();\n }\n\n ui->searchLineEdit->selectAll();\n updateSearchExtraSelections();\n doSearchDown();\n}\n void deactivate() {\n stopDebounce();\n\n hide();\n\n // Clear the search extra selections when closing the search bar\n clearSearchExtraSelections();\n\n _textEdit->setFocus();\n}\n void doSearchDown() { doSearch(true); }\n void doSearchUp() { doSearch(false); }\n void setReplaceMode(bool enabled) {\n ui->replaceToggleButton->setChecked(enabled);\n ui->replaceLabel->setVisible(enabled);\n ui->replaceLineEdit->setVisible(enabled);\n ui->modeLabel->setVisible(enabled);\n ui->buttonFrame->setVisible(enabled);\n ui->matchCaseSensitiveButton->setVisible(enabled);\n}\n void activateReplace() {\n // replacing is prohibited if the text edit is readonly\n if (_textEdit->isReadOnly()) {\n return;\n }\n\n ui->searchLineEdit->setText(_textEdit->textCursor().selectedText());\n ui->searchLineEdit->selectAll();\n activate();\n setReplaceMode(true);\n}\n bool doReplace(bool forAll = false) {\n if (_textEdit->isReadOnly()) {\n return false;\n }\n\n QTextCursor cursor = _textEdit->textCursor();\n\n if (!forAll && cursor.selectedText().isEmpty()) {\n return false;\n }\n\n const int searchMode = ui->modeComboBox->currentIndex();\n if (searchMode == RegularExpressionMode) {\n QString text = cursor.selectedText();\n text.replace(QRegularExpression(ui->searchLineEdit->text()),\n ui->replaceLineEdit->text());\n cursor.insertText(text);\n } else {\n cursor.insertText(ui->replaceLineEdit->text());\n }\n\n if (!forAll) {\n const int position = cursor.position();\n\n if (!doSearch(true)) {\n // restore the last cursor position if text wasn't found any more\n cursor.setPosition(position);\n _textEdit->setTextCursor(cursor);\n }\n }\n\n return true;\n}\n void doReplaceAll() {\n if (_textEdit->isReadOnly()) {\n return;\n }\n\n // start at the top\n _textEdit->moveCursor(QTextCursor::Start);\n\n // replace until everything to the bottom is replaced\n while (doSearch(true, false) && doReplace(true)) {\n }\n}\n void reset() {\n ui->searchLineEdit->clear();\n setSearchMode(SearchMode::PlainTextMode);\n setReplaceMode(false);\n ui->searchCountLabel->setEnabled(false);\n}\n void doSearchCount() {\n // Note that we are moving the anchor, so the search will start from the top\n // again! Alternative: Restore cursor position afterward, but then we will\n // not know\n // at what _currentSearchResult we currently are\n _textEdit->moveCursor(QTextCursor::Start, QTextCursor::MoveAnchor);\n\n bool found;\n _searchResultCount = 0;\n _currentSearchResult = 0;\n const int searchMode = ui->modeComboBox->currentIndex();\n\n do {\n found = doSearch(true, false, false);\n if (found) {\n _searchResultCount++;\n }\n\n // prevent infinite loops from regular expression searches like \"$\", \"^\"\n // or \"\\b\"\n if (searchMode == RegularExpressionMode &&\n _searchResultCount >= 10000) {\n break;\n }\n } while (found);\n\n updateSearchCountLabelText();\n}\n protected:\n void searchLineEditTextChanged(const QString &arg1) {\n _searchTerm = arg1;\n\n if (_debounceTimer.interval() != 0 && !_searchTerm.isEmpty()) {\n _debounceTimer.start();\n ui->searchDownButton->setEnabled(false);\n ui->searchUpButton->setEnabled(false);\n } else {\n performSearch();\n }\n}\n void performSearch() {\n doSearchCount();\n updateSearchExtraSelections();\n doSearchDown();\n}\n void updateSearchCountLabelText() {\n ui->searchCountLabel->setEnabled(true);\n ui->searchCountLabel->setText(QStringLiteral(\"%1/%2\").arg(\n _currentSearchResult == 0 ? QChar('-')\n : QString::number(_currentSearchResult),\n _searchResultCount == 0 ? QChar('-')\n : QString::number(_searchResultCount)));\n}\n void setSearchSelectionColor(const QColor &color) {\n selectionColor = color;\n}\n private:\n void on_modeComboBox_currentIndexChanged(int index) {\n Q_UNUSED(index)\n doSearchCount();\n doSearchDown();\n}\n void on_matchCaseSensitiveButton_toggled(bool checked) {\n Q_UNUSED(checked)\n doSearchCount();\n doSearchDown();\n}\n};"], ["/SpeedyNote/source/SDLControllerManager.h", "class SDLControllerManager {\n Q_OBJECT\npublic:\n explicit SDLControllerManager(QObject *parent = nullptr);\n ~SDLControllerManager() {\n if (joystick) SDL_JoystickClose(joystick);\n if (sdlInitialized) SDL_QuitSubSystem(SDL_INIT_JOYSTICK);\n}\n void setPhysicalButtonMapping(const QString &logicalButton, int physicalSDLButton) {\n physicalButtonMappings[logicalButton] = physicalSDLButton;\n saveControllerMappings();\n}\n int getPhysicalButtonMapping(const QString &logicalButton) const {\n return physicalButtonMappings.value(logicalButton, -1);\n}\n QMap getAllPhysicalMappings() const {\n return physicalButtonMappings;\n}\n void saveControllerMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.beginGroup(\"ControllerPhysicalMappings\");\n for (auto it = physicalButtonMappings.begin(); it != physicalButtonMappings.end(); ++it) {\n settings.setValue(it.key(), it.value());\n }\n settings.endGroup();\n}\n void loadControllerMappings() {\n QSettings settings(\"SpeedyNote\", \"App\");\n settings.beginGroup(\"ControllerPhysicalMappings\");\n QStringList keys = settings.allKeys();\n \n if (keys.isEmpty()) {\n // No saved mappings, use defaults\n physicalButtonMappings = getDefaultMappings();\n saveControllerMappings(); // Save defaults for next time\n } else {\n // Load saved mappings\n for (const QString &key : keys) {\n physicalButtonMappings[key] = settings.value(key).toInt();\n }\n }\n settings.endGroup();\n}\n QStringList getAvailablePhysicalButtons() const {\n QStringList buttons;\n if (joystick) {\n int buttonCount = SDL_JoystickNumButtons(joystick);\n for (int i = 0; i < buttonCount; ++i) {\n buttons << getPhysicalButtonName(i);\n }\n } else {\n // If no joystick connected, show a reasonable range\n for (int i = 0; i < 20; ++i) {\n buttons << getPhysicalButtonName(i);\n }\n }\n return buttons;\n}\n QString getPhysicalButtonName(int sdlButton) const {\n // Return human-readable names for physical SDL joystick buttons\n // Since we're using raw joystick buttons, we'll use generic names\n return QString(\"Button %1\").arg(sdlButton);\n}\n int getJoystickButtonCount() const {\n if (joystick) {\n return SDL_JoystickNumButtons(joystick);\n }\n return 0;\n}\n QMap getDefaultMappings() const {\n // Default mappings for Joy-Con L using raw button indices\n // These will need to be adjusted based on actual Joy-Con button indices\n QMap defaults;\n defaults[\"LEFTSHOULDER\"] = 4; // L button\n defaults[\"RIGHTSHOULDER\"] = 6; // ZL button \n defaults[\"PADDLE2\"] = 14; // SL button\n defaults[\"PADDLE4\"] = 15; // SR button\n defaults[\"Y\"] = 0; // Up arrow\n defaults[\"A\"] = 1; // Down arrow\n defaults[\"B\"] = 2; // Left arrow\n defaults[\"X\"] = 3; // Right arrow\n defaults[\"LEFTSTICK\"] = 10; // Stick press\n defaults[\"START\"] = 8; // Minus button\n defaults[\"GUIDE\"] = 13; // Screenshot button\n return defaults;\n}\n void buttonHeld(QString buttonName);\n void buttonReleased(QString buttonName);\n void buttonSinglePress(QString buttonName);\n void leftStickAngleChanged(int angle);\n void leftStickReleased();\n void rawButtonPressed(int sdlButton, QString buttonName);\n public:\n void start() {\n if (!sdlInitialized) {\n if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) != 0) {\n qWarning() << \"Failed to initialize SDL joystick subsystem:\" << SDL_GetError();\n return;\n }\n sdlInitialized = true;\n }\n\n SDL_JoystickEventState(SDL_ENABLE); // ✅ Enable joystick events\n\n // Look for any available joystick\n int numJoysticks = SDL_NumJoysticks();\n // qDebug() << \"Found\" << numJoysticks << \"joystick(s)\";\n \n for (int i = 0; i < numJoysticks; ++i) {\n const char* joystickName = SDL_JoystickNameForIndex(i);\n // qDebug() << \"Joystick\" << i << \":\" << (joystickName ? joystickName : \"Unknown\");\n \n joystick = SDL_JoystickOpen(i);\n if (joystick) {\n // qDebug() << \"Joystick connected!\";\n // qDebug() << \"Number of buttons:\" << SDL_JoystickNumButtons(joystick);\n // qDebug() << \"Number of axes:\" << SDL_JoystickNumAxes(joystick);\n // qDebug() << \"Number of hats:\" << SDL_JoystickNumHats(joystick);\n break;\n }\n }\n\n if (!joystick) {\n qWarning() << \"No joystick could be opened\";\n }\n\n pollTimer->start(16); // 60 FPS polling\n}\n void stop() {\n pollTimer->stop();\n}\n void reconnect() {\n // Stop current polling\n pollTimer->stop();\n \n // Close existing joystick if open\n if (joystick) {\n SDL_JoystickClose(joystick);\n joystick = nullptr;\n }\n \n // Clear any cached state\n buttonPressTime.clear();\n buttonHeldEmitted.clear();\n lastAngle = -1;\n leftStickActive = false;\n buttonDetectionMode = false;\n \n // Re-initialize SDL joystick subsystem\n SDL_QuitSubSystem(SDL_INIT_JOYSTICK);\n if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) != 0) {\n qWarning() << \"Failed to re-initialize SDL joystick subsystem:\" << SDL_GetError();\n sdlInitialized = false;\n return;\n }\n sdlInitialized = true;\n \n SDL_JoystickEventState(SDL_ENABLE);\n \n // Look for any available joystick\n int numJoysticks = SDL_NumJoysticks();\n qDebug() << \"Reconnect: Found\" << numJoysticks << \"joystick(s)\";\n \n for (int i = 0; i < numJoysticks; ++i) {\n const char* joystickName = SDL_JoystickNameForIndex(i);\n qDebug() << \"Reconnect: Trying joystick\" << i << \":\" << (joystickName ? joystickName : \"Unknown\");\n \n joystick = SDL_JoystickOpen(i);\n if (joystick) {\n qDebug() << \"Reconnect: Joystick connected successfully!\";\n qDebug() << \"Number of buttons:\" << SDL_JoystickNumButtons(joystick);\n qDebug() << \"Number of axes:\" << SDL_JoystickNumAxes(joystick);\n qDebug() << \"Number of hats:\" << SDL_JoystickNumHats(joystick);\n break;\n }\n }\n \n if (!joystick) {\n qWarning() << \"Reconnect: No joystick could be opened\";\n }\n \n // Restart polling\n pollTimer->start(16); // 60 FPS polling\n}\n void startButtonDetection() {\n buttonDetectionMode = true;\n}\n void stopButtonDetection() {\n buttonDetectionMode = false;\n}\n private:\n QTimer *pollTimer;\n SDL_Joystick *joystick = nullptr;\n bool sdlInitialized = false;\n bool leftStickActive = false;\n bool buttonDetectionMode = false;\n int lastAngle = -1;\n QString getButtonName(Uint8 sdlButton) {\n // This method is now deprecated in favor of getLogicalButtonName\n return getLogicalButtonName(sdlButton);\n}\n QString getLogicalButtonName(Uint8 sdlButton) {\n // Find which logical button this physical button is mapped to\n for (auto it = physicalButtonMappings.begin(); it != physicalButtonMappings.end(); ++it) {\n if (it.value() == sdlButton) {\n return it.key(); // Return the logical button name\n }\n }\n return QString(); // Return empty string if not mapped\n}\n QMap physicalButtonMappings;\n QMap buttonPressTime;\n QMap buttonHeldEmitted;\n const quint32 HOLD_THRESHOLD = 300;\n const quint32 POLL_INTERVAL = 16;\n};"], ["/SpeedyNote/markdown/linenumberarea.h", "#ifndef LINENUMBERAREA_H\n#define LINENUMBERAREA_H\n\n#include \n#include \n#include \n#include \n\n#include \"qmarkdowntextedit.h\"\n\nclass LineNumArea final : public QWidget {\n Q_OBJECT\n\n public:\n explicit LineNumArea(QMarkdownTextEdit *parent)\n : QWidget(parent), textEdit(parent) {\n Q_ASSERT(parent);\n\n _currentLineColor = QColor(QStringLiteral(\"#eef067\"));\n _otherLinesColor = QColor(QStringLiteral(\"#a6a6a6\"));\n setHidden(true);\n\n // We always use fixed font to avoid \"width\" issues\n setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont));\n }\n\n void setCurrentLineColor(QColor color) { _currentLineColor = color; }\n\n void setOtherLineColor(QColor color) {\n _otherLinesColor = std::move(color);\n }\n\n int lineNumAreaWidth() const {\n if (!enabled) {\n return 0;\n }\n\n int digits = 2;\n int max = std::max(1, textEdit->blockCount());\n while (max >= 10) {\n max /= 10;\n ++digits;\n }\n\n#if QT_VERSION >= 0x050B00\n int space =\n 13 + textEdit->fontMetrics().horizontalAdvance(u'9') * digits;\n#else\n int space =\n 13 + textEdit->fontMetrics().width(QLatin1Char('9')) * digits;\n#endif\n\n return space;\n }\n\n bool isLineNumAreaEnabled() const { return enabled; }\n\n void setLineNumAreaEnabled(bool e) {\n enabled = e;\n setHidden(!e);\n }\n\n QSize sizeHint() const override { return {lineNumAreaWidth(), 0}; }\n\n protected:\n void paintEvent(QPaintEvent *event) override {\n QPainter painter(this);\n\n painter.fillRect(event->rect(),\n palette().color(QPalette::Active, QPalette::Window));\n\n auto block = textEdit->firstVisibleBlock();\n int blockNumber = block.blockNumber();\n qreal top = textEdit->blockBoundingGeometry(block)\n .translated(textEdit->contentOffset())\n .top();\n // Maybe the top is not 0?\n top += textEdit->viewportMargins().top();\n qreal bottom = top;\n\n const QPen currentLine = _currentLineColor;\n const QPen otherLines = _otherLinesColor;\n painter.setFont(font());\n\n while (block.isValid() && top <= event->rect().bottom()) {\n top = bottom;\n bottom = top + textEdit->blockBoundingRect(block).height();\n if (block.isVisible() && bottom >= event->rect().top()) {\n QString number = QString::number(blockNumber + 1);\n\n auto isCurrentLine =\n textEdit->textCursor().blockNumber() == blockNumber;\n painter.setPen(isCurrentLine ? currentLine : otherLines);\n\n painter.drawText(-5, top, sizeHint().width(),\n textEdit->fontMetrics().height(),\n Qt::AlignRight, number);\n }\n\n block = block.next();\n ++blockNumber;\n }\n }\n\n private:\n bool enabled = false;\n QMarkdownTextEdit *textEdit;\n QColor _currentLineColor;\n QColor _otherLinesColor;\n};\n\n#endif // LINENUMBERAREA_H\n"], ["/SpeedyNote/source/Main.cpp", "#ifdef _WIN32\n#include \n#endif\n\n#include \n#include \n#include \n#include \"MainWindow.h\"\n\nint main(int argc, char *argv[]) {\n#ifdef _WIN32\n FreeConsole(); // Hide console safely on Windows\n\n /*\n AllocConsole();\n freopen(\"CONOUT$\", \"w\", stdout);\n freopen(\"CONOUT$\", \"w\", stderr);\n */\n \n \n // to show console for debugging\n \n \n#endif\n SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI, \"1\");\n SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_SWITCH, \"1\");\n SDL_Init(SDL_INIT_GAMECONTROLLER | SDL_INIT_JOYSTICK);\n\n /*\n qDebug() << \"SDL2 version:\" << SDL_GetRevision();\n qDebug() << \"Num Joysticks:\" << SDL_NumJoysticks();\n\n for (int i = 0; i < SDL_NumJoysticks(); ++i) {\n if (SDL_IsGameController(i)) {\n qDebug() << \"Controller\" << i << \"is\" << SDL_GameControllerNameForIndex(i);\n } else {\n qDebug() << \"Joystick\" << i << \"is not a recognized controller\";\n }\n }\n */ // For sdl2 debugging\n \n\n\n // Enable Windows IME support for multi-language input\n QApplication app(argc, argv);\n \n // Ensure IME is properly enabled for Windows\n #ifdef _WIN32\n app.setAttribute(Qt::AA_EnableHighDpiScaling, true);\n app.setAttribute(Qt::AA_UseHighDpiPixmaps, true);\n #endif\n\n \n QTranslator translator;\n QString locale = QLocale::system().name(); // e.g., \"zh_CN\", \"es_ES\"\n QString langCode = locale.section('_', 0, 0); // e.g., \"zh\"\n\n // printf(\"Locale: %s\\n\", locale.toStdString().c_str());\n // printf(\"Language Code: %s\\n\", langCode.toStdString().c_str());\n\n // QString locale = \"es-ES\"; // e.g., \"zh_CN\", \"es_ES\"\n // QString langCode = \"es\"; // e.g., \"zh\"\n QString translationsPath = QCoreApplication::applicationDirPath();\n\n if (translator.load(translationsPath + \"/app_\" + langCode + \".qm\")) {\n app.installTranslator(&translator);\n }\n\n QString inputFile;\n if (argc >= 2) {\n inputFile = QString::fromLocal8Bit(argv[1]);\n // qDebug() << \"Input file received:\" << inputFile;\n }\n\n MainWindow w;\n if (!inputFile.isEmpty()) {\n // Check file extension to determine how to handle it\n if (inputFile.toLower().endsWith(\".pdf\")) {\n // Handle PDF file association\n w.show(); // Show window first for dialog parent\n w.openPdfFile(inputFile);\n } else if (inputFile.toLower().endsWith(\".snpkg\")) {\n // Handle notebook package import\n w.importNotebookFromFile(inputFile);\n w.show();\n } else {\n // Unknown file type, just show the application\n w.show();\n }\n } else {\n w.show();\n }\n return app.exec();\n}\n"], ["/SpeedyNote/source/ButtonMappingTypes.h", "class InternalDialMode {\n Q_DECLARE_TR_FUNCTIONS(ButtonMappingHelper)\n public:\n static QString dialModeToInternalKey(InternalDialMode mode) {\n switch (mode) {\n case InternalDialMode::None: return \"none\";\n case InternalDialMode::PageSwitching: return \"page_switching\";\n case InternalDialMode::ZoomControl: return \"zoom_control\";\n case InternalDialMode::ThicknessControl: return \"thickness_control\";\n\n case InternalDialMode::ToolSwitching: return \"tool_switching\";\n case InternalDialMode::PresetSelection: return \"preset_selection\";\n case InternalDialMode::PanAndPageScroll: return \"pan_and_page_scroll\";\n }\n return \"none\";\n}\n static QString actionToInternalKey(InternalControllerAction action) {\n switch (action) {\n case InternalControllerAction::None: return \"none\";\n case InternalControllerAction::ToggleFullscreen: return \"toggle_fullscreen\";\n case InternalControllerAction::ToggleDial: return \"toggle_dial\";\n case InternalControllerAction::Zoom50: return \"zoom_50\";\n case InternalControllerAction::ZoomOut: return \"zoom_out\";\n case InternalControllerAction::Zoom200: return \"zoom_200\";\n case InternalControllerAction::AddPreset: return \"add_preset\";\n case InternalControllerAction::DeletePage: return \"delete_page\";\n case InternalControllerAction::FastForward: return \"fast_forward\";\n case InternalControllerAction::OpenControlPanel: return \"open_control_panel\";\n case InternalControllerAction::RedColor: return \"red_color\";\n case InternalControllerAction::BlueColor: return \"blue_color\";\n case InternalControllerAction::YellowColor: return \"yellow_color\";\n case InternalControllerAction::GreenColor: return \"green_color\";\n case InternalControllerAction::BlackColor: return \"black_color\";\n case InternalControllerAction::WhiteColor: return \"white_color\";\n case InternalControllerAction::CustomColor: return \"custom_color\";\n case InternalControllerAction::ToggleSidebar: return \"toggle_sidebar\";\n case InternalControllerAction::Save: return \"save\";\n case InternalControllerAction::StraightLineTool: return \"straight_line_tool\";\n case InternalControllerAction::RopeTool: return \"rope_tool\";\n case InternalControllerAction::SetPenTool: return \"set_pen_tool\";\n case InternalControllerAction::SetMarkerTool: return \"set_marker_tool\";\n case InternalControllerAction::SetEraserTool: return \"set_eraser_tool\";\n case InternalControllerAction::TogglePdfTextSelection: return \"toggle_pdf_text_selection\";\n case InternalControllerAction::ToggleOutline: return \"toggle_outline\";\n case InternalControllerAction::ToggleBookmarks: return \"toggle_bookmarks\";\n case InternalControllerAction::AddBookmark: return \"add_bookmark\";\n case InternalControllerAction::ToggleTouchGestures: return \"toggle_touch_gestures\";\n }\n return \"none\";\n}\n static InternalDialMode internalKeyToDialMode(const QString &key) {\n if (key == \"none\") return InternalDialMode::None;\n if (key == \"page_switching\") return InternalDialMode::PageSwitching;\n if (key == \"zoom_control\") return InternalDialMode::ZoomControl;\n if (key == \"thickness_control\") return InternalDialMode::ThicknessControl;\n\n if (key == \"tool_switching\") return InternalDialMode::ToolSwitching;\n if (key == \"preset_selection\") return InternalDialMode::PresetSelection;\n if (key == \"pan_and_page_scroll\") return InternalDialMode::PanAndPageScroll;\n return InternalDialMode::None;\n}\n static InternalControllerAction internalKeyToAction(const QString &key) {\n if (key == \"none\") return InternalControllerAction::None;\n if (key == \"toggle_fullscreen\") return InternalControllerAction::ToggleFullscreen;\n if (key == \"toggle_dial\") return InternalControllerAction::ToggleDial;\n if (key == \"zoom_50\") return InternalControllerAction::Zoom50;\n if (key == \"zoom_out\") return InternalControllerAction::ZoomOut;\n if (key == \"zoom_200\") return InternalControllerAction::Zoom200;\n if (key == \"add_preset\") return InternalControllerAction::AddPreset;\n if (key == \"delete_page\") return InternalControllerAction::DeletePage;\n if (key == \"fast_forward\") return InternalControllerAction::FastForward;\n if (key == \"open_control_panel\") return InternalControllerAction::OpenControlPanel;\n if (key == \"red_color\") return InternalControllerAction::RedColor;\n if (key == \"blue_color\") return InternalControllerAction::BlueColor;\n if (key == \"yellow_color\") return InternalControllerAction::YellowColor;\n if (key == \"green_color\") return InternalControllerAction::GreenColor;\n if (key == \"black_color\") return InternalControllerAction::BlackColor;\n if (key == \"white_color\") return InternalControllerAction::WhiteColor;\n if (key == \"custom_color\") return InternalControllerAction::CustomColor;\n if (key == \"toggle_sidebar\") return InternalControllerAction::ToggleSidebar;\n if (key == \"save\") return InternalControllerAction::Save;\n if (key == \"straight_line_tool\") return InternalControllerAction::StraightLineTool;\n if (key == \"rope_tool\") return InternalControllerAction::RopeTool;\n if (key == \"set_pen_tool\") return InternalControllerAction::SetPenTool;\n if (key == \"set_marker_tool\") return InternalControllerAction::SetMarkerTool;\n if (key == \"set_eraser_tool\") return InternalControllerAction::SetEraserTool;\n if (key == \"toggle_pdf_text_selection\") return InternalControllerAction::TogglePdfTextSelection;\n if (key == \"toggle_outline\") return InternalControllerAction::ToggleOutline;\n if (key == \"toggle_bookmarks\") return InternalControllerAction::ToggleBookmarks;\n if (key == \"add_bookmark\") return InternalControllerAction::AddBookmark;\n if (key == \"toggle_touch_gestures\") return InternalControllerAction::ToggleTouchGestures;\n return InternalControllerAction::None;\n}\n static QStringList getTranslatedDialModes() {\n return {\n tr(\"None\"),\n tr(\"Page Switching\"),\n tr(\"Zoom Control\"),\n tr(\"Thickness Control\"),\n\n tr(\"Tool Switching\"),\n tr(\"Preset Selection\"),\n tr(\"Pan and Page Scroll\")\n };\n}\n static QStringList getTranslatedActions() {\n return {\n tr(\"None\"),\n tr(\"Toggle Fullscreen\"),\n tr(\"Toggle Dial\"),\n tr(\"Zoom 50%\"),\n tr(\"Zoom Out\"),\n tr(\"Zoom 200%\"),\n tr(\"Add Preset\"),\n tr(\"Delete Page\"),\n tr(\"Fast Forward\"),\n tr(\"Open Control Panel\"),\n tr(\"Red\"),\n tr(\"Blue\"),\n tr(\"Yellow\"),\n tr(\"Green\"),\n tr(\"Black\"),\n tr(\"White\"),\n tr(\"Custom Color\"),\n tr(\"Toggle Sidebar\"),\n tr(\"Save\"),\n tr(\"Straight Line Tool\"),\n tr(\"Rope Tool\"),\n tr(\"Set Pen Tool\"),\n tr(\"Set Marker Tool\"),\n tr(\"Set Eraser Tool\"),\n tr(\"Toggle PDF Text Selection\"),\n tr(\"Toggle PDF Outline\"),\n tr(\"Toggle Bookmarks\"),\n tr(\"Add/Remove Bookmark\"),\n tr(\"Toggle Touch Gestures\")\n };\n}\n static QStringList getTranslatedButtons() {\n return {\n tr(\"Left Shoulder\"),\n tr(\"Right Shoulder\"),\n tr(\"Paddle 2\"),\n tr(\"Paddle 4\"),\n tr(\"Y Button\"),\n tr(\"A Button\"),\n tr(\"B Button\"),\n tr(\"X Button\"),\n tr(\"Left Stick\"),\n tr(\"Start Button\"),\n tr(\"Guide Button\")\n };\n}\n static QStringList getInternalDialModeKeys() {\n return {\n \"none\",\n \"page_switching\",\n \"zoom_control\",\n \"thickness_control\",\n\n \"tool_switching\",\n \"preset_selection\",\n \"pan_and_page_scroll\"\n };\n}\n static QStringList getInternalActionKeys() {\n return {\n \"none\",\n \"toggle_fullscreen\",\n \"toggle_dial\",\n \"zoom_50\",\n \"zoom_out\",\n \"zoom_200\",\n \"add_preset\",\n \"delete_page\",\n \"fast_forward\",\n \"open_control_panel\",\n \"red_color\",\n \"blue_color\",\n \"yellow_color\",\n \"green_color\",\n \"black_color\",\n \"white_color\",\n \"custom_color\",\n \"toggle_sidebar\",\n \"save\",\n \"straight_line_tool\",\n \"rope_tool\",\n \"set_pen_tool\",\n \"set_marker_tool\",\n \"set_eraser_tool\",\n \"toggle_pdf_text_selection\",\n \"toggle_outline\",\n \"toggle_bookmarks\",\n \"add_bookmark\",\n \"toggle_touch_gestures\"\n };\n}\n static QStringList getInternalButtonKeys() {\n return {\n \"LEFTSHOULDER\",\n \"RIGHTSHOULDER\", \n \"PADDLE2\",\n \"PADDLE4\",\n \"Y\",\n \"A\",\n \"B\",\n \"X\",\n \"LEFTSTICK\",\n \"START\",\n \"GUIDE\"\n };\n}\n static QString displayToInternalKey(const QString &displayString, bool isDialMode) {\n if (isDialMode) {\n QStringList translated = getTranslatedDialModes();\n QStringList internal = getInternalDialModeKeys();\n int index = translated.indexOf(displayString);\n return (index >= 0) ? internal[index] : \"none\";\n } else {\n QStringList translated = getTranslatedActions();\n QStringList internal = getInternalActionKeys();\n int index = translated.indexOf(displayString);\n return (index >= 0) ? internal[index] : \"none\";\n }\n}\n static QString internalKeyToDisplay(const QString &internalKey, bool isDialMode) {\n if (isDialMode) {\n QStringList translated = getTranslatedDialModes();\n QStringList internal = getInternalDialModeKeys();\n int index = internal.indexOf(internalKey);\n return (index >= 0) ? translated[index] : tr(\"None\");\n } else {\n QStringList translated = getTranslatedActions();\n QStringList internal = getInternalActionKeys();\n int index = internal.indexOf(internalKey);\n return (index >= 0) ? translated[index] : tr(\"None\");\n }\n}\n};"], ["/SpeedyNote/source/KeyCaptureDialog.h", "class KeyCaptureDialog {\n Q_OBJECT\n\npublic:\n explicit KeyCaptureDialog(QWidget *parent = nullptr);\n protected:\n void keyPressEvent(QKeyEvent *event) override {\n // Build key sequence string\n QStringList modifiers;\n \n if (event->modifiers() & Qt::ControlModifier) modifiers << \"Ctrl\";\n if (event->modifiers() & Qt::ShiftModifier) modifiers << \"Shift\";\n if (event->modifiers() & Qt::AltModifier) modifiers << \"Alt\";\n if (event->modifiers() & Qt::MetaModifier) modifiers << \"Meta\";\n \n // Don't capture modifier keys alone\n if (event->key() == Qt::Key_Control || event->key() == Qt::Key_Shift ||\n event->key() == Qt::Key_Alt || event->key() == Qt::Key_Meta) {\n return;\n }\n \n // Don't capture Escape (let it close the dialog)\n if (event->key() == Qt::Key_Escape) {\n QDialog::keyPressEvent(event);\n return;\n }\n \n QString keyString = QKeySequence(event->key()).toString();\n \n if (!modifiers.isEmpty()) {\n capturedSequence = modifiers.join(\"+\") + \"+\" + keyString;\n } else {\n capturedSequence = keyString;\n }\n \n updateDisplay();\n event->accept();\n}\n private:\n void clearSequence() {\n capturedSequence.clear();\n updateDisplay();\n setFocus(); // Return focus to dialog for key capture\n}\n private:\n QLabel *instructionLabel;\n QLabel *capturedLabel;\n QPushButton *clearButton;\n QPushButton *okButton;\n QPushButton *cancelButton;\n QString capturedSequence;\n void updateDisplay() {\n if (capturedSequence.isEmpty()) {\n capturedLabel->setText(tr(\"(No key captured yet)\"));\n okButton->setEnabled(false);\n } else {\n capturedLabel->setText(capturedSequence);\n okButton->setEnabled(true);\n }\n}\n};"], ["/SpeedyNote/markdown/main.cpp", "/*\n * MIT License\n *\n * Copyright (c) 2014-2025 Patrizio Bekerle -- \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#include \n\n#include \"mainwindow.h\"\n\nint main(int argc, char *argv[]) {\n QApplication a(argc, argv);\n MainWindow w;\n w.show();\n\n return a.exec();\n}\n"], ["/SpeedyNote/markdown/mainwindow.h", "class MainWindow {\n Q_OBJECT\n\n public:\n explicit MainWindow(QWidget *parent = nullptr);\n ~MainWindow() { delete ui; }\n private:\n Ui::MainWindow *ui;\n};"], ["/SpeedyNote/source/ToolType.h", "#ifndef TOOLTYPE_H\n#define TOOLTYPE_H\n\n// ✅ Now it can be used anywhere\nenum class ToolType {\n Pen,\n Marker,\n Eraser\n};\n\n#endif // TOOLTYPE_H"], ["/SpeedyNote/markdown/qownlanguagedata.h", "class qownlanguagedata {\n};"], ["/SpeedyNote/markdown/markdownhighlighter.h", "class QTextDocument {\n};"]], "task_instance_info": {"created_time": "2025-08-20 19:30:37", "created_task_model": "DeepSeek-R1", "class_skeleton": "class\nMarkdownWindow\n{\nQ_OBJECT\n\npublic:\n explicit MarkdownWindowManager(InkCanvas *canvas, QObject *parent = nullptr);\n~MarkdownWindowManager() {}\nMarkdownWindow* createMarkdownWindow(const QRect &rect);\nvoid removeMarkdownWindow(MarkdownWindow *window) {}\nvoid clearAllWindows() {}\nvoid saveWindowsForPage(int pageNumber) {}\nvoid loadWindowsForPage(int pageNumber) {}\nvoid deleteWindowsForPage(int pageNumber) {}\nvoid setSelectionMode(bool enabled) {}\nQList getCurrentPageWindows() const {}\nvoid resetTransparencyTimer() {}\nvoid setWindowsTransparent(bool transparent) {}\nvoid hideAllWindows() {}\nvoid windowCreated(MarkdownWindow *window);\nvoid windowRemoved(MarkdownWindow *window);\nprivate:\nvoid onWindowDeleteRequested(MarkdownWindow *window) {}\nvoid onWindowFocusChanged(MarkdownWindow *window, bool focused) {}\nvoid onWindowContentChanged(MarkdownWindow *window) {}\nvoid onTransparencyTimerTimeout() {}\nprivate:\nInkCanvas *canvas;\nbool selectionMode = false;\nQMap> pageWindows;\nQList currentWindows;\nQTimer *transparencyTimer;\nMarkdownWindow *currentlyFocusedWindow = nullptr;\nbool windowsAreTransparent = false;\nQString getWindowDataFilePath(int pageNumber) const {}\nvoid saveWindowData(int pageNumber, const QList &windows) {}\nQList loadWindowData(int pageNumber) {}\nQString getSaveFolder() const {}\nQString getNotebookId() const {}\nQRect convertScreenToCanvasRect(const QRect &screenRect) const {}\nvoid connectWindowSignals(MarkdownWindow *window) {}\npublic:\nvoid updateAllWindowPositions() {}\n};", "code_description": "This code segment functions to: Manage the lifecycle and state persistence of interactive elements across multiple workspace pages, including visibility control, user interaction handling, and automatic transparency adjustments based on activity patterns."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```cpp\n[TASK_BEGIN]\nclass MarkdownWindowManager\n{\n Q_OBJECT\n\npublic:\n explicit MarkdownWindowManager(InkCanvas *canvas, QObject *parent = nullptr)\n : QObject(parent), canvas(canvas)\n {\n transparencyTimer = new QTimer(this);\n transparencyTimer->setSingleShot(true);\n connect(transparencyTimer, &QTimer::timeout, this, &MarkdownWindowManager::onTransparencyTimerTimeout);\n }\n\n MarkdownWindow* createMarkdownWindow(const QRect &rect)\n {\n MarkdownWindow* window = new MarkdownWindow(canvas->parentWidget());\n window->setGeometry(convertScreenToCanvasRect(rect));\n currentWindows.append(window);\n connectWindowSignals(window);\n emit windowCreated(window);\n return window;\n }\n\n void clearAllWindows()\n {\n qDeleteAll(currentWindows);\n currentWindows.clear();\n }\n\n void saveWindowsForPage(int pageNumber)\n {\n saveWindowData(pageNumber, currentWindows);\n }\n\n void loadWindowsForPage(int pageNumber)\n {\n clearAllWindows();\n currentWindows = loadWindowData(pageNumber);\n for(MarkdownWindow* window : currentWindows) {\n window->setParent(canvas->parentWidget());\n connectWindowSignals(window);\n }\n }\n\n void deleteWindowsForPage(int pageNumber)\n {\n if(pageWindows.contains(pageNumber)) {\n qDeleteAll(pageWindows[pageNumber]);\n pageWindows.remove(pageNumber);\n }\n }\n\n void setSelectionMode(bool enabled) { selectionMode = enabled; }\n QList getCurrentPageWindows() const { return currentWindows; }\n \n void resetTransparencyTimer()\n {\n transparencyTimer->start(3000);\n setWindowsTransparent(false);\n }\n\n void setWindowsTransparent(bool transparent)\n {\n windowsAreTransparent = transparent;\n for(MarkdownWindow* window : currentWindows)\n window->setWindowOpacity(transparent ? 0.3 : 1.0);\n }\n\n void hideAllWindows()\n {\n for(MarkdownWindow* window : currentWindows)\n window->hide();\n }\n\nsignals:\n void windowCreated(MarkdownWindow *window);\n void windowRemoved(MarkdownWindow *window);\n\nprivate:\n void onWindowDeleteRequested(MarkdownWindow *window)\n {\n currentWindows.removeOne(window);\n emit windowRemoved(window);\n window->deleteLater();\n }\n\n void onWindowFocusChanged(MarkdownWindow *window, bool focused)\n {\n if(focused) {\n currentlyFocusedWindow = window;\n resetTransparencyTimer();\n }\n }\n\n void onTransparencyTimerTimeout()\n {\n if(!selectionMode && currentlyFocusedWindow == nullptr)\n setWindowsTransparent(true);\n }\n\n QString getWindowDataFilePath(int pageNumber) const\n {\n return QDir(getSaveFolder()).filePath(QString(\"%1_%2.mw\").arg(getNotebookId()).arg(pageNumber));\n }\n\n void connectWindowSignals(MarkdownWindow *window)\n {\n connect(window, &MarkdownWindow::deleteRequested, this, [=] { onWindowDeleteRequested(window); });\n connect(window, &MarkdownWindow::focusChanged, this, [=](bool focused) { onWindowFocusChanged(window, focused); });\n connect(window, &MarkdownWindow::contentChanged, this, [=] { onWindowContentChanged(window); });\n }\n\nprivate:\n InkCanvas *canvas;\n bool selectionMode = false;\n QMap> pageWindows;\n QList currentWindows;\n QTimer *transparencyTimer;\n MarkdownWindow *currentlyFocusedWindow = nullptr;\n bool windowsAreTransparent = false;\n};\n[TASK_END]\n```", "inference_time": "2025-08-20 19-31-26"}, "editdistance_info": {"edit_distance": 16.5665, "calculate_time": "2025-08-20 19:31:26", "true_code_clean": "class MarkdownWindow {\n Q_OBJECT\npublic:\n explicit MarkdownWindowManager(InkCanvas *canvas, QObject *parent = nullptr);\n ~MarkdownWindowManager() {\n clearAllWindows();\n}\n MarkdownWindow* createMarkdownWindow(const QRect &rect);\n void removeMarkdownWindow(MarkdownWindow *window) {\n if (!window) return;\n currentWindows.removeAll(window);\n for (auto it = pageWindows.begin(); it != pageWindows.end(); ++it) {\n it.value().removeAll(window);\n }\n emit windowRemoved(window);\n window->deleteLater();\n}\n void clearAllWindows() {\n transparencyTimer->stop();\n currentlyFocusedWindow = nullptr;\n windowsAreTransparent = false;\n for (MarkdownWindow *window : currentWindows) {\n window->deleteLater();\n }\n currentWindows.clear();\n for (auto it = pageWindows.begin(); it != pageWindows.end(); ++it) {\n for (MarkdownWindow *window : it.value()) {\n window->deleteLater();\n }\n }\n pageWindows.clear();\n}\n void saveWindowsForPage(int pageNumber) {\n if (!canvas || currentWindows.isEmpty()) return;\n pageWindows[pageNumber] = currentWindows;\n saveWindowData(pageNumber, currentWindows);\n}\n void loadWindowsForPage(int pageNumber) {\n if (!canvas) return;\n QList newPageWindows;\n if (pageWindows.contains(pageNumber)) {\n newPageWindows = pageWindows[pageNumber];\n } else {\n newPageWindows = loadWindowData(pageNumber);\n if (!newPageWindows.isEmpty()) {\n pageWindows[pageNumber] = newPageWindows;\n }\n }\n currentWindows = newPageWindows;\n for (MarkdownWindow *window : currentWindows) {\n if (!window->isValidForCanvas()) {\n QRect canvasBounds = canvas->getCanvasRect();\n QRect windowRect = window->getCanvasRect();\n int newX = qMax(0, qMin(windowRect.x(), canvasBounds.width() - windowRect.width()));\n int newY = qMax(0, qMin(windowRect.y(), canvasBounds.height() - windowRect.height()));\n if (newX != windowRect.x() || newY != windowRect.y()) {\n QRect adjustedRect(newX, newY, windowRect.width(), windowRect.height());\n window->setCanvasRect(adjustedRect);\n }\n }\n window->ensureCanvasConnections();\n window->show();\n window->updateScreenPosition();\n window->setTransparent(false);\n }\n if (!currentWindows.isEmpty()) {\n resetTransparencyTimer();\n } else {\n }\n}\n void deleteWindowsForPage(int pageNumber) {\n if (pageWindows.contains(pageNumber)) {\n QList windows = pageWindows[pageNumber];\n for (MarkdownWindow *window : windows) {\n window->deleteLater();\n }\n pageWindows.remove(pageNumber);\n }\n QString filePath = getWindowDataFilePath(pageNumber);\n if (QFile::exists(filePath)) {\n QFile::remove(filePath);\n }\n if (pageWindows.value(pageNumber) == currentWindows) {\n currentWindows.clear();\n }\n}\n void setSelectionMode(bool enabled) {\n selectionMode = enabled;\n if (canvas) {\n canvas->setCursor(enabled ? Qt::CrossCursor : Qt::ArrowCursor);\n }\n}\n QList getCurrentPageWindows() const {\n return currentWindows;\n}\n void resetTransparencyTimer() {\n transparencyTimer->stop();\n windowsAreTransparent = false; \n transparencyTimer->start();\n}\n void setWindowsTransparent(bool transparent) {\n if (windowsAreTransparent == transparent) return;\n windowsAreTransparent = transparent;\n for (MarkdownWindow *window : currentWindows) {\n if (transparent) {\n if (window != currentlyFocusedWindow) {\n window->setTransparent(true);\n } else {\n window->setTransparent(false);\n }\n } else {\n window->setTransparent(false);\n }\n }\n}\n void hideAllWindows() {\n transparencyTimer->stop();\n currentlyFocusedWindow = nullptr;\n windowsAreTransparent = false;\n for (MarkdownWindow *window : currentWindows) {\n window->hide();\n window->setTransparent(false); \n }\n}\n void windowCreated(MarkdownWindow *window);\n void windowRemoved(MarkdownWindow *window);\n private:\n void onWindowDeleteRequested(MarkdownWindow *window) {\n removeMarkdownWindow(window);\n if (canvas) {\n canvas->setEdited(true);\n }\n if (canvas) {\n MainWindow *mainWindow = qobject_cast(canvas->parent());\n if (mainWindow) {\n int currentPage = mainWindow->getCurrentPageForCanvas(canvas);\n saveWindowsForPage(currentPage);\n }\n }\n}\n void onWindowFocusChanged(MarkdownWindow *window, bool focused) {\n if (focused) {\n currentlyFocusedWindow = window;\n window->setTransparent(false);\n resetTransparencyTimer();\n } else {\n if (currentlyFocusedWindow == window) {\n currentlyFocusedWindow = nullptr;\n }\n bool anyWindowFocused = false;\n for (MarkdownWindow *w : currentWindows) {\n if (w->isEditorFocused()) {\n anyWindowFocused = true;\n currentlyFocusedWindow = w;\n w->setTransparent(false);\n break;\n }\n }\n if (!anyWindowFocused) {\n resetTransparencyTimer();\n } else {\n resetTransparencyTimer();\n }\n }\n}\n void onWindowContentChanged(MarkdownWindow *window) {\n currentlyFocusedWindow = window;\n window->setTransparent(false); \n resetTransparencyTimer();\n}\n void onTransparencyTimerTimeout() {\n setWindowsTransparent(true);\n}\n private:\n InkCanvas *canvas;\n bool selectionMode = false;\n QMap> pageWindows;\n QList currentWindows;\n QTimer *transparencyTimer;\n MarkdownWindow *currentlyFocusedWindow = nullptr;\n bool windowsAreTransparent = false;\n QString getWindowDataFilePath(int pageNumber) const {\n QString saveFolder = getSaveFolder();\n QString notebookId = getNotebookId();\n if (saveFolder.isEmpty() || notebookId.isEmpty()) {\n return QString();\n }\n return saveFolder + QString(\"/.%1_markdown_%2.json\").arg(notebookId).arg(pageNumber, 5, 10, QChar('0'));\n}\n void saveWindowData(int pageNumber, const QList &windows) {\n QString filePath = getWindowDataFilePath(pageNumber);\n if (filePath.isEmpty()) return;\n QJsonArray windowsArray;\n for (MarkdownWindow *window : windows) {\n QVariantMap windowData = window->serialize();\n windowsArray.append(QJsonObject::fromVariantMap(windowData));\n }\n QJsonDocument doc(windowsArray);\n QFile file(filePath);\n if (file.open(QIODevice::WriteOnly)) {\n file.write(doc.toJson());\n file.close();\n #ifdef Q_OS_WIN\n SetFileAttributesW(reinterpret_cast(filePath.utf16()), FILE_ATTRIBUTE_HIDDEN);\n #endif\n }\n}\n QList loadWindowData(int pageNumber) {\n QList windows;\n QString filePath = getWindowDataFilePath(pageNumber);\n if (filePath.isEmpty() || !QFile::exists(filePath)) {\n return windows;\n }\n QFile file(filePath);\n if (!file.open(QIODevice::ReadOnly)) {\n return windows;\n }\n QByteArray data = file.readAll();\n file.close();\n QJsonParseError error;\n QJsonDocument doc = QJsonDocument::fromJson(data, &error);\n if (error.error != QJsonParseError::NoError) {\n qWarning() << \"Failed to parse markdown window data:\" << error.errorString();\n return windows;\n }\n QJsonArray windowsArray = doc.array();\n for (const QJsonValue &value : windowsArray) {\n QJsonObject windowObj = value.toObject();\n QVariantMap windowData = windowObj.toVariantMap();\n MarkdownWindow *window = new MarkdownWindow(QRect(0, 0, 300, 200), canvas);\n window->deserialize(windowData);\n connectWindowSignals(window);\n windows.append(window);\n window->show();\n }\n return windows;\n}\n QString getSaveFolder() const {\n return canvas ? canvas->getSaveFolder() : QString();\n}\n QString getNotebookId() const {\n if (!canvas) return QString();\n QString saveFolder = canvas->getSaveFolder();\n if (saveFolder.isEmpty()) return QString();\n QString idFile = saveFolder + \"/.notebook_id.txt\";\n if (QFile::exists(idFile)) {\n QFile file(idFile);\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QTextStream in(&file);\n QString notebookId = in.readLine().trimmed();\n file.close();\n return notebookId;\n }\n }\n return \"notebook\"; \n}\n QRect convertScreenToCanvasRect(const QRect &screenRect) const {\n if (!canvas) {\n return screenRect;\n }\n QRect canvasRect = canvas->mapWidgetToCanvas(screenRect);\n return canvasRect;\n}\n void connectWindowSignals(MarkdownWindow *window) {\n connect(window, &MarkdownWindow::deleteRequested, this, &MarkdownWindowManager::onWindowDeleteRequested);\n connect(window, &MarkdownWindow::contentChanged, this, [this, window]() {\n onWindowContentChanged(window);\n if (canvas) {\n canvas->setEdited(true);\n MainWindow *mainWindow = qobject_cast(canvas->parent());\n if (mainWindow) {\n int currentPage = mainWindow->getCurrentPageForCanvas(canvas);\n saveWindowsForPage(currentPage);\n }\n }\n });\n connect(window, &MarkdownWindow::windowMoved, this, [this, window](MarkdownWindow*) {\n currentlyFocusedWindow = window;\n window->setTransparent(false); \n resetTransparencyTimer();\n if (canvas) {\n canvas->setEdited(true);\n }\n });\n connect(window, &MarkdownWindow::windowResized, this, [this, window](MarkdownWindow*) {\n currentlyFocusedWindow = window;\n window->setTransparent(false); \n resetTransparencyTimer();\n if (canvas) {\n canvas->setEdited(true);\n }\n });\n connect(window, &MarkdownWindow::focusChanged, this, &MarkdownWindowManager::onWindowFocusChanged);\n connect(window, &MarkdownWindow::editorFocusChanged, this, &MarkdownWindowManager::onWindowFocusChanged);\n connect(window, &MarkdownWindow::windowInteracted, this, [this, window](MarkdownWindow*) {\n currentlyFocusedWindow = window;\n window->setTransparent(false); \n resetTransparencyTimer();\n });\n}\n public:\n void updateAllWindowPositions() {\n for (MarkdownWindow *window : currentWindows) {\n if (window) {\n window->updateScreenPosition();\n }\n }\n}\n}", "predict_code_clean": "class MarkdownWindowManager\n{\n Q_OBJECT\npublic:\n explicit MarkdownWindowManager(InkCanvas *canvas, QObject *parent = nullptr)\n : QObject(parent), canvas(canvas)\n {\n transparencyTimer = new QTimer(this);\n transparencyTimer->setSingleShot(true);\n connect(transparencyTimer, &QTimer::timeout, this, &MarkdownWindowManager::onTransparencyTimerTimeout);\n }\n MarkdownWindow* createMarkdownWindow(const QRect &rect)\n {\n MarkdownWindow* window = new MarkdownWindow(canvas->parentWidget());\n window->setGeometry(convertScreenToCanvasRect(rect));\n currentWindows.append(window);\n connectWindowSignals(window);\n emit windowCreated(window);\n return window;\n }\n void clearAllWindows()\n {\n qDeleteAll(currentWindows);\n currentWindows.clear();\n }\n void saveWindowsForPage(int pageNumber)\n {\n saveWindowData(pageNumber, currentWindows);\n }\n void loadWindowsForPage(int pageNumber)\n {\n clearAllWindows();\n currentWindows = loadWindowData(pageNumber);\n for(MarkdownWindow* window : currentWindows) {\n window->setParent(canvas->parentWidget());\n connectWindowSignals(window);\n }\n }\n void deleteWindowsForPage(int pageNumber)\n {\n if(pageWindows.contains(pageNumber)) {\n qDeleteAll(pageWindows[pageNumber]);\n pageWindows.remove(pageNumber);\n }\n }\n void setSelectionMode(bool enabled) { selectionMode = enabled; }\n QList getCurrentPageWindows() const { return currentWindows; }\n void resetTransparencyTimer()\n {\n transparencyTimer->start(3000);\n setWindowsTransparent(false);\n }\n void setWindowsTransparent(bool transparent)\n {\n windowsAreTransparent = transparent;\n for(MarkdownWindow* window : currentWindows)\n window->setWindowOpacity(transparent ? 0.3 : 1.0);\n }\n void hideAllWindows()\n {\n for(MarkdownWindow* window : currentWindows)\n window->hide();\n }\nsignals:\n void windowCreated(MarkdownWindow *window);\n void windowRemoved(MarkdownWindow *window);\nprivate:\n void onWindowDeleteRequested(MarkdownWindow *window)\n {\n currentWindows.removeOne(window);\n emit windowRemoved(window);\n window->deleteLater();\n }\n void onWindowFocusChanged(MarkdownWindow *window, bool focused)\n {\n if(focused) {\n currentlyFocusedWindow = window;\n resetTransparencyTimer();\n }\n }\n void onTransparencyTimerTimeout()\n {\n if(!selectionMode && currentlyFocusedWindow == nullptr)\n setWindowsTransparent(true);\n }\n QString getWindowDataFilePath(int pageNumber) const\n {\n return QDir(getSaveFolder()).filePath(QString(\"%1_%2.mw\").arg(getNotebookId()).arg(pageNumber));\n }\n void connectWindowSignals(MarkdownWindow *window)\n {\n connect(window, &MarkdownWindow::deleteRequested, this, [=] { onWindowDeleteRequested(window); });\n connect(window, &MarkdownWindow::focusChanged, this, [=](bool focused) { onWindowFocusChanged(window, focused); });\n connect(window, &MarkdownWindow::contentChanged, this, [=] { onWindowContentChanged(window); });\n }\nprivate:\n InkCanvas *canvas;\n bool selectionMode = false;\n QMap> pageWindows;\n QList currentWindows;\n QTimer *transparencyTimer;\n MarkdownWindow *currentlyFocusedWindow = nullptr;\n bool windowsAreTransparent = false;\n};"}}