-
-
Notifications
You must be signed in to change notification settings - Fork 90
Expand file tree
/
Copy pathDocument.js
More file actions
107 lines (91 loc) · 2.48 KB
/
Document.js
File metadata and controls
107 lines (91 loc) · 2.48 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
import Source from "gi://GtkSource";
import Gio from "gi://Gio";
import GLib from "gi://GLib";
export default function Document({ session, code_view, lang }) {
const { buffer } = code_view;
let modified_changed_handler_id = null;
let changed_signal_handler_id = null;
const file = session.file.get_child(lang.default_file);
const file_monitor = file.monitor(Gio.FileMonitorFlags.NONE, null);
function watchFile() {
unwatchFile();
changed_signal_handler_id = file_monitor.connect(
"changed",
(_self, _file, _other_file, event_type) => {
const event_name = Object.entries(Gio.FileMonitorEvent).find(
([_key, value]) => value === event_type,
)?.[0];
console.log("wow", event_name);
},
);
}
function unwatchFile() {
if (changed_signal_handler_id === null) return;
file_monitor.disconnect(changed_signal_handler_id);
changed_signal_handler_id = null;
}
const source_file = new Source.File({
location: file,
});
start();
function save() {
unwatchFile();
saveSourceBuffer({ source_file, buffer })
.catch(console.error)
.finally(() => {
watchFile();
try {
session.settings.set_boolean("edited", true);
} catch (err) {
console.error(err);
}
});
}
function start() {
stop();
modified_changed_handler_id = buffer.connect("modified-changed", () => {
if (!buffer.get_modified()) return;
save();
});
watchFile();
}
function stop() {
if (modified_changed_handler_id !== null) {
buffer.disconnect(modified_changed_handler_id);
modified_changed_handler_id = null;
}
unwatchFile();
}
function load() {
return loadSourceBuffer({ source_file, buffer, lang });
}
return { start, stop, save, code_view, file, load };
}
async function saveSourceBuffer({ source_file, buffer }) {
const file_saver = new Source.FileSaver({
buffer,
file: source_file,
});
const success = await file_saver.save_async(
GLib.PRIORITY_DEFAULT,
null,
null,
);
if (success) {
buffer.set_modified(false);
}
}
async function loadSourceBuffer({ source_file, buffer }) {
const file_loader = new Source.FileLoader({
buffer,
file: source_file,
});
try {
await file_loader.load_async(GLib.PRIORITY_DEFAULT, null, null);
} catch (err) {
if (!err.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.NOT_FOUND)) {
throw err;
}
}
buffer.set_modified(false);
}