const { app, BrowserWindow, Menu, Tray, dialog, ipcMain, nativeImage, safeStorage, screen, shell } = require("electron"); const { autoUpdater } = require("electron-updater"); const { spawn } = require("node:child_process"); const crypto = require("node:crypto"); const fs = require("node:fs"); const http = require("node:http"); const os = require("node:os"); const path = require("node:path"); const APP_DISPLAY_NAME = "SnapCAD Studio"; const DESKTOP_APP_ID = "com.snapcad.desktop"; const MAX_SKF_FILE_BYTES = 256 * 1024 * 1024; const devUrl = process.env.SKETCHFORGE_DESKTOP_DEV_URL?.trim() || ""; // Keep the desktop origin stable. localStorage and IndexedDB are scoped to the // full origin (including the port), so a random port made projects appear to // vanish after every restart. const DESKTOP_PORT = Number.parseInt(process.env.SKETCHFORGE_DESKTOP_PORT || "62158", 10); function resolveSafeHttpUrl(rawUrl, fallbackUrl) { const candidate = String(rawUrl || "").trim(); if (!candidate) return fallbackUrl; try { const parsed = new URL(candidate); if (parsed.protocol === "https:" || parsed.protocol === "http:") { return parsed.toString().replace(/\/+$/, ""); } } catch { // Ignore invalid URL overrides. } return fallbackUrl; } const CLOUD_ORIGIN = resolveSafeHttpUrl(process.env.SNAPCAD_CLOUD_ORIGIN, "https://snap.yakhub.com.tr"); const UPDATE_FEED_URL = resolveSafeHttpUrl(process.env.SNAPCAD_UPDATE_FEED_URL, `${CLOUD_ORIGIN}/updates`); let mainWindow = null; let tray = null; let webServer = null; let webServerOutput = ""; let isQuitting = false; let explicitQuit = false; let isDocumentDirty = false; let closePromptOpen = false; let trayBalloonShown = false; let updaterConfigured = false; let desktopIpcConfigured = false; let updateCheckInFlight = false; let manualUpdateCheck = false; let downloadedUpdateReady = false; let updateInstallRequested = false; let updatePrepareInFlight = null; let pendingUpdateInstallAfterSave = false; let lastUpdateCheckResult = null; let lastUpdateCheckError = ""; let pendingOpenFilePath = null; let windowStateSaveTimer = null; let desktopPrefs = { closeToTray: true }; let desktopAuthSession = null; const desktopCloudCookies = new Map(); let pendingOAuthServer = null; let pendingOAuthTimeout = null; let desktopMenuBuilt = false; const VALID_ACTIVE_WORK_KINDS = new Set([ "none", "3d-project", "drawing-studio", "circuits-studio", "codeblocks-studio", ]); let activeWorkState = { hasOpenWork: false, workKind: "none", projectName: null, shapeCount: 0, hasDiskFile: false, diskFileName: null, hasUnsavedDiskChanges: false, pendingLocalSaveCount: 0, }; const pendingUpdatePrepareResolvers = new Map(); const VALID_VISUAL_STYLES = new Set([ "shaded", "wireframe", "hidden-line", "monochrome", "blueprint", "cyberpunk", "clay", ]); let menuUiState = { inEditor: false, visualStyle: "shaded", xRayMode: false, isOrthographic: false, showLeftToolset: true, showDefaultTray: true, showSecondaryRibbon: false, skyGroundEnabled: false, backEdgesEnabled: false, keymapProfile: "classic-sketchup", }; let updateState = { currentVersion: app.getVersion(), latestVersion: null, updateAvailable: false, downloaded: false, checkedAt: new Date().toISOString(), status: app.isPackaged ? "idle" : "unsupported", progressPercent: 0, bytesPerSecond: 0, transferred: 0, total: 0, feedUrl: UPDATE_FEED_URL, error: undefined, }; // Only file paths returned by native OS dialogs or OS file-association argv // can be overwritten silently by Ctrl+S without showing Save As. const trustedDialogPaths = new Set(); function escapeHtml(raw) { return String(raw ?? "") .replace(/&/g, "&") .replace(//g, ">") .replace(/"/g, """) .replace(/'/g, "'"); } function windowStatePath() { return path.join(app.getPath("userData"), "snapcad-window-state.json"); } function desktopPrefsPath() { return path.join(app.getPath("userData"), "snapcad-desktop-prefs.json"); } function cloudAuthPath() { return path.join(app.getPath("userData"), "snapcad-cloud-auth.json"); } function loadDesktopPrefs() { try { const raw = JSON.parse(fs.readFileSync(desktopPrefsPath(), "utf8")); desktopPrefs = { closeToTray: typeof raw?.closeToTray === "boolean" ? raw.closeToTray : true, }; } catch { desktopPrefs = { closeToTray: true }; } return { ...desktopPrefs }; } function saveDesktopPrefs(patch = {}) { const prevCloseToTray = desktopPrefs.closeToTray; const next = { closeToTray: typeof patch.closeToTray === "boolean" ? patch.closeToTray : desktopPrefs.closeToTray, }; desktopPrefs = next; try { fs.mkdirSync(path.dirname(desktopPrefsPath()), { recursive: true }); fs.writeFileSync(desktopPrefsPath(), JSON.stringify(next, null, 2), "utf8"); } catch { // Best-effort preference persistence. } updateTrayMenu(); if (desktopMenuBuilt && next.closeToTray !== prevCloseToTray) { buildNativeApplicationMenu(); } if (mainWindow && !mainWindow.isDestroyed()) { mainWindow.webContents.send("snapcad:prefs-changed", { ...desktopPrefs }); } return { ...desktopPrefs }; } function updateMenuUiState(patch = {}) { if (!patch || typeof patch !== "object") return { ...menuUiState }; const next = { inEditor: typeof patch.inEditor === "boolean" ? patch.inEditor : menuUiState.inEditor, visualStyle: typeof patch.visualStyle === "string" && VALID_VISUAL_STYLES.has(patch.visualStyle) ? patch.visualStyle : menuUiState.visualStyle, xRayMode: typeof patch.xRayMode === "boolean" ? patch.xRayMode : menuUiState.xRayMode, isOrthographic: typeof patch.isOrthographic === "boolean" ? patch.isOrthographic : menuUiState.isOrthographic, showLeftToolset: typeof patch.showLeftToolset === "boolean" ? patch.showLeftToolset : menuUiState.showLeftToolset, showDefaultTray: typeof patch.showDefaultTray === "boolean" ? patch.showDefaultTray : menuUiState.showDefaultTray, showSecondaryRibbon: typeof patch.showSecondaryRibbon === "boolean" ? patch.showSecondaryRibbon : menuUiState.showSecondaryRibbon, skyGroundEnabled: typeof patch.skyGroundEnabled === "boolean" ? patch.skyGroundEnabled : menuUiState.skyGroundEnabled, backEdgesEnabled: typeof patch.backEdgesEnabled === "boolean" ? patch.backEdgesEnabled : menuUiState.backEdgesEnabled, keymapProfile: patch.keymapProfile === "snapcad-standard" || patch.keymapProfile === "classic-sketchup" ? patch.keymapProfile : menuUiState.keymapProfile, }; const changed = Object.keys(next).some((key) => next[key] !== menuUiState[key]); menuUiState = next; if (changed && desktopMenuBuilt) { buildNativeApplicationMenu(); } return { ...menuUiState }; } function clearDesktopAuthSession() { const hadSession = Boolean(desktopAuthSession); desktopAuthSession = null; try { if (fs.existsSync(cloudAuthPath())) { fs.unlinkSync(cloudAuthPath()); } } catch { // Ignore file delete errors during logout cleanup. } if (hadSession && desktopMenuBuilt) { buildNativeApplicationMenu(); } } function saveDesktopAuthSession(session) { if (!session || typeof session.token !== "string" || !/^[a-f0-9]{64}$/i.test(session.token)) { return false; } const cleanUser = session.user && typeof session.user === "object" ? { id: Number(session.user.id || 0), name: String(session.user.name || "YakNet Kullanıcısı").slice(0, 255), email: String(session.user.email || "").slice(0, 255), avatar: typeof session.user.avatar === "string" ? session.user.avatar.slice(0, 512) : null, auth_source: "yaknet_desktop_token", token_expires_at: typeof session.expiresAt === "string" ? session.expiresAt : undefined, } : null; if (!cleanUser || cleanUser.id <= 0) return false; const cleanToken = session.token.toLowerCase(); desktopAuthSession = { token: cleanToken, user: cleanUser, expiresAt: typeof session.expiresAt === "string" ? session.expiresAt : null, }; try { if (!safeStorage.isEncryptionAvailable()) { // Do not store plaintext long-lived credentials if OS encryption is unavailable. if (desktopMenuBuilt) buildNativeApplicationMenu(); return true; } const encrypted = safeStorage.encryptString(cleanToken).toString("base64"); fs.mkdirSync(path.dirname(cloudAuthPath()), { recursive: true }); fs.writeFileSync( cloudAuthPath(), JSON.stringify({ encrypted: true, token: encrypted, user: cleanUser, expiresAt: desktopAuthSession.expiresAt, savedAt: new Date().toISOString(), }), "utf8", ); } catch { // Keep session in memory even if disk encryption write fails. } if (desktopMenuBuilt) { buildNativeApplicationMenu(); } return true; } function loadDesktopAuthSession() { try { if (!fs.existsSync(cloudAuthPath())) { desktopAuthSession = null; return null; } const raw = JSON.parse(fs.readFileSync(cloudAuthPath(), "utf8")); if (!raw || raw.encrypted !== true || typeof raw.token !== "string" || !safeStorage.isEncryptionAvailable()) { desktopAuthSession = null; return null; } if (typeof raw.expiresAt === "string") { const expiresMs = Date.parse(raw.expiresAt); if (Number.isFinite(expiresMs) && expiresMs <= Date.now()) { clearDesktopAuthSession(); return null; } } const decrypted = safeStorage.decryptString(Buffer.from(raw.token, "base64")).trim().toLowerCase(); if (!/^[a-f0-9]{64}$/.test(decrypted) || !raw.user || Number(raw.user.id || 0) <= 0) { clearDesktopAuthSession(); return null; } desktopAuthSession = { token: decrypted, user: raw.user, expiresAt: typeof raw.expiresAt === "string" ? raw.expiresAt : null, }; return desktopAuthSession; } catch { clearDesktopAuthSession(); return null; } } function emitAuthUpdated(payload) { if (mainWindow && !mainWindow.isDestroyed()) { mainWindow.webContents.send("snapcad:auth-updated", payload); } } function normalizeCloudApiPath(rawPath) { if (typeof rawPath !== "string") return null; const trimmed = rawPath.trim(); if (!trimmed || trimmed.length > 4096) return null; if (trimmed === "/cloud-api.php" || trimmed.startsWith("/cloud-api.php?")) { return trimmed; } return null; } function formatFriendlyUpdateError(rawError) { const message = rawError instanceof Error ? rawError.message : String(rawError || ""); const clean = message.trim(); if (!clean) return "Güncelleme denetlenemedi."; const lower = clean.toLowerCase(); if (lower.includes("404") || lower.includes("latest.yml") || lower.includes("cannot find")) { return "Güncelleme sunucusunda henüz yeni bir masaüstü kurulum paketi yayınlanmadı."; } if ( lower.includes("err_network") || lower.includes("enotfound") || lower.includes("econnrefused") || lower.includes("etimedout") || lower.includes("fetch failed") ) { return "Güncelleme sunucusuna bağlanılamadı. İnternet bağlantınızı kontrol edin."; } return clean; } function clampWindowBoundsToDisplays(rawState) { const fallback = { width: 1500, height: 960, isMaximized: false }; if (!rawState || typeof rawState !== "object") return fallback; const width = Math.max(1100, Math.min(Number(rawState.width) || 1500, 7680)); const height = Math.max(700, Math.min(Number(rawState.height) || 960, 4320)); const isMaximized = Boolean(rawState.isMaximized); if (typeof rawState.x !== "number" || typeof rawState.y !== "number" || !Number.isFinite(rawState.x) || !Number.isFinite(rawState.y)) { return { width, height, isMaximized }; } const candidate = { x: Math.round(rawState.x), y: Math.round(rawState.y), width: Math.round(width), height: Math.round(height) }; try { const displays = screen.getAllDisplays(); const visible = displays.some((display) => { const area = display.workArea; const overlapX = Math.max(0, Math.min(candidate.x + candidate.width, area.x + area.width) - Math.max(candidate.x, area.x)); const overlapY = Math.max(0, Math.min(candidate.y + candidate.height, area.y + area.height) - Math.max(candidate.y, area.y)); return overlapX >= 120 && overlapY >= 80; }); if (visible) { return { ...candidate, isMaximized }; } } catch { // Ignore screen enumeration errors and fall back to centered bounds. } return { width: candidate.width, height: candidate.height, isMaximized }; } function loadSavedWindowState() { try { const raw = fs.readFileSync(windowStatePath(), "utf8"); return clampWindowBoundsToDisplays(JSON.parse(raw)); } catch { return clampWindowBoundsToDisplays(null); } } function saveWindowStateImmediate() { if (!mainWindow || mainWindow.isDestroyed()) return; try { const isMaximized = mainWindow.isMaximized(); const bounds = isMaximized ? mainWindow.getNormalBounds() : mainWindow.getBounds(); fs.mkdirSync(path.dirname(windowStatePath()), { recursive: true }); fs.writeFileSync( windowStatePath(), JSON.stringify({ x: bounds.x, y: bounds.y, width: bounds.width, height: bounds.height, isMaximized, }), "utf8", ); } catch { // Window state persistence is best-effort. } } function scheduleWindowStateSave() { if (windowStateSaveTimer) clearTimeout(windowStateSaveTimer); windowStateSaveTimer = setTimeout(() => { windowStateSaveTimer = null; saveWindowStateImmediate(); }, 280); } function extractSkfFilePathFromArgv(argv) { if (!Array.isArray(argv)) return null; for (let i = 1; i < argv.length; i += 1) { const raw = String(argv[i] || "").trim(); if (!raw || raw.startsWith("-")) continue; const cleaned = raw.replace(/^["']|["']$/g, ""); if (!cleaned.toLowerCase().endsWith(".skf")) continue; try { const resolved = path.resolve(cleaned); const stat = fs.statSync(resolved); if (stat.isFile() && stat.size <= MAX_SKF_FILE_BYTES) { return resolved; } } catch { // Ignore invalid or inaccessible argv paths. } } return null; } function readTrustedSkfFile(filePath) { const resolved = path.resolve(filePath); const stat = fs.statSync(resolved); if (!stat.isFile()) { throw new Error("Secilen oge gecerli bir .skf dosyasi degil."); } if (stat.size > MAX_SKF_FILE_BYTES) { throw new Error("Proje dosyasi 256 MB masaustu sinirini asiyor."); } const buffer = fs.readFileSync(resolved); trustedDialogPaths.add(resolved); return { filePath: resolved, fileName: path.basename(resolved), bytes: new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength), }; } function writeFileAtomic(targetPath, bytes) { const resolved = path.resolve(targetPath); if (!(bytes instanceof Uint8Array)) { throw new Error("Kaydedilecek ikili veri gecersiz."); } if (bytes.byteLength > MAX_SKF_FILE_BYTES) { throw new Error("Dosya boyutu 256 MB sinirini asiyor."); } fs.mkdirSync(path.dirname(resolved), { recursive: true }); const tempPath = `${resolved}.tmp-${process.pid}-${Date.now()}`; let fd = null; try { fd = fs.openSync(tempPath, "w", 0o666); fs.writeSync(fd, bytes, 0, bytes.byteLength, 0); fs.fsyncSync(fd); fs.closeSync(fd); fd = null; fs.renameSync(tempPath, resolved); } catch (error) { if (fd !== null) { try { fs.closeSync(fd); } catch { // Ignore close error on cleanup path. } } try { if (fs.existsSync(tempPath)) fs.unlinkSync(tempPath); } catch { // Ignore unlink error on cleanup path. } throw error; } trustedDialogPaths.add(resolved); return resolved; } function sanitizeWindowTitleInput(title) { const cleaned = String(title || "") .replace(/[\r\n\t\u0000-\u001f\u007f]+/g, " ") .replace(/\s+/g, " ") .trim() .slice(0, 140); return cleaned || APP_DISPLAY_NAME; } function isAllowedExternalUrl(rawUrl) { try { const parsed = new URL(String(rawUrl || "")); return parsed.protocol === "https:" || parsed.protocol === "http:"; } catch { return false; } } function sendMenuCommand(action) { if (!mainWindow || mainWindow.isDestroyed()) return; showMainWindow(); mainWindow.webContents.send("snapcad:menu-command", action); } function deliverOrQueueSkfOpen(filePath) { if (!filePath) return; try { const resolved = path.resolve(filePath); trustedDialogPaths.add(resolved); if (mainWindow && !mainWindow.isDestroyed() && !mainWindow.webContents.isLoadingMainFrame()) { const payload = readTrustedSkfFile(resolved); showMainWindow(); mainWindow.webContents.send("snapcad:open-file", payload); return; } pendingOpenFilePath = resolved; } catch { // Ignore unreadable OS open-file payloads. } } function appendServerOutput(chunk) { webServerOutput += String(chunk); if (webServerOutput.length > 12_000) { webServerOutput = webServerOutput.slice(-12_000); } } async function waitForServer(url, timeoutMs = 30_000) { const deadline = Date.now() + timeoutMs; let lastError = null; while (Date.now() < deadline) { if (webServer && webServer.exitCode !== null) { throw new Error(`SnapCAD yerel sunucu sureci kod ${webServer.exitCode} ile kapandi.`); } try { const response = await fetch(url, { redirect: "manual" }); if (response.status >= 200 && response.status < 500) return; } catch (error) { lastError = error; } await new Promise((resolve) => setTimeout(resolve, 180)); } const detail = lastError instanceof Error ? ` ${lastError.message}` : ""; throw new Error(`SnapCAD yerel web motoru zamaninda baslatilamadi.${detail}`); } async function startPackagedWebServer() { const webRoot = path.join(process.resourcesPath, "web"); const serverPath = path.join(webRoot, "apps", "web", "server.js"); if (!fs.existsSync(serverPath)) { throw new Error(`Masaustu uygulama paketi eksik: ${serverPath}`); } const port = DESKTOP_PORT; const runtimeNodeModules = path.join(webRoot, "runtime_modules"); const packagedNodeModules = path.join(process.resourcesPath, "app.asar", "node_modules"); webServer = spawn(process.execPath, [serverPath], { cwd: path.dirname(serverPath), windowsHide: true, stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, ELECTRON_RUN_AS_NODE: "1", NODE_PATH: [runtimeNodeModules, packagedNodeModules, process.env.NODE_PATH].filter(Boolean).join(path.delimiter), HOSTNAME: "127.0.0.1", PORT: String(port), SKETCHFORGE_DESKTOP: "1", SKETCHFORGE_DESKTOP_VERSION: app.getVersion(), SKETCHFORGE_SHARED_PROJECTS_DIR: "", NEXT_TELEMETRY_DISABLED: "1", }, }); webServer.stdout?.on("data", appendServerOutput); webServer.stderr?.on("data", appendServerOutput); const url = `http://127.0.0.1:${port}`; await waitForServer(url); return url; } function stopPackagedWebServer() { if (!webServer || webServer.exitCode !== null) return; try { webServer.kill(); } catch { // The process may already be gone while Electron is shutting down. } } function assetsDirPath() { return devUrl ? path.join(__dirname, "..", "web", "public", "assets", "sketchforge") : path.join(process.resourcesPath, "web", "apps", "web", "public", "assets", "sketchforge"); } function appIconPath() { const dir = assetsDirPath(); if (process.platform === "win32") { const ico = path.join(dir, "sketchforge-logo.ico"); if (fs.existsSync(ico)) return ico; } return path.join(dir, "sketchforge-logo.png"); } function createTrayImage() { const iconPath = appIconPath(); const loaded = nativeImage.createFromPath(iconPath); if (iconPath.toLowerCase().endsWith(".ico") && !loaded.isEmpty()) { return loaded; } const pngFallback = path.join(assetsDirPath(), "sketchforge-logo.png"); return nativeImage.createFromPath(pngFallback).resize({ width: 20, height: 20, quality: "best" }); } function showMainWindow() { if (!mainWindow || mainWindow.isDestroyed()) return; if (mainWindow.isMinimized()) mainWindow.restore(); mainWindow.show(); mainWindow.focus(); updateTrayMenu(); } function hideToTrayWindow({ showBalloonOnce = false } = {}) { if (!mainWindow || mainWindow.isDestroyed()) return; saveWindowStateImmediate(); mainWindow.hide(); updateTrayMenu(); if (showBalloonOnce && !trayBalloonShown && tray && process.platform === "win32" && typeof tray.displayBalloon === "function") { trayBalloonShown = true; try { tray.displayBalloon({ icon: appIconPath(), title: `${APP_DISPLAY_NAME} Arka Planda Çalışıyor`, content: "Pencere sistem tepsisine (gizli simgeler) küçültüldü. Geri açmak için simgeye tıklayın; tamamen kapatmak için sağ tıklayıp Çıkış'ı seçin.", noSound: true, }); } catch { // Tray balloon is optional cosmetic feedback on Windows. } } } function setUpdateState(patch = {}) { updateState = { ...updateState, ...patch, currentVersion: app.getVersion(), feedUrl: UPDATE_FEED_URL, }; if (mainWindow && !mainWindow.isDestroyed()) { mainWindow.webContents.send("snapcad:update-state", { ...updateState }); if (updateState.status === "downloading") { const pct = Math.max(0, Math.min(100, Number(updateState.progressPercent || 0))); mainWindow.setProgressBar(pct / 100); } else if (updateState.status === "checking" && updateInstallRequested) { mainWindow.setProgressBar(2); } else { mainWindow.setProgressBar(-1); } } return { ...updateState }; } function desktopUpdatePayload(result = lastUpdateCheckResult, errorMessage = lastUpdateCheckError, overrides = {}) { return { currentVersion: app.getVersion(), latestVersion: result?.updateInfo?.version || updateState.latestVersion || null, updateAvailable: Boolean(result?.isUpdateAvailable ?? updateState.updateAvailable), downloaded: downloadedUpdateReady, checkedAt: updateState.checkedAt || new Date().toISOString(), status: updateState.status, progressPercent: updateState.progressPercent, bytesPerSecond: updateState.bytesPerSecond, transferred: updateState.transferred, total: updateState.total, feedUrl: UPDATE_FEED_URL, error: errorMessage || undefined, ...overrides, }; } function sanitizeActiveWorkState(raw) { const input = raw && typeof raw === "object" ? raw : {}; const workKind = typeof input.workKind === "string" && VALID_ACTIVE_WORK_KINDS.has(input.workKind) ? input.workKind : "none"; const projectName = typeof input.projectName === "string" && input.projectName.trim() ? input.projectName.replace(/[\r\n\t\u0000-\u001f\u007f]+/g, " ").trim().slice(0, 140) : null; const diskFileName = typeof input.diskFileName === "string" && input.diskFileName.trim() ? input.diskFileName.replace(/[\r\n\t\u0000-\u001f\u007f]+/g, " ").trim().slice(0, 140) : null; const shapeCount = Number.isFinite(Number(input.shapeCount)) ? Math.max(0, Math.round(Number(input.shapeCount))) : 0; const pendingLocalSaveCount = Number.isFinite(Number(input.pendingLocalSaveCount)) ? Math.max(0, Math.round(Number(input.pendingLocalSaveCount))) : 0; return { hasOpenWork: Boolean(input.hasOpenWork) && workKind !== "none", workKind, projectName, shapeCount, hasDiskFile: Boolean(input.hasDiskFile), diskFileName, hasUnsavedDiskChanges: Boolean(input.hasUnsavedDiskChanges), pendingLocalSaveCount, }; } function sanitizePrepareBeforeUpdateResult(raw) { const base = sanitizeActiveWorkState(raw); const input = raw && typeof raw === "object" ? raw : {}; const cloudStatusText = typeof input.cloudStatusText === "string" && input.cloudStatusText.trim() ? input.cloudStatusText.trim().slice(0, 220) : desktopAuthSession?.user ? "YakNet Bulut senkronizasyonu tamamlanamadı." : "YakNet oturumu açık değil (yalnızca yerel depolamaya kaydedilir)."; return { ...base, localSaved: typeof input.localSaved === "boolean" ? input.localSaved : base.pendingLocalSaveCount === 0, cloudAttempted: Boolean(input.cloudAttempted), cloudSynced: Boolean(input.cloudSynced), cloudStatusText, }; } async function requestRendererPrepareBeforeUpdate(timeoutMs = 8500) { const fallback = sanitizePrepareBeforeUpdateResult({ ...activeWorkState, localSaved: !isDocumentDirty && activeWorkState.pendingLocalSaveCount === 0, cloudAttempted: false, cloudSynced: false, cloudStatusText: desktopAuthSession?.user ? "Yerel değişiklikler kuyruklandı; YakNet Bulut durumu doğrulanamadı." : "YakNet oturumu açık değil (yalnızca yerel depolamaya kaydedilir).", }); if (!mainWindow || mainWindow.isDestroyed() || mainWindow.webContents.isLoadingMainFrame()) { return fallback; } const requestId = crypto.randomBytes(12).toString("hex"); return new Promise((resolve) => { const timer = setTimeout(() => { pendingUpdatePrepareResolvers.delete(requestId); resolve(fallback); }, timeoutMs); timer.unref?.(); pendingUpdatePrepareResolvers.set(requestId, (result) => { clearTimeout(timer); pendingUpdatePrepareResolvers.delete(requestId); resolve(result); }); try { mainWindow.webContents.send("snapcad:prepare-before-update", requestId); } catch { clearTimeout(timer); pendingUpdatePrepareResolvers.delete(requestId); resolve(fallback); } }); } function installDownloadedUpdate() { if (!downloadedUpdateReady) return; pendingUpdateInstallAfterSave = false; explicitQuit = true; isQuitting = true; if (mainWindow && !mainWindow.isDestroyed()) { mainWindow.setProgressBar(-1); } stopPackagedWebServer(); if (tray) { try { tray.destroy(); } catch { // Ignore tray teardown errors during update restart. } tray = null; } setImmediate(() => autoUpdater.quitAndInstall(false, true)); } async function prepareAndInstallDownloadedUpdate() { if (!downloadedUpdateReady) return { started: false }; if (updatePrepareInFlight) return updatePrepareInFlight; updatePrepareInFlight = (async () => { const prep = await requestRendererPrepareBeforeUpdate(); const has3dProject = prep.workKind === "3d-project"; const isSecondaryStudio = prep.workKind === "drawing-studio" || prep.workKind === "circuits-studio" || prep.workKind === "codeblocks-studio"; if (!has3dProject && !isSecondaryStudio && !isDocumentDirty) { installDownloadedUpdate(); return { started: true }; } showMainWindow(); if (isSecondaryStudio) { const studioLabel = prep.workKind === "drawing-studio" ? "Teknik Çizim Stüdyosu" : prep.workKind === "circuits-studio" ? "Elektronik Devreler Stüdyosu" : "Kod Blokları Stüdyosu"; const { response } = await dialog.showMessageBox(visibleDialogParent(), { type: "warning", buttons: ["İptal (Önce Çalışmamı Dışa Aktarayım)", "Yine de Güncelle ve Yeniden Başlat"], defaultId: 0, cancelId: 0, noLink: true, title: `Açık Çalışma Uyarısı — ${APP_DISPLAY_NAME}`, message: `${studioLabel} içinde açık bir çalışma var.`, detail: [ "Teknik Çizim, Devreler ve Kod Blokları çalışma alanları buluta otomatik olarak anlık yedeklenmez.", "Güncelleme için uygulama yeniden başlatılmadan önce çalışmanızı dışa aktarmanız önerilir.", ].join("\n"), }); if (response === 1) { isDocumentDirty = false; installDownloadedUpdate(); return { started: true }; } updateInstallRequested = false; return { started: false, canceled: true }; } const label = prep.projectName || "Açık 3B Proje"; const detailLines = [ `• Yerel uygulama depolaması (IndexedDB): ${prep.localSaved ? "Son değişiklikler kaydedildi." : "Bekleyen yerel yazma tamamlanamadı."}`, `• YakNet Bulut: ${prep.cloudStatusText}`, prep.hasDiskFile && prep.hasUnsavedDiskChanges ? `• "${prep.diskFileName || label}" dosyasında henüz diske yazılmamış değişiklikler var.` : "• İsterseniz yeni sürüm kurulmadan önce çalışmanızı .skf proje dosyası olarak da kaydedebilirsiniz.", "", "Güncelleme kurulmadan önce projenizi .skf dosyasına kaydetmek ister misiniz?", ]; const { response } = await dialog.showMessageBox(visibleDialogParent(), { type: "question", buttons: ["Kaydet (.skf) ve Güncelle", "Kaydetmeden Güncelle ve Yeniden Başlat", "İptal (Daha Sonra Kur)"], defaultId: 0, cancelId: 2, noLink: true, title: `Güncellemeden Önce Kaydet — ${APP_DISPLAY_NAME}`, message: `"${label}" çalışması şu anda açık.`, detail: detailLines.join("\n"), }); if (response === 0) { pendingUpdateInstallAfterSave = true; sendMenuCommand("file:save-and-update"); return { started: true, awaitingSave: true }; } if (response === 1) { pendingUpdateInstallAfterSave = false; isDocumentDirty = false; installDownloadedUpdate(); return { started: true }; } pendingUpdateInstallAfterSave = false; updateInstallRequested = false; return { started: false, canceled: true }; })().finally(() => { updatePrepareInFlight = null; }); return updatePrepareInFlight; } async function downloadAndInstallDesktopUpdate() { if (!app.isPackaged) { return desktopUpdatePayload( null, "Güncellemeler yalnızca kurulu SnapCAD Studio (.exe) uygulamasında indirilebilir.", { status: "unsupported" }, ); } if (downloadedUpdateReady) { void prepareAndInstallDownloadedUpdate(); return desktopUpdatePayload(lastUpdateCheckResult, "", { status: "downloaded", progressPercent: 100 }); } lastUpdateCheckError = ""; try { let result = lastUpdateCheckResult; if (!result?.isUpdateAvailable) { updateInstallRequested = true; setUpdateState({ status: "checking", checkedAt: new Date().toISOString(), error: undefined }); result = await autoUpdater.checkForUpdates(); lastUpdateCheckResult = result; } if (!result?.isUpdateAvailable) { updateInstallRequested = false; setUpdateState({ status: "not-available", latestVersion: result?.updateInfo?.version || null, updateAvailable: false, downloaded: false, checkedAt: new Date().toISOString(), error: undefined, }); return desktopUpdatePayload(result); } updateInstallRequested = true; const expectedTotal = Number(result?.updateInfo?.files?.[0]?.size || 0); setUpdateState({ status: "downloading", latestVersion: result?.updateInfo?.version || null, updateAvailable: true, progressPercent: 0, transferred: 0, total: Number.isFinite(expectedTotal) && expectedTotal > 0 ? expectedTotal : 0, bytesPerSecond: 0, error: undefined, }); await autoUpdater.downloadUpdate(); return desktopUpdatePayload(result); } catch (error) { updateInstallRequested = false; const message = formatFriendlyUpdateError(error); lastUpdateCheckError = message; setUpdateState({ status: "error", checkedAt: new Date().toISOString(), error: message, }); return desktopUpdatePayload(lastUpdateCheckResult, message); } } function visibleDialogParent() { return mainWindow && !mainWindow.isDestroyed() && mainWindow.isVisible() ? mainWindow : undefined; } async function checkForDesktopUpdates(manual = false) { if (!app.isPackaged) { setUpdateState({ status: "unsupported", checkedAt: new Date().toISOString(), updateAvailable: false, downloaded: false, error: undefined, }); if (manual) { await dialog.showMessageBox(visibleDialogParent(), { type: "info", title: `${APP_DISPLAY_NAME} Güncellemeleri`, message: "Otomatik güncelleme yalnızca kurulu masaüstü (.exe) uygulamasında aktiftir.", detail: `Mevcut geliştirme sürümü: ${app.getVersion()}\nGüncelleme adresi: ${UPDATE_FEED_URL}`, }); } return desktopUpdatePayload(null, "", { status: "unsupported" }); } if (downloadedUpdateReady) { if (manual) { void prepareAndInstallDownloadedUpdate(); } return desktopUpdatePayload(); } if (updateCheckInFlight) { return desktopUpdatePayload(); } manualUpdateCheck = manualUpdateCheck || manual; updateCheckInFlight = true; lastUpdateCheckError = ""; setUpdateState({ status: "checking", checkedAt: new Date().toISOString(), error: undefined }); try { const result = await autoUpdater.checkForUpdates(); lastUpdateCheckResult = result; const available = Boolean(result?.isUpdateAvailable); setUpdateState({ status: available ? "available" : "not-available", latestVersion: result?.updateInfo?.version || null, updateAvailable: available, downloaded: downloadedUpdateReady, checkedAt: new Date().toISOString(), error: undefined, }); return desktopUpdatePayload(result); } catch (error) { const message = formatFriendlyUpdateError(error); lastUpdateCheckError = message; setUpdateState({ status: "error", checkedAt: new Date().toISOString(), error: message, }); if (manualUpdateCheck) { manualUpdateCheck = false; dialog.showErrorBox("Güncellemeler denetlenemedi", message); } return desktopUpdatePayload(null, message); } finally { updateCheckInFlight = false; } } function requestForceQuit() { explicitQuit = true; if (!mainWindow || mainWindow.isDestroyed()) { isQuitting = true; app.quit(); return; } if (isDocumentDirty) { showMainWindow(); } mainWindow.close(); } function renderOAuthCallbackHtml({ ok, title, message, userName }) { const accent = ok ? "#10b981" : "#ef4444"; const badge = ok ? "BAŞARILI" : "HATA"; return ` ${escapeHtml(title)} — ${APP_DISPLAY_NAME}
${badge}

${escapeHtml(title)}

${escapeHtml(message)}

${userName ? `

Hesap: ${escapeHtml(userName)}

` : ""}
Bu tarayıcı sekmesini kapatabilir ve ${APP_DISPLAY_NAME} uygulamasına dönebilirsiniz.
`; } function closePendingOAuthServer() { if (pendingOAuthTimeout) { clearTimeout(pendingOAuthTimeout); pendingOAuthTimeout = null; } if (pendingOAuthServer) { try { pendingOAuthServer.close(); } catch { // Ignore close errors. } pendingOAuthServer = null; } } async function startYakNetDesktopLogin() { closePendingOAuthServer(); const expectedNonce = crypto.randomBytes(32).toString("hex"); const expectedNonceBuf = Buffer.from(expectedNonce, "utf8"); emitAuthUpdated({ authenticated: Boolean(desktopAuthSession), pending: true, user: desktopAuthSession?.user ?? null, }); return new Promise((resolve) => { const server = http.createServer(async (req, res) => { try { const reqUrl = new URL(req.url || "/", "http://127.0.0.1"); if (req.method !== "GET" || reqUrl.pathname !== "/oauth-callback") { res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" }); res.end("Not Found"); return; } const returnedNonce = (reqUrl.searchParams.get("nonce") || "").trim().toLowerCase(); const returnedNonceBuf = Buffer.from(returnedNonce, "utf8"); const nonceValid = returnedNonceBuf.length === expectedNonceBuf.length && crypto.timingSafeEqual(returnedNonceBuf, expectedNonceBuf); if (!nonceValid) { res.writeHead(400, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" }); res.end( renderOAuthCallbackHtml({ ok: false, title: "Güvenlik Doğrulaması Başarısız", message: "Oturum doğrulama anahtarı eşleşmedi. Lütfen uygulama içinden tekrar Giriş Yap butonuna basın.", }), ); closePendingOAuthServer(); emitAuthUpdated({ authenticated: Boolean(desktopAuthSession), pending: false, user: desktopAuthSession?.user ?? null, error: "OAuth güvenlik doğrulaması eşleşmedi.", }); showMainWindow(); return; } const errParam = (reqUrl.searchParams.get("error") || "").trim(); if (errParam) { res.writeHead(400, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" }); res.end( renderOAuthCallbackHtml({ ok: false, title: "YakNet Girişi Tamamlanamadı", message: errParam, }), ); closePendingOAuthServer(); emitAuthUpdated({ authenticated: Boolean(desktopAuthSession), pending: false, user: desktopAuthSession?.user ?? null, error: errParam, }); showMainWindow(); return; } const code = (reqUrl.searchParams.get("code") || "").trim().toLowerCase(); if (!/^[a-f0-9]{48,128}$/.test(code)) { res.writeHead(400, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" }); res.end( renderOAuthCallbackHtml({ ok: false, title: "Geçersiz Giriş Kodu", message: "Sunucudan geçerli oturum değişim kodu alınamadı.", }), ); closePendingOAuthServer(); emitAuthUpdated({ authenticated: Boolean(desktopAuthSession), pending: false, user: desktopAuthSession?.user ?? null, error: "Geçersiz oturum değişim kodu.", }); showMainWindow(); return; } const exchangeRes = await fetch(`${CLOUD_ORIGIN}/cloud-api.php?action=desktop_exchange`, { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json", "User-Agent": `SnapCAD-Desktop/${app.getVersion()}`, }, body: JSON.stringify({ action: "desktop_exchange", code, nonce: expectedNonce, }), }); const payload = await exchangeRes.json().catch(() => null); if (!exchangeRes.ok || !payload?.ok || typeof payload.token !== "string" || !payload.user) { const errMsg = payload?.error || "YakNet oturum anahtarı alınamadı."; res.writeHead(502, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" }); res.end( renderOAuthCallbackHtml({ ok: false, title: "Oturum Anahtarı Alınamadı", message: errMsg, }), ); closePendingOAuthServer(); emitAuthUpdated({ authenticated: Boolean(desktopAuthSession), pending: false, user: desktopAuthSession?.user ?? null, error: errMsg, }); showMainWindow(); return; } saveDesktopAuthSession({ token: payload.token, user: payload.user, expiresAt: payload.expires_at, }); res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" }); res.end( renderOAuthCallbackHtml({ ok: true, title: "YakNet Girişi Tamamlandı", message: `${APP_DISPLAY_NAME} oturumunuz güvenle bağlandı ve eşitleniyor.`, userName: payload.user.name, }), ); closePendingOAuthServer(); showMainWindow(); emitAuthUpdated({ authenticated: true, pending: false, user: desktopAuthSession?.user ?? payload.user, cloudLoginCompleted: true, }); } catch (err) { const message = err instanceof Error ? err.message : "Beklenmeyen giriş hatası"; try { res.writeHead(500, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" }); res.end( renderOAuthCallbackHtml({ ok: false, title: "Bağlantı Hatası", message, }), ); } catch { // Ignore broken pipe while sending error response. } closePendingOAuthServer(); emitAuthUpdated({ authenticated: Boolean(desktopAuthSession), pending: false, user: desktopAuthSession?.user ?? null, error: message, }); } }); pendingOAuthServer = server; server.on("error", (err) => { closePendingOAuthServer(); const message = err instanceof Error ? err.message : "Yerel giriş dinleyicisi başlatılamadı."; emitAuthUpdated({ authenticated: Boolean(desktopAuthSession), pending: false, user: desktopAuthSession?.user ?? null, error: message, }); resolve({ started: false, error: message }); }); server.listen(0, "127.0.0.1", () => { const address = server.address(); if (!address || typeof address === "string") { closePendingOAuthServer(); resolve({ started: false, error: "Geri dönüş portu açılamadı." }); return; } pendingOAuthTimeout = setTimeout(() => { closePendingOAuthServer(); emitAuthUpdated({ authenticated: Boolean(desktopAuthSession), pending: false, user: desktopAuthSession?.user ?? null, }); }, 5 * 60 * 1000); pendingOAuthTimeout.unref?.(); const deviceName = os.hostname() || "SnapCAD Masaüstü"; const loginUrl = `${CLOUD_ORIGIN}/login.php?desktop=1` + `&desktop_port=${encodeURIComponent(String(address.port))}` + `&desktop_nonce=${encodeURIComponent(expectedNonce)}` + `&device=${encodeURIComponent(deviceName)}`; void shell.openExternal(loginUrl).then( () => resolve({ started: true }), (err) => { closePendingOAuthServer(); const message = err instanceof Error ? err.message : "Harici tarayıcı açılamadı."; emitAuthUpdated({ authenticated: Boolean(desktopAuthSession), pending: false, user: desktopAuthSession?.user ?? null, error: message, }); resolve({ started: false, error: message }); }, ); }); }); } function storeDesktopCloudCookies(response) { if (!response?.headers) return; const rawSetCookies = typeof response.headers.getSetCookie === "function" ? response.headers.getSetCookie() : response.headers.get("set-cookie") ? [response.headers.get("set-cookie")] : []; for (const rawCookie of rawSetCookies) { const firstPart = String(rawCookie || "").split(";")[0]?.trim(); if (!firstPart) continue; const eqIndex = firstPart.indexOf("="); if (eqIndex <= 0) continue; const name = firstPart.slice(0, eqIndex).trim(); const val = firstPart.slice(eqIndex + 1).trim(); if (!name) continue; if (!val || val === "deleted") { desktopCloudCookies.delete(name); } else { desktopCloudCookies.set(name, val); } } } function buildDesktopCloudCookieHeader() { if (desktopCloudCookies.size === 0) return ""; return Array.from(desktopCloudCookies.entries()) .map(([k, v]) => `${k}=${v}`) .join("; "); } async function logoutYakNetDesktop() { const token = desktopAuthSession?.token; const cookieHeader = buildDesktopCloudCookieHeader(); if (token || cookieHeader) { try { const headers = { Accept: "application/json", "User-Agent": `SnapCAD-Desktop/${app.getVersion()}`, }; if (token) { headers.Authorization = `Bearer ${token}`; headers["X-SnapCAD-Desktop-Token"] = token; } if (cookieHeader) { headers.Cookie = cookieHeader; } await fetch(`${CLOUD_ORIGIN}/cloud-api.php?action=logout`, { method: "POST", headers, }); } catch { // Offline logout should still clear local desktop credentials cleanly. } } desktopCloudCookies.clear(); clearDesktopAuthSession(); emitAuthUpdated({ authenticated: false, pending: false, user: null, loggedOut: true, }); return { ok: true }; } async function proxyDesktopCloudRequest(rawOptions) { const normalizedPath = normalizeCloudApiPath(rawOptions?.path); if (!normalizedPath) { return { ok: false, status: 400, bodyText: JSON.stringify({ ok: false, error: "Geçersiz bulut API yolu." }), contentType: "application/json; charset=utf-8", error: "Geçersiz bulut API yolu.", }; } const rawMethod = String(rawOptions?.method || "GET").trim().toUpperCase(); const method = rawMethod === "POST" ? "POST" : "GET"; const headers = { Accept: "application/json", "User-Agent": `SnapCAD-Desktop/${app.getVersion()}`, }; if (rawOptions?.headers && typeof rawOptions.headers === "object") { for (const [k, v] of Object.entries(rawOptions.headers)) { if (typeof v !== "string") continue; if (k.toLowerCase() === "content-type") { headers["Content-Type"] = v; } } } const cookieHeader = buildDesktopCloudCookieHeader(); if (cookieHeader) { headers.Cookie = cookieHeader; } const hadToken = Boolean(desktopAuthSession?.token); if (desktopAuthSession?.token) { headers.Authorization = `Bearer ${desktopAuthSession.token}`; headers["X-SnapCAD-Desktop-Token"] = desktopAuthSession.token; } try { const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), 20_000); let response; let bodyText; try { response = await fetch(`${CLOUD_ORIGIN}${normalizedPath}`, { method, headers, body: method === "POST" && typeof rawOptions?.body === "string" ? rawOptions.body : undefined, signal: controller.signal, }); storeDesktopCloudCookies(response); bodyText = await response.text(); } finally { clearTimeout(timeout); } if (normalizedPath.includes("action=logout")) { desktopCloudCookies.clear(); clearDesktopAuthSession(); } else if (hadToken) { let parsed = null; try { parsed = JSON.parse(bodyText); } catch { // Ignore non-JSON body when inspecting token invalidity. } if (parsed?.token_invalid === true || (response.status === 401 && parsed?.authenticated === false)) { clearDesktopAuthSession(); emitAuthUpdated({ authenticated: false, pending: false, user: null, loggedOut: true, }); } else if (parsed?.authenticated === true && parsed?.user && desktopAuthSession) { desktopAuthSession.user = parsed.user; } } return { ok: response.ok, status: response.status, bodyText, contentType: response.headers.get("content-type") || "application/json; charset=utf-8", }; } catch (error) { const message = error instanceof Error ? error.message : "YakNet Bulut servisine şu anda ulaşılamıyor."; return { ok: false, status: 0, bodyText: JSON.stringify({ ok: false, error: message }), contentType: "application/json; charset=utf-8", error: message, }; } } function buildNativeApplicationMenu() { if (!app.isReady()) return null; const isMac = process.platform === "darwin"; const isFullScreen = Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isFullScreen()); const isClassicKeymap = menuUiState.keymapProfile !== "snapcad-standard"; const signedInUser = desktopAuthSession?.user ?? null; const template = [ ...(isMac ? [ { label: APP_DISPLAY_NAME, submenu: [ { role: "about", label: `${APP_DISPLAY_NAME} Hakkında` }, { type: "separator" }, { role: "services" }, { type: "separator" }, { role: "hide" }, { role: "hideOthers" }, { role: "unhide" }, { type: "separator" }, { role: "quit", label: "Çıkış" }, ], }, ] : []), { label: "Dosya", submenu: [ { label: "Yeni 3B Proje", accelerator: "CmdOrCtrl+N", click: () => sendMenuCommand("file:new"), }, { label: "Proje Aç (.skf)…", accelerator: "CmdOrCtrl+O", click: () => sendMenuCommand("file:open"), }, { type: "separator" }, { label: "Kaydet", accelerator: "CmdOrCtrl+S", click: () => sendMenuCommand("file:save"), }, { label: "Farklı Kaydet (.skf)…", accelerator: "CmdOrCtrl+Shift+S", click: () => sendMenuCommand("file:save-as"), }, { type: "separator" }, { label: "İçe Aktar (IFC, DWG, DXF, STEP, STL, OBJ, GLB, SVG, Görsel)…", click: () => sendMenuCommand("file:import"), }, { label: "Dışa Aktar", submenu: [ { label: "Dışa Aktar Penceresini Aç…", click: () => sendMenuCommand("file:export-panel") }, { type: "separator" }, { label: "STL 3B Yazıcı Modeli (.stl)…", click: () => sendMenuCommand("file:export-stl") }, { label: "3MF Baskı Paketi (.3mf)…", click: () => sendMenuCommand("file:export-3mf") }, { label: "STEP B-Rep Katı Model (.step)…", click: () => sendMenuCommand("file:export-step") }, { label: "IFC4 Mimari BIM Modeli (.ifc)…", click: () => sendMenuCommand("file:export-ifc") }, { label: "Wavefront 3B Mesh (.obj)…", click: () => sendMenuCommand("file:export-obj") }, { label: "Binary glTF 3B Model (.glb)…", click: () => sendMenuCommand("file:export-glb") }, { label: "AutoCAD 2B/3B DXF (.dxf)…", click: () => sendMenuCommand("file:export-dxf") }, { label: "Vektör Üst Görünüm SVG (.svg)…", click: () => sendMenuCommand("file:export-svg") }, { label: "SnapCAD Proje Arşivi (.skf)…", click: () => sendMenuCommand("file:export-skf") }, ], }, { type: "separator" }, { label: "Model Bilgisi & Çalışma Alanı Birimleri…", click: () => sendMenuCommand("window:workspace-settings"), }, { label: "YakNet Bulut Hesabı", submenu: signedInUser ? [ { label: `Oturum Açık: ${signedInUser.name || signedInUser.email || "YakNet Kullanıcısı"}`, enabled: false, }, { label: "Projeler ve Bulut Senkronizasyon Paneli", click: () => sendMenuCommand("file:dashboard") }, { label: "Başka Hesapla Giriş Yap…", click: () => void startYakNetDesktopLogin() }, { type: "separator" }, { label: "YakNet Hesabından Çıkış Yap", click: () => void logoutYakNetDesktop() }, ] : [ { label: "YakNet ile Giriş Yap (Tarayıcıda)…", click: () => void startYakNetDesktopLogin() }, { label: "Projeler Paneline Dön", click: () => sendMenuCommand("file:dashboard") }, ], }, { type: "separator" }, { label: "Projeler Paneline Dön", click: () => sendMenuCommand("file:dashboard"), }, { label: "Sistem Tepsisine Küçült", click: () => hideToTrayWindow({ showBalloonOnce: true }), }, ...(!isMac ? [ { type: "separator" }, { label: "Tamamen Çıkış Yap", accelerator: "Alt+F4", click: () => requestForceQuit(), }, ] : []), ], }, { label: "Düzenle", submenu: [ { label: "Geri Al", accelerator: "CmdOrCtrl+Z", registerAccelerator: false, click: () => sendMenuCommand("edit:undo") }, { label: "Yinele", accelerator: "CmdOrCtrl+Y", registerAccelerator: false, click: () => sendMenuCommand("edit:redo") }, { type: "separator" }, { label: "Kes", accelerator: "CmdOrCtrl+X", registerAccelerator: false, click: () => sendMenuCommand("edit:cut") }, { label: "Kopyala", accelerator: "CmdOrCtrl+C", registerAccelerator: false, click: () => sendMenuCommand("edit:copy") }, { label: "Yapıştır", accelerator: "CmdOrCtrl+V", registerAccelerator: false, click: () => sendMenuCommand("edit:paste") }, { label: "Çoğalt", accelerator: "CmdOrCtrl+D", registerAccelerator: false, click: () => sendMenuCommand("edit:duplicate") }, { label: "Sil", accelerator: "Delete", registerAccelerator: false, click: () => sendMenuCommand("edit:delete") }, { type: "separator" }, { label: "Tümünü Seç", accelerator: "CmdOrCtrl+A", registerAccelerator: false, click: () => sendMenuCommand("edit:select-all") }, { label: "Seçimi Bırak", accelerator: "Escape", registerAccelerator: false, click: () => sendMenuCommand("edit:clear-selection") }, { type: "separator" }, { label: "Bileşen Oluştur (Make Component)", accelerator: isClassicKeymap ? "G" : undefined, registerAccelerator: false, click: () => sendMenuCommand("edit:make-component"), }, { label: "Bileşeni Benzersiz Yap (Make Unique)", click: () => sendMenuCommand("edit:make-unique") }, { label: "Grupla (Make Group)", accelerator: "CmdOrCtrl+G", registerAccelerator: false, click: () => sendMenuCommand("edit:group") }, { label: "Grubu Çöz (Explode)", accelerator: "CmdOrCtrl+Shift+G", registerAccelerator: false, click: () => sendMenuCommand("edit:ungroup") }, { label: "Kesişim (Boolean Intersection)", click: () => sendMenuCommand("edit:intersect") }, { label: "Biçim (Katı / Delik)", submenu: [ { label: "Katı Forma Dönüştür (Solid)", click: () => sendMenuCommand("edit:make-solid") }, { label: "Deliğe Dönüştür (Hole)", click: () => sendMenuCommand("edit:make-hole") }, ], }, { type: "separator" }, { label: "Aynala (Mirror)", accelerator: "Shift+M", registerAccelerator: false, click: () => sendMenuCommand("edit:mirror") }, { label: "Hizala (Align)", click: () => sendMenuCommand("edit:align") }, { label: "Çalışma Düzlemine İndir", accelerator: "D", registerAccelerator: false, click: () => sendMenuCommand("edit:drop-to-workplane") }, { label: "Izgaraya Oturt (Snap to Grid)", click: () => sendMenuCommand("edit:snap-to-grid") }, { label: "Pah Kır (Chamfer)…", click: () => sendMenuCommand("edit:chamfer") }, { label: "Yuvarla (Fillet)…", click: () => sendMenuCommand("edit:fillet") }, { type: "separator" }, { label: "Seçileni Gizle / Göster", accelerator: "CmdOrCtrl+H", registerAccelerator: false, click: () => sendMenuCommand("edit:hide") }, { label: "Tüm Gizlileri Göster", accelerator: "CmdOrCtrl+Shift+H", registerAccelerator: false, click: () => sendMenuCommand("edit:show-hidden") }, { label: "Kilitle / Kilidi Aç", accelerator: "CmdOrCtrl+L", registerAccelerator: false, click: () => sendMenuCommand("edit:lock") }, ], }, { label: "Görünüm", submenu: [ { label: "Büyük Araç Seti (Sol Panel)", type: "checkbox", checked: Boolean(menuUiState.showLeftToolset), click: () => sendMenuCommand("view:toggle-left-toolset"), }, { label: "Varsayılan Tepsi (Sağ Panel)", type: "checkbox", checked: Boolean(menuUiState.showDefaultTray), click: () => sendMenuCommand("view:toggle-tray"), }, { label: "SnapCAD Üst Araç Şeridi", type: "checkbox", checked: Boolean(menuUiState.showSecondaryRibbon), click: () => sendMenuCommand("view:toggle-secondary-ribbon"), }, { type: "separator" }, { label: "Gökyüzü & Ufuk Zemini", type: "checkbox", checked: Boolean(menuUiState.skyGroundEnabled), click: () => sendMenuCommand("view:sky-ground"), }, { label: "Arka Kenarlar (Back Edges)", type: "checkbox", checked: Boolean(menuUiState.backEdgesEnabled), accelerator: isClassicKeymap ? "K" : undefined, registerAccelerator: false, click: () => sendMenuCommand("view:back-edges"), }, { label: "X-Ray (Röntgen Modu)", type: "checkbox", checked: Boolean(menuUiState.xRayMode), accelerator: "X", registerAccelerator: false, click: () => sendMenuCommand("view:xray"), }, { label: "Kesit Düzlemi (Section Plane)", click: () => sendMenuCommand("tool:section") }, { type: "separator" }, { label: "Yüz Stili", submenu: [ { label: "Dokulu & Gölgeli", type: "radio", checked: menuUiState.visualStyle === "shaded", click: () => sendMenuCommand("view:style-shaded") }, { label: "Monokrom", type: "radio", checked: menuUiState.visualStyle === "monochrome", click: () => sendMenuCommand("view:style-monochrome") }, { label: "Gizli Çizgi (Hidden Line)", type: "radio", checked: menuUiState.visualStyle === "hidden-line", click: () => sendMenuCommand("view:style-hidden-line") }, { label: "Tel Kafes (Wireframe)", type: "radio", checked: menuUiState.visualStyle === "wireframe", click: () => sendMenuCommand("view:style-wireframe") }, { label: "Mimari Ozalit (Blueprint)", type: "radio", checked: menuUiState.visualStyle === "blueprint", click: () => sendMenuCommand("view:style-blueprint") }, { label: "Sıcak Kil (Clay)", type: "radio", checked: menuUiState.visualStyle === "clay", click: () => sendMenuCommand("view:style-clay") }, { label: "Cyberpunk", type: "radio", checked: menuUiState.visualStyle === "cyberpunk", click: () => sendMenuCommand("view:style-cyberpunk") }, ], }, { type: "separator" }, { label: "Etiketler / Katmanlar…", click: () => sendMenuCommand("view:layers") }, { label: "Güneş & Gölgeler Etüdü…", click: () => sendMenuCommand("view:solar") }, { label: "Kılavuz Çizgilerini Temizle", click: () => sendMenuCommand("view:clear-guides") }, { type: "separator" }, { role: "zoomIn", label: "Arayüzü Yakınlaştır" }, { role: "zoomOut", label: "Arayüzü Uzaklaştır" }, { role: "resetZoom", label: "Arayüz Yakınlaştırmasını Sıfırla" }, { type: "separator" }, { label: "Tam Ekran", type: "checkbox", checked: isFullScreen, accelerator: isMac ? "Ctrl+Cmd+F" : "F11", click: () => { if (!mainWindow || mainWindow.isDestroyed()) return; mainWindow.setFullScreen(!mainWindow.isFullScreen()); }, }, ], }, { label: "Kamera", submenu: [ { label: "İzometrik Görünüm", accelerator: "Home", registerAccelerator: false, click: () => sendMenuCommand("camera:isometric") }, { label: "Üst (Top)", accelerator: "5", registerAccelerator: false, click: () => sendMenuCommand("camera:top") }, { label: "Alt (Bottom)", accelerator: "6", registerAccelerator: false, click: () => sendMenuCommand("camera:bottom") }, { label: "Ön (Front)", accelerator: "1", registerAccelerator: false, click: () => sendMenuCommand("camera:front") }, { label: "Arka (Back)", accelerator: "2", registerAccelerator: false, click: () => sendMenuCommand("camera:back") }, { label: "Sol (Left)", accelerator: "3", registerAccelerator: false, click: () => sendMenuCommand("camera:left") }, { label: "Sağ (Right)", accelerator: "4", registerAccelerator: false, click: () => sendMenuCommand("camera:right") }, { type: "separator" }, { label: "Paralel İzdüşüm (Parallel Projection)", type: "checkbox", checked: Boolean(menuUiState.isOrthographic), accelerator: isClassicKeymap ? "Shift+V" : "O", registerAccelerator: false, click: () => sendMenuCommand("view:toggle-projection"), }, { label: "İki Kaçışlı Perspektif (2-Point)", click: () => sendMenuCommand("camera:two-point") }, { label: "Kamerayı Sıfırla", click: () => sendMenuCommand("view:reset-camera") }, { type: "separator" }, { label: "Yörünge (Orbit)", accelerator: isClassicKeymap ? "O" : undefined, registerAccelerator: false, click: () => sendMenuCommand("tool:orbit"), }, { label: "Kaydır (Pan)", accelerator: isClassicKeymap ? "H" : undefined, registerAccelerator: false, click: () => sendMenuCommand("tool:pan"), }, { label: "Yakınlaştır (Zoom)", accelerator: "Z", registerAccelerator: false, click: () => sendMenuCommand("tool:zoom") }, { label: "Ekrana Sığdır (Zoom Extents)", accelerator: "Shift+Z", registerAccelerator: false, click: () => sendMenuCommand("view:zoom-extents") }, { label: "Seçileni Çerçevele (Zoom Selection)", accelerator: "Alt+Z", registerAccelerator: false, click: () => sendMenuCommand("camera:zoom-selection") }, { label: "Önceki Görünüm (Previous)", accelerator: "Alt+P", registerAccelerator: false, click: () => sendMenuCommand("camera:previous") }, { type: "separator" }, { label: "İçinde Yürü (Walk / WASD)", click: () => sendMenuCommand("tool:walk") }, ], }, { label: "Çizim", submenu: [ { label: "Çizgi (Line)", accelerator: "L", registerAccelerator: false, click: () => sendMenuCommand("tool:line") }, { label: "Serbest / Eğri (Freehand)", click: () => sendMenuCommand("tool:freehand") }, { label: "Yay (2-Point Arc)", accelerator: "A", registerAccelerator: false, click: () => sendMenuCommand("tool:arc") }, { type: "separator" }, { label: "Dikdörtgen (Rectangle)", accelerator: "R", registerAccelerator: false, click: () => sendMenuCommand("tool:rectangle") }, { label: "Daire (Circle)", accelerator: "C", registerAccelerator: false, click: () => sendMenuCommand("tool:circle") }, { label: "Çokgen (Polygon)", click: () => sendMenuCommand("tool:polygon") }, { label: "3B Metin Ekle (3D Text)", click: () => sendMenuCommand("tool:3d-text") }, { type: "separator" }, { label: "Temel 3B Şekil Ekle", submenu: [ { label: "Kutu", click: () => sendMenuCommand("draw:shape-box") }, { label: "Silindir", click: () => sendMenuCommand("draw:shape-cylinder") }, { label: "Küre", click: () => sendMenuCommand("draw:shape-sphere") }, { label: "Koni", click: () => sendMenuCommand("draw:shape-cone") }, { label: "Piramit", click: () => sendMenuCommand("draw:shape-pyramid") }, { label: "Kama (Eğim)", click: () => sendMenuCommand("draw:shape-wedge") }, { label: "Yuvarlak Çatı", click: () => sendMenuCommand("draw:shape-round-roof") }, { label: "Yarım Küre", click: () => sendMenuCommand("draw:shape-half-sphere") }, { label: "Halka (Simit)", click: () => sendMenuCommand("draw:shape-torus") }, { label: "Boru", click: () => sendMenuCommand("draw:shape-tube") }, { label: "Dişli Çark", click: () => sendMenuCommand("draw:shape-gear") }, ], }, { type: "separator" }, { label: "2B Eskiz: Ekstrüde (Extrude)", click: () => sendMenuCommand("draw:sketch-extrude") }, { label: "2B Eskiz: Döndür (Revolve)", click: () => sendMenuCommand("draw:sketch-revolve") }, { label: "Seçili Eskizi Düzenle", click: () => sendMenuCommand("draw:sketch-edit") }, { type: "separator" }, { label: "Örnek Mimari Ev Sahnesi Oluştur", click: () => sendMenuCommand("draw:house-scene") }, ], }, { label: "Araçlar", submenu: [ { label: "Seçim (Select)", accelerator: "Space", registerAccelerator: false, click: () => sendMenuCommand("tool:select") }, { label: "Silgi (Eraser)", accelerator: "E", registerAccelerator: false, click: () => sendMenuCommand("tool:eraser") }, { label: "Boya Kovası (Paint Bucket)", accelerator: "B", registerAccelerator: false, click: () => sendMenuCommand("tool:paint") }, { type: "separator" }, { label: "Taşı (Move)", accelerator: "M", registerAccelerator: false, click: () => sendMenuCommand("tool:move") }, { label: "İt / Çek (Push/Pull)", accelerator: "P", registerAccelerator: false, click: () => sendMenuCommand("tool:push-pull") }, { label: "Döndür (Rotate)", accelerator: isClassicKeymap ? "Q" : undefined, registerAccelerator: false, click: () => sendMenuCommand("tool:rotate"), }, { label: "Ölçekle (Scale)", accelerator: "S", registerAccelerator: false, click: () => sendMenuCommand("tool:scale") }, { label: "Ofset (Offset)", accelerator: isClassicKeymap ? "F" : undefined, registerAccelerator: false, click: () => sendMenuCommand("tool:offset"), }, { label: "Beni Takip Et (Follow Me)…", click: () => sendMenuCommand("tool:follow-me") }, { type: "separator" }, { label: "Şerit Metre & Kılavuz", accelerator: "T", registerAccelerator: false, click: () => sendMenuCommand("tool:tape") }, { label: "İletki / Açılı Kılavuz", click: () => sendMenuCommand("tool:protractor") }, { label: "Eksenler / Çalışma Düzlemi", accelerator: "W", registerAccelerator: false, click: () => sendMenuCommand("tool:axes") }, { label: "Kesit Düzlemi (Section Plane)", click: () => sendMenuCommand("tool:section") }, { type: "separator" }, { label: "Duvar Kapı / Pencere Boşluğu Aç…", click: () => sendMenuCommand("tool:wall-opening") }, { label: "Arazi & Yükselti Üreticisi…", click: () => sendMenuCommand("tool:terrain") }, { label: "Mimari BIM, Kat & Metraj Stüdyosu…", accelerator: "Alt+M", registerAccelerator: false, click: () => sendMenuCommand("tool:bim-studio") }, { label: "Çok Katlı Bina & Kot Yöneticisi…", click: () => sendMenuCommand("tool:bim-storeys") }, { label: "Otomatik Metraj, Mahal Alanı & Keşif (BOQ)…", click: () => sendMenuCommand("tool:bim-boq") }, { label: "İmar Yönetmeliği & TS 9111 Denetçisi…", click: () => sendMenuCommand("tool:bim-code-audit") }, { label: "Statik & Deprem Dayanım Testi…", click: () => sendMenuCommand("tool:structural-test") }, { label: "Masamda Gör (AR Ön İzleme)…", click: () => sendMenuCommand("tool:ar-preview") }, { type: "separator" }, { label: "Fizik & Yerçekimi Simülasyonu (Başlat/Duraklat)", click: () => sendMenuCommand("tool:physics-toggle") }, { label: "Fizik Simülasyonunu Sıfırla", click: () => sendMenuCommand("tool:physics-reset") }, ], }, { label: "Pencere", submenu: [ { label: "Varsayılan Tepsi Bölümleri", submenu: [ { label: "Öğe Bilgisi (Entity Info)", click: () => sendMenuCommand("tray:entity-info") }, { label: "Ana Hatlar (Outliner)", click: () => sendMenuCommand("tray:outliner") }, { label: "Bileşenler (3B Havuz)", click: () => sendMenuCommand("tray:components") }, { label: "Malzemeler (Materials)", click: () => sendMenuCommand("tray:materials") }, { label: "Stiller (Styles)", click: () => sendMenuCommand("tray:styles") }, { label: "Etiketler (Tags / Layers)", click: () => sendMenuCommand("tray:tags") }, { label: "Gölgeler & Güneş (Shadows)", click: () => sendMenuCommand("tray:shadows") }, { label: "Sahneler (Scenes)", click: () => sendMenuCommand("tray:scenes") }, { label: "Eğitmen (Instructor)", click: () => sendMenuCommand("tray:instructor") }, ], }, { label: "Sağ Özellik Panelini Göster", type: "checkbox", checked: Boolean(menuUiState.showDefaultTray), click: () => sendMenuCommand("view:toggle-tray"), }, { type: "separator" }, { label: "Kısayol Profili: Mimari Klasik", type: "radio", checked: isClassicKeymap, click: () => sendMenuCommand("window:keymap-classic"), }, { label: "Kısayol Profili: SnapCAD Erişilebilir", type: "radio", checked: !isClassicKeymap, click: () => sendMenuCommand("window:keymap-standard"), }, { type: "separator" }, { label: "Hızlı Komut Paleti…", accelerator: "CmdOrCtrl+K", registerAccelerator: false, click: () => sendMenuCommand("window:command-palette") }, { label: "Erişilebilirlik & NVDA Kontrolleri…", accelerator: "Alt+A", registerAccelerator: false, click: () => sendMenuCommand("window:a11y") }, { label: "Model Bilgisi & Birim Ayarları…", click: () => sendMenuCommand("window:workspace-settings") }, { label: "Uygulama Ayarları…", click: () => sendMenuCommand("window:settings") }, { type: "separator" }, { label: "Kapatınca Gizli Simgelerde Tut", type: "checkbox", checked: Boolean(desktopPrefs.closeToTray), click: (menuItem) => { saveDesktopPrefs({ closeToTray: Boolean(menuItem.checked) }); }, }, { label: "Sistem Tepsisine Küçült", click: () => hideToTrayWindow({ showBalloonOnce: true }), }, ], }, { label: "Stüdyolar", submenu: [ { label: "3B Katı Tasarım (Projeler)", click: () => sendMenuCommand("file:dashboard") }, { label: "Teknik Çizim Stüdyosu", click: () => sendMenuCommand("window:drawing") }, { label: "Elektronik Devreler", click: () => sendMenuCommand("window:circuits") }, { label: "Kod Blokları", click: () => sendMenuCommand("window:codeblocks") }, { type: "separator" }, { label: "Sınıflar & Ortak Alanlar", click: () => sendMenuCommand("window:classrooms") }, { label: "Paylaşılan Projeler", click: () => sendMenuCommand("window:shared") }, { label: "Görevler ve Eğitimler", click: () => sendMenuCommand("window:challenges") }, { label: "Görünüm & Erişilebilirlik Merkezi", click: () => sendMenuCommand("window:customization") }, { type: "separator" }, { label: "Uygulama Ayarları…", click: () => sendMenuCommand("window:settings") }, ], }, { label: "Yardım", submenu: [ { label: "3B Sahne Denetçisi (Erişilebilir Rapor)", accelerator: "F2", registerAccelerator: false, click: () => sendMenuCommand("help:audit") }, { label: "Sesli / Metin CAD Komut Konsolu…", accelerator: "F4", registerAccelerator: false, click: () => sendMenuCommand("help:voice") }, { label: "Sesli 3B Radar Taraması", accelerator: "F8", registerAccelerator: false, click: () => sendMenuCommand("help:radar") }, { label: "Klavye Kısayolları", click: () => sendMenuCommand("help:shortcuts") }, { type: "separator" }, { label: "SnapCAD Akademi İnteraktif Eğitimi…", click: () => sendMenuCommand("help:tutorial") }, { label: "Günün Mimari Görevleri…", click: () => sendMenuCommand("help:daily-challenges") }, { type: "separator" }, { label: "Güncellemeleri Denetle…", click: () => void checkForDesktopUpdates(true) }, { label: "Kurumsal Bilgiler", submenu: [ { label: "Hakkımızda", click: () => sendMenuCommand("window:about") }, { label: "İletişim & Destek", click: () => sendMenuCommand("window:contact") }, { label: "KVKK & Gizlilik Politikası", click: () => sendMenuCommand("window:kvkk") }, { label: "Kullanım Koşulları", click: () => sendMenuCommand("window:terms") }, { label: "Kurumsal Güvenlik", click: () => sendMenuCommand("window:security") }, ], }, { label: `${APP_DISPLAY_NAME} Hakkında`, click: () => { void dialog.showMessageBox(mainWindow ?? undefined, { type: "info", title: `${APP_DISPLAY_NAME} Hakkında`, message: `${APP_DISPLAY_NAME} v${app.getVersion()}`, detail: [ "Yerel-öncelikli 3B Parametrik CAD, HLR Teknik Çizim, BIM (IFC) ve Elektronik Tasarım Stüdyosu.", "Geometri Çekirdekleri: Three.js + three-bvh-csg + three-edge-projection + Manifold + OpenCascade + PlaneGCS + Clipper2 + web-ifc", "Lisans: AGPL-3.0-only", ].join("\n"), }); }, }, ], }, ]; const appMenu = Menu.buildFromTemplate(template); Menu.setApplicationMenu(appMenu); desktopMenuBuilt = true; return appMenu; } function setupDesktopIpc() { if (desktopIpcConfigured) return; desktopIpcConfigured = true; ipcMain.handle("sketchforge:get-version", () => app.getVersion()); ipcMain.handle("sketchforge:check-for-updates", () => checkForDesktopUpdates(false)); ipcMain.handle("sketchforge:install-update", () => downloadAndInstallDesktopUpdate()); ipcMain.handle("snapcad:get-update-state", () => desktopUpdatePayload()); ipcMain.handle("snapcad:get-desktop-prefs", () => ({ ...desktopPrefs })); ipcMain.handle("snapcad:set-desktop-prefs", (_event, patch) => saveDesktopPrefs(patch)); ipcMain.handle("snapcad:hide-to-tray", () => { hideToTrayWindow({ showBalloonOnce: true }); return true; }); ipcMain.on("snapcad:get-auth-state-sync", (event) => { event.returnValue = { authenticated: Boolean(desktopAuthSession?.user), user: desktopAuthSession?.user ? { ...desktopAuthSession.user } : null, }; }); ipcMain.handle("snapcad:get-auth-state", () => ({ authenticated: Boolean(desktopAuthSession?.user), user: desktopAuthSession?.user ? { ...desktopAuthSession.user } : null, })); ipcMain.handle("snapcad:yaknet-login", () => startYakNetDesktopLogin()); ipcMain.handle("snapcad:yaknet-logout", () => logoutYakNetDesktop()); ipcMain.handle("snapcad:cloud-request", (_event, options) => proxyDesktopCloudRequest(options)); ipcMain.handle("snapcad:open-skf-dialog", async () => { const result = await dialog.showOpenDialog(mainWindow ?? undefined, { title: "SnapCAD Projesi Aç (.skf)", properties: ["openFile"], filters: [ { name: "SnapCAD Projesi (.skf)", extensions: ["skf"] }, { name: "Tüm Dosyalar", extensions: ["*"] }, ], }); if (result.canceled || result.filePaths.length === 0) return null; return readTrustedSkfFile(result.filePaths[0]); }); ipcMain.handle("snapcad:save-skf-dialog", async (_event, rawOptions) => { const options = rawOptions && typeof rawOptions === "object" ? rawOptions : {}; const bytes = options.bytes instanceof Uint8Array ? options.bytes : ArrayBuffer.isView(options.bytes) ? new Uint8Array(options.bytes.buffer, options.bytes.byteOffset, options.bytes.byteLength) : null; if (!bytes) { return { canceled: true, error: "Proje verisi gecersiz." }; } const defaultNameRaw = typeof options.defaultFileName === "string" && options.defaultFileName.trim() ? options.defaultFileName.trim() : "snapcad-proje.skf"; const defaultName = defaultNameRaw.toLowerCase().endsWith(".skf") ? defaultNameRaw : `${defaultNameRaw}.skf`; const requestedTarget = typeof options.targetPath === "string" && options.targetPath.trim() ? path.resolve(options.targetPath.trim()) : null; if (!options.forceDialog && requestedTarget && requestedTarget.toLowerCase().endsWith(".skf") && trustedDialogPaths.has(requestedTarget)) { const savedPath = writeFileAtomic(requestedTarget, bytes); return { canceled: false, filePath: savedPath, fileName: path.basename(savedPath) }; } const saveResult = await dialog.showSaveDialog(mainWindow ?? undefined, { title: "SnapCAD Projesini Kaydet", defaultPath: requestedTarget || path.join(app.getPath("documents"), defaultName), filters: [{ name: "SnapCAD Projesi (.skf)", extensions: ["skf"] }], }); if (saveResult.canceled || !saveResult.filePath) { return { canceled: true }; } const target = saveResult.filePath.toLowerCase().endsWith(".skf") ? saveResult.filePath : `${saveResult.filePath}.skf`; const savedPath = writeFileAtomic(target, bytes); return { canceled: false, filePath: savedPath, fileName: path.basename(savedPath) }; }); ipcMain.handle("snapcad:save-export-dialog", async (_event, rawOptions) => { const options = rawOptions && typeof rawOptions === "object" ? rawOptions : {}; const bytes = options.bytes instanceof Uint8Array ? options.bytes : ArrayBuffer.isView(options.bytes) ? new Uint8Array(options.bytes.buffer, options.bytes.byteOffset, options.bytes.byteLength) : null; if (!bytes) { return { canceled: true, error: "Disa aktarilacak veri gecersiz." }; } const defaultFileName = typeof options.defaultFileName === "string" && options.defaultFileName.trim() ? path.basename(options.defaultFileName.trim()) : "snapcad-export.stl"; const filters = Array.isArray(options.filters) && options.filters.length > 0 ? options.filters : [{ name: "Tüm Dosyalar", extensions: ["*"] }]; const saveResult = await dialog.showSaveDialog(mainWindow ?? undefined, { title: "Model / Teknik Çizim Dışa Aktar", defaultPath: path.join(app.getPath("documents"), defaultFileName), filters, }); if (saveResult.canceled || !saveResult.filePath) { return { canceled: true }; } const savedPath = writeFileAtomic(saveResult.filePath, bytes); return { canceled: false, filePath: savedPath, fileName: path.basename(savedPath) }; }); ipcMain.handle("snapcad:consume-pending-open-file", () => { if (!pendingOpenFilePath) return null; const queued = pendingOpenFilePath; pendingOpenFilePath = null; try { return readTrustedSkfFile(queued); } catch { return null; } }); ipcMain.handle("snapcad:set-dirty", (_event, dirty) => { isDocumentDirty = Boolean(dirty); }); ipcMain.handle("snapcad:set-window-title", (_event, title) => { if (mainWindow && !mainWindow.isDestroyed()) { mainWindow.setTitle(sanitizeWindowTitleInput(title)); } }); ipcMain.handle("snapcad:set-active-work-state", (_event, rawState) => { activeWorkState = sanitizeActiveWorkState(rawState); }); ipcMain.handle("snapcad:prepare-before-update-result", (_event, payload) => { const requestId = typeof payload?.requestId === "string" ? payload.requestId : ""; const resolver = pendingUpdatePrepareResolvers.get(requestId); if (resolver) { resolver(sanitizePrepareBeforeUpdateResult(payload?.result)); } }); ipcMain.handle("snapcad:confirm-close-after-save", () => { isDocumentDirty = false; explicitQuit = true; isQuitting = true; saveWindowStateImmediate(); if (mainWindow && !mainWindow.isDestroyed()) { mainWindow.destroy(); } app.quit(); }); ipcMain.handle("snapcad:confirm-update-after-save", () => { if (!pendingUpdateInstallAfterSave) return false; pendingUpdateInstallAfterSave = false; isDocumentDirty = false; installDownloadedUpdate(); return true; }); ipcMain.handle("snapcad:cancel-pending-update-install", () => { pendingUpdateInstallAfterSave = false; updateInstallRequested = false; }); ipcMain.handle("snapcad:open-external", (_event, rawUrl) => { if (!isAllowedExternalUrl(rawUrl)) return false; void shell.openExternal(String(rawUrl)); return true; }); ipcMain.handle("snapcad:set-menu-state", (_event, patch) => { updateMenuUiState(patch); }); } function setupDesktopUpdater() { if (updaterConfigured || !app.isPackaged) return; updaterConfigured = true; autoUpdater.autoDownload = false; autoUpdater.autoInstallOnAppQuit = false; autoUpdater.allowPrerelease = false; try { autoUpdater.setFeedURL({ provider: "generic", url: UPDATE_FEED_URL, }); } catch { // Fallback cleanly to bundled resources/app-update.yml if setFeedURL rejects. } autoUpdater.on("checking-for-update", () => { setUpdateState({ status: "checking", checkedAt: new Date().toISOString(), error: undefined, }); }); autoUpdater.on("update-available", (info) => { setUpdateState({ status: "available", latestVersion: info?.version || null, updateAvailable: true, downloaded: downloadedUpdateReady, checkedAt: new Date().toISOString(), error: undefined, }); if (!manualUpdateCheck) return; manualUpdateCheck = false; void dialog .showMessageBox(visibleDialogParent(), { type: "info", title: `${APP_DISPLAY_NAME} Güncellemesi`, buttons: ["İndir ve Kur", "Ayarları Aç", "Daha Sonra"], defaultId: 0, cancelId: 2, noLink: true, message: `${APP_DISPLAY_NAME} ${info.version} sürümü mevcut.`, detail: "Hemen indirip kurmak veya Ayarlar panelinden ilerlemeyi izlemek ister misiniz?", }) .then(({ response }) => { if (response === 0) { showMainWindow(); if (mainWindow && !mainWindow.isDestroyed()) { const expectedTotal = Number(info?.files?.[0]?.size || 0); mainWindow.webContents.send( "snapcad:open-update-progress", desktopUpdatePayload(null, "", { status: "downloading", latestVersion: info?.version || updateState.latestVersion || null, updateAvailable: true, progressPercent: 0, transferred: 0, total: Number.isFinite(expectedTotal) && expectedTotal > 0 ? expectedTotal : 0, bytesPerSecond: 0, }), ); } void downloadAndInstallDesktopUpdate(); } else if (response === 1) { sendMenuCommand("window:settings"); } }); }); autoUpdater.on("update-not-available", () => { setUpdateState({ status: "not-available", updateAvailable: false, downloaded: false, checkedAt: new Date().toISOString(), error: undefined, }); if (tray) tray.setToolTip(APP_DISPLAY_NAME); if (!manualUpdateCheck) return; manualUpdateCheck = false; void dialog.showMessageBox(visibleDialogParent(), { type: "info", title: `${APP_DISPLAY_NAME} Güncellemeleri`, message: `${APP_DISPLAY_NAME} en güncel sürümde (v${app.getVersion()}).`, }); }); autoUpdater.on("download-progress", (progress) => { const percent = Math.max(0, Math.min(100, Math.round(Number(progress?.percent || 0)))); if (tray) tray.setToolTip(`${APP_DISPLAY_NAME} — güncelleme indiriliyor (%${percent})`); setUpdateState({ status: "downloading", progressPercent: percent, bytesPerSecond: Number(progress?.bytesPerSecond || 0), transferred: Number(progress?.transferred || 0), total: Number(progress?.total || 0), error: undefined, }); }); autoUpdater.on("update-downloaded", (info) => { downloadedUpdateReady = true; updateTrayMenu(); if (tray) tray.setToolTip(`${APP_DISPLAY_NAME} v${info?.version || ""} kuruluma hazır`); setUpdateState({ status: "downloaded", latestVersion: info?.version || updateState.latestVersion, updateAvailable: true, downloaded: true, progressPercent: 100, error: undefined, }); if (updateInstallRequested) { updateInstallRequested = false; void prepareAndInstallDownloadedUpdate(); return; } void dialog .showMessageBox(visibleDialogParent(), { type: "info", title: `${APP_DISPLAY_NAME} Güncellemesi Hazır`, buttons: ["Şimdi Yeniden Başlat ve Kur", "Daha Sonra"], defaultId: 0, cancelId: 1, noLink: true, message: `${APP_DISPLAY_NAME} ${info?.version || ""} indirildi.`, detail: "Güncellemeyi tamamlamak için uygulamayı yeniden başlatabilirsiniz.", }) .then(({ response }) => { if (response === 0) { void prepareAndInstallDownloadedUpdate(); } }); }); autoUpdater.on("error", (error) => { updateInstallRequested = false; pendingUpdateInstallAfterSave = false; const friendly = formatFriendlyUpdateError(error); lastUpdateCheckError = friendly; if (tray) tray.setToolTip(APP_DISPLAY_NAME); setUpdateState({ status: "error", checkedAt: new Date().toISOString(), error: friendly, }); if (!manualUpdateCheck) return; manualUpdateCheck = false; dialog.showErrorBox(`${APP_DISPLAY_NAME} güncellenemedi`, friendly); }); setTimeout(() => void checkForDesktopUpdates(false), 4_000).unref(); setInterval(() => void checkForDesktopUpdates(false), 6 * 60 * 60 * 1000).unref(); } function updateTrayMenu() { if (!tray) return; const visible = Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isVisible()); tray.setContextMenu( Menu.buildFromTemplate([ { label: visible ? "Sistem Tepsisine Küçült" : `${APP_DISPLAY_NAME}'yu Göster`, click: () => { if (visible) { hideToTrayWindow(); } else { showMainWindow(); } }, }, { type: "separator" }, { label: "Kapatınca Gizli Simgelerde Tut", type: "checkbox", checked: Boolean(desktopPrefs.closeToTray), click: (menuItem) => { saveDesktopPrefs({ closeToTray: Boolean(menuItem.checked) }); }, }, downloadedUpdateReady ? { label: "Güncellemeyi Kur ve Yeniden Başlat", click: () => void prepareAndInstallDownloadedUpdate(), } : { label: "Güncellemeleri Denetle…", click: () => void checkForDesktopUpdates(true), }, { type: "separator" }, { label: "Tamamen Çıkış Yap", click: () => { if (downloadedUpdateReady) { void prepareAndInstallDownloadedUpdate(); return; } requestForceQuit(); }, }, ]), ); } function createTray() { if (tray) return; tray = new Tray(createTrayImage()); tray.setToolTip(APP_DISPLAY_NAME); updateTrayMenu(); tray.on("click", showMainWindow); tray.on("double-click", showMainWindow); } function createMainWindow(url) { const appOrigin = new URL(url).origin; const iconPath = appIconPath(); const initialState = loadSavedWindowState(); mainWindow = new BrowserWindow({ x: initialState.x, y: initialState.y, width: initialState.width, height: initialState.height, minWidth: 1100, minHeight: 700, show: false, backgroundColor: "#060810", title: APP_DISPLAY_NAME, icon: iconPath, webPreferences: { contextIsolation: true, nodeIntegration: false, sandbox: true, spellcheck: false, devTools: !app.isPackaged || Boolean(devUrl), preload: path.join(__dirname, "preload.cjs"), }, }); if (initialState.isMaximized) { mainWindow.maximize(); } mainWindow.on("resize", scheduleWindowStateSave); mainWindow.on("move", scheduleWindowStateSave); mainWindow.on("maximize", scheduleWindowStateSave); mainWindow.on("unmaximize", scheduleWindowStateSave); mainWindow.on("show", updateTrayMenu); mainWindow.on("hide", updateTrayMenu); mainWindow.on("enter-full-screen", () => { if (desktopMenuBuilt) buildNativeApplicationMenu(); }); mainWindow.on("leave-full-screen", () => { if (desktopMenuBuilt) buildNativeApplicationMenu(); }); mainWindow.on("app-command", (event, cmd) => { if (cmd === "browser-backward" || cmd === "browser-forward" || cmd === "browser-refresh") { event.preventDefault(); } }); mainWindow.webContents.on("before-input-event", (event, input) => { if (input.type !== "keyDown") return; const key = String(input.key || "").toLowerCase(); const ctrlOrMeta = Boolean(input.control || input.meta); // Block web browser navigation/refresh hotkeys inside desktop CAD runtime. if ( key === "f5" || (ctrlOrMeta && key === "r") || (ctrlOrMeta && key === "l") || (input.alt && (key === "arrowleft" || key === "arrowright")) || (app.isPackaged && !devUrl && (key === "f12" || (ctrlOrMeta && input.shift && key === "i") || (ctrlOrMeta && key === "u"))) ) { event.preventDefault(); } }); mainWindow.webContents.on("context-menu", (_event, params) => { if (!params.isEditable) return; const editableMenu = Menu.buildFromTemplate([ { role: "undo", label: "Geri Al", enabled: params.editFlags.canUndo }, { role: "redo", label: "Yinele", enabled: params.editFlags.canRedo }, { type: "separator" }, { role: "cut", label: "Kes", enabled: params.editFlags.canCut }, { role: "copy", label: "Kopyala", enabled: params.editFlags.canCopy }, { role: "paste", label: "Yapıştır", enabled: params.editFlags.canPaste }, { type: "separator" }, { role: "selectAll", label: "Tümünü Seç", enabled: params.editFlags.canSelectAll }, ]); editableMenu.popup({ window: mainWindow ?? undefined }); }); mainWindow.webContents.setWindowOpenHandler(({ url: targetUrl }) => { try { const target = new URL(targetUrl); if (target.origin === appOrigin) { if (target.pathname === "/login.php") { void startYakNetDesktopLogin(); return { action: "deny" }; } if (target.pathname === "/logout.php") { void logoutYakNetDesktop(); return { action: "deny" }; } return { action: "allow" }; } if (isAllowedExternalUrl(targetUrl)) { void shell.openExternal(targetUrl); } } catch { // Ignore malformed URLs instead of handing them to the OS. } return { action: "deny" }; }); mainWindow.webContents.on("will-navigate", (event, targetUrl) => { try { const target = new URL(targetUrl); if (target.origin === appOrigin) { if (target.pathname === "/login.php") { event.preventDefault(); void startYakNetDesktopLogin(); return; } if (target.pathname === "/logout.php") { event.preventDefault(); void logoutYakNetDesktop(); return; } return; } event.preventDefault(); if (isAllowedExternalUrl(targetUrl)) { void shell.openExternal(targetUrl); } } catch { event.preventDefault(); } }); mainWindow.webContents.on("render-process-gone", (_event, details) => { if (isQuitting || details.reason === "clean-exit") return; const choice = dialog.showMessageBoxSync(mainWindow ?? undefined, { type: "error", buttons: ["Çalışma Alanını Yeniden Başlat", "Uygulamayı Kapat"], defaultId: 0, cancelId: 1, title: `${APP_DISPLAY_NAME} Kurtarma`, message: "Grafik işleme motoru beklenmedik şekilde sonlandı.", detail: `Neden: ${details.reason}. Yerel projenizi geri yüklemek için yeniden başlatabilirsiniz.`, }); if (choice === 0 && mainWindow && !mainWindow.isDestroyed()) { mainWindow.reload(); } else { explicitQuit = true; isQuitting = true; app.quit(); } }); mainWindow.once("ready-to-show", () => { mainWindow?.show(); updateTrayMenu(); }); mainWindow.on("close", (event) => { saveWindowStateImmediate(); if (isQuitting) return; if (!explicitQuit && desktopPrefs.closeToTray) { event.preventDefault(); hideToTrayWindow({ showBalloonOnce: true }); return; } if (!isDocumentDirty) { isQuitting = true; return; } event.preventDefault(); if (closePromptOpen) return; closePromptOpen = true; showMainWindow(); void dialog .showMessageBox(mainWindow, { type: "warning", buttons: ["Kaydet ve Çık (.skf)", "Kaydetmeden Çık", "İptal"], defaultId: 0, cancelId: 2, noLink: true, title: `Kaydedilmemiş Değişiklikler — ${APP_DISPLAY_NAME}`, message: "Açık projede veya disk dosyasında kaydedilmemiş değişiklikler var.", detail: "Çıkmadan önce .skf proje dosyasına kaydetmek ister misiniz?", }) .then(({ response }) => { closePromptOpen = false; if (response === 0) { mainWindow?.webContents.send("snapcad:menu-command", "file:save-and-quit"); } else if (response === 1) { isDocumentDirty = false; explicitQuit = true; isQuitting = true; mainWindow?.destroy(); app.quit(); } else { explicitQuit = false; } }) .catch(() => { closePromptOpen = false; explicitQuit = false; }); }); mainWindow.on("closed", () => { for (const resolvePending of pendingUpdatePrepareResolvers.values()) { try { resolvePending(sanitizePrepareBeforeUpdateResult({ ...activeWorkState, localSaved: false })); } catch { // Ignore resolver cleanup failures. } } pendingUpdatePrepareResolvers.clear(); mainWindow = null; updateTrayMenu(); }); void mainWindow.loadURL(url); } async function startDesktop() { loadDesktopPrefs(); loadDesktopAuthSession(); buildNativeApplicationMenu(); try { const url = devUrl || (await startPackagedWebServer()); setupDesktopIpc(); createTray(); createMainWindow(url); setupDesktopUpdater(); } catch (error) { const message = error instanceof Error ? error.message : String(error); const detail = webServerOutput.trim(); dialog.showErrorBox( `${APP_DISPLAY_NAME} başlatılamadı`, detail ? `${message}\n\n${detail}` : message, ); app.quit(); } } pendingOpenFilePath = extractSkfFilePathFromArgv(process.argv); const hasSingleInstanceLock = app.requestSingleInstanceLock(); if (!hasSingleInstanceLock) { app.quit(); } else { app.on("second-instance", (_event, commandLine) => { showMainWindow(); const candidate = extractSkfFilePathFromArgv(commandLine); if (candidate) { deliverOrQueueSkfOpen(candidate); } }); app.on("open-file", (event, filePath) => { event.preventDefault(); if (filePath && filePath.toLowerCase().endsWith(".skf")) { deliverOrQueueSkfOpen(filePath); } }); app.whenReady().then(() => { app.setName(APP_DISPLAY_NAME); if (process.platform === "win32") app.setAppUserModelId(DESKTOP_APP_ID); void startDesktop(); app.on("activate", () => { if (mainWindow) { showMainWindow(); } else if (BrowserWindow.getAllWindows().length === 0) { void startDesktop(); } }); }); } app.on("before-quit", () => { isQuitting = true; closePendingOAuthServer(); saveWindowStateImmediate(); stopPackagedWebServer(); if (tray) { try { tray.destroy(); } catch { // Ignore tray teardown errors during shutdown. } tray = null; } }); app.on("window-all-closed", () => { if (downloadedUpdateReady) return; if (process.platform !== "darwin") { app.quit(); } });