Files
overlaynote/ui/editor.py
2026-05-24 10:53:42 +00:00

79 lines
1.6 KiB
Python

# v4.1.0 editor-link-click-fix-v1
import re
import webbrowser
from PyQt6.QtCore import (
Qt,
QUrl,
)
from PyQt6.QtGui import (
QDesktopServices,
)
from PyQt6.QtWidgets import (
QTextEdit,
)
URL_PATTERN = re.compile(
r"(https?://[^\s]+|(?:www\.)?[a-zA-Z0-9-]+\.[a-zA-Z]{2,}(?:/[^\s]*)?)",
re.IGNORECASE,
)
class LinkTextEdit(QTextEdit):
def mouseReleaseEvent(
self,
event,
) -> None:
if (
event.button()
== Qt.MouseButton.LeftButton
and event.modifiers()
& Qt.KeyboardModifier.ControlModifier
):
cursor = self.cursorForPosition(
event.position().toPoint()
)
cursor.select(
cursor.SelectionType.WordUnderCursor
)
text = (
cursor.selectedText()
.strip()
)
if URL_PATTERN.fullmatch(text):
target = text
if not target.startswith(
(
"http://",
"https://",
)
):
target = (
f"https://{target}"
)
try:
webbrowser.open(
target
)
except Exception:
QDesktopServices.openUrl(
QUrl(target)
)
event.accept()
return
super().mouseReleaseEvent(
event
)