Repository navigation
Expand file tree
/
Copy patheditor_shell.js
More file actions
530 lines (479 loc) · 17.5 KB
/
Copy patheditor_shell.js
File metadata and controls
530 lines (479 loc) · 17.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
/**
* WriterAgent editor shell: pywebview bridge, toolbar, save/run/cancel wiring,
* dirty tracking, theme and UI strings. All editor-widget calls go through the
* backend object (see backend_monaco.js for the interface). Keep this file free
* of Monaco-specific calls; keep backends free of pywebview and UNO.
*/
// =========================================================================================
// WARNING: PARITY INVARIANT WITH PYTHON HOST & IPC PROTOCOL
// If you modify message parsing, shortcuts, save/run dispatch, or UI strings handling,
// you MUST also update the corresponding Python modules:
// - Python Host Bridge: plugin/scripting/editor_host.py
// - IPC Message Protocol: plugin/scripting/editor_ipc.py
// - UI Strings Catalog: plugin/scripting/editor_ui_strings.py
// - Script Manager Frontend: plugin/contrib/scripting/assets/editor/scripts_manager.js
// - Monaco Backend: plugin/contrib/scripting/assets/editor/backend_monaco.js
// - Native Cell Editor: plugin/calc/python/cell_editor_ui.py
// (calc_cell Save / Save without =PY() / Data enablement / status)
// =========================================================================================
(function () {
"use strict";
var editor = null;
var backend = null;
var pendingCode = "";
var lastSaveCode = null;
var lastSaveDataBinding = null;
var lastSavePlain = false;
var pendingMarkers = [];
var ui = {};
var defaultStatusOkText = "Saved.";
var pendingStatusText = "Saving…";
var currentMode = "calc_cell";
var sessionId = "";
var sessionTarget = {};
var isDirty = false;
var suppressDirty = false;
var dataBindingTitle = "Calc injects `data` and `ranges` from these range(s) at runtime.";
var dataBindingDisabledTitle = "Data ranges apply only when saving as a =PY() formula.";
var followCodeRef = false;
var requestedSave = false;
var savePendingLoad = false;
function t(key, fallback) {
var value = ui[key];
return value !== undefined && value !== null && value !== "" ? value : fallback;
}
function fmt(key) {
var template = t(key, "");
var args = arguments;
return template.replace(/\{(\d+)\}/g, function (_, index) {
var argIndex = parseInt(index, 10) + 1;
return args[argIndex] !== undefined ? args[argIndex] : "";
});
}
function setStatus(text, kind) {
var el = document.getElementById("status");
if (el) {
var prefix = t("status_prefix", "Status:");
var label = text || t("ready", "Ready");
if (prefix && label.indexOf(prefix) !== 0) {
label = prefix + " " + label;
}
el.value = label;
el.classList.remove("status-ok", "status-error");
if (kind === "ok") {
el.classList.add("status-ok");
} else if (kind === "error") {
el.classList.add("status-error");
}
}
}
function applyTheme(tinfo) {
if (!tinfo) return;
var isDark = !!(tinfo.is_dark || (tinfo.monaco && tinfo.monaco.indexOf("dark") !== -1));
document.body.classList.toggle("dark", isDark);
document.body.classList.toggle("light", !isDark);
}
function formatErrorMessage(msg) {
var text = msg.message || t("error", "Error");
if (msg.traceback) {
var lines = String(msg.traceback).split("\n");
for (var i = 0; i < lines.length; i++) {
var line = lines[i].trim();
if (line) {
text = text + " — " + line;
break;
}
}
}
return text;
}
function getDataBindingInput() {
return document.getElementById("data-binding-input");
}
function getPlainTextCheckbox() {
return document.getElementById("chk-plain-text");
}
function setToolbarVisible(elementId, visible) {
var el = document.getElementById(elementId);
if (el) {
el.classList.toggle("toolbar-hidden", !visible);
}
}
function applyUiChrome() {
var runBtn = document.getElementById("btn-run");
if (runBtn) {
runBtn.textContent = t("run_label", "Run");
}
var saveBtn = document.getElementById("btn-save");
if (saveBtn) {
saveBtn.textContent = t("save_label", "Save");
}
var closeBtn = document.getElementById("btn-cancel");
if (closeBtn) {
closeBtn.textContent = t("close_label", currentMode === "run_script" || currentMode === "latex" ? "Close" : "Cancel");
}
var plainTextEl = document.getElementById("plain-text-save-text");
if (plainTextEl) {
plainTextEl.textContent = t("plain_text_label", "Save without =PY()");
}
var dataLabel = document.getElementById("data-binding-label");
if (dataLabel) {
dataLabel.textContent = t("data_label", "Data:");
}
var dataInput = getDataBindingInput();
if (dataInput) {
dataInput.placeholder = t("data_placeholder", "A1:C1 or A1:C1, C1:C5");
}
dataBindingTitle = t(
"data_binding_title",
"Calc injects `data` and `ranges` from these range(s) at runtime."
);
dataBindingDisabledTitle = t(
"data_binding_disabled_title",
"Data ranges apply only when saving as a =PY() formula."
);
if (dataInput) {
dataInput.title = dataBindingTitle;
}
}
function maybeHintJediMissing() {
if (!window.pywebview || !window.pywebview.api || !window.pywebview.api.is_jedi_available) {
return;
}
window.pywebview.api.is_jedi_available().then(function (ok) {
if (!ok) {
setStatus(t("jedi_missing", "Install jedi in the Python venv for completions."), "");
}
}).catch(function () {});
}
function revealToolbar() {
var tb = document.getElementById("toolbar");
if (tb) {
tb.classList.remove("toolbar-loading");
}
}
function applyLoadMessage(msg) {
ui = msg.ui || {};
if (msg.title) {
document.title = msg.title;
}
var showPlainText = msg.show_plain_text !== false;
var showDataBinding = msg.show_data_binding !== false;
currentMode = msg.mode || "calc_cell";
sessionId = msg.session_id || "";
sessionTarget = msg.target && typeof msg.target === "object" ? msg.target : {};
var isRunScript = currentMode === "run_script";
var isCalcCell = currentMode === "calc_cell";
followCodeRef = !!msg.follow_code_ref;
setToolbarVisible("btn-run", isRunScript);
setToolbarVisible("cell-addr", isCalcCell);
var addrEl = document.getElementById("cell-addr");
if (addrEl) {
addrEl.textContent = isCalcCell ? (msg.cell_address || "") : "";
}
setToolbarVisible("plain-text-save-label", showPlainText);
setToolbarVisible("data-binding-label", showDataBinding);
setToolbarVisible("data-binding-input", showDataBinding);
applyUiChrome();
var plainEl = getPlainTextCheckbox();
if (plainEl) {
plainEl.checked = !!msg.save_as_plain;
}
// status_ok_text is a top-level load/saved field, not a ui key.
defaultStatusOkText = t("saved_default", "Saved.");
if (msg.saved_ok_text) {
defaultStatusOkText = msg.saved_ok_text;
} else if (msg.status_ok_text) {
defaultStatusOkText = msg.status_ok_text;
}
pendingStatusText = isRunScript ? t("running", "Running…") : t("saving", "Saving…");
var text = msg.data_binding || "";
var input = getDataBindingInput();
if (input) {
input.value = text || "";
}
setSavePendingLoad(false);
var code = msg.code || "";
pendingCode = code || "";
if (editor) {
suppressDirty = true;
editor.setValue(pendingCode);
editor.setLanguage(msg.language || "python");
editor.setMarkers(msg.markers || []);
suppressDirty = false;
markDirty(false);
setStatus(t("ready", "Ready"), "");
maybeHintJediMissing();
} else {
pendingMarkers = msg.markers || [];
markDirty(false);
}
if (msg.theme) {
if (backend) {
backend.setTheme(!!msg.theme.is_dark, msg.theme.monaco);
}
applyTheme(msg.theme);
}
revealToolbar();
}
setTimeout(revealToolbar, 500);
function markDirty(dirty) {
var next = !!dirty;
if (isDirty === next) {
return;
}
isDirty = next;
if (window.pywebview && window.pywebview.api && window.pywebview.api.notify_dirty) {
try {
window.pywebview.api.notify_dirty(isDirty, sessionId, currentMode, sessionTarget);
} catch (e) {}
}
}
// The host answers a requested save with load, which replaces the text, so anything typed
// after the save was sent would be lost; lock in the same turn we send because a host ack leaves a gap.
function setSavePendingLoad(on) {
savePendingLoad = !!on;
if (editor) {
editor.setReadOnly(savePendingLoad);
}
updateDataBindingEnabled();
}
function lockForRequestedSave() {
if (requestedSave) {
setSavePendingLoad(true);
}
return requestedSave;
}
function updateDataBindingEnabled() {
var plainEl = getPlainTextCheckbox();
var input = getDataBindingInput();
var label = document.getElementById("data-binding-label");
var disabled = !!plainEl && plainEl.checked && !followCodeRef;
if (plainEl) {
plainEl.disabled = savePendingLoad;
}
if (input) {
input.disabled = savePendingLoad || disabled;
input.title = disabled ? dataBindingDisabledTitle : dataBindingTitle;
}
if (label) {
label.classList.toggle("disabled", disabled);
}
}
function pollMessages() {
if (window.pywebview && window.pywebview.api && window.pywebview.api.poll_messages) {
window.pywebview.api.poll_messages().then(function (messages) {
if (messages && messages.length) {
for (var i = 0; i < messages.length; i++) {
var msg = messages[i];
if (msg && msg.type) {
if (msg.session_id && sessionId && msg.session_id !== sessionId && msg.type !== "load") {
continue;
}
if (msg.type === "load") {
applyLoadMessage(msg);
} else if (msg.type === "request_save") {
var saveBtn = document.getElementById("btn-save");
if (saveBtn) {
// Named Run Script saves go through scripts_manager.js's capture listener;
// it calls lockForRequestedSave() so the editor locks before save_script leaves.
requestedSave = true;
saveBtn.click();
requestedSave = false;
}
} else if (msg.type === "scripts_list") {
if (!msg.load_follows) {
setSavePendingLoad(false);
}
} else if (msg.type === "saved") {
if (msg.load_follows) {
// load replaces the buffer next. The host has already ended this session, and pywebview does
// not order calls, so a notify_dirty with this session id could reach the child after load and
// stamp later messages with the ended id.
continue;
}
setSavePendingLoad(false);
var dataInput = getDataBindingInput();
var plainBox = getPlainTextCheckbox();
var codeKept = getEditorCode() === lastSaveCode;
var dataKept = !dataInput || dataInput.value === lastSaveDataBinding;
var plainKept = !plainBox || plainBox.checked === lastSavePlain;
var stillDirty = isDirty && !(codeKept && dataKept && plainKept);
// Only replace text the user has not changed since clicking Save.
if (editor && typeof msg.code === "string" && codeKept) {
suppressDirty = true;
editor.setValue(msg.code);
suppressDirty = false;
}
if (typeof msg.data_binding === "string" && dataInput && dataKept) {
dataInput.value = msg.data_binding;
}
// The host clears its own flag on each successful save; send one call because
// pywebview dispatches each API call on a separate thread and does not order them.
if (stillDirty) {
isDirty = false;
markDirty(true);
} else {
markDirty(false);
}
var okText = msg.status_ok_text || defaultStatusOkText;
setStatus(okText, "ok");
if (editor && Array.isArray(msg.markers)) {
editor.setMarkers(msg.markers);
}
} else if (msg.type === "error") {
setSavePendingLoad(false);
setStatus(formatErrorMessage(msg), "error");
if (editor && Array.isArray(msg.markers)) {
editor.setMarkers(msg.markers);
}
} else if (msg.type === "theme") {
applyTheme(msg);
}
}
}
}
}).catch(function () {});
}
}
function getEditorCode() {
return editor ? editor.getValue() : pendingCode;
}
window.waEditorUi = {
t: t,
fmt: fmt,
setStatus: setStatus,
isDirty: function () {
return isDirty;
},
markDirty: markDirty,
setSuppressDirty: function (suppress) {
suppressDirty = !!suppress;
},
getUi: function () {
return ui;
},
applyUiFromLoad: function (msg) {
if (msg && msg.ui) {
ui = msg.ui;
applyUiChrome();
}
},
lockForRequestedSave: lockForRequestedSave
};
function rememberSent(code) {
var input = getDataBindingInput();
var plainEl = getPlainTextCheckbox();
lastSaveCode = code;
lastSaveDataBinding = input ? input.value : "";
lastSavePlain = !!plainEl && plainEl.checked;
}
document.getElementById("btn-run").addEventListener("click", function () {
var code = getEditorCode();
if (window.pywebview && window.pywebview.api && window.pywebview.api.notify_run) {
rememberSent(code);
window.pywebview.api.notify_run(code, sessionId, currentMode, sessionTarget);
setStatus(t("running", "Running…"), "");
}
});
document.getElementById("btn-save").addEventListener("click", function () {
var code = getEditorCode();
if (window.pywebview && window.pywebview.api) {
if (currentMode === "run_script" && window.pywebview.api.notify_save_script) {
window.pywebview.api.notify_save_script(code, sessionId, currentMode, sessionTarget);
lockForRequestedSave();
setStatus(t("saving", "Saving…"), "");
return;
}
var plainEl = getPlainTextCheckbox();
var saveAsPlain = !!plainEl && plainEl.checked;
var input = getDataBindingInput();
// Follow keeps Data enabled (updateDataBindingEnabled). The plain-text
// box is checked because the code cell is setString'd, but the ranges
// still live on the formula. Sending "" made _apply_followed_ref_save
// treat the ranges as cleared and rewrite =PY($A$1; C1:C10) to
// =PY($A$1). Same rule as cell_editor_ui._save.
var dataBinding = (followCodeRef || !saveAsPlain) ? (input ? input.value.trim() : "") : "";
rememberSent(code);
window.pywebview.api.notify_save(code, saveAsPlain, dataBinding, "cell_save", sessionId, currentMode, sessionTarget);
lockForRequestedSave();
setStatus(pendingStatusText, "");
}
});
document.getElementById("btn-cancel").addEventListener("click", function () {
if (window.editor) {
window.editor.setValue("");
}
if (window.pywebview && window.pywebview.api && window.pywebview.api.notify_cancel) {
window.pywebview.api.notify_cancel();
}
});
var plainCheckbox = getPlainTextCheckbox();
if (plainCheckbox) {
plainCheckbox.addEventListener("change", function () {
updateDataBindingEnabled();
markDirty(true);
});
}
var dataInputEl = getDataBindingInput();
if (dataInputEl) {
dataInputEl.addEventListener("input", function () {
markDirty(true);
});
}
updateDataBindingEnabled();
function getCompletions(code, line, column) {
if (!window.pywebview || !window.pywebview.api || !window.pywebview.api.get_completions) {
return null;
}
return window.pywebview.api.get_completions(code, line, column);
}
function loadScript(src, onLoad, onError) {
var s = document.createElement("script");
s.src = src;
s.onload = onLoad;
s.onerror = onError;
document.head.appendChild(s);
}
function onLoaderError() {
setStatus(t("editor_loader_missing", "Editor loader missing."), "error");
}
var backendName = window.WA_EDITOR_BACKEND === "codemirror" ? "codemirror" : "monaco";
var scripts = backendName === "codemirror"
? ["cm6/cm6.bundle.js", "backend_cm6.js"]
: ["vs/loader.js", "backend_monaco.js"];
function loadScriptsSeq(list, idx, done) {
if (idx >= list.length) {
done();
return;
}
loadScript(list[idx], function () {
loadScriptsSeq(list, idx + 1, done);
}, onLoaderError);
}
loadScriptsSeq(scripts, 0, function () {
backend = window.WaEditorBackends && window.WaEditorBackends[backendName];
if (!backend) {
onLoaderError();
return;
}
backend.create(document.getElementById("editor"), {
value: pendingCode,
language: "python",
getCompletions: getCompletions
}).then(function () {
window.editor = editor = backend;
if (pendingMarkers) {
editor.setMarkers(pendingMarkers);
}
backend.onChange(function () {
if (!suppressDirty) {
markDirty(true);
}
});
setInterval(pollMessages, 80);
pollMessages();
maybeHintJediMissing();
}, onLoaderError);
});
})();