diff --git a/.env.example b/.env.example
index 0c7dbf8..1c16196 100644
--- a/.env.example
+++ b/.env.example
@@ -34,3 +34,6 @@ SNAPCAD_MAX_STORAGE_BYTES_PER_USER='104857600'
# Client-supplied SSO payloads are never trusted. Use OAuth callback or a verified token.
SNAPCAD_ENABLE_CLIENT_SSO_SYNC='false'
+
+# Masaüstü uygulaması (SnapCAD.exe) oturum token geçerlilik süresi (gün). Aktif kullanımda otomatik uzar.
+SNAPCAD_DESKTOP_TOKEN_TTL_DAYS='180'
diff --git a/.gitignore b/.gitignore
index 32a336e..d5b84d7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -10,6 +10,7 @@ node_modules/
out/
build/
dist/
+/updates/
# Environment files
.env
@@ -53,6 +54,8 @@ apps/web/public/occt/
apps/web/public/dwgdxf/
apps/web/public/libredwg/
apps/web/public/libredwg-web/
+apps/web/public/ifc/
+apps/web/public/planegcs/
# PHP dependencies (install with composer install)
/vendor/
@@ -66,6 +69,7 @@ apps/web/public/libredwg-web/
/guvenlik/
/hakkimizda/
/icons/
+/ifc/
/iletisim/
/kullanim-kosullari/
/kurumsal-guvenlik/
@@ -73,6 +77,7 @@ apps/web/public/libredwg-web/
/libredwg/
/libredwg-web/
/occt/
+/planegcs/
/index.html
/index.txt
/404.html
diff --git a/apps/desktop/build-web.mjs b/apps/desktop/build-web.mjs
index 5bba9ff..1abf92a 100644
--- a/apps/desktop/build-web.mjs
+++ b/apps/desktop/build-web.mjs
@@ -6,7 +6,12 @@ import { fileURLToPath } from "node:url";
const desktopDir = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(desktopDir, "..", "..");
const nextBin = path.join(repoRoot, "node_modules", "next", "dist", "bin", "next");
-const copyOcctScript = path.join(repoRoot, "scripts", "copy-occt-wasm.mjs");
+const wasmCopyScripts = [
+ path.join(repoRoot, "scripts", "copy-occt-wasm.mjs"),
+ path.join(repoRoot, "scripts", "copy-dwg-wasm.mjs"),
+ path.join(repoRoot, "scripts", "copy-ifc-wasm.mjs"),
+ path.join(repoRoot, "scripts", "copy-planegcs-wasm.mjs"),
+];
function runNode(args, env = process.env) {
const result = spawnSync(process.execPath, args, {
@@ -25,7 +30,9 @@ function runNode(args, env = process.env) {
}
}
-runNode([copyOcctScript]);
+for (const scriptPath of wasmCopyScripts) {
+ runNode([scriptPath]);
+}
runNode([nextBin, "build", "apps/web"], {
...process.env,
SKETCHFORGE_DOCKER_BUILD: "true",
@@ -34,6 +41,7 @@ runNode([nextBin, "build", "apps/web"], {
const requiredPaths = [
path.join(repoRoot, "apps", "web", ".next", "standalone", "apps", "web", "server.js"),
+ path.join(repoRoot, "apps", "web", ".next", "standalone", "node_modules"),
path.join(repoRoot, "apps", "web", ".next", "static"),
path.join(repoRoot, "apps", "web", "public"),
];
@@ -45,4 +53,9 @@ for (const requiredPath of requiredPaths) {
}
}
-console.log("[desktop:web:build] Standalone SketchForge web bundle is ready.");
+const standaloneModulesSrc = path.join(repoRoot, "apps", "web", ".next", "standalone", "node_modules");
+const stagedRuntimeModules = path.join(repoRoot, "apps", "web", ".next", "desktop-runtime_modules");
+fs.rmSync(stagedRuntimeModules, { recursive: true, force: true });
+fs.cpSync(standaloneModulesSrc, stagedRuntimeModules, { recursive: true, dereference: true });
+
+console.log("[desktop:web:build] Standalone SnapCAD web bundle is ready.");
diff --git a/apps/desktop/dev.mjs b/apps/desktop/dev.mjs
index 51be8b5..2910599 100644
--- a/apps/desktop/dev.mjs
+++ b/apps/desktop/dev.mjs
@@ -7,7 +7,12 @@ import electronPath from "electron";
const desktopDir = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(desktopDir, "..", "..");
const nextBin = path.join(repoRoot, "node_modules", "next", "dist", "bin", "next");
-const copyOcctScript = path.join(repoRoot, "scripts", "copy-occt-wasm.mjs");
+const wasmCopyScripts = [
+ path.join(repoRoot, "scripts", "copy-occt-wasm.mjs"),
+ path.join(repoRoot, "scripts", "copy-dwg-wasm.mjs"),
+ path.join(repoRoot, "scripts", "copy-ifc-wasm.mjs"),
+ path.join(repoRoot, "scripts", "copy-planegcs-wasm.mjs"),
+];
const electronMain = path.join(desktopDir, "main.cjs");
function findFreePort() {
@@ -50,14 +55,16 @@ async function waitForUrl(url, child, timeoutMs = 45_000) {
throw new Error(`Timed out waiting for SketchForge dev server.${detail}`);
}
-const copyResult = spawnSync(process.execPath, [copyOcctScript], {
- cwd: repoRoot,
- stdio: "inherit",
- env: process.env,
-});
+for (const scriptPath of wasmCopyScripts) {
+ const copyResult = spawnSync(process.execPath, [scriptPath], {
+ cwd: repoRoot,
+ stdio: "inherit",
+ env: process.env,
+ });
-if (copyResult.status !== 0) {
- process.exit(copyResult.status ?? 1);
+ if (copyResult.status !== 0) {
+ process.exit(copyResult.status ?? 1);
+ }
}
const port = await findFreePort();
diff --git a/apps/desktop/electron-builder.yml b/apps/desktop/electron-builder.yml
index 458f9b9..651b36f 100644
--- a/apps/desktop/electron-builder.yml
+++ b/apps/desktop/electron-builder.yml
@@ -1,36 +1,61 @@
-appId: com.sketchforge.desktop
-productName: SketchForge
+appId: com.snapcad.desktop
+productName: SnapCAD Studio
+executableName: SnapCAD
asar: true
+npmRebuild: false
directories:
output: dist/desktop
publish:
- provider: github
- owner: Formsmith746
- repo: SketchForge-3D
- releaseType: release
+ provider: generic
+ url: https://snap.yakhub.com.tr/updates
+
+fileAssociations:
+ - ext: skf
+ name: SnapCAD Project
+ description: SnapCAD Studio 3D Parametric CAD Project
+ role: Editor
files:
- apps/desktop/main.cjs
- apps/desktop/preload.cjs
- package.json
+ - "!node_modules/**/*"
+ - "node_modules/electron-updater/**/*"
+ - "node_modules/builder-util-runtime/**/*"
+ - "node_modules/fs-extra/**/*"
+ - "node_modules/graceful-fs/**/*"
+ - "node_modules/jsonfile/**/*"
+ - "node_modules/universalify/**/*"
+ - "node_modules/js-yaml/**/*"
+ - "node_modules/argparse/**/*"
+ - "node_modules/debug/**/*"
+ - "node_modules/ms/**/*"
+ - "node_modules/lazy-val/**/*"
+ - "node_modules/lodash.escaperegexp/**/*"
+ - "node_modules/lodash.isequal/**/*"
+ - "node_modules/sax/**/*"
+ - "node_modules/semver/**/*"
+ - "node_modules/tiny-typed-emitter/**/*"
extraResources:
- from: apps/web/.next/standalone
to: web
+ - from: apps/web/.next/desktop-runtime_modules
+ to: web/runtime_modules
- from: apps/web/.next/static
to: web/apps/web/.next/static
- from: apps/web/public
to: web/apps/web/public
win:
- icon: apps/web/public/assets/sketchforge/sketchforge-logo.png
+ icon: apps/web/public/assets/sketchforge/sketchforge-logo.ico
target:
- target: nsis
arch:
- x64
- artifactName: ${productName}-Setup-${version}-${arch}.${ext}
+ artifactName: SnapCAD-Setup-${version}-${arch}.${ext}
nsis:
oneClick: false
@@ -44,7 +69,7 @@ mac:
- dmg
- zip
category: public.app-category.graphics-design
- artifactName: ${productName}-${version}-${arch}.${ext}
+ artifactName: SnapCAD-${version}-${arch}.${ext}
linux:
syncDesktopName: true
@@ -52,4 +77,4 @@ linux:
target:
- AppImage
category: Graphics
- artifactName: ${productName}-${version}-${arch}.${ext}
+ artifactName: SnapCAD-${version}-${arch}.${ext}
diff --git a/apps/desktop/main.cjs b/apps/desktop/main.cjs
index 0398107..be597f0 100644
--- a/apps/desktop/main.cjs
+++ b/apps/desktop/main.cjs
@@ -1,20 +1,47 @@
-const { app, BrowserWindow, Menu, Tray, dialog, ipcMain, nativeImage, shell } = require("electron");
+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;
@@ -23,6 +50,462 @@ let downloadedUpdateReady = false;
let updateInstallRequested = 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_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);
@@ -37,7 +520,7 @@ async function waitForServer(url, timeoutMs = 30_000) {
while (Date.now() < deadline) {
if (webServer && webServer.exitCode !== null) {
- throw new Error(`SketchForge web process exited with code ${webServer.exitCode}.`);
+ throw new Error(`SnapCAD yerel sunucu sureci kod ${webServer.exitCode} ile kapandi.`);
}
try {
@@ -51,17 +534,18 @@ async function waitForServer(url, timeoutMs = 30_000) {
}
const detail = lastError instanceof Error ? ` ${lastError.message}` : "";
- throw new Error(`SketchForge did not start its local web process in time.${detail}`);
+ 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(`Desktop web bundle is missing: ${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], {
@@ -71,7 +555,7 @@ async function startPackagedWebServer() {
env: {
...process.env,
ELECTRON_RUN_AS_NODE: "1",
- NODE_PATH: [packagedNodeModules, process.env.NODE_PATH].filter(Boolean).join(path.delimiter),
+ NODE_PATH: [runtimeNodeModules, packagedNodeModules, process.env.NODE_PATH].filter(Boolean).join(path.delimiter),
HOSTNAME: "127.0.0.1",
PORT: String(port),
SKETCHFORGE_DESKTOP: "1",
@@ -98,10 +582,29 @@ function stopPackagedWebServer() {
}
}
-function appIconPath() {
+function assetsDirPath() {
return devUrl
- ? path.join(__dirname, "..", "web", "public", "assets", "sketchforge", "sketchforge-logo.png")
- : path.join(process.resourcesPath, "web", "apps", "web", "public", "assets", "sketchforge", "sketchforge-logo.png");
+ ? 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() {
@@ -109,65 +612,172 @@ function showMainWindow() {
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 });
+ }
+ 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 installDownloadedUpdate() {
if (!downloadedUpdateReady) return;
+ explicitQuit = true;
isQuitting = true;
stopPackagedWebServer();
+ if (tray) {
+ try {
+ tray.destroy();
+ } catch {
+ // Ignore tray teardown errors during update restart.
+ }
+ tray = null;
+ }
setImmediate(() => autoUpdater.quitAndInstall(false, true));
}
async function downloadAndInstallDesktopUpdate() {
if (!app.isPackaged) {
- return desktopUpdatePayload(null, "Updates can only be installed from the packaged SketchForge app.");
+ return desktopUpdatePayload(
+ null,
+ "Güncellemeler yalnızca kurulu SnapCAD Studio (.exe) uygulamasında indirilebilir.",
+ { status: "unsupported" },
+ );
+ }
+
+ if (downloadedUpdateReady) {
+ installDownloadedUpdate();
+ return desktopUpdatePayload(lastUpdateCheckResult, "", { status: "downloaded", progressPercent: 100 });
}
lastUpdateCheckError = "";
try {
let result = lastUpdateCheckResult;
if (!result?.isUpdateAvailable) {
+ setUpdateState({ status: "checking", checkedAt: new Date().toISOString(), error: undefined });
result = await autoUpdater.checkForUpdates();
lastUpdateCheckResult = result;
}
if (!result?.isUpdateAvailable) {
+ setUpdateState({
+ status: "not-available",
+ latestVersion: result?.updateInfo?.version || null,
+ updateAvailable: false,
+ downloaded: false,
+ checkedAt: new Date().toISOString(),
+ error: undefined,
+ });
return desktopUpdatePayload(result);
}
updateInstallRequested = true;
+ setUpdateState({
+ status: "downloading",
+ latestVersion: result?.updateInfo?.version || null,
+ updateAvailable: true,
+ progressPercent: 0,
+ error: undefined,
+ });
await autoUpdater.downloadUpdate();
return desktopUpdatePayload(result);
} catch (error) {
updateInstallRequested = false;
- const message = error instanceof Error ? error.message : String(error);
+ const message = formatFriendlyUpdateError(error);
lastUpdateCheckError = message;
+ setUpdateState({
+ status: "error",
+ checkedAt: new Date().toISOString(),
+ error: message,
+ });
return desktopUpdatePayload(lastUpdateCheckResult, message);
}
}
-function desktopUpdatePayload(result = lastUpdateCheckResult, errorMessage = lastUpdateCheckError) {
- return {
- currentVersion: app.getVersion(),
- latestVersion: result?.updateInfo?.version || null,
- updateAvailable: Boolean(result?.isUpdateAvailable),
- downloaded: downloadedUpdateReady,
- checkedAt: new Date().toISOString(),
- error: errorMessage || undefined,
- };
+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({
+ await dialog.showMessageBox(visibleDialogParent(), {
type: "info",
- title: "SketchForge updates",
- message: "Automatic updates are tested from the installed SketchForge app.",
+ 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);
+ return desktopUpdatePayload(null, "", { status: "unsupported" });
}
if (downloadedUpdateReady) {
+ if (manual) {
+ const choice = await 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} ${updateState.latestVersion || ""} kurulumu tamamlanmaya hazır.`,
+ detail: "Uygulama kapatılıp yeni sürüm kurulacak ve ardından yeniden başlatılacaktır.",
+ });
+ if (choice.response === 0) {
+ installDownloadedUpdate();
+ }
+ }
return desktopUpdatePayload();
}
if (updateCheckInFlight) {
@@ -177,16 +787,31 @@ async function checkForDesktopUpdates(manual = false) {
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 = error instanceof Error ? error.message : String(error);
+ const message = formatFriendlyUpdateError(error);
lastUpdateCheckError = message;
+ setUpdateState({
+ status: "error",
+ checkedAt: new Date().toISOString(),
+ error: message,
+ });
if (manualUpdateCheck) {
- dialog.showErrorBox("Could not check for updates", message);
manualUpdateCheck = false;
+ dialog.showErrorBox("Güncellemeler denetlenemedi", message);
}
return desktopUpdatePayload(null, message);
} finally {
@@ -194,6 +819,955 @@ async function checkForDesktopUpdates(manual = 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: "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: "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;
@@ -201,6 +1775,140 @@ function setupDesktopIpc() {
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.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:confirm-close-after-save", () => {
+ isDocumentDirty = false;
+ explicitQuit = true;
+ isQuitting = true;
+ saveWindowStateImmediate();
+ if (mainWindow && !mainWindow.isDestroyed()) {
+ mainWindow.destroy();
+ }
+ app.quit();
+ });
+
+ 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() {
@@ -210,107 +1918,292 @@ function setupDesktopUpdater() {
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("update-available", (info) => {
- if (!manualUpdateCheck) return;
- manualUpdateCheck = false;
- void dialog.showMessageBox({
- type: "info",
- title: "SketchForge update",
- message: `SketchForge ${info.version} is available.`,
- detail: "Open Settings and press Update to install it.",
+ autoUpdater.on("checking-for-update", () => {
+ setUpdateState({
+ status: "checking",
+ checkedAt: new Date().toISOString(),
+ error: undefined,
});
});
- autoUpdater.on("update-not-available", () => {
+ 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({
+ 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();
+ 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: "SketchForge updates",
- message: "SketchForge is up to date.",
+ title: `${APP_DISPLAY_NAME} Güncellemeleri`,
+ message: `${APP_DISPLAY_NAME} en güncel sürümde (v${app.getVersion()}).`,
});
});
autoUpdater.on("download-progress", (progress) => {
- if (tray) tray.setToolTip(`SketchForge - downloading update ${Math.round(progress.percent)}%`);
+ 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;
- if (tray) tray.setToolTip(`SketchForge ${info.version} ready to install`);
- if (updateInstallRequested) installDownloadedUpdate();
+ 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) {
+ installDownloadedUpdate();
+ 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) {
+ installDownloadedUpdate();
+ }
+ });
});
autoUpdater.on("error", (error) => {
- if (tray) tray.setToolTip("SketchForge");
+ 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("Could not update SketchForge", error instanceof Error ? error.message : String(error));
+ 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: installDownloadedUpdate,
+ }
+ : {
+ label: "Güncellemeleri Denetle…",
+ click: () => void checkForDesktopUpdates(true),
+ },
+ { type: "separator" },
+ {
+ label: "Tamamen Çıkış Yap",
+ click: () => {
+ if (downloadedUpdateReady) {
+ installDownloadedUpdate();
+ return;
+ }
+ requestForceQuit();
+ },
+ },
+ ]),
+ );
+}
+
function createTray() {
if (tray) return;
- const icon = nativeImage.createFromPath(appIconPath()).resize({ width: 20, height: 20 });
- tray = new Tray(icon);
- tray.setToolTip("SketchForge");
- tray.setContextMenu(Menu.buildFromTemplate([
- {
- label: "Open SketchForge",
- click: showMainWindow,
- },
- {
- label: "Check for Updates",
- click: () => void checkForDesktopUpdates(true),
- },
- { type: "separator" },
- {
- label: "Quit SketchForge",
- click: () => {
- if (downloadedUpdateReady) {
- installDownloadedUpdate();
- return;
- }
- isQuitting = true;
- app.quit();
- },
- },
- ]));
+ 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({
- width: 1500,
- height: 960,
+ x: initialState.x,
+ y: initialState.y,
+ width: initialState.width,
+ height: initialState.height,
minWidth: 1100,
minHeight: 700,
show: false,
- title: "SketchForge",
+ 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"),
},
});
- mainWindow.removeMenu();
+ 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) return { action: "allow" };
- if (target.protocol === "http:" || target.protocol === "https:") {
+ 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 {
@@ -322,9 +2215,21 @@ function createMainWindow(url) {
mainWindow.webContents.on("will-navigate", (event, targetUrl) => {
try {
const target = new URL(targetUrl);
- if (target.origin === appOrigin) return;
+ 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 (target.protocol === "http:" || target.protocol === "https:") {
+ if (isAllowedExternalUrl(targetUrl)) {
void shell.openExternal(targetUrl);
}
} catch {
@@ -332,28 +2237,97 @@ function createMainWindow(url) {
}
});
+ 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();
- mainWindow?.hide();
+ 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", () => {
mainWindow = null;
+ updateTrayMenu();
});
void mainWindow.loadURL(url);
}
async function startDesktop() {
- Menu.setApplicationMenu(null);
+ loadDesktopPrefs();
+ loadDesktopAuthSession();
+ buildNativeApplicationMenu();
try {
- const url = devUrl || await startPackagedWebServer();
+ const url = devUrl || (await startPackagedWebServer());
setupDesktopIpc();
createTray();
createMainWindow(url);
@@ -362,22 +2336,38 @@ async function startDesktop() {
const message = error instanceof Error ? error.message : String(error);
const detail = webServerOutput.trim();
dialog.showErrorBox(
- "SketchForge could not start",
+ `${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", showMainWindow);
+ 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(() => {
- if (process.platform === "win32") app.setAppUserModelId("com.sketchforge.desktop");
+ app.setName(APP_DISPLAY_NAME);
+ if (process.platform === "win32") app.setAppUserModelId(DESKTOP_APP_ID);
void startDesktop();
app.on("activate", () => {
@@ -392,10 +2382,22 @@ if (!hasSingleInstanceLock) {
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", () => {
- // Keep SketchForge available from the system tray. Use Quit SketchForge
- // from the tray menu when the user wants to fully stop the application.
+ if (downloadedUpdateReady) return;
+ if (process.platform !== "darwin") {
+ app.quit();
+ }
});
diff --git a/apps/desktop/preload.cjs b/apps/desktop/preload.cjs
index 7a77a05..b5de2c7 100644
--- a/apps/desktop/preload.cjs
+++ b/apps/desktop/preload.cjs
@@ -1,7 +1,81 @@
const { contextBridge, ipcRenderer } = require("electron");
-contextBridge.exposeInMainWorld("sketchforgeDesktop", {
+function toUint8Array(data) {
+ if (data instanceof Uint8Array) return data;
+ if (data instanceof ArrayBuffer) return new Uint8Array(data);
+ if (ArrayBuffer.isView(data)) {
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
+ }
+ return new Uint8Array(0);
+}
+
+function subscribeChannel(channel, transform) {
+ return (listener) => {
+ if (typeof listener !== "function") return () => {};
+ const wrapped = (_event, payload) => {
+ listener(transform ? transform(payload) : payload);
+ };
+ ipcRenderer.on(channel, wrapped);
+ return () => {
+ ipcRenderer.removeListener(channel, wrapped);
+ };
+ };
+}
+
+function normalizeOpenedFile(payload) {
+ if (!payload || typeof payload.filePath !== "string" || typeof payload.fileName !== "string") {
+ return null;
+ }
+ return {
+ filePath: payload.filePath,
+ fileName: payload.fileName,
+ bytes: toUint8Array(payload.bytes),
+ };
+}
+
+const desktopBridge = Object.freeze({
+ isDesktop: true,
+ platform: process.platform,
getVersion: () => ipcRenderer.invoke("sketchforge:get-version"),
checkForUpdates: () => ipcRenderer.invoke("sketchforge:check-for-updates"),
installUpdate: () => ipcRenderer.invoke("sketchforge:install-update"),
+ getUpdateState: () => ipcRenderer.invoke("snapcad:get-update-state"),
+ onUpdateState: subscribeChannel("snapcad:update-state"),
+ getDesktopPrefs: () => ipcRenderer.invoke("snapcad:get-desktop-prefs"),
+ setDesktopPrefs: (patch) =>
+ ipcRenderer.invoke("snapcad:set-desktop-prefs", patch && typeof patch === "object" ? patch : {}),
+ hideToTray: () => ipcRenderer.invoke("snapcad:hide-to-tray"),
+ onDesktopPrefsChanged: subscribeChannel("snapcad:prefs-changed"),
+ startYakNetLogin: () => ipcRenderer.invoke("snapcad:yaknet-login"),
+ logoutYakNet: () => ipcRenderer.invoke("snapcad:yaknet-logout"),
+ cloudRequest: (options) =>
+ ipcRenderer.invoke("snapcad:cloud-request", options && typeof options === "object" ? options : {}),
+ onAuthUpdated: subscribeChannel("snapcad:auth-updated"),
+ openSkfDialog: async () => normalizeOpenedFile(await ipcRenderer.invoke("snapcad:open-skf-dialog")),
+ saveSkfDialog: (options) =>
+ ipcRenderer.invoke("snapcad:save-skf-dialog", {
+ defaultFileName: options?.defaultFileName,
+ targetPath: options?.targetPath ?? null,
+ forceDialog: Boolean(options?.forceDialog),
+ bytes: toUint8Array(options?.bytes),
+ }),
+ saveExportFileDialog: (options) =>
+ ipcRenderer.invoke("snapcad:save-export-dialog", {
+ defaultFileName: options?.defaultFileName,
+ filters: Array.isArray(options?.filters) ? options.filters : undefined,
+ bytes: toUint8Array(options?.bytes),
+ }),
+ consumePendingOpenFile: async () =>
+ normalizeOpenedFile(await ipcRenderer.invoke("snapcad:consume-pending-open-file")),
+ onOpenFile: subscribeChannel("snapcad:open-file", normalizeOpenedFile),
+ onMenuCommand: subscribeChannel("snapcad:menu-command"),
+ setMenuState: (state) =>
+ ipcRenderer.invoke("snapcad:set-menu-state", state && typeof state === "object" ? state : {}),
+ setDirty: (dirty) => ipcRenderer.invoke("snapcad:set-dirty", Boolean(dirty)),
+ setWindowTitle: (title) => ipcRenderer.invoke("snapcad:set-window-title", String(title ?? "")),
+ confirmCloseAfterSave: () => ipcRenderer.invoke("snapcad:confirm-close-after-save"),
+ openExternal: (url) => ipcRenderer.invoke("snapcad:open-external", String(url ?? "")),
});
+
+contextBridge.exposeInMainWorld("snapcadDesktop", desktopBridge);
+contextBridge.exposeInMainWorld("sketchforgeDesktop", desktopBridge);
diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts
index e64168d..e53dcf1 100644
--- a/apps/web/next.config.ts
+++ b/apps/web/next.config.ts
@@ -1,8 +1,28 @@
import type { NextConfig } from "next";
+import fs from "node:fs";
import path from "node:path";
+function readRootAppVersion(): string {
+ const candidates = [
+ path.resolve(process.cwd(), "package.json"),
+ path.resolve(process.cwd(), "..", "..", "package.json"),
+ ];
+ for (const candidate of candidates) {
+ try {
+ const parsed = JSON.parse(fs.readFileSync(candidate, "utf8")) as { version?: unknown };
+ if (typeof parsed.version === "string" && parsed.version.trim()) {
+ return parsed.version.trim();
+ }
+ } catch {
+ // Ignore missing or unreadable package.json candidate.
+ }
+ }
+ return "1.0.10";
+}
+
const isStaticExport = process.env.STATIC_EXPORT === "true";
const isDockerBuild = process.env.SKETCHFORGE_DOCKER_BUILD === "true";
+const appVersion = readRootAppVersion();
const extraAllowedDevOrigins = (process.env.SKETCHFORGE_ALLOWED_DEV_ORIGINS ?? "")
.split(",")
.map((origin) => origin.trim())
@@ -18,6 +38,7 @@ const nextConfig: NextConfig = {
allowedDevOrigins: ["localhost", "127.0.0.1", ...extraAllowedDevOrigins],
env: {
NEXT_PUBLIC_STATIC_EXPORT: isStaticExport ? "true" : "false",
+ NEXT_PUBLIC_APP_VERSION: appVersion,
},
images: {
unoptimized: true
diff --git a/apps/web/public/.htaccess b/apps/web/public/.htaccess
index 566b9ed..de0741a 100644
--- a/apps/web/public/.htaccess
+++ b/apps/web/public/.htaccess
@@ -6,6 +6,8 @@ ServerSignature Off
AddType application/wasm .wasm
AddType application/javascript .js .mjs
AddType image/svg+xml .svg
+ AddType text/yaml .yml
+ AddType application/octet-stream .exe .blockmap
@@ -26,8 +28,8 @@ ServerSignature Off
-# Service worker ve manifest güncellemeleri tarayıcıda takılı kalmasın.
-
+# Service worker, manifest ve masaüstü güncelleme bildirimleri önbellekte takılı kalmasın.
+
Header set Cache-Control "no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
diff --git a/apps/web/public/assets/sketchforge/sketchforge-logo.ico b/apps/web/public/assets/sketchforge/sketchforge-logo.ico
new file mode 100644
index 0000000..cb78c28
Binary files /dev/null and b/apps/web/public/assets/sketchforge/sketchforge-logo.ico differ
diff --git a/apps/web/public/sw.js b/apps/web/public/sw.js
index 940a97f..766c937 100644
--- a/apps/web/public/sw.js
+++ b/apps/web/public/sw.js
@@ -1,5 +1,5 @@
// SnapCAD Studio Progressive Web App (PWA) Service Worker
-const CACHE_NAME = "snapcad-v1.2.0";
+const CACHE_NAME = "snapcad-v1.2.1";
const PRECACHE_ASSETS = [
"/",
"/manifest.json",
diff --git a/apps/web/src/app/api/app-update/route.ts b/apps/web/src/app/api/app-update/route.ts
index 99dc176..bd56eca 100644
--- a/apps/web/src/app/api/app-update/route.ts
+++ b/apps/web/src/app/api/app-update/route.ts
@@ -10,8 +10,8 @@ import { SKF_CREATED_WITH_VERSION } from "@/lib/skfProject";
export const runtime = "nodejs";
export const revalidate = false;
-const DEFAULT_MANIFEST_URL = "https://raw.githubusercontent.com/Formsmith746/SketchForge-3D/main/package.json";
-const OFFICIAL_REPO_URL = "https://github.com/Formsmith746/SketchForge-3D.git";
+const DEFAULT_MANIFEST_URL = "https://snap.yakhub.com.tr/updates/latest.yml";
+const OFFICIAL_REPO_URL = "https://yakhub.com.tr/YakNet/snapcad-studio.git";
const UPDATE_CACHE_MS = 5 * 60 * 1000;
const UPDATE_TRIGGER_COOLDOWN_MS = 15 * 1000;
const execFileAsync = promisify(execFile);
@@ -103,14 +103,21 @@ async function latestOfficialVersion(force = false) {
try {
const response = await fetch(process.env.SKETCHFORGE_UPDATE_MANIFEST_URL?.trim() || DEFAULT_MANIFEST_URL, {
cache: "no-store",
- headers: { Accept: "application/json", "User-Agent": "SketchForge update checker" },
+ headers: { Accept: "application/json, text/yaml, text/plain", "User-Agent": "SnapCAD-Studio update checker" },
signal: controller.signal,
});
- if (!response.ok) throw new Error(`Update server returned ${response.status}`);
- const payload = await response.json() as { version?: unknown };
- const version = typeof payload.version === "string" ? payload.version.trim() : "";
+ if (!response.ok) throw new Error(`Güncelleme sunucusu yanıt vermedi (${response.status})`);
+ const rawText = await response.text();
+ let version = "";
+ try {
+ const payload = JSON.parse(rawText) as { version?: unknown };
+ version = typeof payload.version === "string" ? payload.version.trim() : "";
+ } catch {
+ const yamlMatch = rawText.match(/^\s*version:\s*['"]?([^\s'"]+)['"]?\s*$/m);
+ version = yamlMatch?.[1]?.trim() ?? "";
+ }
if (!VERSION_PATTERN.test(version)) {
- throw new Error("Update server returned an invalid version");
+ throw new Error("Güncelleme sunucusundan geçersiz sürüm bilgisi döndü");
}
cachedLatest = { version, expiresAt: Date.now() + UPDATE_CACHE_MS };
return version;
diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css
index 58c22bb..803ea28 100644
--- a/apps/web/src/app/globals.css
+++ b/apps/web/src/app/globals.css
@@ -1444,6 +1444,62 @@ button {
to { transform: rotate(360deg); }
}
+.dashboard-update-actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+}
+
+.dashboard-update-progress-track {
+ width: 100%;
+ height: 7px;
+ overflow: hidden;
+ border-radius: 999px;
+ background: #dce5ec;
+}
+
+.dashboard-update-progress-fill {
+ height: 100%;
+ border-radius: 999px;
+ background: linear-gradient(90deg, #0e69f1, #10b981);
+ transition: width 180ms ease;
+}
+
+.dashboard-desktop-toggle {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ color: #263f57;
+ font-size: 13px;
+ font-weight: 700;
+ cursor: pointer;
+}
+
+.dashboard-desktop-toggle input {
+ width: 16px;
+ height: 16px;
+ accent-color: #0e69f1;
+}
+
+.dashboard-tray-hide-btn {
+ display: inline-flex;
+ min-height: 34px;
+ align-items: center;
+ justify-content: center;
+ padding: 0 12px;
+ color: #31526b;
+ border: 1px solid #cbd9e3;
+ border-radius: 6px;
+ background: #ffffff;
+ font-size: 12.5px;
+ font-weight: 750;
+ cursor: pointer;
+}
+
+.dashboard-tray-hide-btn:hover {
+ background: #edf3f8;
+}
+
.dashboard-update-dialog {
width: min(500px, 100%);
}
@@ -7223,6 +7279,24 @@ html[data-theme="dark"] .dashboard-check-update {
background: #1b2a35;
}
+html[data-theme="dark"] .dashboard-update-progress-track {
+ background: #233442;
+}
+
+html[data-theme="dark"] .dashboard-desktop-toggle {
+ color: #e1edf5;
+}
+
+html[data-theme="dark"] .dashboard-tray-hide-btn {
+ color: #d8e6f1;
+ border-color: #3a4e5d;
+ background: #1b2a35;
+}
+
+html[data-theme="dark"] .dashboard-tray-hide-btn:hover {
+ background: #243644;
+}
+
html[data-theme="dark"] .dashboard-update-safety,
html[data-theme="dark"] .dashboard-update-note,
html[data-theme="dark"] .dashboard-update-message {
@@ -14230,7 +14304,7 @@ html[data-theme="light"] .email-meta-label {
}
.snapcad-page-transition {
- animation: snapcad-smooth-page-enter 0.35s cubic-bezier(0.16, 1, 0.3, 1) both;
+ animation: snapcad-smooth-page-enter 0.35s cubic-bezier(0.16, 1, 0.3, 1) backwards;
}
/* 2. Full-Screen Preloader */
@@ -14405,31 +14479,31 @@ html[data-theme="light"] .preloader-status-text {
}
.gcp-cascade-topbar {
- animation: gcp-cascade-down 0.4s cubic-bezier(0.16, 1, 0.3, 1) 0ms both;
+ animation: gcp-cascade-down 0.4s cubic-bezier(0.16, 1, 0.3, 1) 0ms backwards;
}
.gcp-cascade-sidebar {
- animation: gcp-cascade-down 0.42s cubic-bezier(0.16, 1, 0.3, 1) 70ms both;
+ animation: gcp-cascade-down 0.42s cubic-bezier(0.16, 1, 0.3, 1) 70ms backwards;
}
.gcp-cascade-actions {
- animation: gcp-cascade-down 0.44s cubic-bezier(0.16, 1, 0.3, 1) 130ms both;
+ animation: gcp-cascade-down 0.44s cubic-bezier(0.16, 1, 0.3, 1) 130ms backwards;
}
.gcp-cascade-starters {
- animation: gcp-cascade-down 0.44s cubic-bezier(0.16, 1, 0.3, 1) 190ms both;
+ animation: gcp-cascade-down 0.44s cubic-bezier(0.16, 1, 0.3, 1) 190ms backwards;
}
.gcp-cascade-header {
- animation: gcp-cascade-down 0.44s cubic-bezier(0.16, 1, 0.3, 1) 250ms both;
+ animation: gcp-cascade-down 0.44s cubic-bezier(0.16, 1, 0.3, 1) 250ms backwards;
}
.gcp-cascade-card {
- animation: gcp-cascade-down 0.48s cubic-bezier(0.16, 1, 0.3, 1) both;
+ animation: gcp-cascade-down 0.48s cubic-bezier(0.16, 1, 0.3, 1) backwards;
}
.gcp-cascade-footer {
- animation: gcp-cascade-down 0.48s cubic-bezier(0.16, 1, 0.3, 1) 400ms both;
+ animation: gcp-cascade-down 0.48s cubic-bezier(0.16, 1, 0.3, 1) 400ms backwards;
}
/* --- Google Cloud Console Linear Progress Bar --- */
@@ -15856,4 +15930,30 @@ html[data-theme="light"] .tray-instructor-steps {
}
}
+html[data-desktop-runtime="true"],
+html[data-desktop-runtime="true"] body {
+ overscroll-behavior: none;
+}
+
+html[data-desktop-runtime="true"] #nprogress {
+ display: none !important;
+}
+
+html[data-desktop-runtime="true"] .sketchforge-editor,
+html[data-desktop-runtime="true"] .sketchup-menubar,
+html[data-desktop-runtime="true"] .enterprise-topbar,
+html[data-desktop-runtime="true"] .secondary-toolbar {
+ user-select: none;
+}
+
+html[data-desktop-runtime="true"] input,
+html[data-desktop-runtime="true"] textarea,
+html[data-desktop-runtime="true"] select,
+html[data-desktop-runtime="true"] [contenteditable="true"],
+html[data-desktop-runtime="true"] pre,
+html[data-desktop-runtime="true"] code {
+ user-select: text;
+}
+
+
diff --git a/apps/web/src/app/layout.tsx b/apps/web/src/app/layout.tsx
index 80bbdee..0477554 100644
--- a/apps/web/src/app/layout.tsx
+++ b/apps/web/src/app/layout.tsx
@@ -1,7 +1,7 @@
import type { Metadata } from "next";
import NextTopLoader from "nextjs-toploader";
import { AppErrorBoundary } from "@/components/snapcad/AppErrorBoundary";
-import { PwaManager } from "@/components/snapcad/PwaManager";
+import { WebRuntimeChrome } from "@/components/snapcad/WebRuntimeChrome";
import "./globals.css";
export const metadata: Metadata = {
@@ -57,6 +57,9 @@ export default function RootLayout({
var isDark = theme === "dark" || (theme === "system" && window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches);
document.documentElement.setAttribute("data-theme", isDark ? "dark" : "light");
document.documentElement.style.backgroundColor = isDark ? "#060810" : "#fafafa";
+ if (window.snapcadDesktop || window.sketchforgeDesktop || /\bElectron\//i.test(navigator.userAgent || "")) {
+ document.documentElement.setAttribute("data-desktop-runtime", "true");
+ }
} catch(e) {}
})()`,
}}
@@ -75,7 +78,7 @@ export default function RootLayout({
shadow="0 0 10px #38bdf8,0 0 5px #0284c7"
/>
{children}
-
+