1
0
mirror of https://github.com/AvengeMedia/DankMaterialShell.git synced 2025-12-06 05:25:41 -05:00

Merge branch 'master' of github.com:bbedward/DankMaterialShell

This commit is contained in:
bbedward
2025-09-15 17:48:02 -04:00
5 changed files with 611 additions and 220 deletions

7
.gitignore vendored
View File

@@ -63,6 +63,11 @@ CLAUDE-temp.md
niri-colors.generated.kdl
ghostty-colors.generated.conf
# Notepad files (should be in ~/.local/state/DankMaterialShell/)
untitled-*.txt
file:*
notepad-files/
result
# If you prefer the allow list template instead of the deny list, see community template:
@@ -96,4 +101,4 @@ go.work.sum
# Editor/IDE
# .idea/
# .vscode/
# .vscode/

View File

@@ -44,12 +44,6 @@ Singleton {
property int wallpaperCyclingInterval: 300 // seconds (5 minutes)
property string wallpaperCyclingTime: "06:00" // HH:mm format
property string lastBrightnessDevice: ""
property string notepadContent: ""
property string notepadCurrentFileName: ""
property string notepadCurrentFileUrl: ""
property string notepadLastSavedContent: ""
property var notepadTabs: []
property int notepadCurrentTabIndex: 0
Component.onCompleted: {
loadSettings()
@@ -104,45 +98,11 @@ Singleton {
wallpaperCyclingInterval = settings.wallpaperCyclingInterval !== undefined ? settings.wallpaperCyclingInterval : 300
wallpaperCyclingTime = settings.wallpaperCyclingTime !== undefined ? settings.wallpaperCyclingTime : "06:00"
lastBrightnessDevice = settings.lastBrightnessDevice !== undefined ? settings.lastBrightnessDevice : ""
notepadContent = settings.notepadContent !== undefined ? settings.notepadContent : ""
// Generate system themes but don't override user's theme choice
if (typeof Theme !== "undefined") {
Theme.generateSystemThemesFromCurrentTheme()
}
notepadCurrentFileName = settings.notepadCurrentFileName !== undefined ? settings.notepadCurrentFileName : ""
notepadCurrentFileUrl = settings.notepadCurrentFileUrl !== undefined ? settings.notepadCurrentFileUrl : ""
notepadLastSavedContent = settings.notepadLastSavedContent !== undefined ? settings.notepadLastSavedContent : ""
notepadTabs = settings.notepadTabs !== undefined ? settings.notepadTabs : []
notepadCurrentTabIndex = settings.notepadCurrentTabIndex !== undefined ? settings.notepadCurrentTabIndex : 0
// Migrate legacy single notepad to tabs if needed
if (notepadTabs.length === 0 && (notepadContent || notepadCurrentFileName)) {
notepadTabs = [{
id: Date.now(),
title: notepadCurrentFileName || "Untitled",
content: notepadContent,
fileName: notepadCurrentFileName,
fileUrl: notepadCurrentFileUrl,
lastSavedContent: notepadLastSavedContent,
hasUnsavedChanges: false
}]
notepadCurrentTabIndex = 0
}
// Ensure at least one tab exists
if (notepadTabs.length === 0) {
notepadTabs = [{
id: Date.now(),
title: "Untitled",
content: "",
fileName: "",
fileUrl: "",
lastSavedContent: "",
hasUnsavedChanges: false
}]
notepadCurrentTabIndex = 0
}
}
} catch (e) {
@@ -178,13 +138,7 @@ Singleton {
"wallpaperCyclingMode": wallpaperCyclingMode,
"wallpaperCyclingInterval": wallpaperCyclingInterval,
"wallpaperCyclingTime": wallpaperCyclingTime,
"lastBrightnessDevice": lastBrightnessDevice,
"notepadContent": notepadContent,
"notepadCurrentFileName": notepadCurrentFileName,
"notepadCurrentFileUrl": notepadCurrentFileUrl,
"notepadLastSavedContent": notepadLastSavedContent,
"notepadTabs": notepadTabs,
"notepadCurrentTabIndex": notepadCurrentTabIndex
"lastBrightnessDevice": lastBrightnessDevice
}, null, 2))
}
@@ -594,4 +548,4 @@ Singleton {
}
}
}
}
}

View File

@@ -18,79 +18,95 @@ PanelWindow {
property bool isVisible: false
property bool fileDialogOpen: false
property string currentFileName: ""
property bool hasUnsavedChanges: false
property url currentFileUrl
property var targetScreen: null
property var modelData: null
property bool confirmationDialogOpen: false
property string pendingAction: ""
property url pendingFileUrl
property string lastSavedFileContent: ""
property bool expandedWidth: false
property var currentTab: SessionData.notepadTabs.length > SessionData.notepadCurrentTabIndex ? SessionData.notepadTabs[SessionData.notepadCurrentTabIndex] : null
property int nextTabId: Date.now()
property var currentTab: NotepadStorageService.tabs.length > NotepadStorageService.currentTabIndex ? NotepadStorageService.tabs[NotepadStorageService.currentTabIndex] : null
property string currentContent: ""
property string lastSavedContent: ""
property bool contentLoaded: false
function hasFileChanges() {
if (!currentTab) return false
return currentTab.content !== currentTab.lastSavedContent
}
function getCurrentTabData() {
return currentTab || {
id: 0,
title: "Untitled",
content: "",
fileName: "",
fileUrl: "",
lastSavedContent: "",
hasUnsavedChanges: false
function hasUnsavedChanges() {
if (!currentTab || !contentLoaded) {
return false
}
// For temporary files, show unsaved if there's any content that hasn't been hard-saved
if (currentTab.isTemporary) {
return textArea.text.length > 0
}
// For non-temporary files, show unsaved if content differs from last saved state
return textArea.text !== lastSavedContent
}
function updateCurrentTab(properties, saveImmediately = false) {
function hasUnsavedTemporaryContent() {
return hasUnsavedChanges()
}
function hasUnsavedChangesForTab(tab) {
if (!tab) return false
// Only the currently active tab can show real unsaved status
if (tab.id === currentTab?.id) {
return hasUnsavedChanges()
}
return false
}
function loadCurrentTabContent() {
if (!currentTab) return
var tabs = [...SessionData.notepadTabs]
var tabIndex = SessionData.notepadCurrentTabIndex
if (tabIndex >= 0 && tabIndex < tabs.length) {
var updatedTab = Object.assign({}, tabs[tabIndex])
Object.assign(updatedTab, properties)
tabs[tabIndex] = updatedTab
SessionData.notepadTabs = tabs
if (saveImmediately) {
SessionData.saveSettings()
contentLoaded = false
NotepadStorageService.loadTabContent(
NotepadStorageService.currentTabIndex,
(content) => {
currentContent = content
lastSavedContent = content
textArea.text = content
contentLoaded = true
}
}
)
}
function saveCurrentTabContent() {
if (!currentTab || !contentLoaded) return
NotepadStorageService.saveTabContent(
NotepadStorageService.currentTabIndex,
textArea.text
)
currentContent = textArea.text
lastSavedContent = textArea.text
}
function autoSaveToSession() {
if (!currentTab || !contentLoaded) return
currentContent = textArea.text
saveCurrentTabContent()
}
function createNewTab() {
var newTab = {
id: ++nextTabId,
title: "Untitled",
content: "",
fileName: "",
fileUrl: "",
lastSavedContent: "",
hasUnsavedChanges: false
}
var tabs = [...SessionData.notepadTabs]
tabs.push(newTab)
SessionData.notepadTabs = tabs
SessionData.notepadCurrentTabIndex = tabs.length - 1
performCreateNewTab()
}
function performCreateNewTab() {
NotepadStorageService.createNewTab()
textArea.text = ""
currentContent = ""
lastSavedContent = ""
contentLoaded = true
textArea.forceActiveFocus()
deferredSaveTimer.restart()
}
function closeTab(tabIndex) {
var tabToClose = SessionData.notepadTabs[tabIndex]
var hasChanges = tabToClose && tabToClose.content !== tabToClose.lastSavedContent
if (hasChanges) {
if (tabIndex === NotepadStorageService.currentTabIndex && hasUnsavedChanges()) {
root.pendingAction = "close_tab_" + tabIndex
root.confirmationDialogOpen = true
confirmationDialog.open()
@@ -100,54 +116,27 @@ PanelWindow {
}
function performCloseTab(tabIndex) {
var tabs = [...SessionData.notepadTabs]
if (tabs.length <= 1) {
tabs[0] = {
id: ++nextTabId,
title: "Untitled",
content: "",
fileName: "",
fileUrl: "",
lastSavedContent: "",
hasUnsavedChanges: false
}
SessionData.notepadCurrentTabIndex = 0
} else {
tabs.splice(tabIndex, 1)
if (SessionData.notepadCurrentTabIndex >= tabs.length) {
SessionData.notepadCurrentTabIndex = tabs.length - 1
} else if (SessionData.notepadCurrentTabIndex > tabIndex) {
SessionData.notepadCurrentTabIndex -= 1
}
}
SessionData.notepadTabs = tabs
NotepadStorageService.closeTab(tabIndex)
Qt.callLater(() => {
if (currentTab) {
textArea.text = currentTab.content
}
loadCurrentTabContent()
})
deferredSaveTimer.restart()
}
function switchToTab(tabIndex) {
if (tabIndex < 0 || tabIndex >= SessionData.notepadTabs.length) return
SessionData.notepadCurrentTabIndex = tabIndex
if (tabIndex < 0 || tabIndex >= NotepadStorageService.tabs.length) return
if (contentLoaded) {
autoSaveToSession()
}
NotepadStorageService.switchToTab(tabIndex)
Qt.callLater(() => {
loadCurrentTabContent()
if (currentTab) {
textArea.text = currentTab.content
root.currentFileName = currentTab.fileName
root.currentFileUrl = currentTab.fileUrl
root.lastSavedFileContent = currentTab.lastSavedContent
root.currentFileName = currentTab.fileName || ""
root.currentFileUrl = currentTab.fileUrl || ""
}
})
deferredSaveTimer.restart()
}
function show() {
@@ -303,18 +292,17 @@ PanelWindow {
spacing: Theme.spacingXS
Repeater {
model: SessionData.notepadTabs
model: NotepadStorageService.tabs
delegate: Rectangle {
required property int index
required property var modelData
readonly property bool isActive: SessionData.notepadCurrentTabIndex === index
readonly property bool tabHasChanges: modelData.content !== modelData.lastSavedContent
readonly property bool isActive: NotepadStorageService.currentTabIndex === index
readonly property bool isHovered: tabMouseArea.containsMouse && !closeMouseArea.containsMouse
readonly property real calculatedWidth: {
const textWidth = tabText.paintedWidth || 100
const closeButtonWidth = SessionData.notepadTabs.length > 1 ? 20 : 0
const closeButtonWidth = NotepadStorageService.tabs.length > 1 ? 20 : 0
const spacing = Theme.spacingXS
const padding = Theme.spacingM * 2
return Math.max(120, Math.min(200, textWidth + closeButtonWidth + spacing + padding))
@@ -344,7 +332,13 @@ PanelWindow {
StyledText {
id: tabText
text: (tabHasChanges ? "● " : "") + (modelData.title || "Untitled")
text: {
var prefix = ""
if (hasUnsavedChangesForTab(modelData)) {
prefix = "● "
}
return prefix + (modelData.title || "Untitled")
}
font.pixelSize: Theme.fontSizeSmall
color: isActive ? Theme.primary : Theme.surfaceText
font.weight: isActive ? Font.Medium : Font.Normal
@@ -359,7 +353,7 @@ PanelWindow {
height: 20
radius: 10
color: closeMouseArea.containsMouse ? Theme.surfaceTextHover : "transparent"
visible: SessionData.notepadTabs.length > 1
visible: NotepadStorageService.tabs.length > 1
anchors.verticalCenter: parent.verticalCenter
DankIcon {
@@ -432,6 +426,7 @@ PanelWindow {
focus: root.isVisible
activeFocusOnTab: true
textFormat: TextEdit.PlainText
inputMethodHints: Qt.ImhNoPredictiveText | Qt.ImhNoAutoUppercase
persistentSelection: true
tabStopDistance: 40
leftPadding: Theme.spacingM
@@ -440,32 +435,35 @@ PanelWindow {
bottomPadding: Theme.spacingM
Component.onCompleted: {
loadCurrentTabContent()
if (currentTab) {
text = currentTab.content
root.currentFileName = currentTab.fileName
root.currentFileUrl = currentTab.fileUrl
root.lastSavedFileContent = currentTab.lastSavedContent
root.currentFileName = currentTab.fileName || ""
root.currentFileUrl = currentTab.fileUrl || ""
}
}
Connections {
target: root
function onCurrentTabChanged() {
if (currentTab && textArea.text !== currentTab.content) {
textArea.text = currentTab.content
root.currentFileName = currentTab.fileName
root.currentFileUrl = currentTab.fileUrl
root.lastSavedFileContent = currentTab.lastSavedContent
target: NotepadStorageService
function onCurrentTabIndexChanged() {
loadCurrentTabContent()
if (currentTab) {
root.currentFileName = currentTab.fileName || ""
root.currentFileUrl = currentTab.fileUrl || ""
}
}
function onTabsChanged() {
if (NotepadStorageService.tabs.length > 0 && !contentLoaded) {
loadCurrentTabContent()
if (currentTab) {
root.currentFileName = currentTab.fileName || ""
root.currentFileUrl = currentTab.fileUrl || ""
}
}
}
}
onTextChanged: {
if (currentTab && text !== currentTab.content) {
updateCurrentTab({
content: text,
hasUnsavedChanges: true
})
if (contentLoaded && text !== lastSavedContent) {
autoSaveTimer.restart()
}
}
@@ -480,16 +478,19 @@ PanelWindow {
switch (event.key) {
case Qt.Key_S:
event.accepted = true
if (currentTab && currentTab.fileUrl) {
saveToFile(currentTab.fileUrl)
if (currentTab && !currentTab.isTemporary && currentTab.filePath) {
// For non-temporary tabs, save directly to the original file
var fileUrl = "file://" + currentTab.filePath
saveToFile(fileUrl)
} else {
// For temporary tabs or new files, open save dialog
root.fileDialogOpen = true
saveBrowser.open()
}
break
case Qt.Key_O:
event.accepted = true
if (hasFileChanges()) {
if (hasUnsavedChanges()) {
root.pendingAction = "open"
root.confirmationDialogOpen = true
confirmationDialog.open()
@@ -500,7 +501,7 @@ PanelWindow {
break
case Qt.Key_N:
event.accepted = true
if (hasFileChanges()) {
if (hasUnsavedChanges()) {
root.pendingAction = "new"
root.confirmationDialogOpen = true
confirmationDialog.open()
@@ -538,7 +539,7 @@ PanelWindow {
iconName: "save"
iconSize: Theme.iconSize - 2
iconColor: Theme.primary
enabled: currentTab && (hasFileChanges() || currentTab.content.length > 0)
enabled: currentTab && (hasUnsavedChanges() || textArea.text.length > 0)
onClicked: {
root.fileDialogOpen = true
saveBrowser.open()
@@ -559,7 +560,7 @@ PanelWindow {
iconSize: Theme.iconSize - 2
iconColor: Theme.secondary
onClicked: {
if (hasFileChanges()) {
if (hasUnsavedChanges()) {
root.pendingAction = "open"
root.confirmationDialogOpen = true
confirmationDialog.open()
@@ -599,7 +600,7 @@ PanelWindow {
spacing: Theme.spacingL
StyledText {
text: currentTab && currentTab.content.length > 0 ? qsTr("%1 characters").arg(currentTab.content.length) : qsTr("Empty")
text: textArea.text.length > 0 ? qsTr("%1 characters").arg(textArea.text.length) : qsTr("Empty")
font.pixelSize: Theme.fontSizeSmall
color: Theme.surfaceTextMedium
}
@@ -608,14 +609,38 @@ PanelWindow {
text: qsTr("Lines: %1").arg(textArea.lineCount)
font.pixelSize: Theme.fontSizeSmall
color: Theme.surfaceTextMedium
visible: currentTab && currentTab.content.length > 0
visible: textArea.text.length > 0
}
StyledText {
text: autoSaveTimer.running ? qsTr("Auto-saving...") : (hasFileChanges() ? qsTr("Unsaved changes") : qsTr("Auto-saved"))
text: {
if (autoSaveTimer.running) {
return qsTr("Auto-saving...")
}
if (hasUnsavedChanges()) {
if (currentTab && currentTab.isTemporary) {
return qsTr("Unsaved note...")
} else {
return qsTr("Unsaved changes")
}
} else {
return qsTr("Saved")
}
}
font.pixelSize: Theme.fontSizeSmall
color: hasFileChanges() ? Theme.warning : (autoSaveTimer.running ? Theme.primary : Theme.surfaceTextMedium)
opacity: currentTab && currentTab.content.length > 0 ? 1 : 0
color: {
if (autoSaveTimer.running) {
return Theme.primary
}
if (hasUnsavedChanges()) {
return Theme.warning
} else {
return Theme.success
}
}
opacity: textArea.text.length > 0 ? 1 : 0
}
}
}
@@ -627,30 +652,18 @@ PanelWindow {
interval: 2000
repeat: false
onTriggered: {
if (currentTab) {
updateCurrentTab({
hasUnsavedChanges: false
}, true)
}
autoSaveToSession()
}
}
Timer {
id: deferredSaveTimer
interval: 500
repeat: false
onTriggered: {
SessionData.saveSettings()
}
}
property string pendingSaveContent: ""
function saveToFile(fileUrl) {
if (!currentTab) return
const content = currentTab.content
const filePath = fileUrl.toString().replace(/^file:\/\//, '')
var content = textArea.text
var filePath = fileUrl.toString().replace(/^file:\/\//, '')
saveFileView.path = ""
pendingSaveContent = content
@@ -660,8 +673,22 @@ PanelWindow {
Qt.callLater(() => {
saveFileView.setText(pendingSaveContent)
})
} function loadFromFile(fileUrl) {
}
function loadFromFile(fileUrl) {
if (hasUnsavedTemporaryContent()) {
root.pendingFileUrl = fileUrl
root.pendingAction = "load_file"
root.confirmationDialogOpen = true
confirmationDialog.open()
} else {
performLoadFromFile(fileUrl)
}
}
function performLoadFromFile(fileUrl) {
const filePath = fileUrl.toString().replace(/^file:\/\//, '')
const fileName = filePath.split('/').pop()
loadFileView.path = ""
loadFileView.path = filePath
@@ -669,19 +696,25 @@ PanelWindow {
// Wait for the file to be loaded before reading
if (loadFileView.waitForJob()) {
Qt.callLater(() => {
const content = loadFileView.text()
var content = loadFileView.text()
if (currentTab && content !== undefined && content !== null) {
updateCurrentTab({
content: content,
hasUnsavedChanges: false,
lastSavedContent: content
}, true)
textArea.text = content
currentContent = content
lastSavedContent = content
contentLoaded = true
root.lastSavedFileContent = content
NotepadStorageService.updateTabMetadata(NotepadStorageService.currentTabIndex, {
title: fileName,
filePath: filePath,
isTemporary: false
})
root.currentFileName = fileName
root.currentFileUrl = fileUrl
saveCurrentTabContent()
}
})
} else {
console.warn("Notepad: Failed to load file - waitForJob returned false")
}
}
@@ -694,17 +727,16 @@ PanelWindow {
onSaved: {
if (currentTab && saveFileView.path && pendingSaveContent) {
updateCurrentTab({
NotepadStorageService.updateTabMetadata(NotepadStorageService.currentTabIndex, {
hasUnsavedChanges: false,
lastSavedContent: pendingSaveContent
}, true)
})
root.lastSavedFileContent = pendingSaveContent
pendingSaveContent = ""
}
}
onSaveFailed: (error) => {
console.warn("Notepad: Failed to save file:", error, "Path:", saveFileView.path)
pendingSaveContent = ""
}
}
@@ -717,7 +749,6 @@ PanelWindow {
printErrors: true
onLoadFailed: (error) => {
console.warn("Notepad: Failed to load file:", error)
}
}
@@ -730,7 +761,16 @@ PanelWindow {
fileExtensions: ["*.txt", "*.md", "*.*"]
allowStacking: true
saveMode: true
defaultFileName: (currentTab && currentTab.fileName) || "note.txt"
defaultFileName: {
if (currentTab && currentTab.title && currentTab.title !== "Untitled") {
return currentTab.title
} else if (currentTab && !currentTab.isTemporary && currentTab.filePath) {
// Extract filename from path for non-temporary files
return currentTab.filePath.split('/').pop()
} else {
return "note.txt"
}
}
WlrLayershell.layer: WlrLayershell.Overlay
@@ -742,15 +782,14 @@ PanelWindow {
root.currentFileName = fileName
root.currentFileUrl = fileUrl
if (currentTab) {
updateCurrentTab({
title: fileName,
fileName: fileName,
fileUrl: fileUrl
})
NotepadStorageService.saveTabAs(
NotepadStorageService.currentTabIndex,
cleanPath
)
}
saveToFile(fileUrl)
if (root.pendingAction === "new") {
@@ -798,14 +837,6 @@ PanelWindow {
root.currentFileName = fileName
root.currentFileUrl = fileUrl
if (currentTab) {
updateCurrentTab({
title: fileName,
fileName: fileName,
fileUrl: fileUrl
})
}
loadFromFile(fileUrl)
close()
}
@@ -863,7 +894,9 @@ PanelWindow {
qsTr("You have unsaved changes. Save before creating a new file?") :
root.pendingAction.startsWith("close_tab_") ?
qsTr("You have unsaved changes. Save before closing this tab?") :
qsTr("You have unsaved changes. Save before opening a file?")
root.pendingAction === "load_file" || root.pendingAction === "open" ?
qsTr("You have unsaved changes. Save before opening a file?") :
qsTr("You have unsaved changes. Save before continuing?")
font.pixelSize: Theme.fontSizeMedium
color: Theme.surfaceTextMedium
width: parent.width
@@ -921,11 +954,14 @@ PanelWindow {
} else if (root.pendingAction === "open") {
root.fileDialogOpen = true
loadBrowser.open()
} else if (root.pendingAction === "load_file") {
performLoadFromFile(root.pendingFileUrl)
} else if (root.pendingAction.startsWith("close_tab_")) {
var tabIndex = parseInt(root.pendingAction.split("_")[2])
performCloseTab(tabIndex)
}
root.pendingAction = ""
root.pendingFileUrl = ""
}
}
}

View File

@@ -1,5 +1,6 @@
import QtQuick
import qs.Common
import qs.Services
import qs.Widgets
Rectangle {
@@ -45,7 +46,7 @@ Rectangle {
anchors.top: parent.top
anchors.rightMargin: SettingsData.topBarNoBackground ? 0 : 4
anchors.topMargin: SettingsData.topBarNoBackground ? 0 : 4
visible: SessionData.notepadContent.length > 0
visible: NotepadStorageService.tabs && NotepadStorageService.tabs.length > 0
opacity: 0.8
}
@@ -68,4 +69,4 @@ Rectangle {
}
}
}

View File

@@ -0,0 +1,395 @@
import QtQuick
import QtCore
import Quickshell
import Quickshell.Io
pragma Singleton
pragma ComponentBehavior: Bound
Singleton {
id: root
readonly property string baseDir: StandardPaths.writableLocation(StandardPaths.GenericStateLocation) + "/DankMaterialShell"
readonly property string filesDir: baseDir + "/notepad-files"
readonly property string metadataPath: baseDir + "/notepad-session.json"
property var tabs: []
property int currentTabIndex: 0
property var tabsBeingCreated: ({})
Component.onCompleted: {
ensureDirectoryProcess.running = true
}
Process {
id: ensureDirectoryProcess
command: ["mkdir", "-p", root.filesDir]
onExited: loadMetadata()
}
FileView {
id: metadataFile
path: root.metadataPath
blockWrites: true
atomicWrites: true
onLoaded: {
try {
var data = JSON.parse(text())
root.tabs = data.tabs || []
root.currentTabIndex = data.currentTabIndex || 0
validateTabs()
} catch(e) {
console.warn("Failed to parse notepad metadata:", e)
createDefaultTab()
}
}
onLoadFailed: {
createDefaultTab()
}
}
function loadMetadata() {
metadataFile.path = ""
metadataFile.path = root.metadataPath
}
function createDefaultTab() {
var id = Date.now()
var filePath = "notepad-files/untitled-" + id + ".txt"
var fullPath = baseDir + "/" + filePath
var newTabsBeingCreated = Object.assign({}, tabsBeingCreated)
newTabsBeingCreated[id] = true
tabsBeingCreated = newTabsBeingCreated
createEmptyFile(fullPath, function() {
root.tabs = [{
id: id,
title: "Untitled",
filePath: filePath,
isTemporary: true,
lastModified: new Date().toISOString(),
cursorPosition: 0,
scrollPosition: 0
}]
root.currentTabIndex = 0
var updatedTabsBeingCreated = Object.assign({}, tabsBeingCreated)
delete updatedTabsBeingCreated[id]
tabsBeingCreated = updatedTabsBeingCreated
saveMetadata()
})
}
function saveMetadata() {
var metadata = {
version: 1,
currentTabIndex: currentTabIndex,
tabs: tabs
}
metadataFile.setText(JSON.stringify(metadata, null, 2))
}
function loadTabContent(tabIndex, callback) {
if (tabIndex < 0 || tabIndex >= tabs.length) {
callback("")
return
}
var tab = tabs[tabIndex]
var fullPath = tab.isTemporary
? baseDir + "/" + tab.filePath
: tab.filePath
if (tabsBeingCreated[tab.id]) {
Qt.callLater(() => {
loadTabContent(tabIndex, callback)
})
return
}
var loader = tabFileLoaderComponent.createObject(root, {
path: fullPath,
callback: callback
})
}
function saveTabContent(tabIndex, content) {
if (tabIndex < 0 || tabIndex >= tabs.length) return
var tab = tabs[tabIndex]
var fullPath = tab.isTemporary
? baseDir + "/" + tab.filePath
: tab.filePath
var saver = tabFileSaverComponent.createObject(root, {
path: fullPath,
content: content,
tabIndex: tabIndex
})
}
function createNewTab() {
var id = Date.now()
var filePath = "notepad-files/untitled-" + id + ".txt"
var fullPath = baseDir + "/" + filePath
var newTab = {
id: id,
title: "Untitled",
filePath: filePath,
isTemporary: true,
lastModified: new Date().toISOString(),
cursorPosition: 0,
scrollPosition: 0
}
var newTabsBeingCreated = Object.assign({}, tabsBeingCreated)
newTabsBeingCreated[id] = true
tabsBeingCreated = newTabsBeingCreated
createEmptyFile(fullPath, function() {
var newTabs = tabs.slice()
newTabs.push(newTab)
tabs = newTabs
currentTabIndex = tabs.length - 1
var updatedTabsBeingCreated = Object.assign({}, tabsBeingCreated)
delete updatedTabsBeingCreated[id]
tabsBeingCreated = updatedTabsBeingCreated
saveMetadata()
})
return newTab
}
function closeTab(tabIndex) {
if (tabIndex < 0 || tabIndex >= tabs.length) return
var newTabs = tabs.slice()
if (newTabs.length <= 1) {
var id = Date.now()
var filePath = "notepad-files/untitled-" + id + ".txt"
var newTabsBeingCreated = Object.assign({}, tabsBeingCreated)
newTabsBeingCreated[id] = true
tabsBeingCreated = newTabsBeingCreated
createEmptyFile(baseDir + "/" + filePath, function() {
newTabs[0] = {
id: id,
title: "Untitled",
filePath: filePath,
isTemporary: true,
lastModified: new Date().toISOString(),
cursorPosition: 0,
scrollPosition: 0
}
currentTabIndex = 0
tabs = newTabs
var updatedTabsBeingCreated = Object.assign({}, tabsBeingCreated)
delete updatedTabsBeingCreated[id]
tabsBeingCreated = updatedTabsBeingCreated
saveMetadata()
})
return
} else {
var tabToDelete = newTabs[tabIndex]
if (tabToDelete && tabToDelete.isTemporary) {
deleteFile(baseDir + "/" + tabToDelete.filePath)
}
newTabs.splice(tabIndex, 1)
if (currentTabIndex >= newTabs.length) {
currentTabIndex = newTabs.length - 1
} else if (currentTabIndex > tabIndex) {
currentTabIndex -= 1
}
}
tabs = newTabs
saveMetadata()
}
function switchToTab(tabIndex) {
if (tabIndex < 0 || tabIndex >= tabs.length) return
currentTabIndex = tabIndex
saveMetadata()
}
function saveTabAs(tabIndex, userPath) {
if (tabIndex < 0 || tabIndex >= tabs.length) return
var tab = tabs[tabIndex]
var fileName = userPath.split('/').pop()
if (tab.isTemporary) {
var tempPath = baseDir + "/" + tab.filePath
copyFile(tempPath, userPath)
deleteFile(tempPath)
}
var newTabs = tabs.slice()
newTabs[tabIndex] = Object.assign({}, tab, {
title: fileName,
filePath: userPath,
isTemporary: false,
lastModified: new Date().toISOString()
})
tabs = newTabs
saveMetadata()
}
function updateTabMetadata(tabIndex, properties) {
if (tabIndex < 0 || tabIndex >= tabs.length) return
var newTabs = tabs.slice()
var updatedTab = Object.assign({}, newTabs[tabIndex], properties)
updatedTab.lastModified = new Date().toISOString()
newTabs[tabIndex] = updatedTab
tabs = newTabs
saveMetadata()
}
function validateTabs() {
var validTabs = []
for (var i = 0; i < tabs.length; i++) {
var tab = tabs[i]
validTabs.push(tab)
}
tabs = validTabs
if (tabs.length === 0) {
createDefaultTab()
}
}
Component {
id: tabFileLoaderComponent
FileView {
property var callback
blockLoading: true
preload: true
onLoaded: {
callback(text())
destroy()
}
onLoadFailed: {
callback("")
destroy()
}
}
}
Component {
id: tabFileSaverComponent
FileView {
property string content
property int tabIndex
property var creationCallback
blockWrites: false
atomicWrites: true
Component.onCompleted: setText(content)
onSaved: {
if (tabIndex >= 0) {
updateTabMetadata(tabIndex, {})
}
if (creationCallback) {
creationCallback()
}
destroy()
}
onSaveFailed: {
console.error("Failed to save tab content")
if (creationCallback) {
creationCallback()
}
destroy()
}
}
}
function createEmptyFile(path, callback) {
// Ensure path is a local file path, not a URL
var cleanPath = path.toString()
if (cleanPath.startsWith("file://")) {
cleanPath = cleanPath.substring(7)
}
// Validate the cleaned path is absolute and in the right location
if (!cleanPath.startsWith("/")) {
cleanPath = baseDir + "/" + cleanPath
}
var creator = fileCreatorComponent.createObject(root, {
filePath: cleanPath,
creationCallback: callback
})
}
function copyFile(source, destination) {
copyProcess.source = source
copyProcess.destination = destination
copyProcess.running = true
}
function deleteFile(path) {
deleteProcess.filePath = path
deleteProcess.running = true
}
Component {
id: fileCreatorComponent
QtObject {
property string filePath
property var creationCallback
Component.onCompleted: {
var touchProcess = touchProcessComponent.createObject(this, {
filePath: filePath,
callback: creationCallback
})
}
}
}
Component {
id: touchProcessComponent
Process {
property string filePath
property var callback
command: ["touch", filePath]
Component.onCompleted: running = true
onExited: (exitCode) => {
if (callback) callback()
destroy()
}
}
}
Process {
id: copyProcess
property string source
property string destination
command: ["cp", source, destination]
}
Process {
id: deleteProcess
property string filePath
command: ["rm", "-f", filePath]
}
}