Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions shell/plugins/panels/dropbox/Panel.qml
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,6 @@ Panel {
onOpenedChanged: if (opened) {
cursorActive = false
if (panelFlick) panelFlick.contentY = 0
dropbox.refresh()
Qt.callLater(function() { keyCatcher.forceActiveFocus() })
}
onFileIndexChanged: scrollCursorIntoView()
Expand All @@ -148,6 +147,7 @@ Panel {
id: dropbox
settings: root.settings
omarchyPath: root.omarchyPath
inventoryRequested: root.opened
}

Connections {
Expand Down Expand Up @@ -283,10 +283,10 @@ Panel {

Text {
textFormat: Text.PlainText
visible: dropbox.actionStatus !== "" || dropbox.lastError !== ""
visible: dropbox.actionStatus !== "" || dropbox.lastError !== "" || dropbox.inventoryError !== ""
width: parent.width
text: dropbox.actionStatus !== "" ? dropbox.actionStatus : dropbox.lastError
color: dropbox.lastError !== "" && dropbox.actionStatus === "" ? root.urgent : root.dim
text: dropbox.actionStatus !== "" ? dropbox.actionStatus : (dropbox.lastError || dropbox.inventoryError)
color: (dropbox.lastError !== "" || dropbox.inventoryError !== "") && dropbox.actionStatus === "" ? root.urgent : root.dim
font.family: root.fontFamily
font.pixelSize: Style.font.bodySmall
wrapMode: Text.WordWrap
Expand All @@ -305,7 +305,7 @@ Panel {
Column {
width: parent.width
spacing: Style.spacing.labelGap
InfoPair { label: "Stored"; value: Model.usageText(dropbox.usedBytes, dropbox.quotaBytes, dropbox.quotaKnown) }
InfoPair { label: "Stored"; value: dropbox.inventoryLoaded ? Model.usageText(dropbox.usedBytes, dropbox.quotaBytes, dropbox.quotaKnown) : (dropbox.inventoryRefreshing ? "Loading…" : "Unavailable") }
}
}

Expand All @@ -327,8 +327,9 @@ Panel {

Text {
visible: dropbox.files.length === 0
textFormat: Text.PlainText
width: parent.width
text: "No synced files found."
text: dropbox.inventoryLoaded ? "No synced files found." : (dropbox.inventoryRefreshing ? "Loading recent files…" : "Recent files unavailable.")
color: root.dim
font.family: root.fontFamily
font.pixelSize: Style.font.body
Expand Down
93 changes: 82 additions & 11 deletions shell/plugins/panels/dropbox/Service.qml
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import QtQuick
import Quickshell
import Quickshell.Io
import qs.Commons
import "Model.js" as Model

Item {
Expand All @@ -13,6 +12,11 @@ Item {
property bool installed: false
property bool running: false
property bool authenticated: false
property bool inventoryRequested: false
property bool inventoryLoaded: false
readonly property bool inventoryRefreshing: inventoryProcess.running
property string inventoryError: ""
property bool inventoryPending: false

// Optimistic sync state so the UI reacts the instant you click, rather than
// waiting for dropboxd to actually settle. _desired is -1 while we just
Expand Down Expand Up @@ -56,15 +60,40 @@ Item {
return n
}

function refresh() {
function refresh(includeInventory) {
if (root.inventoryRequested && includeInventory !== false) root.inventoryPending = true
if (statusProcess.running || helperPath === "/shell/plugins/panels/dropbox/status.py") return
_statusOutput = ""
_statusError = ""
refreshing = true
statusProcess.command = ["python3", helperPath, "25"]
statusProcess.command = ["timeout", "--kill-after=2s", "8s", "python3", helperPath, "--status-only"]
statusProcess.running = true
}

function refreshInventory() {
if (!root.inventoryRequested || !root.authenticated || inventoryProcess.running) return
root.inventoryPending = false
inventoryProcess.accountPath = root.accountPath
inventoryProcess.cancelRequested = false
inventoryProcess.command = ["timeout", "--kill-after=2s", "15s", "python3", helperPath, "--inventory-only", "25"]
inventoryProcess.running = true
}

function cancelInventory() {
root.inventoryPending = false
if (inventoryProcess.running) {
inventoryProcess.cancelRequested = true
// Signal timeout, which forwards TERM to the scan's process group and
// escalates after its grace period if a helper does not stop.
inventoryProcess.signal(15)
}
}

onInventoryRequestedChanged: {
if (inventoryRequested) refresh()
else cancelInventory()
}

function applyStatus(raw) {
var parsed = Model.parseStatus(raw)
if (!parsed.ok) {
Expand All @@ -77,16 +106,39 @@ Item {
// Reality caught up to the pending pause/resume — stop overriding.
if (_desired !== -1 && running === (_desired === 1)) _desired = -1
statusText = String(parsed.statusText || (installed ? "Stopped" : "Not installed"))
accountPath = String(parsed.accountPath || "")
var nextPath = String(parsed.accountPath || "")
if (nextPath !== accountPath || !authenticated) {
cancelInventory()
inventoryLoaded = false
inventoryError = ""
usedBytes = 0
usagePercent = 0
files = []
inventoryPending = inventoryRequested && authenticated
Comment on lines +110 to +117

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Cached files disappear

If the same Dropbox folder becomes temporarily unavailable, read_status() reports authenticated: false without changing accountPath. This branch then clears files, usedBytes, and inventoryLoaded, so the last successful results are lost until another scan succeeds.

Keep the cache when the account path is unchanged. Cancel the scan without treating a temporarily missing folder as an account change.

}
accountPath = nextPath
plan = String(parsed.plan || "")
usedBytes = Number(parsed.usedBytes || 0)
quotaBytes = Number(parsed.quotaBytes || 0)
usagePercent = Number(parsed.usagePercent || 0)
usagePercent = quotaBytes > 0 ? usedBytes / quotaBytes * 100 : 0
quotaKnown = parsed.quotaKnown === true
files = parsed.files || []
lastError = ""
}

function applyInventory(raw, expectedPath) {
var parsed = Model.parseStatus(raw)
if (!parsed.ok || parsed.inventoryLoaded !== true || parsed.authenticated !== true) {
inventoryError = "Could not read Dropbox file inventory"
return
}
// A status refresh can change account while a scan is still exiting.
if (!authenticated || expectedPath !== accountPath || String(parsed.accountPath || "") !== accountPath) return
usedBytes = Number(parsed.usedBytes || 0)
usagePercent = quotaBytes > 0 ? usedBytes / quotaBytes * 100 : 0
files = parsed.files || []
inventoryLoaded = true
inventoryError = ""
}

function elideStatus(text) {
var value = String(text || "").replace(/\s+/g, " ").trim()
return value.length > 140 ? value.substring(0, 137) + "…" : value
Expand Down Expand Up @@ -179,15 +231,15 @@ Item {
onTriggered: {
ticks += 1
if (root.running || ticks >= 15) startupRamp.running = false
else root.refresh()
else root.refresh(false)
}
}

Timer {
id: delayedRefresh
interval: 1000
repeat: false
onTriggered: root.refresh()
onTriggered: root.refresh(false)
}

Timer {
Expand All @@ -208,7 +260,7 @@ Item {
running: false
onTriggered: {
settleTimer.ticks += 1
root.refresh()
root.refresh(false)
if (settleTimer.ticks >= 4) {
settleTimer.ticks = 0
settleTimer.running = false
Expand All @@ -227,11 +279,30 @@ Item {
root.refreshing = false
var stdout = String(statusStdout.text || root._statusOutput || "")
var stderr = String(statusStderr.text || root._statusError || "")
if (exitCode === 0) root.applyStatus(stdout)
if (exitCode === 0) {
root.applyStatus(stdout)
if (root.inventoryPending) root.refreshInventory()
}
else root.lastError = root.elideStatus(stderr || stdout || "Could not read Dropbox status")
}
}

Process {
id: inventoryProcess
property string accountPath: ""
property bool cancelRequested: false
stdout: StdioCollector { id: inventoryStdout; waitForEnd: true }
onExited: function(exitCode) {
if (!cancelRequested && root.inventoryRequested && accountPath === root.accountPath) {
if (exitCode === 0) root.applyInventory(inventoryStdout.text, accountPath)
else root.inventoryError = exitCode === 124 || exitCode === 137
? "Dropbox file inventory timed out"
: "Could not read Dropbox file inventory"
}
if (root.inventoryPending) root.refreshInventory()
}
}

Process {
id: loginProcess
running: false
Expand Down
113 changes: 63 additions & 50 deletions shell/plugins/panels/dropbox/status.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import argparse
import json
import os
import shutil
import subprocess
import sys
import heapq
from pathlib import Path

Expand Down Expand Up @@ -47,48 +47,43 @@ def scan_dropbox(path, limit):
total = 0
counter = 0
recent = []
try:
for root, dirs, files in os.walk(path):
dirs[:] = [name for name in dirs if not os.path.islink(os.path.join(root, name))]
for name in files:
file_path = os.path.join(root, name)
if os.path.islink(file_path):
continue
try:
stat = os.stat(file_path)
except OSError:
continue
total += stat.st_size
rel = os.path.relpath(file_path, path)
folder = os.path.dirname(rel)
row = {
"name": name,
"path": file_path,
"folder": "/" if folder in ("", ".") else folder,
"modifiedTs": int(stat.st_mtime),
"sizeBytes": stat.st_size,
}
counter += 1
entry = (row["modifiedTs"], counter, row)
if len(recent) < limit:
heapq.heappush(recent, entry)
else:
heapq.heappushpop(recent, entry)
except OSError:
return 0, []
def walk_error(error):
# os.walk otherwise hides unreadable/disappeared directories and returns
# an incomplete total as if the inventory succeeded.
raise error

for root, dirs, files in os.walk(path, onerror=walk_error):
dirs[:] = [name for name in dirs if not os.path.islink(os.path.join(root, name))]
for name in files:
file_path = os.path.join(root, name)
if os.path.islink(file_path):
continue
try:
stat = os.stat(file_path)
except FileNotFoundError:
# Files can be removed normally while Dropbox is syncing.
continue
total += stat.st_size
rel = os.path.relpath(file_path, path)
folder = os.path.dirname(rel)
row = {
"name": name,
"path": file_path,
"folder": "/" if folder in ("", ".") else folder,
"modifiedTs": int(stat.st_mtime),
"sizeBytes": stat.st_size,
}
counter += 1
entry = (row["modifiedTs"], counter, row)
if len(recent) < limit:
heapq.heappush(recent, entry)
else:
heapq.heappushpop(recent, entry)
rows = [entry[2] for entry in sorted(recent, reverse=True)]
return total, rows


def main():
limit = 25
if len(sys.argv) > 1:
try:
limit = max(1, min(100, int(sys.argv[1])))
except ValueError:
limit = 25

dropbox_cli = shutil.which("dropbox-cli")
def read_status(limit=25, status_only=False, inventory_only=False):
info = read_info()
account = dropbox_account(info)
account_path = account.get("path") if isinstance(account.get("path"), str) else ""
Expand All @@ -98,30 +93,48 @@ def main():

running = False
status_text = "Not installed"
dropbox_cli = shutil.which("dropbox-cli") if not inventory_only else None
if dropbox_cli:
status_exit, status_output = command_output([dropbox_cli, "status"])
status_text = status_output if status_exit == 0 and status_output else "Stopped"
lowered = status_text.lower()
stopped = "not running" in lowered or "isn't running" in lowered or lowered == "stopped"
running = status_exit == 0 and status_output != "" and not stopped

used, files = scan_dropbox(account_path, limit) if authenticated else (0, [])
usage_percent = (used / quota * 100) if quota > 0 else 0

print(json.dumps({
result = {
"ok": True,
"installed": dropbox_cli is not None,
"running": running,
"authenticated": authenticated,
"statusText": status_text,
"accountPath": account_path,
"plan": plan,
"usedBytes": used,
"quotaBytes": quota,
"usagePercent": usage_percent,
"quotaKnown": quota > 0,
"files": files,
}))
"inventoryLoaded": False,
}
if not inventory_only:
result.update(installed=dropbox_cli is not None, running=running, statusText=status_text)
if not status_only and authenticated:
try:
used, files = scan_dropbox(account_path, limit)
except OSError:
result["inventoryError"] = "Could not read Dropbox file inventory"
else:
result.update(inventoryLoaded=True, usedBytes=used, files=files, usagePercent=(used / quota * 100) if quota > 0 else 0)
return result


def main():
parser = argparse.ArgumentParser(description="Read Dropbox daemon status or on-demand file inventory")
parser.add_argument("limit", nargs="?", default="25")
mode = parser.add_mutually_exclusive_group()
mode.add_argument("--status-only", action="store_true")
mode.add_argument("--inventory-only", action="store_true")
args = parser.parse_args()
try:
limit = max(1, min(100, int(args.limit)))
except ValueError:
limit = 25
# Keep the original `status.py 25` interface for callers wanting both.
print(json.dumps(read_status(limit, args.status_only, args.inventory_only)))


if __name__ == "__main__":
Expand Down
28 changes: 28 additions & 0 deletions test/shell.d/dropbox-collection-runtime-test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#!/bin/bash

set -euo pipefail
source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh"

qml_test_runner=""
for candidate in /usr/lib/qt6/bin/qmltestrunner /usr/lib/qt6/qmltestrunner; do
if [[ -x $candidate ]]; then
qml_test_runner=$candidate
break
fi
done
if [[ -z $qml_test_runner ]]; then
skip "qt6 qmltestrunner not found; skipping Dropbox collection runtime tests"
exit 0
fi

fixture="$SHELL_TEST_DIR/fixtures/dropbox-collection"
mocks="$SHELL_TEST_DIR/fixtures/passwordless-sudo-status/mocks"
scratch=$(mktemp -d)
trap 'rm -rf "$scratch"' EXIT
mkdir -p "$scratch/DropboxUnderTest"
cp "$ROOT/shell/plugins/panels/dropbox/Service.qml" "$ROOT/shell/plugins/panels/dropbox/Model.js" "$scratch/DropboxUnderTest/"
printf '%s\n' 'module DropboxUnderTest' 'DropboxService 1.0 Service.qml' >"$scratch/DropboxUnderTest/qmldir"
output=$(QT_QPA_PLATFORM=offscreen QT_QUICK_BACKEND=software "$qml_test_runner" \
-import "$scratch" -import "$mocks" -input "$fixture" -o -,txt 2>&1) ||
fail "Dropbox separates background status from visible inventory in QML" "$output"
pass "Dropbox separates background status from visible inventory in QML"
Loading