Files
2026-08-29 17:24:30 +08:00

1017 lines
46 KiB
Python

import sys
import json
import sqlite3
import datetime
# ==========================================
# 0. 開啟 Chromium GPU 高幀率與渲染優化參數
# ==========================================
sys.argv.extend([
'--ignore-gpu-blocklist',
'--enable-gpu-rasterization',
'--enable-zero-copy',
'--disable-frame-rate-limit',
])
from PyQt6.QtCore import Qt, QObject, pyqtSlot, QUrl
from PyQt6.QtWidgets import QApplication, QMainWindow
from PyQt6.QtWebEngineWidgets import QWebEngineView
from PyQt6.QtWebChannel import QWebChannel
# ==========================================
# 1. Python 後端 API
# ==========================================
class CalendarAPI(QObject):
def __init__(self, window):
super().__init__()
self.window = window
self.conn = sqlite3.connect("widget_tasks.db", check_same_thread=False)
self.cursor = self.conn.cursor()
# 建立 待辦事項 (Tasks) 資料表
self.cursor.execute("""
CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
date TEXT NOT NULL,
content TEXT NOT NULL,
color TEXT NOT NULL DEFAULT '#00f0ff',
category TEXT NOT NULL DEFAULT '工作',
is_done INTEGER NOT NULL DEFAULT 0
)
""")
# 建立 節日與行程 (Events) 資料表
self.cursor.execute("""
CREATE TABLE IF NOT EXISTS events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
event_date TEXT NOT NULL,
content TEXT NOT NULL,
color TEXT NOT NULL DEFAULT '#ff007f',
category TEXT NOT NULL DEFAULT '節日'
)
""")
# 向後相容舊資料庫檢查
self.cursor.execute("PRAGMA table_info(tasks)")
columns = [col[1] for col in self.cursor.fetchall()]
if 'is_done' not in columns:
self.cursor.execute("ALTER TABLE tasks ADD COLUMN is_done INTEGER NOT NULL DEFAULT 0")
self.conn.commit()
@pyqtSlot()
def start_drag(self):
if self.window.windowHandle():
self.window.windowHandle().startSystemMove()
@pyqtSlot()
def finish_minimize(self):
curr_geom = self.window.geometry()
self.window.setGeometry(curr_geom.x(), curr_geom.y(), 110, 110)
@pyqtSlot()
def prepare_expand(self):
screen = self.window.screen().availableGeometry()
curr_geom = self.window.geometry()
exp_w, exp_h = 550, 1000
new_x = min(curr_geom.x(), screen.x() + screen.width() - exp_w)
new_y = min(curr_geom.y(), screen.y() + screen.height() - exp_h)
new_x = max(screen.x(), new_x)
new_y = max(screen.y(), new_y)
self.window.setGeometry(int(new_x), int(new_y), exp_w, exp_h)
@pyqtSlot()
def close_window(self):
QApplication.quit()
# --- 待辦事項 API ---
@pyqtSlot(result=str)
def get_all_tasks_json(self):
"""讀取所有待辦事項(依日期時間順序排列)"""
self.cursor.execute(
"SELECT id, date, content, color, category, is_done FROM tasks ORDER BY date ASC, id DESC"
)
rows = self.cursor.fetchall()
tasks = [
{"id": r[0], "date": r[1], "content": r[2], "color": r[3], "category": r[4], "is_done": bool(r[5])}
for r in rows
]
return json.dumps(tasks)
@pyqtSlot(str, str, str, str, result=bool)
def add_task(self, date_str, content, color, category):
if not content.strip():
return False
self.cursor.execute(
"INSERT INTO tasks (date, content, color, category, is_done) VALUES (?, ?, ?, ?, 0)",
(date_str, content, color, category)
)
self.conn.commit()
return True
@pyqtSlot(int, result=bool)
def toggle_task_done(self, task_id):
self.cursor.execute("UPDATE tasks SET is_done = CASE WHEN is_done = 1 THEN 0 ELSE 1 END WHERE id = ?", (task_id,))
self.conn.commit()
return True
@pyqtSlot(int, result=bool)
def delete_task(self, task_id):
self.cursor.execute("DELETE FROM tasks WHERE id = ?", (task_id,))
self.conn.commit()
return True
# --- 節日與行程 API ---
@pyqtSlot(result=str)
def get_all_events_json(self):
"""讀取所有節日與行程事件(依日期升冪排序)"""
self.cursor.execute(
"SELECT id, event_date, content, color, category FROM events ORDER BY event_date ASC, id DESC"
)
rows = self.cursor.fetchall()
events = [
{"id": r[0], "event_date": r[1], "content": r[2], "color": r[3], "category": r[4]}
for r in rows
]
return json.dumps(events)
@pyqtSlot(str, str, str, str, result=bool)
def add_event(self, event_date, content, color, category):
if not content.strip() or not event_date:
return False
self.cursor.execute(
"INSERT INTO events (event_date, content, color, category) VALUES (?, ?, ?, ?)",
(event_date, content, color, category)
)
self.conn.commit()
return True
@pyqtSlot(int, result=bool)
def delete_event(self, event_id):
self.cursor.execute("DELETE FROM events WHERE id = ?", (event_id,))
self.conn.commit()
return True
# --- 日曆圓點與小球跑馬燈 ---
@pyqtSlot(str, result=str)
def get_month_dots_json(self, year_month):
result = {}
# 載入待辦事項點點
self.cursor.execute("SELECT date, color FROM tasks WHERE date LIKE ?", (f"{year_month}%",))
for date, color in self.cursor.fetchall():
if date not in result: result[date] = []
if color not in result[date]: result[date].append(color)
# 載入節日行程點點
self.cursor.execute("SELECT event_date, color FROM events WHERE event_date LIKE ?", (f"{year_month}%",))
for date, color in self.cursor.fetchall():
if date not in result: result[date] = []
if color not in result[date]: result[date].append(color)
return json.dumps(result)
@pyqtSlot(result=str)
def get_upcoming_task_json(self):
today_str = datetime.date.today().strftime("%Y-%m-%d")
# 優先找近期未完成待辦
self.cursor.execute(
"SELECT date, content FROM tasks WHERE date >= ? AND is_done = 0 ORDER BY date ASC, id ASC LIMIT 1",
(today_str,)
)
row = self.cursor.fetchone()
# 次之找最近的節日行程
if not row:
self.cursor.execute(
"SELECT event_date, content FROM events WHERE event_date >= ? ORDER BY event_date ASC, id ASC LIMIT 1",
(today_str,)
)
row = self.cursor.fetchone()
if row:
d_parts = row[0].split('-')
short_date = f"{int(d_parts[1])}/{int(d_parts[2])}"
return json.dumps({"found": True, "date": short_date, "content": row[1]})
return json.dumps({"found": False, "content": "無待辦事項"})
# ==========================================
# 2. 前端 HTML / CSS / JS
# ==========================================
HTML_CONTENT = """
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<script src="qrc:///qtwebchannel/qwebchannel.js"></script>
<style>
@import url('https://fonts.googleapis.com/css2?family=Fredoka:wght@700&display=swap');
html, body {
margin: 0; padding: 0; width: 100vw; height: 100vh;
background: transparent !important;
font-family: -apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", "Microsoft JhengHei", sans-serif;
overflow: hidden; color: #fff; font-weight: 600; -webkit-font-smoothing: antialiased;
}
* { box-sizing: border-box; user-select: none; font-weight: 600; }
::-webkit-scrollbar { width: 5px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, 0.22); border-radius: 10px; }
::-webkit-scrollbar-thumb:hover { background: rgba(255, 255, 255, 0.45); }
.app-container {
position: absolute; top: 13px; left: 13px; width: 434px; height: 874px;
padding: 16px; display: flex; flex-direction: column; border-radius: 32px;
background-size: cover;
box-shadow: inset 0 0 0 1.5px rgba(255, 255, 255, 0.22), inset 0 1px 2px rgba(255, 255, 255, 0.35);
overflow: hidden;
transition: width 0.35s cubic-bezier(0.16, 1, 0.3, 1), height 0.35s cubic-bezier(0.16, 1, 0.3, 1), border-radius 0.35s cubic-bezier(0.16, 1, 0.3, 1);
will-change: width, height, border-radius;
}
.app-container.minimized {
width: 84px; height: 84px; padding: 0; border-radius: 50%; cursor: pointer;
box-shadow: inset 0 0 0 2px rgba(255, 255, 255, 0.45);
}
.full-content {
width: 100%; height: 100%; display: flex; flex-direction: column;
opacity: 1; transform: scale(1);
transition: opacity 0.22s cubic-bezier(0.16, 1, 0.3, 1), transform 0.28s cubic-bezier(0.16, 1, 0.3, 1);
min-height: 0; will-change: opacity, transform;
}
.app-container.minimized .full-content { opacity: 0; transform: scale(0.85); pointer-events: none; position: absolute; inset: 16px; }
/* 球球模式 */
.bubble-content {
position: absolute; inset: 0; display: none; align-items: center; justify-content: center;
font-family: 'Fredoka', 'Quicksand', sans-serif; font-weight: 700; color: #ffffff;
text-shadow: 0 0 8px rgba(0, 240, 255, 0.9), 0 2px 4px rgba(0, 0, 0, 0.8);
opacity: 0; transform: scale(0.5); transition: opacity 0.18s ease, transform 0.28s cubic-bezier(0.16, 1, 0.3, 1);
pointer-events: none;
}
.app-container.minimized .bubble-content { display: flex; opacity: 1; transform: scale(1); pointer-events: auto; }
.bubble-date { font-size: 20px; color: #00f0ff; }
.bubble-time { font-size: 15px; color: #ffffff; }
.marquee-wrapper { width: 74px; overflow: hidden; white-space: nowrap; display: flex; align-items: center; }
.marquee-text { display: inline-block; white-space: nowrap; font-size: 17px; font-weight: 700; color: #00f0ff; text-shadow: 0 0 6px rgba(0, 240, 255, 0.9); }
@keyframes marquee-scroll { 0% { transform: translateX(74px); } 100% { transform: translateX(-100%); } }
/* 發光特效 */
.glow-target { position: relative; --mouse-x: 50%; --mouse-y: 50%; }
.glow-target::before {
content: ""; position: absolute; inset: 0; border-radius: inherit;
background: radial-gradient(120px circle at var(--mouse-x, 50%) var(--mouse-y, 50%), rgba(255, 255, 255, 0.25) 0%, rgba(255, 255, 255, 0.02) 55%, transparent 80%);
opacity: 0; pointer-events: none; transition: opacity 0.28s ease; z-index: 1;
}
.glow-target::after {
content: ""; position: absolute; inset: 0; border-radius: inherit; padding: 1.5px;
background: radial-gradient(110px circle at var(--mouse-x, 50%) var(--mouse-y, 50%), rgba(255, 255, 255, 0.85) 0%, rgba(255, 255, 255, 0.2) 45%, transparent 80%);
-webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0); -webkit-mask-composite: xor; mask-composite: exclude; pointer-events: none; opacity: 0; transition: opacity 0.28s ease; z-index: 2;
}
.glow-target:hover::before, .glow-target:hover::after { opacity: 1; }
.title-bar { display: flex; justify-content: space-between; align-items: center; padding: 2px 4px 10px 4px; cursor: move; flex-shrink: 0; }
.title-text { font-size: 17px; font-weight: 700; opacity: 0.98; letter-spacing: 0.5px; }
.window-controls { display: flex; gap: 8px; }
.liquid-glass-btn, .glass-card {
color: rgba(255, 255, 255, 0.98); background: rgba(255, 255, 255, 0.12);
box-shadow: inset 0 1.5px 1px 0 rgba(255, 255, 255, 0.45), inset 0 -1.5px 2px 0 rgba(255, 255, 255, 0.12), inset 0 0 0 1px rgba(255, 255, 255, 0.18);
border-radius: 22px; overflow: hidden; backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px);
}
.control-btn {
width: 32px; height: 32px; border-radius: 50% !important; border: none;
display: flex; align-items: center; justify-content: center;
font-size: 14px; font-weight: 700; cursor: pointer; outline: none; padding: 0;
transition: transform 0.22s ease, background 0.22s ease;
}
.control-btn:active { transform: scale(0.88); }
.close-btn:hover { background: rgba(255, 46, 99, 0.75); }
.min-btn:hover, .settings-btn:hover { background: rgba(255, 255, 255, 0.32); }
/* 行事曆 */
.cal-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; padding: 0 4px; }
.nav-btn {
background: rgba(255,255,255,0.18); border: none; color: #fff;
padding: 6px 14px; border-radius: 12px; cursor: pointer; font-size: 15px; font-weight: 700;
transition: background 0.22s ease, transform 0.2s ease;
}
.nav-btn:hover { background: rgba(255,255,255,0.35); }
.nav-btn:active { transform: scale(0.92); }
.cal-grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 4px; text-align: center; }
.weekday { font-size: 13px; font-weight: 700; opacity: 0.85; padding-bottom: 4px; }
.day-cell {
height: 40px; display: flex; flex-direction: column; align-items: center; justify-content: center;
border-radius: 14px; cursor: pointer; font-size: 14px; font-weight: 700; position: relative;
transition: background 0.2s ease, transform 0.18s ease; background: rgba(255,255,255,0.06);
}
.day-cell:hover { background: rgba(255, 255, 255, 0.22); transform: translateY(-1px); }
.day-cell.selected { background: rgba(255, 255, 255, 0.32); box-shadow: inset 0 0 0 1.5px rgba(255, 255, 255, 0.9); }
.day-cell.today { color: #00f0ff; font-weight: 800; }
.dots-container { display: flex; gap: 3px; position: absolute; bottom: 3px; justify-content: center; }
.dot { width: 5px; height: 5px; border-radius: 50%; }
/* ==========================================
3. 下方卡片 - 瀏覽器風格頁籤 (Browser Tabs)
========================================== */
.tab-section-wrapper {
flex: 1; margin-top: 10px; display: flex; flex-direction: column; min-height: 0;
}
.browser-tabs-header {
display: flex; gap: 6px; padding-left: 10px; z-index: 10; margin-bottom: -1px; flex-shrink: 0;
}
.browser-tab {
padding: 8px 16px; border-radius: 16px 16px 0 0;
background: rgba(255, 255, 255, 0.08); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px);
box-shadow: inset 0 1px 1px 0 rgba(255, 255, 255, 0.25);
font-size: 13px; font-weight: 700; cursor: pointer; color: rgba(255, 255, 255, 0.65);
transition: all 0.22s cubic-bezier(0.16, 1, 0.3, 1);
display: flex; align-items: center; gap: 6px; border: 1px solid rgba(255, 255, 255, 0.12); border-bottom: none;
}
.browser-tab:hover { background: rgba(255, 255, 255, 0.18); color: #fff; }
.browser-tab.active {
background: rgba(255, 255, 255, 0.2); color: #ffffff; font-weight: 700;
box-shadow: inset 0 1.5px 1px 0 rgba(255, 255, 255, 0.45);
border-color: rgba(255, 255, 255, 0.25);
}
.task-section {
flex: 1; padding: 14px; display: flex; flex-direction: column; gap: 10px; overflow: hidden; min-height: 0;
}
.tab-view { flex: 1; display: flex; flex-direction: column; gap: 10px; min-height: 0; }
.task-list { flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 8px; padding-right: 4px; }
/* 待辦事項 Item */
.task-item {
display: flex; align-items: center; justify-content: space-between;
padding: 10px 14px; background: rgba(255,255,255,0.14);
border-radius: 14px; font-size: 14px; font-weight: 600; transition: all 0.2s ease;
}
.task-item:hover { background: rgba(255, 255, 255, 0.22); }
.task-item.completed { opacity: 0.5; }
.task-item.completed .task-text { text-decoration: line-through; color: rgba(255, 255, 255, 0.7); }
.task-checkbox {
width: 18px; height: 18px; border-radius: 50%; border: 2px solid rgba(255, 255, 255, 0.6);
margin-right: 10px; cursor: pointer; display: flex; align-items: center; justify-content: center;
font-size: 11px; flex-shrink: 0; transition: all 0.2s ease;
}
.task-item.completed .task-checkbox { background: #00ff88; border-color: #00ff88; color: #000; font-weight: 800; }
.task-tag { width: 10px; height: 10px; border-radius: 50%; margin-right: 10px; flex-shrink: 0; }
.task-content { flex: 1; display: flex; align-items: center; min-width: 0; cursor: pointer; }
.task-text { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
/* 行程事件 Item */
.event-item {
display: flex; align-items: center; justify-content: space-between;
padding: 10px 14px; background: rgba(255,255,255,0.14);
border-radius: 14px; font-size: 14px; font-weight: 600; transition: background 0.2s ease;
}
.event-item:hover { background: rgba(255, 255, 255, 0.22); }
.date-badge {
background: rgba(0, 240, 255, 0.22); border: 1px solid rgba(0, 240, 255, 0.5);
color: #00f0ff; padding: 2px 8px; border-radius: 8px; font-size: 12px; font-weight: 700; margin-right: 8px; flex-shrink: 0;
}
.event-cat-badge {
font-size: 11px; padding: 2px 8px; border-radius: 8px; color: #fff; font-weight: 700; margin-right: 8px; flex-shrink: 0;
}
/* 輸入區塊 */
.input-row { display: flex; gap: 8px; align-items: center; margin-top: 2px; width: 100%; flex-shrink: 0; }
.task-input {
flex: 1; min-width: 0; background: rgba(0, 0, 0, 0.35); border: 1.5px solid rgba(255, 255, 255, 0.28);
border-radius: 18px; padding: 9px 12px; color: #fff; font-size: 13px; font-weight: 600; outline: none;
transition: border-color 0.22s ease;
}
.task-input:focus { border-color: rgba(255, 255, 255, 0.7); }
.date-picker-input { width: 115px; flex: none; text-align: center; }
/* 新增按鈕 (+) */
.add-btn {
display: flex; align-items: center; justify-content: center; border: none; cursor: pointer;
color: rgba(255, 255, 255, 0.98); transition: transform 0.2s ease, background 0.22s ease;
}
.add-btn:hover { background: rgba(255, 255, 255, 0.3); }
.add-btn:active { transform: scale(0.88); }
.add-btn svg { display: block; }
/* 下拉選單 */
.menu-wrapper { position: relative; width: 95px; height: 36px; flex-shrink: 0; }
.liquid-glass-menu {
position: absolute; bottom: 0; right: 0; width: 95px; height: 36px; border-radius: 18px; cursor: pointer;
display: flex; flex-direction: column-reverse; color: rgba(255, 255, 255, 0.98); background: rgba(255, 255, 255, 0.16);
backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
box-shadow: inset 0 1.5px 1px 0 rgba(255, 255, 255, 0.5), inset 0 -1.5px 2px 0 rgba(255, 255, 255, 0.15), inset 0 0 0 1px rgba(255, 255, 255, 0.25);
transition: height 0.35s cubic-bezier(0.16, 1, 0.3, 1), background 0.3s ease; z-index: 50; overflow: hidden;
}
.menu-header { height: 36px; display: flex; align-items: center; justify-content: center; font-size: 12px; font-weight: 700; gap: 4px; flex-shrink: 0; }
.menu-arrow { font-size: 10px; transition: transform 0.35s ease; opacity: 0.85; }
.liquid-glass-menu.is-open { height: 180px; border-radius: 18px; background: rgba(255, 255, 255, 0.22); }
.liquid-glass-menu.is-open .menu-arrow { transform: rotate(180deg); }
.menu-list { padding: 6px 4px; display: flex; flex-direction: column; gap: 4px; opacity: 0; pointer-events: none; transition: opacity 0.22s ease 0.05s; }
.liquid-glass-menu.is-open .menu-list { opacity: 1; pointer-events: auto; }
.menu-item { padding: 6px 8px; border-radius: 10px; font-size: 12px; font-weight: 600; display: flex; align-items: center; gap: 6px; white-space: nowrap; }
.menu-item:hover { background: rgba(255, 255, 255, 0.28); }
.menu-item .dot, .selected-cat-dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; }
.settings-modal {
position: absolute; top: 0; left: 0; right: 0; bottom: 0;
border-radius: 32px; background: rgba(18, 18, 30, 0.96); z-index: 100; padding: 24px;
display: flex; flex-direction: column; gap: 16px; opacity: 0; pointer-events: none; transform: scale(0.95);
transition: opacity 0.28s ease, transform 0.28s ease;
}
.settings-modal.active { opacity: 1; pointer-events: auto; transform: scale(1); }
.settings-header { display: flex; justify-content: space-between; align-items: center; font-size: 17px; font-weight: 700; border-bottom: 1px solid rgba(255,255,255,0.2); padding-bottom: 12px; }
.theme-option { display: flex; align-items: center; justify-content: space-between; padding: 14px; background: rgba(255,255,255,0.08); border-radius: 14px; cursor: pointer; font-size: 15px; font-weight: 600; }
.theme-option:hover { background: rgba(255,255,255,0.2); }
</style>
</head>
<body>
<div class="app-container" id="appContainer">
<div class="full-content" id="fullContent">
<div class="title-bar" id="dragArea">
<span class="title-text">📅 桌面行事曆</span>
<div class="window-controls">
<button class="liquid-glass-btn control-btn settings-btn glow-target" onclick="openSettings()">⚙️</button>
<button class="liquid-glass-btn control-btn min-btn glow-target" onclick="minimizeToBubble()">─</button>
<button class="liquid-glass-btn control-btn close-btn glow-target" onclick="pyapi.close_window()">✕</button>
</div>
</div>
<!-- 日曆月曆卡片 -->
<div class="glass-card glow-target" id="calendarCard" style="padding: 12px;">
<div class="cal-header">
<button class="nav-btn glow-target" onclick="changeMonth(-1)">◀</button>
<span id="monthYearLabel" style="font-weight:700; font-size:16px;"></span>
<button class="nav-btn glow-target" onclick="changeMonth(1)">▶</button>
</div>
<div class="cal-grid" id="weekdayGrid"></div>
<div class="cal-grid" id="calendarDays"></div>
</div>
<!-- 下方頁籤與內容區域 -->
<div class="tab-section-wrapper">
<div class="browser-tabs-header">
<div class="browser-tab active" id="tabTodo" onclick="switchTab('todo')">📌 待辦事項</div>
<div class="browser-tab" id="tabEvent" onclick="switchTab('event')">📅 節日與行程</div>
</div>
<div class="glass-card task-section glow-target">
<!-- 分頁 1: 待辦事項 -->
<div id="todoView" class="tab-view">
<div class="task-list" id="taskList"></div>
<div class="input-row">
<input type="text" id="taskInput" class="task-input" placeholder="新增待辦事項..." onkeypress="if(event.key==='Enter') addTask()">
<div class="menu-wrapper">
<div class="liquid-glass-menu glow-target" id="todoCategoryMenu">
<div class="menu-header" onclick="toggleMenu('todoCategoryMenu')">
<span class="selected-cat-dot" id="todoSelectedCatDot" style="background:#00f0ff;"></span>
<span id="todoSelectedCatText">工作</span>
<span class="menu-arrow">▲</span>
</div>
<div class="menu-list">
<div class="menu-item" onclick="selectTodoCat('工作', '#00f0ff')"><span class="dot" style="background:#00f0ff;"></span>工作</div>
<div class="menu-item" onclick="selectTodoCat('個人', '#ff007f')"><span class="dot" style="background:#ff007f;"></span>個人</div>
<div class="menu-item" onclick="selectTodoCat('重要', '#7000ff')"><span class="dot" style="background:#7000ff;"></span>重要</div>
<div class="menu-item" onclick="selectTodoCat('學習', '#00ff88')"><span class="dot" style="background:#00ff88;"></span>學習</div>
</div>
</div>
</div>
<button class="liquid-glass-btn glow-target add-btn" style="width:36px; height:36px; border-radius:18px;" onclick="addTask()">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12 5V19M5 12H19" stroke="currentColor" stroke-width="3.4" stroke-linecap="round"/></svg>
</button>
</div>
</div>
<!-- 分頁 2: 節日與行程 -->
<div id="eventView" class="tab-view" style="display: none;">
<div class="task-list" id="eventList"></div>
<div class="input-row">
<input type="date" id="eventDateInput" class="task-input date-picker-input">
<input type="text" id="eventInput" class="task-input" placeholder="新增節日/行程..." onkeypress="if(event.key==='Enter') addEvent()">
<div class="menu-wrapper">
<div class="liquid-glass-menu glow-target" id="eventCategoryMenu">
<div class="menu-header" onclick="toggleMenu('eventCategoryMenu')">
<span class="selected-cat-dot" id="eventSelectedCatDot" style="background:#ff007f;"></span>
<span id="eventSelectedCatText">節日</span>
<span class="menu-arrow">▲</span>
</div>
<div class="menu-list">
<div class="menu-item" onclick="selectEventCat('節日', '#ff007f')"><span class="dot" style="background:#ff007f;"></span>節日</div>
<div class="menu-item" onclick="selectEventCat('紀念日', '#7000ff')"><span class="dot" style="background:#7000ff;"></span>紀念日</div>
<div class="menu-item" onclick="selectEventCat('會議', '#00f0ff')"><span class="dot" style="background:#00f0ff;"></span>會議</div>
<div class="menu-item" onclick="selectEventCat('活動', '#00ff88')"><span class="dot" style="background:#00ff88;"></span>活動</div>
</div>
</div>
</div>
<button class="liquid-glass-btn glow-target add-btn" style="width:36px; height:36px; border-radius:18px;" onclick="addEvent()">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12 5V19M5 12H19" stroke="currentColor" stroke-width="3.4" stroke-linecap="round"/></svg>
</button>
</div>
</div>
</div>
</div>
<!-- 設定彈窗 -->
<div class="settings-modal" id="settingsModal">
<div class="settings-header">
<span>⚙️ 小工具設定</span>
<span style="cursor:pointer;" onclick="closeSettings()">✕</span>
</div>
<div style="font-size: 14px; font-weight: 700; opacity:0.85;">選擇背景風格:</div>
<div class="theme-option" onclick="changeTheme('obsidian')">
<span>🌑 深邃黑曜石 (預設)</span>
<span class="dot" style="background:#aaaaaa; width:12px; height:12px;"></span>
</div>
<div class="theme-option" onclick="changeTheme('cyber')">
<span>🌌 賽博霓虹</span>
<span class="dot" style="background:#ff007f; width:12px; height:12px;"></span>
</div>
<div class="theme-option" onclick="changeTheme('aurora')">
<span>🌌 極光森林</span>
<span class="dot" style="background:#00ff88; width:12px; height:12px;"></span>
</div>
</div>
</div>
<!-- 最小化小球球顯示區域 -->
<div class="bubble-content" id="bubbleContent"></div>
</div>
<script>
let pyapi = null;
let currDate = new Date();
let selectedDateStr = formatDate(new Date());
let currentTab = 'todo';
let todoCategory = '工作', todoColor = '#00f0ff';
let eventCategory = '節日', eventColor = '#ff007f';
let isAnimating = false;
let bubbleLoopTimer = null, bubbleClockInterval = null, bubbleStep = 0;
const themeStyles = {
obsidian: `radial-gradient(circle at 50% 50%, #2a2a3c, #0a0a12)`,
cyber: `radial-gradient(circle at 20% 20%, rgba(255, 0, 127, 0.55), transparent 50%), radial-gradient(circle at 80% 80%, rgba(0, 240, 255, 0.55), transparent 50%), radial-gradient(circle at 50% 50%, #4a00a8, #0d0d18)`,
aurora: `radial-gradient(circle at 20% 20%, rgba(0, 255, 136, 0.55), transparent 50%), radial-gradient(circle at 80% 80%, rgba(0, 170, 255, 0.55), transparent 50%), radial-gradient(circle at 50% 50%, #052c28, #050d1a)`
};
const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
function escapeHtml(str) {
return str.replace(/[&<>"']/g, function(m) {
return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' }[m];
});
}
function formatDate(d) {
const y = d.getFullYear();
const m = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
return `${y}-${m}-${day}`;
}
document.addEventListener("DOMContentLoaded", () => {
document.getElementById('eventDateInput').value = selectedDateStr;
let mouseFrame = null;
document.addEventListener('mousemove', (e) => {
if (mouseFrame) return;
mouseFrame = requestAnimationFrame(() => {
mouseFrame = null;
const target = e.target.closest('.glow-target');
if (target) {
const rect = target.getBoundingClientRect();
target.style.setProperty('--mouse-x', `${e.clientX - rect.left}px`);
target.style.setProperty('--mouse-y', `${e.clientY - rect.top}px`);
}
});
});
new QWebChannel(qt.webChannelTransport, function(channel) {
pyapi = channel.objects.pyapi;
document.getElementById('dragArea').addEventListener('mousedown', (e) => {
if (!e.target.closest('.window-controls')) pyapi.start_drag();
});
const appContainer = document.getElementById('appContainer');
let startX = 0, startY = 0, isDragging = false;
appContainer.addEventListener('mousedown', (e) => {
if (!appContainer.classList.contains('minimized')) return;
if (e.button !== 0) return;
startX = e.screenX; startY = e.screenY; isDragging = false;
const onMouseMove = (e) => {
if (Math.hypot(e.screenX - startX, e.screenY - startY) > 5) {
isDragging = true;
window.removeEventListener('mousemove', onMouseMove);
window.removeEventListener('mouseup', onMouseUp);
pyapi.start_drag();
}
};
const onMouseUp = () => {
window.removeEventListener('mousemove', onMouseMove);
window.removeEventListener('mouseup', onMouseUp);
if (!isDragging && appContainer.classList.contains('minimized')) {
expandFromBubble();
}
};
window.addEventListener('mousemove', onMouseMove);
window.addEventListener('mouseup', onMouseUp);
});
changeTheme('obsidian');
renderCalendar();
loadAllTasks();
loadAllEvents();
});
});
/* --- 分頁切換 --- */
function switchTab(tab) {
currentTab = tab;
document.getElementById('tabTodo').classList.toggle('active', tab === 'todo');
document.getElementById('tabEvent').classList.toggle('active', tab === 'event');
document.getElementById('todoView').style.display = tab === 'todo' ? 'flex' : 'none';
document.getElementById('eventView').style.display = tab === 'event' ? 'flex' : 'none';
if (tab === 'todo') loadAllTasks();
else loadAllEvents();
}
/* --- 載入所有待辦事項 --- */
function loadAllTasks() {
pyapi.get_all_tasks_json((jsonStr) => {
const tasks = JSON.parse(jsonStr);
const listEl = document.getElementById('taskList');
if (tasks.length === 0) {
listEl.innerHTML = `<div style="text-align:center; opacity:0.5; font-size:13px; margin-top:20px;">目前尚無待辦事項</div>`;
return;
}
listEl.innerHTML = tasks.map(t => `
<div class="task-item ${t.is_done ? 'completed' : ''}">
<div class="task-content" onclick="toggleTaskDone(${t.id})">
<div class="task-checkbox">${t.is_done ? '✓' : ''}</div>
<span class="date-badge">${t.date.substring(5)}</span>
<span class="task-tag" style="background:${t.color}; box-shadow: 0 0 6px ${t.color};"></span>
<span class="task-text">${escapeHtml(t.content)}</span>
</div>
<span style="cursor:pointer; opacity:0.6; font-size:13px; font-weight:700; padding-left:8px;" onclick="deleteTask(${t.id})">✕</span>
</div>
`).join('');
});
}
/* --- 載入所有節日與行程 --- */
function loadAllEvents() {
pyapi.get_all_events_json((jsonStr) => {
const events = JSON.parse(jsonStr);
const listEl = document.getElementById('eventList');
if (events.length === 0) {
listEl.innerHTML = `<div style="text-align:center; opacity:0.5; font-size:13px; margin-top:20px;">目前尚無行程或節日</div>`;
return;
}
listEl.innerHTML = events.map(e => `
<div class="event-item">
<div style="display:flex; align-items:center; min-width:0; flex:1;">
<span class="date-badge">${e.event_date.substring(5)}</span>
<span class="event-cat-badge" style="background:${e.color};">${e.category}</span>
<span style="overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">${escapeHtml(e.content)}</span>
</div>
<span style="cursor:pointer; opacity:0.6; font-size:13px; font-weight:700; padding-left:8px;" onclick="deleteEvent(${e.id})">✕</span>
</div>
`).join('');
});
}
/* --- 新增/異動待辦與行程 --- */
function addTask() {
const input = document.getElementById('taskInput');
const val = input.value.trim();
if (!val) return;
pyapi.add_task(selectedDateStr, val, todoColor, todoCategory, (ok) => {
if (ok) {
input.value = '';
loadAllTasks();
renderCalendar();
}
});
}
function toggleTaskDone(id) {
pyapi.toggle_task_done(id, () => {
loadAllTasks();
});
}
function deleteTask(id) {
pyapi.delete_task(id, () => {
loadAllTasks();
renderCalendar();
});
}
function addEvent() {
const dateVal = document.getElementById('eventDateInput').value;
const input = document.getElementById('eventInput');
const val = input.value.trim();
if (!val || !dateVal) return;
pyapi.add_event(dateVal, val, eventColor, eventCategory, (ok) => {
if (ok) {
input.value = '';
loadAllEvents();
renderCalendar();
}
});
}
function deleteEvent(id) {
pyapi.delete_event(id, () => {
loadAllEvents();
renderCalendar();
});
}
/* --- 下拉選單控制 --- */
function toggleMenu(menuId) {
document.getElementById(menuId).classList.toggle('is-open');
}
function selectTodoCat(cat, color) {
todoCategory = cat; todoColor = color;
document.getElementById('todoSelectedCatText').innerText = cat;
document.getElementById('todoSelectedCatDot').style.background = color;
document.getElementById('todoCategoryMenu').classList.remove('is-open');
}
function selectEventCat(cat, color) {
eventCategory = cat; eventColor = color;
document.getElementById('eventSelectedCatText').innerText = cat;
document.getElementById('eventSelectedCatDot').style.background = color;
document.getElementById('eventCategoryMenu').classList.remove('is-open');
}
/* --- 日曆繪製 --- */
function renderCalendar(callback) {
const year = currDate.getFullYear();
const month = currDate.getMonth();
document.getElementById('monthYearLabel').innerText = `${year}年 ${month + 1}月`;
const wkGrid = document.getElementById('weekdayGrid');
wkGrid.innerHTML = weekdays.map(w => `<div class="weekday">${w}</div>`).join('');
const ymStr = `${year}-${String(month + 1).padStart(2, '0')}`;
pyapi.get_month_dots_json(ymStr, (jsonStr) => {
const monthDots = JSON.parse(jsonStr);
const firstDay = new Date(year, month, 1).getDay();
const totalDays = new Date(year, month + 1, 0).getDate();
const calGrid = document.getElementById('calendarDays');
calGrid.innerHTML = '';
for (let i = 0; i < firstDay; i++) calGrid.appendChild(document.createElement('div'));
const todayStr = formatDate(new Date());
for (let day = 1; day <= totalDays; day++) {
const dObj = new Date(year, month, day);
const dateStr = formatDate(dObj);
const cell = document.createElement('div');
cell.className = `day-cell ${dateStr === selectedDateStr ? 'selected' : ''} ${dateStr === todayStr ? 'today' : ''}`;
cell.innerText = day;
cell.onclick = () => selectDate(dateStr);
if (monthDots[dateStr]) {
const dotsDiv = document.createElement('div');
dotsDiv.className = 'dots-container';
monthDots[dateStr].forEach(color => {
const dot = document.createElement('div');
dot.className = 'dot';
dot.style.background = color;
dotsDiv.appendChild(dot);
});
cell.appendChild(dotsDiv);
}
calGrid.appendChild(cell);
}
if (callback) callback();
});
}
function selectDate(dateStr) {
selectedDateStr = dateStr;
document.getElementById('eventDateInput').value = dateStr;
renderCalendar();
}
function changeMonth(delta) {
if (isAnimating) return;
isAnimating = true;
const calCard = document.getElementById('calendarCard');
const calGrid = document.getElementById('calendarDays');
const oldCardHeight = calCard.getBoundingClientRect().height;
calGrid.style.transition = 'transform 0.15s ease-in, opacity 0.15s ease-in';
calGrid.style.transform = `translate3d(${delta > 0 ? '-20px' : '20px'}, 0, 0)`;
calGrid.style.opacity = '0';
setTimeout(() => {
currDate.setMonth(currDate.getMonth() + delta);
renderCalendar(() => {
calGrid.style.transition = 'none';
calGrid.style.transform = `translate3d(${delta > 0 ? '20px' : '-20px'}, 0, 0)`;
/* 若月曆行數(5列/6列)造成上方卡片高度改變,凍結在舊高度以便接著做動畫 */
calCard.style.transition = 'none';
calCard.style.height = `${oldCardHeight}px`;
calCard.getBoundingClientRect(); // 強制 reflow
const newCardHeight = calCard.scrollHeight;
requestAnimationFrame(() => {
calGrid.style.transition = 'transform 0.22s ease-out, opacity 0.22s ease-out';
calGrid.style.transform = 'translate3d(0, 0, 0)';
calGrid.style.opacity = '1';
if (Math.abs(newCardHeight - oldCardHeight) > 0.5) {
/* 上方卡片變形的同時,下方卡片(flex:1)也會跟著每一幀重新計算高度,形成同步動畫 */
calCard.style.transition = 'height 0.32s cubic-bezier(0.16, 1, 0.3, 1)';
calCard.style.height = `${newCardHeight}px`;
calCard.addEventListener('transitionend', function onCardResizeEnd(e) {
if (e.propertyName === 'height') {
calCard.style.transition = '';
calCard.style.height = '';
calCard.removeEventListener('transitionend', onCardResizeEnd);
}
});
} else {
calCard.style.height = '';
}
setTimeout(() => { isAnimating = false; }, 220);
});
});
}, 150);
}
/* --- 小球球輪播機制 --- */
function startBubbleLoop() {
stopBubbleLoop();
bubbleStep = 0;
runBubbleStep();
}
function stopBubbleLoop() {
if (bubbleLoopTimer) clearTimeout(bubbleLoopTimer);
if (bubbleClockInterval) clearInterval(bubbleClockInterval);
bubbleLoopTimer = null; bubbleClockInterval = null;
const el = document.getElementById('bubbleContent');
if (el) el.innerHTML = '';
}
function runBubbleStep() {
const container = document.getElementById('appContainer');
if (!container || !container.classList.contains('minimized')) return;
const el = document.getElementById('bubbleContent');
el.style.opacity = '0';
setTimeout(() => {
if (!container.classList.contains('minimized')) return;
if (bubbleClockInterval) { clearInterval(bubbleClockInterval); bubbleClockInterval = null; }
if (bubbleStep === 0) {
const now = new Date();
el.innerHTML = `<div class="bubble-date">${now.getMonth() + 1}/${now.getDate()}</div>`;
el.style.opacity = '1';
bubbleStep = 1;
bubbleLoopTimer = setTimeout(runBubbleStep, 2000);
} else if (bubbleStep === 1) {
const updateClock = () => {
const now = new Date();
el.innerHTML = `<div class="bubble-time">${String(now.getHours()).padStart(2,'0')}:${String(now.getMinutes()).padStart(2,'0')}:${String(now.getSeconds()).padStart(2,'0')}</div>`;
};
updateClock();
bubbleClockInterval = setInterval(updateClock, 1000);
el.style.opacity = '1';
bubbleStep = 2;
bubbleLoopTimer = setTimeout(runBubbleStep, 2000);
} else if (bubbleStep === 2) {
pyapi.get_upcoming_task_json((jsonStr) => {
if (!container.classList.contains('minimized')) return;
const res = JSON.parse(jsonStr);
let text = res.found ? `${res.date} ${res.content}` : "無待辦事項";
el.innerHTML = `<div class="marquee-wrapper"><div class="marquee-text" id="marqueeText">${escapeHtml(text)}</div></div>`;
el.style.opacity = '1';
const marqueeEl = document.getElementById('marqueeText');
if (marqueeEl) {
const duration = Math.max(2.5, (74 + marqueeEl.scrollWidth) / 35);
marqueeEl.style.animation = `marquee-scroll ${duration}s linear 1`;
marqueeEl.addEventListener('animationend', () => {
if (container.classList.contains('minimized')) { bubbleStep = 0; runBubbleStep(); }
}, { once: true });
} else {
bubbleStep = 0; bubbleLoopTimer = setTimeout(runBubbleStep, 3000);
}
});
}
}, 180);
}
function changeTheme(themeKey) {
document.getElementById('appContainer').style.background = themeStyles[themeKey] || themeStyles.obsidian;
closeSettings();
}
function minimizeToBubble() {
document.getElementById('appContainer').classList.add('minimized');
startBubbleLoop();
setTimeout(() => { if (pyapi) pyapi.finish_minimize(); }, 350);
}
function expandFromBubble() {
stopBubbleLoop();
if (pyapi) pyapi.prepare_expand();
requestAnimationFrame(() => {
document.getElementById('appContainer').classList.remove('minimized');
});
}
function openSettings() { document.getElementById('settingsModal').classList.add('active'); }
function closeSettings() { document.getElementById('settingsModal').classList.remove('active'); }
</script>
</body>
</html>
"""
# ==========================================
# 3. Qt6 主視窗與啟動
# ==========================================
class GlassWidgetWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowFlags(Qt.WindowType.FramelessWindowHint | Qt.WindowType.WindowStaysOnTopHint)
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
self.resize(550, 1000)
self.web = QWebEngineView(self)
self.web.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
self.web.setStyleSheet("background: transparent;")
self.web.page().setBackgroundColor(Qt.GlobalColor.transparent)
self.setCentralWidget(self.web)
self.channel = QWebChannel()
self.api = CalendarAPI(self)
self.channel.registerObject("pyapi", self.api)
self.web.page().setWebChannel(self.channel)
self.web.setHtml(HTML_CONTENT, QUrl("file:///"))
if __name__ == "__main__":
app = QApplication(sys.argv)
window = GlassWidgetWindow()
window.show()
sys.exit(app.exec())