Files
PYAS/Interface/static/js/main.js
T
2026-05-01 23:15:59 +08:00

977 lines
47 KiB
JavaScript

document.addEventListener('DOMContentLoaded', () => {
let currentLang = "english_switch";
let isScanning = false;
const { dict, langMap } = window.AppI18n;
const themes = {
"white_switch": { "--bg-window": "245, 245, 247", "--bg-nav": "255, 255, 255", "--bg-panel": "255, 255, 255", "--bg-hover": "rgba(0,0,0,0.05)", "--text-primary": "29, 29, 31", "--text-secondary": "134, 134, 139", "--border-color":"210, 210, 215", "--accent-color":"0, 122, 255", "--accent-alpha":"rgba(0, 122, 255, 0.1)", "--accent-shadow":"rgba(0, 122, 255, 0.2)", "--accent-hover":"rgba(0, 122, 255, 0.3)" },
"black_switch": { "--bg-window": "0, 0, 0", "--bg-nav": "28, 28, 30", "--bg-panel": "28, 28, 30", "--bg-hover": "rgba(255,255,255,0.1)", "--text-primary": "245, 245, 247", "--text-secondary": "134, 134, 139", "--border-color":"44, 44, 46", "--accent-color":"10, 132, 255", "--accent-alpha":"rgba(10, 132, 255, 0.1)", "--accent-shadow":"rgba(10, 132, 255, 0.2)", "--accent-hover":"rgba(10, 132, 255, 0.3)" },
"red_switch": { "--bg-window": "253, 246, 246", "--bg-nav": "255, 240, 240", "--bg-panel": "255, 255, 255", "--bg-hover": "rgba(255,59,48,0.05)", "--text-primary": "29, 29, 31", "--text-secondary": "134, 134, 139", "--border-color":"250, 220, 220", "--accent-color":"255, 59, 48", "--accent-alpha":"rgba(255, 59, 48, 0.1)", "--accent-shadow":"rgba(255, 59, 48, 0.2)", "--accent-hover":"rgba(255, 59, 48, 0.3)" },
"yellow_switch": { "--bg-window": "254, 251, 243", "--bg-nav": "255, 248, 230", "--bg-panel": "255, 255, 255", "--bg-hover": "rgba(255,149,0,0.05)", "--text-primary": "29, 29, 31", "--text-secondary": "134, 134, 139", "--border-color":"250, 240, 215", "--accent-color":"255, 149, 0", "--accent-alpha":"rgba(255, 149, 0, 0.1)", "--accent-shadow":"rgba(255, 149, 0, 0.2)", "--accent-hover":"rgba(255, 149, 0, 0.3)" },
"green_switch": { "--bg-window": "246, 253, 248", "--bg-nav": "235, 250, 240", "--bg-panel": "255, 255, 255", "--bg-hover": "rgba(52,199,89,0.05)", "--text-primary": "29, 29, 31", "--text-secondary": "134, 134, 139", "--border-color":"220, 240, 225", "--accent-color":"52, 199, 89", "--accent-alpha":"rgba(52, 199, 89, 0.1)", "--accent-shadow":"rgba(52, 199, 89, 0.2)", "--accent-hover":"rgba(52, 199, 89, 0.3)" },
"blue_switch": { "--bg-window": "246, 249, 253", "--bg-nav": "235, 244, 255", "--bg-panel": "255, 255, 255", "--bg-hover": "rgba(0,122,255,0.05)", "--text-primary": "29, 29, 31", "--text-secondary": "134, 134, 139", "--border-color":"220, 230, 250", "--accent-color":"0, 122, 255", "--accent-alpha":"rgba(0, 122, 255, 0.1)", "--accent-shadow":"rgba(0, 122, 255, 0.2)", "--accent-hover":"rgba(0, 122, 255, 0.3)" }
};
const getMsg = (key) => (dict[currentLang] || dict["english_switch"])[key] || key;
function initCustomSelects() {
document.querySelectorAll('select.modern-select').forEach(select => {
select.style.display = 'none';
const wrapper = document.createElement('div');
wrapper.className = 'custom-select-wrapper';
const trigger = document.createElement('div');
trigger.className = 'custom-select-trigger';
const triggerText = document.createElement('span');
triggerText.className = 'custom-select-text';
const selectedOpt = select.options[select.selectedIndex];
if(selectedOpt) {
triggerText.textContent = selectedOpt.textContent;
if(selectedOpt.hasAttribute('data-i18n')) triggerText.setAttribute('data-i18n', '');
if(selectedOpt.hasAttribute('data-origin-text')) triggerText.dataset.originText = selectedOpt.dataset.originText;
}
trigger.appendChild(triggerText);
const icon = document.createElement('div');
icon.className = 'custom-select-icon';
icon.innerHTML = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"></polyline></svg>`;
trigger.appendChild(icon);
const optionsContainer = document.createElement('ul');
optionsContainer.className = 'custom-select-options';
const phantom = document.createElement('div');
phantom.className = 'custom-select-phantom';
phantom.setAttribute('aria-hidden', 'true');
Array.from(select.options).forEach(option => {
if(option.disabled) return;
const li = document.createElement('li');
li.className = 'custom-select-option';
li.textContent = option.textContent;
li.dataset.value = option.value;
if(option.hasAttribute('data-i18n')) li.setAttribute('data-i18n', '');
if(option.hasAttribute('data-origin-text')) li.dataset.originText = option.dataset.originText;
if(option.selected) li.classList.add('selected');
li.addEventListener('click', (e) => {
e.stopPropagation();
select.value = option.value;
select.dispatchEvent(new Event('change'));
triggerText.textContent = li.textContent;
if(li.hasAttribute('data-origin-text')) {
triggerText.dataset.originText = li.dataset.originText;
}
wrapper.classList.remove('open');
optionsContainer.querySelectorAll('.custom-select-option').forEach(el => el.classList.remove('selected'));
li.classList.add('selected');
});
optionsContainer.appendChild(li);
const phantomSpan = document.createElement('span');
phantomSpan.textContent = option.textContent;
if(option.hasAttribute('data-i18n')) phantomSpan.setAttribute('data-i18n', '');
if(option.hasAttribute('data-origin-text')) phantomSpan.dataset.originText = option.dataset.originText;
phantom.appendChild(phantomSpan);
});
wrapper.appendChild(phantom);
wrapper.appendChild(trigger);
wrapper.appendChild(optionsContainer);
select.parentNode.insertBefore(wrapper, select.nextSibling);
trigger.addEventListener('click', (e) => {
e.stopPropagation();
const isOpen = wrapper.classList.contains('open');
document.querySelectorAll('.custom-select-wrapper').forEach(w => w.classList.remove('open'));
if (!isOpen) wrapper.classList.add('open');
});
});
document.addEventListener('click', () => {
document.querySelectorAll('.custom-select-wrapper').forEach(w => w.classList.remove('open'));
});
}
initCustomSelects();
document.querySelectorAll("[data-i18n]").forEach(el => { el.dataset.originText = el.textContent.trim(); });
document.querySelectorAll("[data-i18n-placeholder]").forEach(el => { el.dataset.originPlaceholder = el.getAttribute('placeholder'); });
document.querySelectorAll("option[data-i18n]").forEach(el => { el.dataset.originText = el.textContent.trim(); });
const translateText = (lang) => {
currentLang = lang;
const currentDict = dict[lang] || dict["english_switch"];
document.querySelectorAll("[data-i18n]").forEach(el => {
const originText = el.dataset.originText;
el.textContent = currentDict[originText] || originText;
});
document.querySelectorAll("[data-i18n-placeholder]").forEach(el => {
const originText = el.dataset.originPlaceholder;
el.setAttribute('placeholder', currentDict[originText] || originText);
});
document.documentElement.lang = langMap[currentLang] || "en";
};
const applyTheme = (theme) => {
const themeVars = themes[theme];
if (themeVars) {
for (const [key, value] of Object.entries(themeVars)) {
document.documentElement.style.setProperty(key, value.startsWith("rgba") ? value : `rgb(${value})`);
}
}
};
function updateCustomSelectUI(selectId, val) {
const select = document.getElementById(selectId);
if (!select) return;
select.value = val;
const wrapper = select.nextElementSibling;
if (wrapper && wrapper.classList.contains('custom-select-wrapper')) {
const triggerText = wrapper.querySelector('.custom-select-text');
const selectedOpt = select.options[select.selectedIndex];
if(selectedOpt) {
triggerText.textContent = selectedOpt.textContent;
if(selectedOpt.hasAttribute('data-origin-text')) {
triggerText.dataset.originText = selectedOpt.dataset.originText;
}
}
wrapper.querySelectorAll('.custom-select-option').forEach(el => {
el.classList.toggle('selected', el.dataset.value === val);
});
}
}
let processInterval = null;
const switchPage = (targetId) => {
const oldActive = document.querySelector('.page.active');
if (oldActive && oldActive.id !== targetId) {
if (oldActive.id === 'junk_window') {
currentJunkList = [];
const list = document.querySelector('#junk_window .manage-list');
if (list) list.innerHTML = '';
const searchInput = document.querySelector('#junk_window .search-box input');
if (searchInput) searchInput.value = '';
} else if (oldActive.id === 'repair_window') {
const list = document.querySelector('#repair_window .manage-list');
if (list) list.innerHTML = '';
}
}
document.querySelectorAll('.page').forEach(page => page.classList.remove('active'));
document.querySelectorAll('.nav-btn').forEach(btn => btn.classList.remove('active'));
const targetPage = document.getElementById(targetId);
if (targetPage) targetPage.classList.add('active');
const activeNav = document.querySelector(`aside .nav-btn[data-target="${targetId}"]`);
if (activeNav) activeNav.classList.add('active');
if (targetId === 'taskmgr_window') {
const fetchProcs = () => {
if (window.pywebview && document.querySelectorAll('#taskmgr_window .manage-list-item input[type="checkbox"]:checked').length === 0) {
window.pywebview.api.get_process_list().then(updateProcessList);
}
};
fetchProcs();
if (!processInterval) processInterval = setInterval(fetchProcs, 2000);
} else {
if (processInterval) {
clearInterval(processInterval);
processInterval = null;
}
}
if (['whitelist_window', 'quarantine_window', 'popup_window', 'custom_protect_window'].includes(targetId)) {
refreshConfigLists();
}
if (targetId === 'log_export_window' && window.pywebview) {
window.pywebview.api.get_logs().then(logs => {
const logList = logs.reverse().map(log => {
let displayStr = `[${log.time_str}] ${log.level} | ${log.action}`;
if (log.source) displayStr += ` | ${log.source.split('\\').pop().split('/').pop()}`;
if (log.detail) displayStr += ` | ${log.detail}`;
return {
display: displayStr,
value: log.id
};
});
renderManageList('#log_export_window', logList, 'display', 'value', true);
});
}
};
document.querySelectorAll('[data-target]').forEach(btn => {
btn.addEventListener('click', (e) => {
const targetId = e.currentTarget.getAttribute('data-target');
if (targetId) switchPage(targetId);
});
});
document.getElementById('quick_scan_btn')?.addEventListener('click', () => {
switchPage('scan_window');
if (window.pywebview) {
triggerScan('smart');
}
});
const scanMethodSelect = document.getElementById('scan_method_select');
const stopBtn = document.getElementById('stop_btn');
const progressText = document.getElementById('progress_text');
const progressTitle = document.querySelector('#scan_window .section-title');
const virusList = document.getElementById('virus_list');
const virusState = new Map();
function rebuildCustomSelect(selectId) {
const select = document.getElementById(selectId);
if (!select) return;
const existingWrapper = select.nextElementSibling;
if (existingWrapper && existingWrapper.classList.contains('custom-select-wrapper')) {
existingWrapper.remove();
}
select.style.display = 'none';
const wrapper = document.createElement('div');
wrapper.className = 'custom-select-wrapper';
const trigger = document.createElement('div');
trigger.className = 'custom-select-trigger';
const triggerText = document.createElement('span');
triggerText.className = 'custom-select-text';
const selectedOpt = select.options[select.selectedIndex];
if(selectedOpt) {
triggerText.textContent = selectedOpt.textContent;
if(selectedOpt.hasAttribute('data-i18n')) triggerText.setAttribute('data-i18n', '');
if(selectedOpt.hasAttribute('data-origin-text')) triggerText.dataset.originText = selectedOpt.dataset.originText;
}
trigger.appendChild(triggerText);
const icon = document.createElement('div');
icon.className = 'custom-select-icon';
icon.innerHTML = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"></polyline></svg>`;
trigger.appendChild(icon);
const optionsContainer = document.createElement('ul');
optionsContainer.className = 'custom-select-options';
const phantom = document.createElement('div');
phantom.className = 'custom-select-phantom';
phantom.setAttribute('aria-hidden', 'true');
Array.from(select.options).forEach(option => {
if(option.disabled) return;
const li = document.createElement('li');
li.className = 'custom-select-option';
li.textContent = option.textContent;
li.dataset.value = option.value;
if(option.hasAttribute('data-i18n')) li.setAttribute('data-i18n', '');
if(option.hasAttribute('data-origin-text')) li.dataset.originText = option.dataset.originText;
if(option.selected) li.classList.add('selected');
li.addEventListener('click', (e) => {
e.stopPropagation();
select.value = option.value;
select.dispatchEvent(new Event('change'));
triggerText.textContent = li.textContent;
if(li.hasAttribute('data-origin-text')) {
triggerText.dataset.originText = li.dataset.originText;
}
wrapper.classList.remove('open');
optionsContainer.querySelectorAll('.custom-select-option').forEach(el => el.classList.remove('selected'));
li.classList.add('selected');
});
optionsContainer.appendChild(li);
const phantomSpan = document.createElement('span');
phantomSpan.textContent = option.textContent;
if(option.hasAttribute('data-i18n')) phantomSpan.setAttribute('data-i18n', '');
if(option.hasAttribute('data-origin-text')) phantomSpan.dataset.originText = option.dataset.originText;
phantom.appendChild(phantomSpan);
});
wrapper.appendChild(phantom);
wrapper.appendChild(trigger);
wrapper.appendChild(optionsContainer);
select.parentNode.insertBefore(wrapper, select.nextSibling);
trigger.addEventListener('click', (e) => {
e.stopPropagation();
const isOpen = wrapper.classList.contains('open');
document.querySelectorAll('.custom-select-wrapper').forEach(w => w.classList.remove('open'));
if (!isOpen) wrapper.classList.add('open');
});
}
function changeScanSelectMode(mode) {
if (!scanMethodSelect) return;
scanMethodSelect.innerHTML = '';
if (mode === 'scan') {
scanMethodSelect.innerHTML = `
<option value="none" selected disabled data-i18n>選擇</option>
<option value="smart" data-i18n>智能掃描</option>
<option value="file" data-i18n>檔案掃描</option>
<option value="path" data-i18n>路徑掃描</option>
<option value="full" data-i18n>全盤掃描</option>
`;
} else if (mode === 'action') {
scanMethodSelect.innerHTML = `
<option value="none" selected disabled data-i18n>選擇</option>
<option value="delete" data-i18n>刪除項目</option>
<option value="ignore" data-i18n>忽略項目</option>
<option value="quarantine" data-i18n>加入隔離區</option>
<option value="whitelist" data-i18n>加入白名單</option>
`;
}
scanMethodSelect.querySelectorAll('option[data-i18n]').forEach(el => {
el.dataset.originText = el.textContent.trim();
el.textContent = getMsg(el.dataset.originText);
});
rebuildCustomSelect('scan_method_select');
}
function handleVirusActions(action) {
if (!window.pywebview) return;
const paths = Array.from(virusState.entries())
.filter(([_, isChecked]) => isChecked)
.map(([path, _]) => path);
if (paths.length === 0) {
updateCustomSelectUI('scan_method_select', 'none');
return;
}
const wrapper = scanMethodSelect.nextElementSibling;
if (wrapper) wrapper.style.pointerEvents = 'none';
const finalizeAction = () => {
if (wrapper) wrapper.style.pointerEvents = '';
checkVirusListEmpty();
};
if (action === 'delete') {
window.pywebview.api.solve_scan(paths).then((deletedPaths) => {
const deletedSet = new Set(deletedPaths);
deletedPaths.forEach(p => virusState.delete(p));
Array.from(virusList.children).forEach(li => {
if (deletedSet.has(li.dataset.path)) li.remove();
});
finalizeAction();
});
} else if (action === 'ignore') {
paths.forEach(p => virusState.delete(p));
Array.from(virusList.children).forEach(li => {
if (paths.includes(li.dataset.path)) li.remove();
});
finalizeAction();
} else if (action === 'quarantine' || action === 'whitelist') {
const listKey = action === 'quarantine' ? 'quarantine' : 'white_list';
window.pywebview.api.manage_named_list(listKey, paths, 'add').then(() => {
window.pywebview.api.remove_virus_result(paths).then(() => {
paths.forEach(p => virusState.delete(p));
Array.from(virusList.children).forEach(li => {
if (paths.includes(li.dataset.path)) li.remove();
});
finalizeAction();
});
});
}
}
function checkVirusListEmpty() {
updateCustomSelectUI('scan_method_select', 'none');
if (virusState.size === 0) {
changeScanSelectMode('scan');
}
}
window.addVirusResult = (label, path) => {
if (!virusState.has(path)) {
virusState.set(path, true);
const li = document.createElement('li');
li.className = 'manage-list-item';
li.dataset.path = path;
li.innerHTML = `
<input type="checkbox" value="${path}" checked>
<div class="manage-list-item-content"><strong>${label}</strong> | ${path}</div>
`;
virusList.appendChild(li);
}
};
virusList.addEventListener('click', (e) => {
const li = e.target.closest('.manage-list-item');
if (!li) return;
const cb = li.querySelector('input');
if (e.target.tagName !== 'INPUT') {
cb.checked = !cb.checked;
}
virusState.set(li.dataset.path, cb.checked);
});
virusList.addEventListener('contextmenu', (e) => {
e.preventDefault();
const li = e.target.closest('.manage-list-item');
if (!li || !window.pywebview) return;
const path = li.dataset.path;
window.pywebview.api.prompt_virus_action(path).then(action => {
if (action === '1') {
window.pywebview.api.manage_named_list('white_list', [path], 'add').then(() => {
window.pywebview.api.remove_virus_result([path]).then(() => {
virusState.delete(path);
li.remove();
checkVirusListEmpty();
});
});
} else if (action === '2') {
window.pywebview.api.manage_named_list('quarantine', [path], 'add').then(() => {
window.pywebview.api.remove_virus_result([path]).then(() => {
virusState.delete(path);
li.remove();
checkVirusListEmpty();
});
});
}
});
});
window.updateScanProgress = (path) => {
if (progressTitle) progressTitle.textContent = getMsg("正在掃描");
progressText.textContent = path;
};
window.updateDeleteProgress = (path) => {
if (progressTitle) progressTitle.textContent = getMsg("正在刪除");
progressText.textContent = path;
};
window.finishScan = (msg, count) => {
isScanning = false;
if (progressTitle) progressTitle.textContent = getMsg("病毒掃描");
progressText.textContent = msg;
stopBtn.classList.add('hidden');
scanMethodSelect.classList.remove('hidden');
if (count > 0) {
changeScanSelectMode('action');
} else {
changeScanSelectMode('scan');
}
updateCustomSelectUI('scan_method_select', 'none');
};
function triggerScan(method) {
if (!window.pywebview) return;
isScanning = true;
virusState.clear();
virusList.innerHTML = '';
changeScanSelectMode('scan');
scanMethodSelect.classList.add('hidden');
stopBtn.classList.remove('hidden');
stopBtn.disabled = false;
if (progressTitle) progressTitle.textContent = getMsg("正在掃描");
progressText.textContent = getMsg("正在初始化中");
window.pywebview.api.trigger_scan(method);
}
scanMethodSelect?.addEventListener('change', () => {
const val = scanMethodSelect.value;
if (val === 'none') return;
if (!isScanning) {
if (['smart', 'file', 'path', 'full'].includes(val)) {
triggerScan(val);
} else if (['delete', 'ignore', 'quarantine', 'whitelist'].includes(val)) {
handleVirusActions(val);
}
}
});
stopBtn?.addEventListener('click', () => {
if (window.pywebview) window.pywebview.api.stop_scan();
stopBtn.disabled = true;
});
document.getElementById('theme_select').addEventListener('change', (e) => {
applyTheme(e.target.value);
if (window.pywebview) window.pywebview.api.update_config('theme', e.target.value);
});
document.getElementById('lang_select').addEventListener('change', (e) => {
translateText(e.target.value);
if (window.pywebview) window.pywebview.api.update_config('language', e.target.value);
});
window.revertSwitch = (switchKey) => {
const switchMap = ["process_switch", "document_switch", "system_switch", "driver_switch", "network_switch", "sensitive_switch", "extension_switch", "cloud_switch", "context_switch"];
const index = switchMap.indexOf(switchKey);
if (index !== -1) {
const toggle = document.querySelectorAll('.toggle-switch input')[index];
if (toggle) {
toggle.checked = false;
}
}
};
document.querySelectorAll('.toggle-switch input').forEach((toggle, index) => {
toggle.addEventListener('change', async (e) => {
const switchMap = ["process_switch", "document_switch", "system_switch", "driver_switch", "network_switch", "sensitive_switch", "extension_switch", "cloud_switch", "context_switch"];
const key = switchMap[index];
if (window.pywebview && key) {
toggle.disabled = true;
try {
const result = await window.pywebview.api.update_config(key, e.target.checked);
if (result !== undefined && result !== null) {
toggle.checked = result;
}
} catch (err) {
toggle.checked = !e.target.checked;
} finally {
toggle.disabled = false;
}
}
});
});
window.triggerContextScan = (path) => {
if (isScanning) return;
switchPage('scan_window');
if (window.pywebview) {
isScanning = true;
virusState.clear();
virusList.innerHTML = '';
scanMethodSelect.classList.add('hidden');
stopBtn.classList.remove('hidden');
changeScanSelectMode('scan');
if (progressTitle) progressTitle.textContent = getMsg("正在掃描");
progressText.textContent = getMsg("正在初始化中");
window.pywebview.api.start_scan([path]);
}
};
window.addEventListener('pywebviewready', () => {
window.pywebview.api.get_config().then(cfg => {
const theme = cfg.theme || "white_switch";
const lang = cfg.language || "english_switch";
applyTheme(theme);
translateText(lang);
updateCustomSelectUI('theme_select', theme);
updateCustomSelectUI('lang_select', lang);
const switchMap = ["process_switch", "document_switch", "system_switch", "driver_switch", "network_switch", "sensitive_switch", "extension_switch", "cloud_switch", "context_switch"];
document.querySelectorAll('.toggle-switch input').forEach((toggle, index) => {
if (switchMap[index]) {
toggle.checked = !!cfg[switchMap[index]];
}
});
});
window.pywebview.api.init_ui_ready();
});
function renderManageList(containerSelector, dataList, displayKey, valKey, defaultChecked = false) {
const container = document.querySelector(`${containerSelector} .manage-list`);
const searchInput = document.querySelector(`${containerSelector} .search-box input`);
if (!container) return;
container.renderData = (filterText = "") => {
container.innerHTML = '';
dataList.forEach(item => {
const displayStr = typeof item === 'object' ? item[displayKey] : item;
const valueStr = typeof item === 'object' ? item[valKey] : item;
if (filterText && !String(displayStr).toLowerCase().includes(filterText.toLowerCase())) return;
const li = document.createElement('li');
li.className = 'manage-list-item';
const checkedAttr = defaultChecked ? 'checked' : '';
li.innerHTML = `
<input type="checkbox" value="${valueStr}" ${checkedAttr}>
<div class="manage-list-item-content">${displayStr}</div>
`;
li.addEventListener('click', (e) => {
if (e.target.tagName !== 'INPUT') {
const cb = li.querySelector('input');
cb.checked = !cb.checked;
}
});
container.appendChild(li);
});
};
container.renderData(searchInput ? searchInput.value : "");
if (searchInput) {
searchInput.oninput = (e) => container.renderData(e.target.value);
}
}
function getCheckedValues(containerSelector) {
const checkboxes = document.querySelectorAll(`${containerSelector} .manage-list-item input[type="checkbox"]:checked`);
return Array.from(checkboxes).map(cb => cb.value);
}
function formatSize(bytes) {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
let currentJunkList = [];
document.querySelector('#junk_window .primary-btn')?.addEventListener('click', () => {
if (!window.pywebview) return;
const btn = document.querySelector('#junk_window .primary-btn');
btn.textContent = getMsg("正在初始化中");
window.pywebview.api.scan_system_junk().then(list => {
currentJunkList = list.map(item => ({
display: `${item.path} (${formatSize(item.size)})`,
value: item.path
}));
renderManageList('#junk_window', currentJunkList, 'display', 'value', true);
btn.textContent = getMsg("掃描");
});
});
document.querySelector('#junk_window .danger-btn')?.addEventListener('click', () => {
if (!window.pywebview) return;
const checkedPaths = getCheckedValues('#junk_window');
if (checkedPaths.length === 0) return;
window.pywebview.api.clean_system_junk(checkedPaths).then(deletedSize => {
const msg = getMsg("已清理 ");
window.pywebview.api.show_alert(getMsg("提示"), `${msg}${formatSize(deletedSize)}`, "info");
currentJunkList = currentJunkList.filter(item => !checkedPaths.includes(item.value));
renderManageList('#junk_window', currentJunkList, 'display', 'value', true);
});
});
function refreshConfigLists() {
if (!window.pywebview) return;
window.pywebview.api.get_config().then(cfg => {
renderManageList('#whitelist_window', cfg.white_list || [], 'file', 'file');
renderManageList('#quarantine_window', cfg.quarantine || [], 'file', 'file');
renderManageList('#custom_protect_window', cfg.custom_rule || [], 'file', 'file');
const popupRules = (cfg.block_list || []).map(item => ({
display: `${item.exe || '*'} | ${item.class || '*'} | ${item.title || '*'}`,
value: item.exe || item.title
}));
renderManageList('#popup_window', popupRules, 'display', 'value');
});
}
document.querySelector('#whitelist_window .modern-btn:not(.primary-btn)')?.addEventListener('click', () => {
if (!window.pywebview) return;
const checked = getCheckedValues('#whitelist_window');
if (checked.length > 0) {
window.pywebview.api.remove_list_items('white_list', checked).then(refreshConfigLists);
}
});
document.querySelector('#quarantine_window .modern-btn:not(.primary-btn)')?.addEventListener('click', () => {
if (!window.pywebview) return;
const checked = getCheckedValues('#quarantine_window');
if (checked.length > 0) {
window.pywebview.api.remove_list_items('quarantine', checked).then(refreshConfigLists);
}
});
document.querySelector('#popup_window .modern-btn:not(.primary-btn)')?.addEventListener('click', () => {
if (!window.pywebview) return;
const checked = getCheckedValues('#popup_window');
if (checked.length > 0) {
window.pywebview.api.remove_list_items('block_list', checked).then(refreshConfigLists);
}
});
document.querySelector('#custom_protect_window .modern-btn:not(.primary-btn)')?.addEventListener('click', () => {
if (!window.pywebview) return;
const checked = getCheckedValues('#custom_protect_window');
if (checked.length > 0) {
window.pywebview.api.remove_list_items('custom_rule', checked).then(refreshConfigLists);
}
});
document.querySelector('#whitelist_window .primary-btn')?.addEventListener('click', () => {
window.pywebview?.api.select_files().then(files => {
if (files && files.length > 0) {
window.pywebview.api.manage_named_list('white_list', files, 'add').then(refreshConfigLists);
}
});
});
document.querySelector('#quarantine_window .primary-btn')?.addEventListener('click', () => {
window.pywebview?.api.select_files().then(files => {
if (files && files.length > 0) {
window.pywebview.api.manage_named_list('quarantine', files, 'add').then(refreshConfigLists);
}
});
});
document.querySelector('#custom_protect_window .primary-btn')?.addEventListener('click', () => {
window.pywebview?.api.select_files().then(files => {
if (files && files.length > 0) {
window.pywebview.api.manage_named_list('custom_rule', files, 'add').then(refreshConfigLists);
}
});
});
document.querySelector('#repair_window .primary-btn')?.addEventListener('click', () => {
if (!window.pywebview) return;
window.pywebview.api.scan_system_repair().then(list => {
const translatedList = list.map(item => ({
display: getMsg(item.display),
value: item.value
}));
renderManageList('#repair_window', translatedList, 'display', 'value', true);
});
});
document.querySelector('#repair_window .danger-btn')?.addEventListener('click', () => {
if (!window.pywebview) return;
const checkedPaths = getCheckedValues('#repair_window');
if (checkedPaths.length === 0) return;
window.pywebview.api.execute_system_repair(checkedPaths).then(() => {
const msg = getMsg("已修復選取項目");
window.pywebview.api.show_alert(getMsg("提示"), msg, "info");
document.querySelector('#repair_window .manage-list').innerHTML = '';
});
});
document.getElementById('minimize_button')?.addEventListener('click', () => window.pywebview?.api.minimize());
document.getElementById('close_button')?.addEventListener('click', () => window.pywebview?.api.hide_window());
window.updateLogs = (entry) => {
const logWidget = document.querySelector('.log-text');
if (logWidget) {
let parts = [`[${entry.time_str}]`, entry.level, entry.action];
if (entry.source) parts.push(`Src: ${entry.source}`);
if (entry.target) parts.push(`Tgt: ${entry.target}`);
if (entry.code) parts.push(`Code: ${entry.code}`);
if (entry.pid) parts.push(`PID: ${entry.pid}`);
if (entry.hash) parts.push(`Hash: ${entry.hash}`);
if (entry.detail) parts.push(`Detail: ${entry.detail}`);
if (entry.operate !== null) parts.push(`Op: ${entry.operate}`);
parts.push(`Success: ${entry.success}`);
logWidget.value += parts.join(' | ') + '\n';
logWidget.scrollTop = logWidget.scrollHeight;
}
const exportWindow = document.getElementById('log_export_window');
if (exportWindow && exportWindow.classList.contains('active')) {
if (window.pywebview) {
window.pywebview.api.get_logs().then(logs => {
const logList = logs.reverse().map(log => {
let displayStr = `[${log.time_str}] ${log.level} | ${log.action}`;
if (log.source) displayStr += ` | ${log.source.split('\\').pop().split('/').pop()}`;
if (log.detail) displayStr += ` | ${log.detail}`;
return { display: displayStr, value: log.id };
});
renderManageList('#log_export_window', logList, 'display', 'value', true);
});
}
}
if ((entry.action === 'System' && entry.detail === 'Engine Initialization Complete') ||
(entry.level === 'WARN' && entry.action === 'init_engine_thread')) {
const overlay = document.getElementById('loading_overlay');
const appContainer = document.querySelector('.app-container');
if (overlay && !overlay.classList.contains('fade-out')) {
overlay.classList.add('fade-out');
setTimeout(() => {
if (appContainer) appContainer.classList.add('fade-in');
}, 400);
}
}
};
const websiteBtn = Array.from(document.querySelectorAll('#about_window .list-item')).find(el => el.textContent.includes('官方網站') || el.textContent.includes('Website'));
if (websiteBtn) {
websiteBtn.querySelector('button').addEventListener('click', () => {
if (window.pywebview) window.pywebview.api.open_website();
});
}
const updateBtn = Array.from(document.querySelectorAll('#about_window .list-item')).find(el => el.textContent.includes('檢查更新') || el.textContent.includes('Update'));
if (updateBtn) {
updateBtn.querySelector('button').addEventListener('click', () => {
if (window.pywebview) {
window.pywebview.api.check_update().then(res => {
if (res.error) {
window.pywebview.api.show_alert(getMsg("錯誤"), getMsg("檢查更新失敗"), "error");
} else if (res.has_update) {
const msg = getMsg("發現新版本");
window.pywebview.api.show_confirm(getMsg("提示"), `${msg} ${res.latest}\n(${res.current} -> ${res.latest})`).then(confirmRes => {
if (confirmRes) window.pywebview.api.open_url(res.url);
});
} else {
const msg = getMsg("當前已是最新版本");
window.pywebview.api.show_alert(getMsg("提示"), `${msg} ${res.current}`, "info");
}
});
}
});
}
const resetBtn = Array.from(document.querySelectorAll('#setting_window .list-item')).find(el => el.textContent.includes('重置選項') || el.textContent.includes('Reset'));
if (resetBtn) {
resetBtn.querySelector('button').addEventListener('click', () => {
const confirmMsg = getMsg("此選項可以重置所有設定");
if (window.pywebview) {
window.pywebview.api.show_confirm(getMsg("提示"), confirmMsg).then(res => {
if (res) {
window.pywebview.api.reset_config().then(() => {
window.pywebview.api.show_alert(getMsg("提示"), getMsg("設定已重置,請重新啟動程式以套用預設值。"), "info");
});
}
});
}
});
}
document.querySelector('#log_export_window .primary-btn')?.addEventListener('click', () => {
if (window.pywebview) {
const checkedIds = getCheckedValues('#log_export_window');
if (checkedIds.length === 0) {
window.pywebview.api.show_alert(getMsg("提示"), getMsg("請選擇要導出的日誌"), "warning");
return;
}
window.pywebview.api.export_logs(checkedIds).then(res => {
if (res) window.pywebview.api.show_alert(getMsg("提示"), getMsg("導出成功"), "info");
});
}
});
document.querySelector('#log_export_window .danger-btn')?.addEventListener('click', () => {
const checkedIds = getCheckedValues('#log_export_window');
if (checkedIds.length === 0) return;
const confirmMsg = getMsg("確定刪除選取的日誌記錄嗎?");
if (window.pywebview) {
window.pywebview.api.show_confirm(getMsg("提示"), confirmMsg).then(res => {
if (res) {
window.pywebview.api.clear_logs(checkedIds).then(() => {
window.pywebview.api.get_logs().then(logs => {
const logList = logs.reverse().map(log => {
let displayStr = `[${log.time_str}] ${log.level} | ${log.action}`;
if (log.source) displayStr += ` | ${log.source.split('\\').pop().split('/').pop()}`;
if (log.detail) displayStr += ` | ${log.detail}`;
return { display: displayStr, value: log.id };
});
renderManageList('#log_export_window', logList, 'display', 'value', true);
});
const successMsg = getMsg("選取的日誌已刪除。");
window.pywebview.api.show_alert(getMsg("提示"), successMsg, "info");
});
}
});
}
});
let currentProcessList = [];
function renderProcessList(filterText = "") {
const list = document.querySelector('#taskmgr_window .manage-list');
if (!list) return;
list.innerHTML = '';
currentProcessList.forEach(p => {
if (filterText && !p.name.toLowerCase().includes(filterText.toLowerCase())) return;
const li = document.createElement('li');
li.className = 'manage-list-item';
const unknownPathText = getMsg("未知路徑");
const pathText = p.path && p.path !== "None" ? p.path : unknownPathText;
li.innerHTML = `
<input type="checkbox" value="${p.pid}" data-path="${p.path || ''}">
<div class="manage-list-item-content">${p.name} | PID: ${p.pid} | ${pathText}</div>
`;
li.addEventListener('click', (e) => {
if (e.target.tagName !== 'INPUT') {
const cb = li.querySelector('input');
cb.checked = !cb.checked;
}
});
li.addEventListener('contextmenu', (e) => {
e.preventDefault();
const confirmMsg = getMsg("結束進程?");
if (window.pywebview) {
window.pywebview.api.show_confirm(getMsg("提示"), confirmMsg).then(res => {
if (res) {
window.pywebview.api.kill_process(p.pid).then(() => window.pywebview.api.get_process_list().then(updateProcessList));
}
});
}
});
list.appendChild(li);
});
}
function updateProcessList(procs) {
currentProcessList = procs;
const searchInput = document.querySelector('#taskmgr_window .search-box input');
renderProcessList(searchInput ? searchInput.value : "");
}
const procSearchInput = document.querySelector('#taskmgr_window .search-box input');
if (procSearchInput) {
procSearchInput.addEventListener('input', (e) => renderProcessList(e.target.value));
}
document.querySelector('#taskmgr_window .primary-btn')?.addEventListener('click', () => {
const cbs = document.querySelectorAll('#taskmgr_window .manage-list-item input[type="checkbox"]:checked');
if (cbs.length > 0 && window.pywebview) {
cbs.forEach(cb => {
const path = cb.dataset.path;
if (path && path !== "Unknown" && path !== "None") {
window.pywebview.api.open_file_location(path);
}
});
}
});
document.querySelector('#popup_window .primary-btn')?.addEventListener('click', () => {
if (!window.pywebview) return;
const btn = document.querySelector('#popup_window .primary-btn');
const originalText = btn.textContent;
const waitText = getMsg("請在5秒內點擊目標視窗...");
btn.textContent = waitText;
btn.disabled = true;
window.pywebview.api.capture_popup_window().then(rule => {
btn.textContent = originalText;
btn.disabled = false;
if (rule) {
window.pywebview.api.add_popup_rule(rule).then(success => {
if (success) refreshConfigLists();
});
}
});
});
document.querySelector('#taskmgr_window .danger-btn')?.addEventListener('click', () => {
const cbs = document.querySelectorAll('#taskmgr_window .manage-list-item input[type="checkbox"]:checked');
const confirmMsg = getMsg("確定要結束選取的進程嗎?");
if (cbs.length > 0 && window.pywebview) {
window.pywebview.api.show_confirm(getMsg("提示"), confirmMsg).then(res => {
if (res) {
const promises = Array.from(cbs).map(cb => window.pywebview.api.kill_process(parseInt(cb.value)));
Promise.all(promises).then(() => {
window.pywebview.api.get_process_list().then(updateProcessList);
});
}
});
}
});
});