Luca448 commited on
Commit
1435006
·
1 Parent(s): 536aa4b

Savestate: Add gemini-3.5-flash-lite and gemini-3.6-flash models to dropdowns and Dynamic Island

Browse files
index.html CHANGED
@@ -65,7 +65,7 @@
65
  </head>
66
  <body class="dark-theme in-chat-view">
67
 
68
- <div id="live-version-badge" style="position: fixed; top: 50px; left: 50%; transform: translateX(-50%); font-size: 10px; color: var(--text-secondary); opacity: 0.6; z-index: 99999; pointer-events: none; font-weight: 500; font-family: monospace; letter-spacing: 1px; background: rgba(0,0,0,0.2); padding: 2px 8px; border-radius: 10px; border: 1px solid rgba(255,255,255,0.05);">BUILD 1.8.210</div>
69
 
70
  <!-- SVG Filters for Liquid Glass Refraction -->
71
  <svg width="0" height="0" style="position: absolute; pointer-events: none;">
 
65
  </head>
66
  <body class="dark-theme in-chat-view">
67
 
68
+ <div id="live-version-badge" style="position: fixed; top: 50px; left: 50%; transform: translateX(-50%); font-size: 10px; color: var(--text-secondary); opacity: 0.6; z-index: 99999; pointer-events: none; font-weight: 500; font-family: monospace; letter-spacing: 1px; background: rgba(0,0,0,0.2); padding: 2px 8px; border-radius: 10px; border: 1px solid rgba(255,255,255,0.05);">BUILD 1.8.211</div>
69
 
70
  <!-- SVG Filters for Liquid Glass Refraction -->
71
  <svg width="0" height="0" style="position: absolute; pointer-events: none;">
src/views/chat/chat-view.js CHANGED
@@ -2164,7 +2164,9 @@ body { margin: 0; padding: 0; background: #000; overflow: hidden; display: flex;
2164
 
2165
  const modelNames = {
2166
  // Gemini
 
2167
  'gemini-3.5-flash': 'Gemini 3.5 Flash',
 
2168
  'gemini-3.1-flash-lite': 'Gemini 3.1 Flash Lite',
2169
  'gemini-3-flash-preview': 'Gemini 3 Flash Preview',
2170
  'gemini-2.5-flash': 'Gemini 2.5 Flash',
@@ -2230,7 +2232,9 @@ body { margin: 0; padding: 0; background: #000; overflow: hidden; display: flex;
2230
  {
2231
  title: 'Gemini',
2232
  models: [
 
2233
  { id: 'gemini-3.5-flash', desc: '' },
 
2234
  { id: 'gemini-3.1-flash-lite', desc: '' },
2235
  { id: 'gemini-3-flash-preview', desc: '' },
2236
  { id: 'gemini-2.5-flash', desc: '' }
 
2164
 
2165
  const modelNames = {
2166
  // Gemini
2167
+ 'gemini-3.6-flash': 'Gemini 3.6 Flash',
2168
  'gemini-3.5-flash': 'Gemini 3.5 Flash',
2169
+ 'gemini-3.5-flash-lite': 'Gemini 3.5 Flash Lite',
2170
  'gemini-3.1-flash-lite': 'Gemini 3.1 Flash Lite',
2171
  'gemini-3-flash-preview': 'Gemini 3 Flash Preview',
2172
  'gemini-2.5-flash': 'Gemini 2.5 Flash',
 
2232
  {
2233
  title: 'Gemini',
2234
  models: [
2235
+ { id: 'gemini-3.6-flash', desc: '' },
2236
  { id: 'gemini-3.5-flash', desc: '' },
2237
+ { id: 'gemini-3.5-flash-lite', desc: '' },
2238
  { id: 'gemini-3.1-flash-lite', desc: '' },
2239
  { id: 'gemini-3-flash-preview', desc: '' },
2240
  { id: 'gemini-2.5-flash', desc: '' }
src/views/scan/scan-view.js CHANGED
@@ -1,906 +1,908 @@
1
- import perspective from '../../utils/perspective.js';
2
- import { gemini } from '../../ai/gemini.js';
3
- import { db } from '../../db/database.js';
4
- import { Camera } from '@capacitor/camera';
5
- import { fsService } from '../../services/file-system.js';
6
- import { folderAgent } from '../../ai/folder-agent.js?v=2';
7
-
8
- export class ScanView {
9
- constructor(containerId) {
10
- this.container = document.getElementById(containerId);
11
- this.isProcessing = false;
12
- this.stream = null;
13
- }
14
-
15
- destroy() {
16
- if (this.stream) {
17
- this.stream.getTracks().forEach(track => track.stop());
18
- this.stream = null;
19
- }
20
- }
21
-
22
- async init() {
23
- // Add handwriting font if not present
24
- if (!document.getElementById('font-caveat')) {
25
- const link = document.createElement('link');
26
- link.id = 'font-caveat';
27
- link.rel = 'stylesheet';
28
- link.href = 'https://fonts.googleapis.com/css2?family=Caveat:wght@400;700&display=swap';
29
- document.head.appendChild(link);
30
- }
31
- }
32
-
33
- render() {
34
-
35
- this.container.innerHTML = `
36
- <div style="padding: 24px; padding-top: calc(env(safe-area-inset-top, 20px) + 24px); max-width: 800px; margin: 0 auto; display: flex; flex-direction: column; gap: 24px; height: 100%; box-sizing: border-box; position: relative;">
37
-
38
- <!-- Header -->
39
- <div style="position: relative; margin-bottom: 16px;">
40
- <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 8px;">
41
- <button onclick="window.openView('Hub')" class="icon-btn" style="background: transparent; padding: 0; width: 32px; height: 32px; display: flex; align-items: center; justify-content: center; color: var(--text-secondary);">
42
- <svg viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"></polyline></svg>
43
- </button>
44
- <h2 style="font-size: 24px; font-weight: 600; margin: 0;">Arbeitsblatt Scan</h2>
45
- </div>
46
- <p style="color: var(--text-secondary); font-size: 14px;">Mache ein Foto deines leeren Arbeitsblattes. Die KI löst die Aufgaben und füllt es in Handschrift für dich aus.</p>
47
- </div>
48
-
49
- <!-- Crop Modal Overlay -->
50
- <div id="crop-modal" style="display: none; position: absolute; inset: 0; background: #000; z-index: 100; flex-direction: column; border-radius: 16px; overflow: hidden;">
51
- <div style="padding: 16px; background: rgba(255,255,255,0.1); text-align: center; color: white; font-weight: 500;">Passe die Ecken an das Blatt an</div>
52
- <div id="crop-area" style="flex: 1; position: relative; overflow: hidden; touch-action: none;">
53
- <img id="crop-img" style="position: absolute; top: 0; left: 0; transform-origin: top left; pointer-events: none;" />
54
- <svg id="crop-svg" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none;">
55
- <polygon id="crop-polygon" fill="rgba(64, 156, 255, 0.2)" stroke="#409cff" stroke-width="2"></polygon>
56
- <!-- We will generate grid lines dynamically in JS -->
57
- <g id="crop-grid-group"></g>
58
- </svg>
59
- <!-- 4 Drag Handles -->
60
- <div class="crop-handle" data-index="0" style="position: absolute; width: 30px; height: 30px; background: rgba(64,156,255,0.8); border: 2px solid white; border-radius: 50%; transform: translate(-50%, -50%); cursor: grab; touch-action: none;"></div>
61
- <div class="crop-handle" data-index="1" style="position: absolute; width: 30px; height: 30px; background: rgba(64,156,255,0.8); border: 2px solid white; border-radius: 50%; transform: translate(-50%, -50%); cursor: grab; touch-action: none;"></div>
62
- <div class="crop-handle" data-index="2" style="position: absolute; width: 30px; height: 30px; background: rgba(64,156,255,0.8); border: 2px solid white; border-radius: 50%; transform: translate(-50%, -50%); cursor: grab; touch-action: none;"></div>
63
- <div class="crop-handle" data-index="3" style="position: absolute; width: 30px; height: 30px; background: rgba(64,156,255,0.8); border: 2px solid white; border-radius: 50%; transform: translate(-50%, -50%); cursor: grab; touch-action: none;"></div>
64
- </div>
65
- <div style="padding: 16px; display: flex; gap: 12px; background: rgba(255,255,255,0.05);">
66
- <button id="crop-cancel-btn" style="flex: 1; padding: 12px; background: rgba(255,255,255,0.1); color: white; border: none; border-radius: 8px;">Abbrechen</button>
67
- <button id="crop-confirm-btn" class="primary-btn" style="flex: 2; padding: 12px; justify-content: center;">Zuschneiden & Analysieren</button>
68
- </div>
69
- </div>
70
-
71
-
72
- <!-- Upload & Camera Area -->
73
- <div id="scan-upload-area" style="flex: 1; display: flex; flex-direction: column; gap: 16px;">
74
-
75
- <!-- Camera Preview Container -->
76
- <div id="camera-container" style="display: none; flex: 1; border-radius: 16px; overflow: hidden; position: relative; background: #000; min-height: 350px; box-shadow: 0 8px 32px rgba(0,0,0,0.3);">
77
- <video id="camera-video" autoplay playsinline style="width: 100%; height: 100%; object-fit: cover;"></video>
78
- <button id="camera-capture-btn" style="position: absolute; bottom: 24px; left: 50%; transform: translateX(-50%); width: 64px; height: 64px; border-radius: 50%; background: rgba(255,255,255,0.3); border: 4px solid #fff; cursor: pointer; backdrop-filter: blur(4px); box-shadow: 0 4px 16px rgba(0,0,0,0.3); transition: transform 0.1s;"></button>
79
- <button id="camera-close-btn" class="icon-btn" style="position: absolute; top: 16px; right: 16px; background: rgba(0,0,0,0.5); color: #fff;">
80
- <svg viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" stroke-width="2" fill="none"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
81
- </button>
82
- </div>
83
-
84
- <div id="scan-action-buttons" style="flex: 1; border: 2px dashed rgba(255,255,255,0.2); border-radius: 16px; display: flex; flex-direction: column; align-items: center; justify-content: center; background: rgba(255,255,255,0.02); min-height: 200px; padding: 24px;">
85
- <svg viewBox="0 0 24 24" width="48" height="48" stroke="currentColor" stroke-width="1.5" fill="none" style="opacity: 0.5; margin-bottom: 16px;"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg>
86
-
87
- <div style="display: flex; gap: 12px; width: 100%; max-width: 300px;">
88
- <button id="scan-open-camera-btn" class="primary-btn" style="flex: 1; justify-content: center; padding: 12px;">
89
- <svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" stroke-width="2" fill="none" style="margin-right: 8px;"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"></path><circle cx="12" cy="13" r="4"></circle></svg>
90
- Kamera
91
- </button>
92
-
93
- <button id="scan-upload-file-btn" style="flex: 1; justify-content: center; padding: 12px; background: rgba(255,255,255,0.1); border-radius: 8px; color: #fff; font-weight: 500; border: none; cursor: pointer; display: flex; align-items: center;">
94
- <svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" stroke-width="2" fill="none" style="margin-right: 8px;"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="17 8 12 3 7 8"></polyline><line x1="12" y1="3" x2="12" y2="15"></line></svg>
95
- Datei
96
- </button>
97
- <input type="file" id="scan-file-input" accept="image/*" capture="environment" style="display: none;" />
98
- </div>
99
-
100
- <div style="margin-top: 24px; width: 100%; max-width: 300px; padding-top: 16px; border-top: 1px solid rgba(255,255,255,0.1);">
101
- <label style="display: block; font-size: 12px; color: rgba(255,255,255,0.6); margin-bottom: 6px; text-align: left;">Scan-Modell</label>
102
- <select id="scan-local-model" style="width: 100%; padding: 10px; border-radius: 8px; background: rgba(0,0,0,0.4); border: 1px solid rgba(255,255,255,0.1); color: white; font-size: 14px; outline: none; appearance: none;">
103
- <option value="gemini-3.5-flash">Gemini 3.5 Flash (Schnell & Standard)</option>
104
- <option value="gemini-3.1-flash-lite">Gemini 3.1 Flash Lite (Effizient)</option>
105
- <option value="gemini-3-flash-preview">Gemini 3 Flash Preview (Sehr Stabil)</option>
106
- <option value="gemini-2.5-flash">Gemini 2.5 Flash</option>
107
- <option value="gemini-2.5-flash-lite">Gemini 2.5 Flash Lite</option>
108
- <option value="gemma-4-31b-it">Gemma 4 31B (Open Weights)</option>
109
- <option value="groq-llama-3.3-70b-versatile">Llama 3.3 70B (Groq)</option>
110
- <option value="local-phone-qwen">Lokal Handy (Qwen 1.5B)</option>
111
- <option value="local-pc-llama">Lokal PC (Llama 3 8B)</option>
112
- </select>
113
- </div>
114
- </div>
115
- </div>
116
-
117
- <!-- Processing State -->
118
- <div id="scan-processing" style="display: none; flex-direction: column; align-items: center; justify-content: center; padding: 40px; background: rgba(255,255,255,0.05); border-radius: 16px;">
119
- <div style="width: 40px; height: 40px; border: 3px solid rgba(255,255,255,0.1); border-top-color: var(--primary-color); border-radius: 50%; animation: spin 1s linear infinite; margin-bottom: 16px;"></div>
120
- <div id="scan-processing-text" style="font-weight: 500;">Analysiere Arbeitsblatt...</div>
121
- <div style="font-size: 13px; color: var(--text-secondary); margin-top: 8px; text-align: center;">Die KI liest die Aufgaben, berechnet die Lösungen und ermittelt die perfekten Koordinaten zum Ausfüllen. Das dauert ca. 5-10 Sekunden.</div>
122
- </div>
123
-
124
- <!-- Result Area -->
125
- <div id="scan-result-area" style="display: none; flex-direction: column; gap: 16px;">
126
- <div id="scan-result-img-container" style="position: relative; border-radius: 12px; overflow: hidden; background: #fff; box-shadow: 0 8px 32px rgba(0,0,0,0.3); cursor: zoom-in;">
127
- <canvas id="scan-canvas" style="width: 100%; height: auto; display: block;"></canvas>
128
- </div>
129
-
130
- <div style="display: flex; gap: 12px; width: 100%;">
131
- <button id="scan-download-btn" class="primary-btn" style="flex: 1; padding: 16px; font-size: 16px; justify-content: center;">
132
- <svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" stroke-width="2" fill="none" style="margin-right: 8px;"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
133
- Speichern
134
- </button>
135
- <button id="scan-vault-btn" class="liquid-glass-heavy" style="flex: 1; padding: 16px; font-size: 16px; justify-content: center; font-weight: 500; display: flex; align-items: center; border-radius: 16px;">
136
- <svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" stroke-width="2" fill="none" style="margin-right: 8px;"><path d="M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2Z"/></svg>
137
- In Vault
138
- </button>
139
- <button id="scan-flashcards-btn" class="liquid-glass-heavy" style="flex: 1; padding: 16px; font-size: 16px; justify-content: center; font-weight: 500; display: flex; align-items: center; border-radius: 16px;">
140
- <svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" stroke-width="2" fill="none" style="margin-right: 8px;"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"></path><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"></path></svg>
141
- Lernen
142
- </button>
143
- </div>
144
-
145
- <div id="scan-explanation" style="padding: 16px; background: rgba(255,255,255,0.05); border-radius: 12px; font-size: 14px; line-height: 1.5; color: var(--text-primary); border-left: 4px solid var(--primary-color);">
146
- <!-- Explanation will appear here -->
147
- </div>
148
-
149
- <button id="scan-reset-btn" class="icon-btn" style="align-self: center; margin-top: 8px; padding: 8px 16px; background: rgba(255,255,255,0.1); border-radius: 20px;">
150
- Neues Arbeitsblatt einscannen
151
- </button>
152
- </div>
153
-
154
- <!-- Fullscreen Viewer Modal -->
155
- <div id="scan-fullscreen-modal" style="display: none; position: fixed; inset: 0; background: #000; z-index: 1000; flex-direction: column;">
156
- <div style="padding: 16px; display: flex; justify-content: space-between; align-items: center; background: rgba(0,0,0,0.5); position: absolute; top: 0; left: 0; right: 0; z-index: 1001;">
157
- <button id="fullscreen-close-btn" class="icon-btn" style="color: white; font-size: 24px;">✕</button>
158
- <span style="color: white; font-weight: 500;">Vollbild (Pinch to zoom)</span>
159
- <div style="width: 24px;"></div>
160
- </div>
161
- <div style="flex: 1; overflow: auto; display: flex; align-items: center; justify-content: center; touch-action: pan-x pan-y pinch-zoom;">
162
- <img id="scan-fullscreen-img" style="max-width: 200%; max-height: none; width: 100%; object-fit: contain; transition: transform 0.2s;" />
163
- </div>
164
- </div>
165
-
166
-
167
- </div>
168
- `;
169
-
170
- this.bindEvents();
171
- }
172
-
173
- bindEvents() {
174
- const fileInput = document.getElementById('scan-file-input');
175
- const resetBtn = document.getElementById('scan-reset-btn');
176
- const downloadBtn = document.getElementById('scan-download-btn');
177
- const openCameraBtn = document.getElementById('scan-open-camera-btn');
178
- const uploadFileBtn = document.getElementById('scan-upload-file-btn');
179
-
180
- // Camera Elements
181
- const cameraContainer = document.getElementById('camera-container');
182
- const actionButtons = document.getElementById('scan-action-buttons');
183
- const cameraVideo = document.getElementById('camera-video');
184
- const cameraCaptureBtn = document.getElementById('camera-capture-btn');
185
- const cameraCloseBtn = document.getElementById('camera-close-btn');
186
-
187
- this.stream = null;
188
-
189
- uploadFileBtn.addEventListener('click', () => fileInput.click());
190
-
191
- fileInput.addEventListener('change', (e) => {
192
- if (e.target.files && e.target.files[0]) {
193
- this.processImage(e.target.files[0]);
194
- }
195
- });
196
-
197
- // Live Camera Logic
198
- openCameraBtn.addEventListener('click', async () => {
199
- try {
200
- try {
201
- await Camera.requestPermissions();
202
- } catch (e) {
203
- console.log('Capacitor Camera plugin requestPermissions fallback', e);
204
- }
205
- this.stream = await navigator.mediaDevices.getUserMedia({
206
- video: { facingMode: 'environment', width: { ideal: 1920 }, height: { ideal: 1080 } }
207
- });
208
- cameraVideo.srcObject = this.stream;
209
- actionButtons.style.display = 'none';
210
- cameraContainer.style.display = 'block';
211
- } catch (err) {
212
- console.error('getUserMedia failed, falling back to file input:', err);
213
- // Fallback to native file input which supports capture="environment"
214
- document.getElementById('scan-file-input').click();
215
- }
216
- });
217
-
218
- const stopCamera = () => {
219
- if (this.stream) {
220
- this.stream.getTracks().forEach(track => track.stop());
221
- this.stream = null;
222
- }
223
- cameraContainer.style.display = 'none';
224
- actionButtons.style.display = 'flex';
225
- };
226
-
227
- cameraCloseBtn.addEventListener('click', stopCamera);
228
-
229
- cameraCaptureBtn.addEventListener('mousedown', () => cameraCaptureBtn.style.transform = 'translateX(-50%) scale(0.9)');
230
- cameraCaptureBtn.addEventListener('mouseup', () => cameraCaptureBtn.style.transform = 'translateX(-50%) scale(1)');
231
- cameraCaptureBtn.addEventListener('mouseleave', () => cameraCaptureBtn.style.transform = 'translateX(-50%) scale(1)');
232
-
233
- cameraCaptureBtn.addEventListener('click', () => {
234
- // Create an invisible canvas to grab the frame
235
- const tmpCanvas = document.createElement('canvas');
236
- tmpCanvas.width = cameraVideo.videoWidth;
237
- tmpCanvas.height = cameraVideo.videoHeight;
238
- const ctx = tmpCanvas.getContext('2d');
239
- ctx.drawImage(cameraVideo, 0, 0, tmpCanvas.width, tmpCanvas.height);
240
-
241
- // Convert to blob and process
242
- tmpCanvas.toBlob((blob) => {
243
- if (blob) {
244
- const file = new File([blob], "scan.jpg", { type: "image/jpeg" });
245
- stopCamera();
246
- this.processImage(file);
247
- }
248
- }, 'image/jpeg', 0.95);
249
- });
250
-
251
-
252
- // Fullscreen Events
253
- const vaultBtn = document.getElementById('scan-vault-btn');
254
- const flashcardsBtn = document.getElementById('scan-flashcards-btn');
255
-
256
- document.getElementById('scan-result-img-container').addEventListener('click', () => {
257
- const canvas = document.getElementById('scan-canvas');
258
- this.openFullscreen(canvas.toDataURL('image/jpeg', 0.9));
259
- });
260
-
261
- document.getElementById('fullscreen-close-btn').addEventListener('click', () => {
262
- const fsModal = document.getElementById('scan-fullscreen-modal');
263
- if (fsModal) fsModal.style.display = 'none';
264
- });
265
-
266
- resetBtn.addEventListener('click', () => {
267
- document.getElementById('scan-result-area').style.display = 'none';
268
- document.getElementById('scan-upload-area').style.display = 'flex';
269
- fileInput.value = '';
270
- });
271
-
272
- flashcardsBtn.addEventListener('click', async () => {
273
- if (this.isProcessing) return;
274
-
275
- const explanationText = this.lastExplanation || "";
276
- if (!explanationText) {
277
- alert("Keine Texte zum Generieren gefunden.");
278
- return;
279
- }
280
-
281
- const originalHtml = flashcardsBtn.innerHTML;
282
- flashcardsBtn.innerHTML = '<div style="width: 16px; height: 16px; border: 2px solid rgba(255,255,255,0.2); border-top-color: white; border-radius: 50%; animation: spin 1s linear infinite; margin-right: 8px;"></div> Erstelle...';
283
- flashcardsBtn.disabled = true;
284
-
285
- try {
286
- const prompt = `Extrahiere aus dem folgenden Text alle relevanten Fakten, Fragen/Antworten oder Vokabeln und erstelle daraus sinnvolle Karteikarten. Formatiere die Ausgabe als JSON, um das Tool 'create_flashcards' aufzurufen. Text:\n\n${explanationText}`;
287
- const apiKey = db.getSetting('gemini_api_key');
288
-
289
- await gemini.generateContent(
290
- prompt,
291
- 'gemini-1.5-flash',
292
- apiKey,
293
- "Du rufst ausschließlich das Tool 'create_flashcards' auf, um Karteikarten zu erstellen. Erfinde einen passenden 'deck_title'.",
294
- []
295
- );
296
-
297
- flashcardsBtn.innerHTML = 'Erledigt! ✔️';
298
- setTimeout(() => {
299
- flashcardsBtn.innerHTML = originalHtml;
300
- flashcardsBtn.disabled = false;
301
- }, 3000);
302
- } catch (err) {
303
- console.error("Fehler beim Erstellen der Karteikarten:", err);
304
- alert("Fehler: " + err.message);
305
- flashcardsBtn.innerHTML = originalHtml;
306
- flashcardsBtn.disabled = false;
307
- }
308
- });
309
- downloadBtn.addEventListener('click', () => {
310
- const canvas = document.getElementById('scan-canvas');
311
- const link = document.createElement('a');
312
- link.download = 'Lösung_Arbeitsblatt.png';
313
- link.href = canvas.toDataURL('image/png');
314
- link.click();
315
- });
316
-
317
- vaultBtn.addEventListener('click', async () => {
318
- if (this.isProcessing) return;
319
-
320
- const explanationText = this.lastExplanation || "Ausgefülltes Arbeitsblatt";
321
- const originalHtml = vaultBtn.innerHTML;
322
-
323
- vaultBtn.innerHTML = '<div style="width: 16px; height: 16px; border: 2px solid rgba(255,255,255,0.2); border-top-color: white; border-radius: 50%; animation: spin 1s linear infinite; margin-right: 8px;"></div> Speichere...';
324
- vaultBtn.disabled = true;
325
-
326
- try {
327
- const folders = await folderAgent.suggestFolders(explanationText);
328
- const bestFolder = folders[0] || "Arbeitsblätter";
329
- const filename = await folderAgent.generateFilename(explanationText);
330
-
331
- await fsService.createFolder(bestFolder);
332
-
333
- const meta = db.getFolderMetadata(bestFolder);
334
- if (!meta || !meta.emoji) {
335
- const visuals = await folderAgent.generateVisualsForFolder(bestFolder);
336
- db.saveFolderMetadata(bestFolder, visuals.emoji, visuals.color);
337
- }
338
-
339
- const canvas = document.getElementById('scan-canvas');
340
- const dataUrl = canvas.toDataURL('image/jpeg', 0.9);
341
- const base64Data = dataUrl.split(',')[1];
342
-
343
- await fsService.writeFile(`${bestFolder}/${filename}.jpg`, base64Data);
344
-
345
- vaultBtn.innerHTML = '<svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" stroke-width="2" fill="none" style="margin-right: 8px;"><polyline points="20 6 9 17 4 12"></polyline></svg> In ' + bestFolder;
346
- vaultBtn.style.background = 'rgba(76, 175, 80, 0.2)';
347
- vaultBtn.style.borderColor = 'rgba(76, 175, 80, 0.5)';
348
- vaultBtn.style.color = '#81c784';
349
-
350
- } catch (e) {
351
- console.error(e);
352
- vaultBtn.innerHTML = 'Fehler beim Speichern';
353
- vaultBtn.disabled = false;
354
- setTimeout(() => {
355
- vaultBtn.innerHTML = originalHtml;
356
- }, 3000);
357
- }
358
- });
359
- }
360
-
361
-
362
- openFullscreen(imageSrc) {
363
- const modal = document.getElementById('scan-fullscreen-modal');
364
- const img = document.getElementById('scan-fullscreen-img');
365
- img.src = imageSrc;
366
- img.style.transform = 'scale(1)'; // reset zoom
367
- modal.style.display = 'flex';
368
- }
369
-
370
- async isHeicFile(file) {
371
- // Quick check
372
- if (file.type === 'image/heic' || file.type === 'image/heif' || file.name.match(/\.(heic|heif)$/i)) return true;
373
- // Deep check
374
- try {
375
- const buffer = await file.slice(0, 12).arrayBuffer();
376
- const arr = new Uint8Array(buffer);
377
- const sig = String.fromCharCode(...arr.slice(4, 12));
378
- return sig.includes('heic') || sig.includes('mif1') || sig.includes('heix') || sig.includes('hevc');
379
- } catch (e) {
380
- return false;
381
- }
382
- }
383
-
384
- async processImage(file) {
385
- const explanationDiv = document.getElementById('scan-explanation');
386
-
387
- // HEIC Auto-Conversion
388
- let processableFile = file;
389
- const isHeic = await this.isHeicFile(file);
390
- if (isHeic) {
391
- try {
392
- explanationDiv.innerHTML = "<div style='color: var(--primary-color);'>Konvertiere iPhone-Foto (HEIC) in Browser-Format... Bitte warten.</div>";
393
- document.getElementById('scan-processing').style.display = 'flex';
394
- document.getElementById('scan-upload-area').style.display = 'none';
395
-
396
- const heic2any = (await import('heic2any')).default;
397
- const convertedBlob = await heic2any({ blob: file, toType: "image/jpeg", quality: 0.8 });
398
- processableFile = new File(
399
- [Array.isArray(convertedBlob) ? convertedBlob[0] : convertedBlob],
400
- "converted.jpg",
401
- { type: "image/jpeg" }
402
- );
403
- } catch (err) {
404
- console.error("HEIC conversion failed:", err);
405
- alert("Das iPhone-Bild konnte nicht umgewandelt werden. Bitte lade ein Standard-JPG hoch.");
406
- document.getElementById('scan-processing').style.display = 'none';
407
- document.getElementById('scan-upload-area').style.display = 'flex';
408
- return;
409
- }
410
- }
411
-
412
- const isImage = processableFile.type.startsWith('image/') || processableFile.name.match(/\.(jpg|jpeg|png|gif|webp)$/i);
413
- if (!isImage) {
414
- alert('Bitte lade ein gültiges Bild hoch.');
415
- return;
416
- }
417
-
418
- const uploadArea = document.getElementById('scan-upload-area');
419
- const processingArea = document.getElementById('scan-processing');
420
- const resultArea = document.getElementById('scan-result-area');
421
-
422
- uploadArea.style.display = 'none';
423
- processingArea.style.display = 'flex';
424
- resultArea.style.display = 'none';
425
-
426
- try {
427
- // Load file into an Image element to show in Crop UI
428
- const base64DataOriginal = await new Promise((resolve, reject) => {
429
- const reader = new FileReader();
430
- reader.onload = () => resolve(reader.result);
431
- reader.onerror = () => reject(new Error('Fehler beim Lesen der Datei'));
432
- reader.readAsDataURL(processableFile);
433
- });
434
-
435
- const imgElem = new Image();
436
- await new Promise(resolve => {
437
- imgElem.onload = resolve;
438
- imgElem.src = base64DataOriginal;
439
- });
440
-
441
- // Show Crop Modal
442
- const croppedBase64 = await this.openCropModal(imgElem);
443
- if (!croppedBase64) {
444
- uploadArea.style.display = 'flex';
445
- processingArea.style.display = 'none';
446
- return; // User cancelled
447
- }
448
-
449
- const explanationDiv = document.getElementById('scan-explanation');
450
- explanationDiv.innerHTML = "<div style='color: var(--primary-color);'>Analysiere Arbeitsblatt...</div>";
451
-
452
- const base64Data = croppedBase64;
453
- const apiKey = db.getSetting('gemini_api_key');
454
-
455
- if (!apiKey) {
456
- throw new Error('Gemini API Key ist nicht konfiguriert. Bitte in den Einstellungen eintragen.');
457
- }
458
-
459
- // System Instruction for the AI
460
- const systemInstruction = `Du bist ein Lehrer-Assistent mit exzellentem räumlichen Vorstellungsvermögen. Analysiere das begradigte Foto eines Arbeitsblattes und löse alle Aufgaben.
461
-
462
- DEINE AUFGABE:
463
- 1. Lies das gesamte Arbeitsblatt sorgfältig.
464
- 2. Identifiziere ALLE leeren Linien, Kästchen oder Lücken, an denen der Schüler etwas eintragen soll.
465
- 3. Löse jede Aufgabe korrekt.
466
- 4. Gib für JEDE Antwortzeile eine 2D Bounding Box an, die den verfuegbaren Leerraum (die Linie) repraesentiert.
467
-
468
- KOORDINATEN-REGELN:
469
- - Format: [ymin, xmin, ymax, xmax] (0 bis 1000). y: 0=oben, 1000=unten. x: 0=links, 1000=rechts.
470
- - WICHTIG: Die Box MUSS den reinen FREIRAUM markieren, in dem die Handschrift stehen soll.
471
- - ymax ist die Position der gedruckten Unterstrich-Linie. Die Schrift wird auf dieser y-Koordinate horizontal gezeichnet.
472
-
473
- ANTWORT-FORMAT:
474
- - Wenn für eine Antwort mehrere Linien zur Verfügung stehen, erstelle für JEDE leere Linie ein eigenes Objekt in der JSON.
475
- - Teile lange Antworten sinnvoll auf diese Linien auf.
476
- - Halte die Antworten präzise und so kurz, dass sie in die Breite passen.
477
-
478
- JSON (NUR reines JSON, KEIN Markdown):
479
- {
480
- "explanation": "Kurze Erklärung des Themas.",
481
- "answers": [
482
- {
483
- "text": "Antwort für die erste Linie",
484
- "box_2d": [250, 250, 260, 900],
485
- "has_printed_prefix": true
486
- },
487
- {
488
- "text": "Antwort für die zweite Linie",
489
- "box_2d": [300, 50, 310, 900],
490
- "has_printed_prefix": false
491
- }
492
- ]
493
- }`;
494
-
495
- const prompt = `Löse alle Aufgaben auf diesem begradigten Arbeitsblatt. Gib für jede auszufüllende Linie die perfekte Bounding Box an. Achte streng darauf, dass die Box keinen gedruckten Text überlappt!\n![image](${base64Data})`;
496
-
497
- // 4. Call Gemini
498
- const localModelSelect = document.getElementById('scan-local-model');
499
- const modelToUse = localModelSelect ? localModelSelect.value : (db.getSetting('model') || 'gemini-3.5-flash');
500
- const rawResponse = await gemini.generateContent(
501
- prompt,
502
- modelToUse,
503
- apiKey,
504
- systemInstruction,
505
- [],
506
- { responseMimeType: "application/json" }
507
- );
508
-
509
- let parsedData;
510
- try {
511
- const cleanJson = rawResponse.replace(/^```json/m, '').replace(/```$/m, '').trim();
512
- parsedData = JSON.parse(cleanJson);
513
- } catch (err) {
514
- console.error('Failed to parse AI response:', rawResponse);
515
- throw new Error('Die KI hat eine ungültige Antwort zurückgegeben. Bitte versuche es noch einmal.');
516
- }
517
-
518
- // Reset UI
519
- document.getElementById('scan-upload-area').style.display = 'none';
520
- const processingText = document.getElementById('scan-processing-text');
521
- processingArea.style.display = 'flex';
522
- processingText.innerText = "Handschrift wird erzeugt...";
523
-
524
- // Draw the final result
525
- await this.drawOnCanvas(base64Data, parsedData);
526
-
527
- // Show result
528
- processingArea.style.display = 'none';
529
- document.getElementById('scan-result-area').style.display = 'flex';
530
-
531
- let explanationHtml = parsedData.explanation ? `<p>${parsedData.explanation}</p>` : "<p>Arbeitsblatt ausgewertet.</p>";
532
- this.lastExplanation = parsedData.explanation || "";
533
- explanationHtml += `<details style="margin-top: 12px; padding: 12px; background: rgba(255,255,255,0.05); border-radius: 8px; font-size: 12px;">
534
- <summary style="cursor: pointer; color: #aaa;">🔍 Debug: KI-Rohdaten anzeigen</summary>
535
- <pre style="white-space: pre-wrap; word-break: break-all; margin-top: 8px; color: #8f8; font-family: monospace; max-height: 300px; overflow: auto;">${JSON.stringify(parsedData, null, 2)}</pre>
536
- </details>`;
537
- explanationDiv.innerHTML = explanationHtml;
538
-
539
- } catch (error) {
540
- console.error(error);
541
- alert('Fehler beim Analysieren des Arbeitsblattes: ' + error.message);
542
- uploadArea.style.display = 'flex';
543
- processingArea.style.display = 'none';
544
- }
545
- }
546
-
547
- async drawOnCanvas(imageSrc, parsedData) {
548
- const canvas = document.getElementById('scan-canvas');
549
- const ctx = canvas.getContext('2d');
550
-
551
- return new Promise((resolve, reject) => {
552
- const img = new Image();
553
- img.onload = () => {
554
- try {
555
- canvas.width = img.width;
556
- canvas.height = img.height;
557
- ctx.drawImage(img, 0, 0);
558
-
559
- const answers = parsedData.answers;
560
- if (!answers || !Array.isArray(answers) || answers.length === 0) {
561
- return resolve();
562
- }
563
-
564
- const imgWidth = img.width;
565
- const imgHeight = img.height;
566
-
567
- answers.forEach(answer => {
568
- if (!answer.text || !answer.box_2d || !Array.isArray(answer.box_2d) || answer.box_2d.length !== 4) return;
569
-
570
- // Format: [ymin, xmin, ymax, xmax] from 0 to 1000
571
- const [ymin_1000, xmin_1000, ymax_1000, xmax_1000] = answer.box_2d;
572
-
573
- // Normalize to 0-1
574
- let x1 = xmin_1000 / 1000;
575
- const y1 = ymin_1000 / 1000;
576
- let x2 = xmax_1000 / 1000;
577
- const y2 = ymax_1000 / 1000;
578
-
579
- // Enforce margin if there is a printed prefix
580
- if (answer.has_printed_prefix && x1 < 0.18) {
581
- x1 = 0.18;
582
- }
583
-
584
- // Convert AI coordinates to pixels
585
- let finalX1 = Math.floor(x1 * img.width);
586
- let finalX2 = Math.floor(Math.max(x1 + 0.05, x2) * img.width);
587
- // We use ymax (y2) as the baseline for the text
588
- let finalY = Math.floor(y2 * img.height);
589
-
590
- const lineLength = Math.max(10, finalX2 - finalX1);
591
-
592
- // Standard font size based on image height (e.g. 1.8%)
593
- let fontSize = Math.floor(img.height * 0.018);
594
-
595
- // If the text is short, don't make it giant! Just keep the natural handwriting size.
596
- // Only shrink if it's too long.
597
- ctx.font = `${fontSize}px 'Caveat', cursive, sans-serif`;
598
- let textWidth = ctx.measureText(answer.text).width;
599
-
600
- // Padding so handwriting doesn't touch the very edges of the line
601
- const paddingX = Math.max(5, img.width * 0.015);
602
- const availableLength = Math.max(10, lineLength - paddingX * 2);
603
-
604
- if (textWidth > availableLength) {
605
- // Shrink font to fit the line
606
- fontSize = Math.max(12, Math.floor(fontSize * (availableLength / textWidth) * 0.95));
607
- }
608
-
609
- ctx.font = `${fontSize}px 'Caveat', cursive, sans-serif`;
610
- ctx.fillStyle = '#1a3a8a';
611
- ctx.textBaseline = 'alphabetic';
612
-
613
- ctx.save();
614
-
615
- // Move origin to x1
616
- // For Y, we shift it up by ~15% of the font size so the letters sit clearly ABOVE the physical line,
617
- // instead of cutting exactly through it.
618
- ctx.translate(finalX1 + paddingX, finalY - Math.floor(fontSize * 0.15));
619
-
620
- const naturalJitterAngle = (Math.random() - 0.5) * 0.015;
621
- ctx.rotate(naturalJitterAngle);
622
-
623
- ctx.fillText(answer.text, 0, 0);
624
- ctx.restore();
625
- });
626
-
627
- resolve();
628
- } catch (e) {
629
- console.error("Canvas drawing error:", e);
630
- reject(e);
631
- }
632
- };
633
- img.onerror = () => reject(new Error('Konnte das Bild nicht für das Canvas laden.'));
634
- img.src = imageSrc;
635
- });
636
- }
637
-
638
- openCropModal(imgElem) {
639
- return new Promise((resolve) => {
640
- const modal = document.getElementById('crop-modal');
641
- const img = document.getElementById('crop-img');
642
- const svg = document.getElementById('crop-svg');
643
- const polygon = document.getElementById('crop-polygon');
644
- const handles = Array.from(document.querySelectorAll('.crop-handle'));
645
- const cancelBtn = document.getElementById('crop-cancel-btn');
646
- const confirmBtn = document.getElementById('crop-confirm-btn');
647
- const cropArea = document.getElementById('crop-area');
648
-
649
- modal.style.display = 'flex';
650
-
651
- // Calculate fit
652
- const areaRect = cropArea.getBoundingClientRect();
653
- const areaAspect = areaRect.width / areaRect.height;
654
- const imgAspect = imgElem.width / imgElem.height;
655
-
656
- let scale = 1;
657
- let left = 0;
658
- let top = 0;
659
-
660
- if (imgAspect > areaAspect) {
661
- scale = areaRect.width / imgElem.width;
662
- top = (areaRect.height - imgElem.height * scale) / 2;
663
- } else {
664
- scale = areaRect.height / imgElem.height;
665
- left = (areaRect.width - imgElem.width * scale) / 2;
666
- }
667
-
668
- img.src = imgElem.src;
669
- img.style.width = imgElem.width + 'px';
670
- img.style.height = imgElem.height + 'px';
671
- img.style.transform = `translate(${left}px, ${top}px) scale(${scale})`;
672
-
673
- // Initial Corners (10% margin)
674
- const margin = 0.1;
675
- const w = imgElem.width * scale;
676
- const h = imgElem.height * scale;
677
- let corners = [
678
- {x: left + w * margin, y: top + h * margin},
679
- {x: left + w * (1 - margin), y: top + h * margin},
680
- {x: left + w * (1 - margin), y: top + h * (1 - margin)},
681
- {x: left + w * margin, y: top + h * (1 - margin)}
682
- ];
683
-
684
- const updateUI = () => {
685
- // Update Polygon
686
- polygon.setAttribute('points', corners.map(c => `${c.x},${c.y}`).join(' '));
687
-
688
- // Update Grid (6x6 Grid)
689
- const gridGroup = document.getElementById('crop-grid-group');
690
- if (gridGroup) {
691
- gridGroup.innerHTML = '';
692
- // We want 6 inner lines vertically and 6 horizontally
693
- for (let i = 1; i <= 6; i++) {
694
- const fraction = i / 7;
695
-
696
- // Vertical lines
697
- const topPt = { x: corners[0].x + (corners[1].x - corners[0].x) * fraction, y: corners[0].y + (corners[1].y - corners[0].y) * fraction };
698
- const botPt = { x: corners[3].x + (corners[2].x - corners[3].x) * fraction, y: corners[3].y + (corners[2].y - corners[3].y) * fraction };
699
-
700
- const vLine = document.createElementNS('http://www.w3.org/2000/svg', 'line');
701
- vLine.setAttribute('x1', topPt.x);
702
- vLine.setAttribute('y1', topPt.y);
703
- vLine.setAttribute('x2', botPt.x);
704
- vLine.setAttribute('y2', botPt.y);
705
- vLine.setAttribute('stroke', '#ff4040');
706
- vLine.setAttribute('stroke-width', '1');
707
- vLine.setAttribute('opacity', '0.6');
708
- gridGroup.appendChild(vLine);
709
-
710
- // Horizontal lines
711
- const leftPt = { x: corners[0].x + (corners[3].x - corners[0].x) * fraction, y: corners[0].y + (corners[3].y - corners[0].y) * fraction };
712
- const rightPt = { x: corners[1].x + (corners[2].x - corners[1].x) * fraction, y: corners[1].y + (corners[2].y - corners[1].y) * fraction };
713
-
714
- const hLine = document.createElementNS('http://www.w3.org/2000/svg', 'line');
715
- hLine.setAttribute('x1', leftPt.x);
716
- hLine.setAttribute('y1', leftPt.y);
717
- hLine.setAttribute('x2', rightPt.x);
718
- hLine.setAttribute('y2', rightPt.y);
719
- hLine.setAttribute('stroke', '#ff4040');
720
- hLine.setAttribute('stroke-width', '1');
721
- hLine.setAttribute('opacity', '0.6');
722
- gridGroup.appendChild(hLine);
723
- }
724
- }
725
-
726
- // Update Handles
727
- handles.forEach((handle, i) => {
728
- handle.style.left = corners[i].x + 'px';
729
- handle.style.top = corners[i].y + 'px';
730
- });
731
- };
732
-
733
- updateUI();
734
-
735
- // Drag Logic
736
- let activeHandle = null;
737
-
738
- const onMove = (e) => {
739
- if (activeHandle === null) return;
740
- e.preventDefault();
741
- const clientX = e.touches ? e.touches[0].clientX : e.clientX;
742
- const clientY = e.touches ? e.touches[0].clientY : e.clientY;
743
- const rect = cropArea.getBoundingClientRect();
744
-
745
- let nx = clientX - rect.left;
746
- let ny = clientY - rect.top;
747
-
748
- // Bounds check against image visually
749
- nx = Math.max(left, Math.min(left + w, nx));
750
- ny = Math.max(top, Math.min(top + h, ny));
751
-
752
- corners[activeHandle] = {x: nx, y: ny};
753
- updateUI();
754
- };
755
-
756
- const onUp = () => {
757
- activeHandle = null;
758
- document.removeEventListener('mousemove', onMove);
759
- document.removeEventListener('mouseup', onUp);
760
- document.removeEventListener('touchmove', onMove);
761
- document.removeEventListener('touchend', onUp);
762
- };
763
-
764
- const onDown = (e, index) => {
765
- e.preventDefault();
766
- activeHandle = index;
767
- document.addEventListener('mousemove', onMove, {passive: false});
768
- document.addEventListener('mouseup', onUp);
769
- document.addEventListener('touchmove', onMove, {passive: false});
770
- document.addEventListener('touchend', onUp);
771
- };
772
-
773
- handles.forEach((handle, i) => {
774
- handle.onmousedown = (e) => onDown(e, i);
775
- handle.ontouchstart = (e) => onDown(e, i);
776
- });
777
-
778
- const cleanup = () => {
779
- modal.style.display = 'none';
780
- cancelBtn.onclick = null;
781
- confirmBtn.onclick = null;
782
- handles.forEach(h => { h.onmousedown = null; h.ontouchstart = null; });
783
- };
784
-
785
- cancelBtn.onclick = () => {
786
- cleanup();
787
- resolve(null);
788
- };
789
-
790
- confirmBtn.onclick = async () => {
791
- confirmBtn.innerHTML = "Wird begradigt...";
792
- confirmBtn.disabled = true;
793
-
794
- // Convert screen coordinates to original image pixels
795
- const pixelCorners = corners.map(c => ({
796
- x: (c.x - left) / scale,
797
- y: (c.y - top) / scale
798
- }));
799
-
800
- // Warp Image
801
- // Use a small timeout to let the UI update the button text
802
- await new Promise(r => setTimeout(r, 50));
803
-
804
- try {
805
- const resultBase64 = await this.warpImage(imgElem, pixelCorners);
806
- cleanup();
807
- confirmBtn.innerHTML = "Zuschneiden & Analysieren";
808
- confirmBtn.disabled = false;
809
- resolve(resultBase64);
810
- } catch(e) {
811
- console.error("Warp failed", e);
812
- alert("Fehler beim Begradigen des Bildes.");
813
- cleanup();
814
- confirmBtn.innerHTML = "Zuschneiden & Analysieren";
815
- confirmBtn.disabled = false;
816
- resolve(null);
817
- }
818
- };
819
- });
820
- }
821
-
822
- async warpImage(imgElement, corners) {
823
- const wTop = Math.hypot(corners[1].x - corners[0].x, corners[1].y - corners[0].y);
824
- const wBot = Math.hypot(corners[2].x - corners[3].x, corners[2].y - corners[3].y);
825
- const hLeft = Math.hypot(corners[3].x - corners[0].x, corners[3].y - corners[0].y);
826
- const hRight = Math.hypot(corners[2].x - corners[1].x, corners[2].y - corners[1].y);
827
-
828
- const dstW = Math.round(Math.max(wTop, wBot));
829
- const dstH = Math.round(Math.max(hLeft, hRight));
830
-
831
- const srcPts = [
832
- corners[0].x, corners[0].y,
833
- corners[1].x, corners[1].y,
834
- corners[2].x, corners[2].y,
835
- corners[3].x, corners[3].y
836
- ];
837
- const dstPts = [
838
- 0, 0,
839
- dstW, 0,
840
- dstW, dstH,
841
- 0, dstH
842
- ];
843
-
844
- const pt = perspective(srcPts, dstPts);
845
-
846
- const srcCanvas = document.createElement('canvas');
847
- srcCanvas.width = imgElement.width;
848
- srcCanvas.height = imgElement.height;
849
- const srcCtx = srcCanvas.getContext('2d', { willReadFrequently: true });
850
- srcCtx.drawImage(imgElement, 0, 0);
851
- const srcData = srcCtx.getImageData(0, 0, srcCanvas.width, srcCanvas.height);
852
-
853
- const dstCanvas = document.createElement('canvas');
854
- dstCanvas.width = dstW;
855
- dstCanvas.height = dstH;
856
- const dstCtx = dstCanvas.getContext('2d');
857
- const dstData = dstCtx.createImageData(dstW, dstH);
858
-
859
- for (let y = 0; y < dstH; y++) {
860
- for (let x = 0; x < dstW; x++) {
861
- const [srcX, srcY] = pt.transformInverse(x, y);
862
- const sx = Math.floor(srcX);
863
- const sy = Math.floor(srcY);
864
-
865
- if (sx >= 0 && sx < srcCanvas.width && sy >= 0 && sy < srcCanvas.height) {
866
- const dstIdx = (y * dstW + x) * 4;
867
- const srcIdx = (sy * srcCanvas.width + sx) * 4;
868
- dstData.data[dstIdx] = srcData.data[srcIdx];
869
- dstData.data[dstIdx+1] = srcData.data[srcIdx+1];
870
- dstData.data[dstIdx+2] = srcData.data[srcIdx+2];
871
- dstData.data[dstIdx+3] = srcData.data[srcIdx+3];
872
- }
873
- }
874
- }
875
-
876
- dstCtx.putImageData(dstData, 0, 0);
877
- return dstCanvas.toDataURL('image/jpeg', 0.9);
878
- }
879
-
880
- showCustomConfirm(title, text, onConfirm) {
881
- const overlay = document.createElement('div');
882
- overlay.className = 'custom-modal-overlay';
883
- overlay.innerHTML = `
884
- <div class="custom-modal">
885
- <h3>${title}</h3>
886
- <p>${text}</p>
887
- <div class="modal-actions">
888
- <button class="modal-btn cancel">Abbrechen</button>
889
- <button class="modal-btn confirm danger">Löschen</button>
890
- </div>
891
- </div>
892
- `;
893
- document.body.appendChild(overlay);
894
-
895
- const close = () => {
896
- overlay.classList.add('fade-out');
897
- setTimeout(() => overlay.remove(), 200);
898
- };
899
-
900
- overlay.querySelector('.cancel').onclick = close;
901
- overlay.querySelector('.confirm').onclick = () => {
902
- onConfirm();
903
- close();
904
- };
905
- }
 
 
906
  }
 
1
+ import perspective from '../../utils/perspective.js';
2
+ import { gemini } from '../../ai/gemini.js';
3
+ import { db } from '../../db/database.js';
4
+ import { Camera } from '@capacitor/camera';
5
+ import { fsService } from '../../services/file-system.js';
6
+ import { folderAgent } from '../../ai/folder-agent.js?v=2';
7
+
8
+ export class ScanView {
9
+ constructor(containerId) {
10
+ this.container = document.getElementById(containerId);
11
+ this.isProcessing = false;
12
+ this.stream = null;
13
+ }
14
+
15
+ destroy() {
16
+ if (this.stream) {
17
+ this.stream.getTracks().forEach(track => track.stop());
18
+ this.stream = null;
19
+ }
20
+ }
21
+
22
+ async init() {
23
+ // Add handwriting font if not present
24
+ if (!document.getElementById('font-caveat')) {
25
+ const link = document.createElement('link');
26
+ link.id = 'font-caveat';
27
+ link.rel = 'stylesheet';
28
+ link.href = 'https://fonts.googleapis.com/css2?family=Caveat:wght@400;700&display=swap';
29
+ document.head.appendChild(link);
30
+ }
31
+ }
32
+
33
+ render() {
34
+
35
+ this.container.innerHTML = `
36
+ <div style="padding: 24px; padding-top: calc(env(safe-area-inset-top, 20px) + 24px); max-width: 800px; margin: 0 auto; display: flex; flex-direction: column; gap: 24px; height: 100%; box-sizing: border-box; position: relative;">
37
+
38
+ <!-- Header -->
39
+ <div style="position: relative; margin-bottom: 16px;">
40
+ <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 8px;">
41
+ <button onclick="window.openView('Hub')" class="icon-btn" style="background: transparent; padding: 0; width: 32px; height: 32px; display: flex; align-items: center; justify-content: center; color: var(--text-secondary);">
42
+ <svg viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"></polyline></svg>
43
+ </button>
44
+ <h2 style="font-size: 24px; font-weight: 600; margin: 0;">Arbeitsblatt Scan</h2>
45
+ </div>
46
+ <p style="color: var(--text-secondary); font-size: 14px;">Mache ein Foto deines leeren Arbeitsblattes. Die KI löst die Aufgaben und füllt es in Handschrift für dich aus.</p>
47
+ </div>
48
+
49
+ <!-- Crop Modal Overlay -->
50
+ <div id="crop-modal" style="display: none; position: absolute; inset: 0; background: #000; z-index: 100; flex-direction: column; border-radius: 16px; overflow: hidden;">
51
+ <div style="padding: 16px; background: rgba(255,255,255,0.1); text-align: center; color: white; font-weight: 500;">Passe die Ecken an das Blatt an</div>
52
+ <div id="crop-area" style="flex: 1; position: relative; overflow: hidden; touch-action: none;">
53
+ <img id="crop-img" style="position: absolute; top: 0; left: 0; transform-origin: top left; pointer-events: none;" />
54
+ <svg id="crop-svg" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none;">
55
+ <polygon id="crop-polygon" fill="rgba(64, 156, 255, 0.2)" stroke="#409cff" stroke-width="2"></polygon>
56
+ <!-- We will generate grid lines dynamically in JS -->
57
+ <g id="crop-grid-group"></g>
58
+ </svg>
59
+ <!-- 4 Drag Handles -->
60
+ <div class="crop-handle" data-index="0" style="position: absolute; width: 30px; height: 30px; background: rgba(64,156,255,0.8); border: 2px solid white; border-radius: 50%; transform: translate(-50%, -50%); cursor: grab; touch-action: none;"></div>
61
+ <div class="crop-handle" data-index="1" style="position: absolute; width: 30px; height: 30px; background: rgba(64,156,255,0.8); border: 2px solid white; border-radius: 50%; transform: translate(-50%, -50%); cursor: grab; touch-action: none;"></div>
62
+ <div class="crop-handle" data-index="2" style="position: absolute; width: 30px; height: 30px; background: rgba(64,156,255,0.8); border: 2px solid white; border-radius: 50%; transform: translate(-50%, -50%); cursor: grab; touch-action: none;"></div>
63
+ <div class="crop-handle" data-index="3" style="position: absolute; width: 30px; height: 30px; background: rgba(64,156,255,0.8); border: 2px solid white; border-radius: 50%; transform: translate(-50%, -50%); cursor: grab; touch-action: none;"></div>
64
+ </div>
65
+ <div style="padding: 16px; display: flex; gap: 12px; background: rgba(255,255,255,0.05);">
66
+ <button id="crop-cancel-btn" style="flex: 1; padding: 12px; background: rgba(255,255,255,0.1); color: white; border: none; border-radius: 8px;">Abbrechen</button>
67
+ <button id="crop-confirm-btn" class="primary-btn" style="flex: 2; padding: 12px; justify-content: center;">Zuschneiden & Analysieren</button>
68
+ </div>
69
+ </div>
70
+
71
+
72
+ <!-- Upload & Camera Area -->
73
+ <div id="scan-upload-area" style="flex: 1; display: flex; flex-direction: column; gap: 16px;">
74
+
75
+ <!-- Camera Preview Container -->
76
+ <div id="camera-container" style="display: none; flex: 1; border-radius: 16px; overflow: hidden; position: relative; background: #000; min-height: 350px; box-shadow: 0 8px 32px rgba(0,0,0,0.3);">
77
+ <video id="camera-video" autoplay playsinline style="width: 100%; height: 100%; object-fit: cover;"></video>
78
+ <button id="camera-capture-btn" style="position: absolute; bottom: 24px; left: 50%; transform: translateX(-50%); width: 64px; height: 64px; border-radius: 50%; background: rgba(255,255,255,0.3); border: 4px solid #fff; cursor: pointer; backdrop-filter: blur(4px); box-shadow: 0 4px 16px rgba(0,0,0,0.3); transition: transform 0.1s;"></button>
79
+ <button id="camera-close-btn" class="icon-btn" style="position: absolute; top: 16px; right: 16px; background: rgba(0,0,0,0.5); color: #fff;">
80
+ <svg viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" stroke-width="2" fill="none"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
81
+ </button>
82
+ </div>
83
+
84
+ <div id="scan-action-buttons" style="flex: 1; border: 2px dashed rgba(255,255,255,0.2); border-radius: 16px; display: flex; flex-direction: column; align-items: center; justify-content: center; background: rgba(255,255,255,0.02); min-height: 200px; padding: 24px;">
85
+ <svg viewBox="0 0 24 24" width="48" height="48" stroke="currentColor" stroke-width="1.5" fill="none" style="opacity: 0.5; margin-bottom: 16px;"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg>
86
+
87
+ <div style="display: flex; gap: 12px; width: 100%; max-width: 300px;">
88
+ <button id="scan-open-camera-btn" class="primary-btn" style="flex: 1; justify-content: center; padding: 12px;">
89
+ <svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" stroke-width="2" fill="none" style="margin-right: 8px;"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"></path><circle cx="12" cy="13" r="4"></circle></svg>
90
+ Kamera
91
+ </button>
92
+
93
+ <button id="scan-upload-file-btn" style="flex: 1; justify-content: center; padding: 12px; background: rgba(255,255,255,0.1); border-radius: 8px; color: #fff; font-weight: 500; border: none; cursor: pointer; display: flex; align-items: center;">
94
+ <svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" stroke-width="2" fill="none" style="margin-right: 8px;"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="17 8 12 3 7 8"></polyline><line x1="12" y1="3" x2="12" y2="15"></line></svg>
95
+ Datei
96
+ </button>
97
+ <input type="file" id="scan-file-input" accept="image/*" capture="environment" style="display: none;" />
98
+ </div>
99
+
100
+ <div style="margin-top: 24px; width: 100%; max-width: 300px; padding-top: 16px; border-top: 1px solid rgba(255,255,255,0.1);">
101
+ <label style="display: block; font-size: 12px; color: rgba(255,255,255,0.6); margin-bottom: 6px; text-align: left;">Scan-Modell</label>
102
+ <select id="scan-local-model" style="width: 100%; padding: 10px; border-radius: 8px; background: rgba(0,0,0,0.4); border: 1px solid rgba(255,255,255,0.1); color: white; font-size: 14px; outline: none; appearance: none;">
103
+ <option value="gemini-3.6-flash">Gemini 3.6 Flash</option>
104
+ <option value="gemini-3.5-flash">Gemini 3.5 Flash (Schnell & Standard)</option>
105
+ <option value="gemini-3.5-flash-lite">Gemini 3.5 Flash Lite</option>
106
+ <option value="gemini-3.1-flash-lite">Gemini 3.1 Flash Lite (Effizient)</option>
107
+ <option value="gemini-3-flash-preview">Gemini 3 Flash Preview (Sehr Stabil)</option>
108
+ <option value="gemini-2.5-flash">Gemini 2.5 Flash</option>
109
+ <option value="gemini-2.5-flash-lite">Gemini 2.5 Flash Lite</option>
110
+ <option value="gemma-4-31b-it">Gemma 4 31B (Open Weights)</option>
111
+ <option value="groq-llama-3.3-70b-versatile">Llama 3.3 70B (Groq)</option>
112
+ <option value="local-phone-qwen">Lokal Handy (Qwen 1.5B)</option>
113
+ <option value="local-pc-llama">Lokal PC (Llama 3 8B)</option>
114
+ </select>
115
+ </div>
116
+ </div>
117
+ </div>
118
+
119
+ <!-- Processing State -->
120
+ <div id="scan-processing" style="display: none; flex-direction: column; align-items: center; justify-content: center; padding: 40px; background: rgba(255,255,255,0.05); border-radius: 16px;">
121
+ <div style="width: 40px; height: 40px; border: 3px solid rgba(255,255,255,0.1); border-top-color: var(--primary-color); border-radius: 50%; animation: spin 1s linear infinite; margin-bottom: 16px;"></div>
122
+ <div id="scan-processing-text" style="font-weight: 500;">Analysiere Arbeitsblatt...</div>
123
+ <div style="font-size: 13px; color: var(--text-secondary); margin-top: 8px; text-align: center;">Die KI liest die Aufgaben, berechnet die Lösungen und ermittelt die perfekten Koordinaten zum Ausfüllen. Das dauert ca. 5-10 Sekunden.</div>
124
+ </div>
125
+
126
+ <!-- Result Area -->
127
+ <div id="scan-result-area" style="display: none; flex-direction: column; gap: 16px;">
128
+ <div id="scan-result-img-container" style="position: relative; border-radius: 12px; overflow: hidden; background: #fff; box-shadow: 0 8px 32px rgba(0,0,0,0.3); cursor: zoom-in;">
129
+ <canvas id="scan-canvas" style="width: 100%; height: auto; display: block;"></canvas>
130
+ </div>
131
+
132
+ <div style="display: flex; gap: 12px; width: 100%;">
133
+ <button id="scan-download-btn" class="primary-btn" style="flex: 1; padding: 16px; font-size: 16px; justify-content: center;">
134
+ <svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" stroke-width="2" fill="none" style="margin-right: 8px;"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
135
+ Speichern
136
+ </button>
137
+ <button id="scan-vault-btn" class="liquid-glass-heavy" style="flex: 1; padding: 16px; font-size: 16px; justify-content: center; font-weight: 500; display: flex; align-items: center; border-radius: 16px;">
138
+ <svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" stroke-width="2" fill="none" style="margin-right: 8px;"><path d="M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2Z"/></svg>
139
+ In Vault
140
+ </button>
141
+ <button id="scan-flashcards-btn" class="liquid-glass-heavy" style="flex: 1; padding: 16px; font-size: 16px; justify-content: center; font-weight: 500; display: flex; align-items: center; border-radius: 16px;">
142
+ <svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" stroke-width="2" fill="none" style="margin-right: 8px;"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"></path><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"></path></svg>
143
+ Lernen
144
+ </button>
145
+ </div>
146
+
147
+ <div id="scan-explanation" style="padding: 16px; background: rgba(255,255,255,0.05); border-radius: 12px; font-size: 14px; line-height: 1.5; color: var(--text-primary); border-left: 4px solid var(--primary-color);">
148
+ <!-- Explanation will appear here -->
149
+ </div>
150
+
151
+ <button id="scan-reset-btn" class="icon-btn" style="align-self: center; margin-top: 8px; padding: 8px 16px; background: rgba(255,255,255,0.1); border-radius: 20px;">
152
+ Neues Arbeitsblatt einscannen
153
+ </button>
154
+ </div>
155
+
156
+ <!-- Fullscreen Viewer Modal -->
157
+ <div id="scan-fullscreen-modal" style="display: none; position: fixed; inset: 0; background: #000; z-index: 1000; flex-direction: column;">
158
+ <div style="padding: 16px; display: flex; justify-content: space-between; align-items: center; background: rgba(0,0,0,0.5); position: absolute; top: 0; left: 0; right: 0; z-index: 1001;">
159
+ <button id="fullscreen-close-btn" class="icon-btn" style="color: white; font-size: 24px;">✕</button>
160
+ <span style="color: white; font-weight: 500;">Vollbild (Pinch to zoom)</span>
161
+ <div style="width: 24px;"></div>
162
+ </div>
163
+ <div style="flex: 1; overflow: auto; display: flex; align-items: center; justify-content: center; touch-action: pan-x pan-y pinch-zoom;">
164
+ <img id="scan-fullscreen-img" style="max-width: 200%; max-height: none; width: 100%; object-fit: contain; transition: transform 0.2s;" />
165
+ </div>
166
+ </div>
167
+
168
+
169
+ </div>
170
+ `;
171
+
172
+ this.bindEvents();
173
+ }
174
+
175
+ bindEvents() {
176
+ const fileInput = document.getElementById('scan-file-input');
177
+ const resetBtn = document.getElementById('scan-reset-btn');
178
+ const downloadBtn = document.getElementById('scan-download-btn');
179
+ const openCameraBtn = document.getElementById('scan-open-camera-btn');
180
+ const uploadFileBtn = document.getElementById('scan-upload-file-btn');
181
+
182
+ // Camera Elements
183
+ const cameraContainer = document.getElementById('camera-container');
184
+ const actionButtons = document.getElementById('scan-action-buttons');
185
+ const cameraVideo = document.getElementById('camera-video');
186
+ const cameraCaptureBtn = document.getElementById('camera-capture-btn');
187
+ const cameraCloseBtn = document.getElementById('camera-close-btn');
188
+
189
+ this.stream = null;
190
+
191
+ uploadFileBtn.addEventListener('click', () => fileInput.click());
192
+
193
+ fileInput.addEventListener('change', (e) => {
194
+ if (e.target.files && e.target.files[0]) {
195
+ this.processImage(e.target.files[0]);
196
+ }
197
+ });
198
+
199
+ // Live Camera Logic
200
+ openCameraBtn.addEventListener('click', async () => {
201
+ try {
202
+ try {
203
+ await Camera.requestPermissions();
204
+ } catch (e) {
205
+ console.log('Capacitor Camera plugin requestPermissions fallback', e);
206
+ }
207
+ this.stream = await navigator.mediaDevices.getUserMedia({
208
+ video: { facingMode: 'environment', width: { ideal: 1920 }, height: { ideal: 1080 } }
209
+ });
210
+ cameraVideo.srcObject = this.stream;
211
+ actionButtons.style.display = 'none';
212
+ cameraContainer.style.display = 'block';
213
+ } catch (err) {
214
+ console.error('getUserMedia failed, falling back to file input:', err);
215
+ // Fallback to native file input which supports capture="environment"
216
+ document.getElementById('scan-file-input').click();
217
+ }
218
+ });
219
+
220
+ const stopCamera = () => {
221
+ if (this.stream) {
222
+ this.stream.getTracks().forEach(track => track.stop());
223
+ this.stream = null;
224
+ }
225
+ cameraContainer.style.display = 'none';
226
+ actionButtons.style.display = 'flex';
227
+ };
228
+
229
+ cameraCloseBtn.addEventListener('click', stopCamera);
230
+
231
+ cameraCaptureBtn.addEventListener('mousedown', () => cameraCaptureBtn.style.transform = 'translateX(-50%) scale(0.9)');
232
+ cameraCaptureBtn.addEventListener('mouseup', () => cameraCaptureBtn.style.transform = 'translateX(-50%) scale(1)');
233
+ cameraCaptureBtn.addEventListener('mouseleave', () => cameraCaptureBtn.style.transform = 'translateX(-50%) scale(1)');
234
+
235
+ cameraCaptureBtn.addEventListener('click', () => {
236
+ // Create an invisible canvas to grab the frame
237
+ const tmpCanvas = document.createElement('canvas');
238
+ tmpCanvas.width = cameraVideo.videoWidth;
239
+ tmpCanvas.height = cameraVideo.videoHeight;
240
+ const ctx = tmpCanvas.getContext('2d');
241
+ ctx.drawImage(cameraVideo, 0, 0, tmpCanvas.width, tmpCanvas.height);
242
+
243
+ // Convert to blob and process
244
+ tmpCanvas.toBlob((blob) => {
245
+ if (blob) {
246
+ const file = new File([blob], "scan.jpg", { type: "image/jpeg" });
247
+ stopCamera();
248
+ this.processImage(file);
249
+ }
250
+ }, 'image/jpeg', 0.95);
251
+ });
252
+
253
+
254
+ // Fullscreen Events
255
+ const vaultBtn = document.getElementById('scan-vault-btn');
256
+ const flashcardsBtn = document.getElementById('scan-flashcards-btn');
257
+
258
+ document.getElementById('scan-result-img-container').addEventListener('click', () => {
259
+ const canvas = document.getElementById('scan-canvas');
260
+ this.openFullscreen(canvas.toDataURL('image/jpeg', 0.9));
261
+ });
262
+
263
+ document.getElementById('fullscreen-close-btn').addEventListener('click', () => {
264
+ const fsModal = document.getElementById('scan-fullscreen-modal');
265
+ if (fsModal) fsModal.style.display = 'none';
266
+ });
267
+
268
+ resetBtn.addEventListener('click', () => {
269
+ document.getElementById('scan-result-area').style.display = 'none';
270
+ document.getElementById('scan-upload-area').style.display = 'flex';
271
+ fileInput.value = '';
272
+ });
273
+
274
+ flashcardsBtn.addEventListener('click', async () => {
275
+ if (this.isProcessing) return;
276
+
277
+ const explanationText = this.lastExplanation || "";
278
+ if (!explanationText) {
279
+ alert("Keine Texte zum Generieren gefunden.");
280
+ return;
281
+ }
282
+
283
+ const originalHtml = flashcardsBtn.innerHTML;
284
+ flashcardsBtn.innerHTML = '<div style="width: 16px; height: 16px; border: 2px solid rgba(255,255,255,0.2); border-top-color: white; border-radius: 50%; animation: spin 1s linear infinite; margin-right: 8px;"></div> Erstelle...';
285
+ flashcardsBtn.disabled = true;
286
+
287
+ try {
288
+ const prompt = `Extrahiere aus dem folgenden Text alle relevanten Fakten, Fragen/Antworten oder Vokabeln und erstelle daraus sinnvolle Karteikarten. Formatiere die Ausgabe als JSON, um das Tool 'create_flashcards' aufzurufen. Text:\n\n${explanationText}`;
289
+ const apiKey = db.getSetting('gemini_api_key');
290
+
291
+ await gemini.generateContent(
292
+ prompt,
293
+ 'gemini-1.5-flash',
294
+ apiKey,
295
+ "Du rufst ausschließlich das Tool 'create_flashcards' auf, um Karteikarten zu erstellen. Erfinde einen passenden 'deck_title'.",
296
+ []
297
+ );
298
+
299
+ flashcardsBtn.innerHTML = 'Erledigt! ✔️';
300
+ setTimeout(() => {
301
+ flashcardsBtn.innerHTML = originalHtml;
302
+ flashcardsBtn.disabled = false;
303
+ }, 3000);
304
+ } catch (err) {
305
+ console.error("Fehler beim Erstellen der Karteikarten:", err);
306
+ alert("Fehler: " + err.message);
307
+ flashcardsBtn.innerHTML = originalHtml;
308
+ flashcardsBtn.disabled = false;
309
+ }
310
+ });
311
+ downloadBtn.addEventListener('click', () => {
312
+ const canvas = document.getElementById('scan-canvas');
313
+ const link = document.createElement('a');
314
+ link.download = 'Lösung_Arbeitsblatt.png';
315
+ link.href = canvas.toDataURL('image/png');
316
+ link.click();
317
+ });
318
+
319
+ vaultBtn.addEventListener('click', async () => {
320
+ if (this.isProcessing) return;
321
+
322
+ const explanationText = this.lastExplanation || "Ausgefülltes Arbeitsblatt";
323
+ const originalHtml = vaultBtn.innerHTML;
324
+
325
+ vaultBtn.innerHTML = '<div style="width: 16px; height: 16px; border: 2px solid rgba(255,255,255,0.2); border-top-color: white; border-radius: 50%; animation: spin 1s linear infinite; margin-right: 8px;"></div> Speichere...';
326
+ vaultBtn.disabled = true;
327
+
328
+ try {
329
+ const folders = await folderAgent.suggestFolders(explanationText);
330
+ const bestFolder = folders[0] || "Arbeitsblätter";
331
+ const filename = await folderAgent.generateFilename(explanationText);
332
+
333
+ await fsService.createFolder(bestFolder);
334
+
335
+ const meta = db.getFolderMetadata(bestFolder);
336
+ if (!meta || !meta.emoji) {
337
+ const visuals = await folderAgent.generateVisualsForFolder(bestFolder);
338
+ db.saveFolderMetadata(bestFolder, visuals.emoji, visuals.color);
339
+ }
340
+
341
+ const canvas = document.getElementById('scan-canvas');
342
+ const dataUrl = canvas.toDataURL('image/jpeg', 0.9);
343
+ const base64Data = dataUrl.split(',')[1];
344
+
345
+ await fsService.writeFile(`${bestFolder}/${filename}.jpg`, base64Data);
346
+
347
+ vaultBtn.innerHTML = '<svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" stroke-width="2" fill="none" style="margin-right: 8px;"><polyline points="20 6 9 17 4 12"></polyline></svg> In ' + bestFolder;
348
+ vaultBtn.style.background = 'rgba(76, 175, 80, 0.2)';
349
+ vaultBtn.style.borderColor = 'rgba(76, 175, 80, 0.5)';
350
+ vaultBtn.style.color = '#81c784';
351
+
352
+ } catch (e) {
353
+ console.error(e);
354
+ vaultBtn.innerHTML = 'Fehler beim Speichern';
355
+ vaultBtn.disabled = false;
356
+ setTimeout(() => {
357
+ vaultBtn.innerHTML = originalHtml;
358
+ }, 3000);
359
+ }
360
+ });
361
+ }
362
+
363
+
364
+ openFullscreen(imageSrc) {
365
+ const modal = document.getElementById('scan-fullscreen-modal');
366
+ const img = document.getElementById('scan-fullscreen-img');
367
+ img.src = imageSrc;
368
+ img.style.transform = 'scale(1)'; // reset zoom
369
+ modal.style.display = 'flex';
370
+ }
371
+
372
+ async isHeicFile(file) {
373
+ // Quick check
374
+ if (file.type === 'image/heic' || file.type === 'image/heif' || file.name.match(/\.(heic|heif)$/i)) return true;
375
+ // Deep check
376
+ try {
377
+ const buffer = await file.slice(0, 12).arrayBuffer();
378
+ const arr = new Uint8Array(buffer);
379
+ const sig = String.fromCharCode(...arr.slice(4, 12));
380
+ return sig.includes('heic') || sig.includes('mif1') || sig.includes('heix') || sig.includes('hevc');
381
+ } catch (e) {
382
+ return false;
383
+ }
384
+ }
385
+
386
+ async processImage(file) {
387
+ const explanationDiv = document.getElementById('scan-explanation');
388
+
389
+ // HEIC Auto-Conversion
390
+ let processableFile = file;
391
+ const isHeic = await this.isHeicFile(file);
392
+ if (isHeic) {
393
+ try {
394
+ explanationDiv.innerHTML = "<div style='color: var(--primary-color);'>Konvertiere iPhone-Foto (HEIC) in Browser-Format... Bitte warten.</div>";
395
+ document.getElementById('scan-processing').style.display = 'flex';
396
+ document.getElementById('scan-upload-area').style.display = 'none';
397
+
398
+ const heic2any = (await import('heic2any')).default;
399
+ const convertedBlob = await heic2any({ blob: file, toType: "image/jpeg", quality: 0.8 });
400
+ processableFile = new File(
401
+ [Array.isArray(convertedBlob) ? convertedBlob[0] : convertedBlob],
402
+ "converted.jpg",
403
+ { type: "image/jpeg" }
404
+ );
405
+ } catch (err) {
406
+ console.error("HEIC conversion failed:", err);
407
+ alert("Das iPhone-Bild konnte nicht umgewandelt werden. Bitte lade ein Standard-JPG hoch.");
408
+ document.getElementById('scan-processing').style.display = 'none';
409
+ document.getElementById('scan-upload-area').style.display = 'flex';
410
+ return;
411
+ }
412
+ }
413
+
414
+ const isImage = processableFile.type.startsWith('image/') || processableFile.name.match(/\.(jpg|jpeg|png|gif|webp)$/i);
415
+ if (!isImage) {
416
+ alert('Bitte lade ein gültiges Bild hoch.');
417
+ return;
418
+ }
419
+
420
+ const uploadArea = document.getElementById('scan-upload-area');
421
+ const processingArea = document.getElementById('scan-processing');
422
+ const resultArea = document.getElementById('scan-result-area');
423
+
424
+ uploadArea.style.display = 'none';
425
+ processingArea.style.display = 'flex';
426
+ resultArea.style.display = 'none';
427
+
428
+ try {
429
+ // Load file into an Image element to show in Crop UI
430
+ const base64DataOriginal = await new Promise((resolve, reject) => {
431
+ const reader = new FileReader();
432
+ reader.onload = () => resolve(reader.result);
433
+ reader.onerror = () => reject(new Error('Fehler beim Lesen der Datei'));
434
+ reader.readAsDataURL(processableFile);
435
+ });
436
+
437
+ const imgElem = new Image();
438
+ await new Promise(resolve => {
439
+ imgElem.onload = resolve;
440
+ imgElem.src = base64DataOriginal;
441
+ });
442
+
443
+ // Show Crop Modal
444
+ const croppedBase64 = await this.openCropModal(imgElem);
445
+ if (!croppedBase64) {
446
+ uploadArea.style.display = 'flex';
447
+ processingArea.style.display = 'none';
448
+ return; // User cancelled
449
+ }
450
+
451
+ const explanationDiv = document.getElementById('scan-explanation');
452
+ explanationDiv.innerHTML = "<div style='color: var(--primary-color);'>Analysiere Arbeitsblatt...</div>";
453
+
454
+ const base64Data = croppedBase64;
455
+ const apiKey = db.getSetting('gemini_api_key');
456
+
457
+ if (!apiKey) {
458
+ throw new Error('Gemini API Key ist nicht konfiguriert. Bitte in den Einstellungen eintragen.');
459
+ }
460
+
461
+ // System Instruction for the AI
462
+ const systemInstruction = `Du bist ein Lehrer-Assistent mit exzellentem räumlichen Vorstellungsvermögen. Analysiere das begradigte Foto eines Arbeitsblattes und löse alle Aufgaben.
463
+
464
+ DEINE AUFGABE:
465
+ 1. Lies das gesamte Arbeitsblatt sorgfältig.
466
+ 2. Identifiziere ALLE leeren Linien, Kästchen oder Lücken, an denen der Schüler etwas eintragen soll.
467
+ 3. Löse jede Aufgabe korrekt.
468
+ 4. Gib für JEDE Antwortzeile eine 2D Bounding Box an, die den verfuegbaren Leerraum (die Linie) repraesentiert.
469
+
470
+ KOORDINATEN-REGELN:
471
+ - Format: [ymin, xmin, ymax, xmax] (0 bis 1000). y: 0=oben, 1000=unten. x: 0=links, 1000=rechts.
472
+ - WICHTIG: Die Box MUSS den reinen FREIRAUM markieren, in dem die Handschrift stehen soll.
473
+ - ymax ist die Position der gedruckten Unterstrich-Linie. Die Schrift wird auf dieser y-Koordinate horizontal gezeichnet.
474
+
475
+ ANTWORT-FORMAT:
476
+ - Wenn für eine Antwort mehrere Linien zur Verfügung stehen, erstelle für JEDE leere Linie ein eigenes Objekt in der JSON.
477
+ - Teile lange Antworten sinnvoll auf diese Linien auf.
478
+ - Halte die Antworten präzise und so kurz, dass sie in die Breite passen.
479
+
480
+ JSON (NUR reines JSON, KEIN Markdown):
481
+ {
482
+ "explanation": "Kurze Erklärung des Themas.",
483
+ "answers": [
484
+ {
485
+ "text": "Antwort für die erste Linie",
486
+ "box_2d": [250, 250, 260, 900],
487
+ "has_printed_prefix": true
488
+ },
489
+ {
490
+ "text": "Antwort für die zweite Linie",
491
+ "box_2d": [300, 50, 310, 900],
492
+ "has_printed_prefix": false
493
+ }
494
+ ]
495
+ }`;
496
+
497
+ const prompt = `Löse alle Aufgaben auf diesem begradigten Arbeitsblatt. Gib für jede auszufüllende Linie die perfekte Bounding Box an. Achte streng darauf, dass die Box keinen gedruckten Text überlappt!\n![image](${base64Data})`;
498
+
499
+ // 4. Call Gemini
500
+ const localModelSelect = document.getElementById('scan-local-model');
501
+ const modelToUse = localModelSelect ? localModelSelect.value : (db.getSetting('model') || 'gemini-3.5-flash');
502
+ const rawResponse = await gemini.generateContent(
503
+ prompt,
504
+ modelToUse,
505
+ apiKey,
506
+ systemInstruction,
507
+ [],
508
+ { responseMimeType: "application/json" }
509
+ );
510
+
511
+ let parsedData;
512
+ try {
513
+ const cleanJson = rawResponse.replace(/^```json/m, '').replace(/```$/m, '').trim();
514
+ parsedData = JSON.parse(cleanJson);
515
+ } catch (err) {
516
+ console.error('Failed to parse AI response:', rawResponse);
517
+ throw new Error('Die KI hat eine ungültige Antwort zurückgegeben. Bitte versuche es noch einmal.');
518
+ }
519
+
520
+ // Reset UI
521
+ document.getElementById('scan-upload-area').style.display = 'none';
522
+ const processingText = document.getElementById('scan-processing-text');
523
+ processingArea.style.display = 'flex';
524
+ processingText.innerText = "Handschrift wird erzeugt...";
525
+
526
+ // Draw the final result
527
+ await this.drawOnCanvas(base64Data, parsedData);
528
+
529
+ // Show result
530
+ processingArea.style.display = 'none';
531
+ document.getElementById('scan-result-area').style.display = 'flex';
532
+
533
+ let explanationHtml = parsedData.explanation ? `<p>${parsedData.explanation}</p>` : "<p>Arbeitsblatt ausgewertet.</p>";
534
+ this.lastExplanation = parsedData.explanation || "";
535
+ explanationHtml += `<details style="margin-top: 12px; padding: 12px; background: rgba(255,255,255,0.05); border-radius: 8px; font-size: 12px;">
536
+ <summary style="cursor: pointer; color: #aaa;">🔍 Debug: KI-Rohdaten anzeigen</summary>
537
+ <pre style="white-space: pre-wrap; word-break: break-all; margin-top: 8px; color: #8f8; font-family: monospace; max-height: 300px; overflow: auto;">${JSON.stringify(parsedData, null, 2)}</pre>
538
+ </details>`;
539
+ explanationDiv.innerHTML = explanationHtml;
540
+
541
+ } catch (error) {
542
+ console.error(error);
543
+ alert('Fehler beim Analysieren des Arbeitsblattes: ' + error.message);
544
+ uploadArea.style.display = 'flex';
545
+ processingArea.style.display = 'none';
546
+ }
547
+ }
548
+
549
+ async drawOnCanvas(imageSrc, parsedData) {
550
+ const canvas = document.getElementById('scan-canvas');
551
+ const ctx = canvas.getContext('2d');
552
+
553
+ return new Promise((resolve, reject) => {
554
+ const img = new Image();
555
+ img.onload = () => {
556
+ try {
557
+ canvas.width = img.width;
558
+ canvas.height = img.height;
559
+ ctx.drawImage(img, 0, 0);
560
+
561
+ const answers = parsedData.answers;
562
+ if (!answers || !Array.isArray(answers) || answers.length === 0) {
563
+ return resolve();
564
+ }
565
+
566
+ const imgWidth = img.width;
567
+ const imgHeight = img.height;
568
+
569
+ answers.forEach(answer => {
570
+ if (!answer.text || !answer.box_2d || !Array.isArray(answer.box_2d) || answer.box_2d.length !== 4) return;
571
+
572
+ // Format: [ymin, xmin, ymax, xmax] from 0 to 1000
573
+ const [ymin_1000, xmin_1000, ymax_1000, xmax_1000] = answer.box_2d;
574
+
575
+ // Normalize to 0-1
576
+ let x1 = xmin_1000 / 1000;
577
+ const y1 = ymin_1000 / 1000;
578
+ let x2 = xmax_1000 / 1000;
579
+ const y2 = ymax_1000 / 1000;
580
+
581
+ // Enforce margin if there is a printed prefix
582
+ if (answer.has_printed_prefix && x1 < 0.18) {
583
+ x1 = 0.18;
584
+ }
585
+
586
+ // Convert AI coordinates to pixels
587
+ let finalX1 = Math.floor(x1 * img.width);
588
+ let finalX2 = Math.floor(Math.max(x1 + 0.05, x2) * img.width);
589
+ // We use ymax (y2) as the baseline for the text
590
+ let finalY = Math.floor(y2 * img.height);
591
+
592
+ const lineLength = Math.max(10, finalX2 - finalX1);
593
+
594
+ // Standard font size based on image height (e.g. 1.8%)
595
+ let fontSize = Math.floor(img.height * 0.018);
596
+
597
+ // If the text is short, don't make it giant! Just keep the natural handwriting size.
598
+ // Only shrink if it's too long.
599
+ ctx.font = `${fontSize}px 'Caveat', cursive, sans-serif`;
600
+ let textWidth = ctx.measureText(answer.text).width;
601
+
602
+ // Padding so handwriting doesn't touch the very edges of the line
603
+ const paddingX = Math.max(5, img.width * 0.015);
604
+ const availableLength = Math.max(10, lineLength - paddingX * 2);
605
+
606
+ if (textWidth > availableLength) {
607
+ // Shrink font to fit the line
608
+ fontSize = Math.max(12, Math.floor(fontSize * (availableLength / textWidth) * 0.95));
609
+ }
610
+
611
+ ctx.font = `${fontSize}px 'Caveat', cursive, sans-serif`;
612
+ ctx.fillStyle = '#1a3a8a';
613
+ ctx.textBaseline = 'alphabetic';
614
+
615
+ ctx.save();
616
+
617
+ // Move origin to x1
618
+ // For Y, we shift it up by ~15% of the font size so the letters sit clearly ABOVE the physical line,
619
+ // instead of cutting exactly through it.
620
+ ctx.translate(finalX1 + paddingX, finalY - Math.floor(fontSize * 0.15));
621
+
622
+ const naturalJitterAngle = (Math.random() - 0.5) * 0.015;
623
+ ctx.rotate(naturalJitterAngle);
624
+
625
+ ctx.fillText(answer.text, 0, 0);
626
+ ctx.restore();
627
+ });
628
+
629
+ resolve();
630
+ } catch (e) {
631
+ console.error("Canvas drawing error:", e);
632
+ reject(e);
633
+ }
634
+ };
635
+ img.onerror = () => reject(new Error('Konnte das Bild nicht für das Canvas laden.'));
636
+ img.src = imageSrc;
637
+ });
638
+ }
639
+
640
+ openCropModal(imgElem) {
641
+ return new Promise((resolve) => {
642
+ const modal = document.getElementById('crop-modal');
643
+ const img = document.getElementById('crop-img');
644
+ const svg = document.getElementById('crop-svg');
645
+ const polygon = document.getElementById('crop-polygon');
646
+ const handles = Array.from(document.querySelectorAll('.crop-handle'));
647
+ const cancelBtn = document.getElementById('crop-cancel-btn');
648
+ const confirmBtn = document.getElementById('crop-confirm-btn');
649
+ const cropArea = document.getElementById('crop-area');
650
+
651
+ modal.style.display = 'flex';
652
+
653
+ // Calculate fit
654
+ const areaRect = cropArea.getBoundingClientRect();
655
+ const areaAspect = areaRect.width / areaRect.height;
656
+ const imgAspect = imgElem.width / imgElem.height;
657
+
658
+ let scale = 1;
659
+ let left = 0;
660
+ let top = 0;
661
+
662
+ if (imgAspect > areaAspect) {
663
+ scale = areaRect.width / imgElem.width;
664
+ top = (areaRect.height - imgElem.height * scale) / 2;
665
+ } else {
666
+ scale = areaRect.height / imgElem.height;
667
+ left = (areaRect.width - imgElem.width * scale) / 2;
668
+ }
669
+
670
+ img.src = imgElem.src;
671
+ img.style.width = imgElem.width + 'px';
672
+ img.style.height = imgElem.height + 'px';
673
+ img.style.transform = `translate(${left}px, ${top}px) scale(${scale})`;
674
+
675
+ // Initial Corners (10% margin)
676
+ const margin = 0.1;
677
+ const w = imgElem.width * scale;
678
+ const h = imgElem.height * scale;
679
+ let corners = [
680
+ {x: left + w * margin, y: top + h * margin},
681
+ {x: left + w * (1 - margin), y: top + h * margin},
682
+ {x: left + w * (1 - margin), y: top + h * (1 - margin)},
683
+ {x: left + w * margin, y: top + h * (1 - margin)}
684
+ ];
685
+
686
+ const updateUI = () => {
687
+ // Update Polygon
688
+ polygon.setAttribute('points', corners.map(c => `${c.x},${c.y}`).join(' '));
689
+
690
+ // Update Grid (6x6 Grid)
691
+ const gridGroup = document.getElementById('crop-grid-group');
692
+ if (gridGroup) {
693
+ gridGroup.innerHTML = '';
694
+ // We want 6 inner lines vertically and 6 horizontally
695
+ for (let i = 1; i <= 6; i++) {
696
+ const fraction = i / 7;
697
+
698
+ // Vertical lines
699
+ const topPt = { x: corners[0].x + (corners[1].x - corners[0].x) * fraction, y: corners[0].y + (corners[1].y - corners[0].y) * fraction };
700
+ const botPt = { x: corners[3].x + (corners[2].x - corners[3].x) * fraction, y: corners[3].y + (corners[2].y - corners[3].y) * fraction };
701
+
702
+ const vLine = document.createElementNS('http://www.w3.org/2000/svg', 'line');
703
+ vLine.setAttribute('x1', topPt.x);
704
+ vLine.setAttribute('y1', topPt.y);
705
+ vLine.setAttribute('x2', botPt.x);
706
+ vLine.setAttribute('y2', botPt.y);
707
+ vLine.setAttribute('stroke', '#ff4040');
708
+ vLine.setAttribute('stroke-width', '1');
709
+ vLine.setAttribute('opacity', '0.6');
710
+ gridGroup.appendChild(vLine);
711
+
712
+ // Horizontal lines
713
+ const leftPt = { x: corners[0].x + (corners[3].x - corners[0].x) * fraction, y: corners[0].y + (corners[3].y - corners[0].y) * fraction };
714
+ const rightPt = { x: corners[1].x + (corners[2].x - corners[1].x) * fraction, y: corners[1].y + (corners[2].y - corners[1].y) * fraction };
715
+
716
+ const hLine = document.createElementNS('http://www.w3.org/2000/svg', 'line');
717
+ hLine.setAttribute('x1', leftPt.x);
718
+ hLine.setAttribute('y1', leftPt.y);
719
+ hLine.setAttribute('x2', rightPt.x);
720
+ hLine.setAttribute('y2', rightPt.y);
721
+ hLine.setAttribute('stroke', '#ff4040');
722
+ hLine.setAttribute('stroke-width', '1');
723
+ hLine.setAttribute('opacity', '0.6');
724
+ gridGroup.appendChild(hLine);
725
+ }
726
+ }
727
+
728
+ // Update Handles
729
+ handles.forEach((handle, i) => {
730
+ handle.style.left = corners[i].x + 'px';
731
+ handle.style.top = corners[i].y + 'px';
732
+ });
733
+ };
734
+
735
+ updateUI();
736
+
737
+ // Drag Logic
738
+ let activeHandle = null;
739
+
740
+ const onMove = (e) => {
741
+ if (activeHandle === null) return;
742
+ e.preventDefault();
743
+ const clientX = e.touches ? e.touches[0].clientX : e.clientX;
744
+ const clientY = e.touches ? e.touches[0].clientY : e.clientY;
745
+ const rect = cropArea.getBoundingClientRect();
746
+
747
+ let nx = clientX - rect.left;
748
+ let ny = clientY - rect.top;
749
+
750
+ // Bounds check against image visually
751
+ nx = Math.max(left, Math.min(left + w, nx));
752
+ ny = Math.max(top, Math.min(top + h, ny));
753
+
754
+ corners[activeHandle] = {x: nx, y: ny};
755
+ updateUI();
756
+ };
757
+
758
+ const onUp = () => {
759
+ activeHandle = null;
760
+ document.removeEventListener('mousemove', onMove);
761
+ document.removeEventListener('mouseup', onUp);
762
+ document.removeEventListener('touchmove', onMove);
763
+ document.removeEventListener('touchend', onUp);
764
+ };
765
+
766
+ const onDown = (e, index) => {
767
+ e.preventDefault();
768
+ activeHandle = index;
769
+ document.addEventListener('mousemove', onMove, {passive: false});
770
+ document.addEventListener('mouseup', onUp);
771
+ document.addEventListener('touchmove', onMove, {passive: false});
772
+ document.addEventListener('touchend', onUp);
773
+ };
774
+
775
+ handles.forEach((handle, i) => {
776
+ handle.onmousedown = (e) => onDown(e, i);
777
+ handle.ontouchstart = (e) => onDown(e, i);
778
+ });
779
+
780
+ const cleanup = () => {
781
+ modal.style.display = 'none';
782
+ cancelBtn.onclick = null;
783
+ confirmBtn.onclick = null;
784
+ handles.forEach(h => { h.onmousedown = null; h.ontouchstart = null; });
785
+ };
786
+
787
+ cancelBtn.onclick = () => {
788
+ cleanup();
789
+ resolve(null);
790
+ };
791
+
792
+ confirmBtn.onclick = async () => {
793
+ confirmBtn.innerHTML = "Wird begradigt...";
794
+ confirmBtn.disabled = true;
795
+
796
+ // Convert screen coordinates to original image pixels
797
+ const pixelCorners = corners.map(c => ({
798
+ x: (c.x - left) / scale,
799
+ y: (c.y - top) / scale
800
+ }));
801
+
802
+ // Warp Image
803
+ // Use a small timeout to let the UI update the button text
804
+ await new Promise(r => setTimeout(r, 50));
805
+
806
+ try {
807
+ const resultBase64 = await this.warpImage(imgElem, pixelCorners);
808
+ cleanup();
809
+ confirmBtn.innerHTML = "Zuschneiden & Analysieren";
810
+ confirmBtn.disabled = false;
811
+ resolve(resultBase64);
812
+ } catch(e) {
813
+ console.error("Warp failed", e);
814
+ alert("Fehler beim Begradigen des Bildes.");
815
+ cleanup();
816
+ confirmBtn.innerHTML = "Zuschneiden & Analysieren";
817
+ confirmBtn.disabled = false;
818
+ resolve(null);
819
+ }
820
+ };
821
+ });
822
+ }
823
+
824
+ async warpImage(imgElement, corners) {
825
+ const wTop = Math.hypot(corners[1].x - corners[0].x, corners[1].y - corners[0].y);
826
+ const wBot = Math.hypot(corners[2].x - corners[3].x, corners[2].y - corners[3].y);
827
+ const hLeft = Math.hypot(corners[3].x - corners[0].x, corners[3].y - corners[0].y);
828
+ const hRight = Math.hypot(corners[2].x - corners[1].x, corners[2].y - corners[1].y);
829
+
830
+ const dstW = Math.round(Math.max(wTop, wBot));
831
+ const dstH = Math.round(Math.max(hLeft, hRight));
832
+
833
+ const srcPts = [
834
+ corners[0].x, corners[0].y,
835
+ corners[1].x, corners[1].y,
836
+ corners[2].x, corners[2].y,
837
+ corners[3].x, corners[3].y
838
+ ];
839
+ const dstPts = [
840
+ 0, 0,
841
+ dstW, 0,
842
+ dstW, dstH,
843
+ 0, dstH
844
+ ];
845
+
846
+ const pt = perspective(srcPts, dstPts);
847
+
848
+ const srcCanvas = document.createElement('canvas');
849
+ srcCanvas.width = imgElement.width;
850
+ srcCanvas.height = imgElement.height;
851
+ const srcCtx = srcCanvas.getContext('2d', { willReadFrequently: true });
852
+ srcCtx.drawImage(imgElement, 0, 0);
853
+ const srcData = srcCtx.getImageData(0, 0, srcCanvas.width, srcCanvas.height);
854
+
855
+ const dstCanvas = document.createElement('canvas');
856
+ dstCanvas.width = dstW;
857
+ dstCanvas.height = dstH;
858
+ const dstCtx = dstCanvas.getContext('2d');
859
+ const dstData = dstCtx.createImageData(dstW, dstH);
860
+
861
+ for (let y = 0; y < dstH; y++) {
862
+ for (let x = 0; x < dstW; x++) {
863
+ const [srcX, srcY] = pt.transformInverse(x, y);
864
+ const sx = Math.floor(srcX);
865
+ const sy = Math.floor(srcY);
866
+
867
+ if (sx >= 0 && sx < srcCanvas.width && sy >= 0 && sy < srcCanvas.height) {
868
+ const dstIdx = (y * dstW + x) * 4;
869
+ const srcIdx = (sy * srcCanvas.width + sx) * 4;
870
+ dstData.data[dstIdx] = srcData.data[srcIdx];
871
+ dstData.data[dstIdx+1] = srcData.data[srcIdx+1];
872
+ dstData.data[dstIdx+2] = srcData.data[srcIdx+2];
873
+ dstData.data[dstIdx+3] = srcData.data[srcIdx+3];
874
+ }
875
+ }
876
+ }
877
+
878
+ dstCtx.putImageData(dstData, 0, 0);
879
+ return dstCanvas.toDataURL('image/jpeg', 0.9);
880
+ }
881
+
882
+ showCustomConfirm(title, text, onConfirm) {
883
+ const overlay = document.createElement('div');
884
+ overlay.className = 'custom-modal-overlay';
885
+ overlay.innerHTML = `
886
+ <div class="custom-modal">
887
+ <h3>${title}</h3>
888
+ <p>${text}</p>
889
+ <div class="modal-actions">
890
+ <button class="modal-btn cancel">Abbrechen</button>
891
+ <button class="modal-btn confirm danger">Löschen</button>
892
+ </div>
893
+ </div>
894
+ `;
895
+ document.body.appendChild(overlay);
896
+
897
+ const close = () => {
898
+ overlay.classList.add('fade-out');
899
+ setTimeout(() => overlay.remove(), 200);
900
+ };
901
+
902
+ overlay.querySelector('.cancel').onclick = close;
903
+ overlay.querySelector('.confirm').onclick = () => {
904
+ onConfirm();
905
+ close();
906
+ };
907
+ }
908
  }
src/views/settings/settings-view.js CHANGED
@@ -50,7 +50,9 @@ export class SettingsView {
50
  <label style="display: block; margin-bottom: 8px; color: var(--text-secondary); font-size: 14px;">Aktives Modell</label>
51
  <select id="model-select" style="width: 100%; padding: 12px; border-radius: 12px; background: rgba(0,0,0,0.4); border: 1px solid rgba(255,255,255,0.1); color: white; font-family: var(--font-ui); font-size: 16px; margin-bottom: 16px; outline: none; appearance: none;">
52
  <optgroup label="Google Gemini">
 
53
  <option value="gemini-3.5-flash" ${currentModel === 'gemini-3.5-flash' ? 'selected' : ''}>Gemini 3.5 Flash</option>
 
54
  <option value="gemini-3.1-flash-lite" ${currentModel === 'gemini-3.1-flash-lite' ? 'selected' : ''}>Gemini 3.1 Flash Lite</option>
55
  <option value="gemini-3-flash-preview" ${currentModel === 'gemini-3-flash-preview' ? 'selected' : ''}>Gemini 3 Flash Preview</option>
56
  <option value="gemini-2.5-flash" ${currentModel === 'gemini-2.5-flash' ? 'selected' : ''}>Gemini 2.5 Flash</option>
 
50
  <label style="display: block; margin-bottom: 8px; color: var(--text-secondary); font-size: 14px;">Aktives Modell</label>
51
  <select id="model-select" style="width: 100%; padding: 12px; border-radius: 12px; background: rgba(0,0,0,0.4); border: 1px solid rgba(255,255,255,0.1); color: white; font-family: var(--font-ui); font-size: 16px; margin-bottom: 16px; outline: none; appearance: none;">
52
  <optgroup label="Google Gemini">
53
+ <option value="gemini-3.6-flash" ${currentModel === 'gemini-3.6-flash' ? 'selected' : ''}>Gemini 3.6 Flash</option>
54
  <option value="gemini-3.5-flash" ${currentModel === 'gemini-3.5-flash' ? 'selected' : ''}>Gemini 3.5 Flash</option>
55
+ <option value="gemini-3.5-flash-lite" ${currentModel === 'gemini-3.5-flash-lite' ? 'selected' : ''}>Gemini 3.5 Flash Lite</option>
56
  <option value="gemini-3.1-flash-lite" ${currentModel === 'gemini-3.1-flash-lite' ? 'selected' : ''}>Gemini 3.1 Flash Lite</option>
57
  <option value="gemini-3-flash-preview" ${currentModel === 'gemini-3-flash-preview' ? 'selected' : ''}>Gemini 3 Flash Preview</option>
58
  <option value="gemini-2.5-flash" ${currentModel === 'gemini-2.5-flash' ? 'selected' : ''}>Gemini 2.5 Flash</option>