store.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. import GLib from 'gi://GLib';
  2. import Gio from 'gi://Gio';
  3. import * as DS from './dataStructures.js';
  4. let EXTENSION_UUID;
  5. let CACHE_DIR;
  6. const OLD_REGISTRY_FILE = GLib.build_filenamev([
  7. GLib.get_user_cache_dir(),
  8. 'clipboard-indicator@tudmotu.com',
  9. 'registry.txt',
  10. ]);
  11. /**
  12. * Stores our compacting log implementation. Here are its key ideas:
  13. * - We only ever append to the log.
  14. * - This means there will be operations that cancel each other out. These are wasted/useless ops
  15. * that must be occasionally pruned. MAX_WASTED_OPS limits the number of useless ops.
  16. * - The available operations are listed in the OP_TYPE_* constants.
  17. * - An add op never moves (until compaction), allowing us to derive globally unique entry IDs based
  18. * on the order in which these add ops are discovered.
  19. */
  20. let DATABASE_FILE;
  21. const BYTE_ORDER = Gio.DataStreamByteOrder.LITTLE_ENDIAN;
  22. // Don't use zero b/c DataInputStream uses 0 as its error value
  23. const OP_TYPE_SAVE_TEXT = 1;
  24. const OP_TYPE_DELETE_TEXT = 2;
  25. const OP_TYPE_FAVORITE_ITEM = 3;
  26. const OP_TYPE_UNFAVORITE_ITEM = 4;
  27. const OP_TYPE_MOVE_ITEM_TO_END = 5;
  28. const MAX_WASTED_OPS = 500;
  29. let uselessOpCount;
  30. let opQueue = new DS.LinkedList();
  31. let opInProgress = false;
  32. let writeStream;
  33. export function init(uuid) {
  34. EXTENSION_UUID = uuid;
  35. CACHE_DIR = GLib.build_filenamev([GLib.get_user_cache_dir(), EXTENSION_UUID]);
  36. DATABASE_FILE = GLib.build_filenamev([CACHE_DIR, 'database.log']);
  37. if (GLib.mkdir_with_parents(CACHE_DIR, 0o775) !== 0) {
  38. console.log(
  39. EXTENSION_UUID,
  40. "Failed to create cache dir, extension likely won't work",
  41. CACHE_DIR,
  42. );
  43. }
  44. }
  45. export function destroy() {
  46. _pushToOpQueue((resolve) => {
  47. if (writeStream) {
  48. writeStream.close_async(0, null, (src, res) => {
  49. src.close_finish(res);
  50. resolve();
  51. });
  52. writeStream = undefined;
  53. } else {
  54. resolve();
  55. }
  56. });
  57. }
  58. export function buildClipboardStateFromLog(callback) {
  59. if (typeof callback !== 'function') {
  60. throw TypeError('`callback` must be a function');
  61. }
  62. uselessOpCount = 0;
  63. Gio.File.new_for_path(DATABASE_FILE).read_async(0, null, (src, res) => {
  64. try {
  65. _parseLog(src.read_finish(res), callback);
  66. } catch (e) {
  67. if (e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.NOT_FOUND)) {
  68. _readAndConsumeOldFormat(callback);
  69. } else {
  70. throw e;
  71. }
  72. }
  73. });
  74. }
  75. function _parseLog(stream, callback) {
  76. stream = Gio.DataInputStream.new(stream);
  77. stream.set_byte_order(BYTE_ORDER);
  78. const state = {
  79. entries: new DS.LinkedList(),
  80. favorites: new DS.LinkedList(),
  81. nextId: 1,
  82. };
  83. _consumeStream(stream, state, callback);
  84. }
  85. function _consumeStream(stream, state, callback) {
  86. const finish = () => {
  87. callback(state.entries, state.favorites, state.nextId);
  88. };
  89. const forceFill = (minBytes, fillCallback) => {
  90. stream.fill_async(/*count=*/ -1, 0, null, (src, res) => {
  91. if (src.fill_finish(res) < minBytes) {
  92. finish();
  93. } else {
  94. fillCallback();
  95. }
  96. });
  97. };
  98. let parseAvailableAware;
  99. function loop() {
  100. if (stream.get_available() === 0) {
  101. forceFill(1, loop);
  102. return;
  103. }
  104. const opType = stream.read_byte(null);
  105. if (opType === OP_TYPE_SAVE_TEXT) {
  106. stream.read_upto_async(
  107. /*stop_chars=*/ '\0',
  108. /*stop_chars_len=*/ 1,
  109. 0,
  110. null,
  111. (src, res) => {
  112. const [text] = src.read_upto_finish(res);
  113. src.read_byte(null);
  114. const node = new DS.LLNode();
  115. node.diskId = node.id = state.nextId++;
  116. node.type = DS.TYPE_TEXT;
  117. node.text = text || '';
  118. node.favorite = false;
  119. state.entries.append(node);
  120. loop();
  121. },
  122. );
  123. } else if (opType === OP_TYPE_DELETE_TEXT) {
  124. uselessOpCount += 2;
  125. parseAvailableAware(4, () => {
  126. const id = stream.read_uint32(null);
  127. (state.entries.findById(id) || state.favorites.findById(id)).detach();
  128. });
  129. } else if (opType === OP_TYPE_FAVORITE_ITEM) {
  130. parseAvailableAware(4, () => {
  131. const id = stream.read_uint32(null);
  132. const entry = state.entries.findById(id);
  133. entry.favorite = true;
  134. state.favorites.append(entry);
  135. });
  136. } else if (opType === OP_TYPE_UNFAVORITE_ITEM) {
  137. uselessOpCount += 2;
  138. parseAvailableAware(4, () => {
  139. const id = stream.read_uint32(null);
  140. const entry = state.favorites.findById(id);
  141. entry.favorite = false;
  142. state.entries.append(entry);
  143. });
  144. } else if (opType === OP_TYPE_MOVE_ITEM_TO_END) {
  145. uselessOpCount++;
  146. parseAvailableAware(4, () => {
  147. const id = stream.read_uint32(null);
  148. const entry =
  149. state.entries.findById(id) || state.favorites.findById(id);
  150. if (entry.favorite) {
  151. state.favorites.append(entry);
  152. } else {
  153. state.entries.append(entry);
  154. }
  155. });
  156. } else {
  157. console.log(EXTENSION_UUID, 'Unknown op type, aborting load.', opType);
  158. finish();
  159. }
  160. }
  161. parseAvailableAware = (minBytes, parse) => {
  162. const safeParse = (cont) => {
  163. try {
  164. parse();
  165. cont();
  166. } catch (e) {
  167. console.log(EXTENSION_UUID, 'Parsing error');
  168. console.error(e);
  169. const entries = new DS.LinkedList();
  170. let nextId = 1;
  171. const addEntry = (text) => {
  172. const node = new DS.LLNode();
  173. node.id = nextId++;
  174. node.type = DS.TYPE_TEXT;
  175. node.text = text;
  176. node.favorite = false;
  177. entries.prepend(node);
  178. };
  179. addEntry('Your clipboard data has been corrupted and was moved to:');
  180. addEntry('~/.cache/clipboard-history@alexsaveau.dev/corrupted.log');
  181. addEntry('Please file a bug report at:');
  182. addEntry(
  183. 'https://github.com/SUPERCILEX/gnome-clipboard-history/issues/new?assignees=&labels=bug&template=1-bug.md',
  184. );
  185. try {
  186. if (
  187. !Gio.File.new_for_path(DATABASE_FILE).move(
  188. Gio.File.new_for_path(
  189. GLib.build_filenamev([CACHE_DIR, 'corrupted.log']),
  190. ),
  191. Gio.FileCopyFlags.OVERWRITE,
  192. null,
  193. null,
  194. )
  195. ) {
  196. console.log(EXTENSION_UUID, 'Failed to move database file');
  197. }
  198. } catch (e) {
  199. console.log(EXTENSION_UUID, 'Crash moving database file');
  200. console.error(e);
  201. }
  202. callback(entries, new DS.LinkedList(), nextId, 1);
  203. }
  204. };
  205. if (stream.get_available() < minBytes) {
  206. forceFill(minBytes, () => {
  207. safeParse(loop);
  208. });
  209. } else {
  210. safeParse(loop);
  211. }
  212. };
  213. loop();
  214. }
  215. function _readAndConsumeOldFormat(callback) {
  216. Gio.File.new_for_path(OLD_REGISTRY_FILE).load_contents_async(
  217. null,
  218. (src, res) => {
  219. const entries = new DS.LinkedList();
  220. const favorites = new DS.LinkedList();
  221. let id = 1;
  222. let contents;
  223. try {
  224. [, contents] = src.load_contents_finish(res);
  225. } catch (e) {
  226. if (e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.NOT_FOUND)) {
  227. callback(entries, favorites, id);
  228. return;
  229. } else {
  230. throw e;
  231. }
  232. }
  233. let registry = [];
  234. try {
  235. registry = JSON.parse(GLib.ByteArray.toString(contents));
  236. } catch (e) {
  237. console.error(e);
  238. }
  239. for (const entry of registry) {
  240. const node = new DS.LLNode();
  241. node.diskId = node.id = id;
  242. node.type = DS.TYPE_TEXT;
  243. if (typeof entry === 'string') {
  244. node.text = entry;
  245. node.favorite = false;
  246. entries.append(node);
  247. } else {
  248. node.text = entry.contents;
  249. node.favorite = entry.favorite;
  250. favorites.append(node);
  251. }
  252. id++;
  253. }
  254. resetDatabase(() => entries.toArray().concat(favorites.toArray()));
  255. Gio.File.new_for_path(OLD_REGISTRY_FILE).trash_async(
  256. 0,
  257. null,
  258. (src, res) => {
  259. src.trash_finish(res);
  260. },
  261. );
  262. callback(entries, favorites, id);
  263. },
  264. );
  265. }
  266. export function maybePerformLogCompaction(currentStateBuilder) {
  267. if (uselessOpCount >= MAX_WASTED_OPS) {
  268. resetDatabase(currentStateBuilder);
  269. }
  270. }
  271. export function resetDatabase(currentStateBuilder) {
  272. uselessOpCount = 0;
  273. const state = currentStateBuilder();
  274. _pushToOpQueue((resolve) => {
  275. // Sigh, can't use truncate because it doesn't have an async variant. Instead, nuke the stream
  276. // and let the next append re-create it. Note that we can't use this stream because it tries to
  277. // apply our operations atomically and therefore writes to a temporary file instead of the one
  278. // we asked for.
  279. writeStream = undefined;
  280. const priority = -10;
  281. Gio.File.new_for_path(DATABASE_FILE).replace_async(
  282. /*etag=*/ null,
  283. /*make_backup=*/ false,
  284. Gio.FileCreateFlags.PRIVATE,
  285. priority,
  286. null,
  287. (src, res) => {
  288. const stream = _intoDataStream(src.replace_finish(res));
  289. const finish = () => {
  290. stream.close_async(priority, null, (src, res) => {
  291. src.close_finish(res);
  292. resolve();
  293. });
  294. };
  295. if (state.length === 0) {
  296. finish();
  297. return;
  298. }
  299. let i = 0;
  300. _writeToStream(stream, priority, finish, (dataStream) => {
  301. do {
  302. const entry = state[i];
  303. if (entry.type === DS.TYPE_TEXT) {
  304. _storeTextOp(entry.text)(dataStream);
  305. } else {
  306. throw new TypeError('Unknown type: ' + entry.type);
  307. }
  308. if (entry.favorite) {
  309. _updateFavoriteStatusOp(entry.diskId, true)(dataStream);
  310. }
  311. i++;
  312. } while (i % 1000 !== 0 && i < state.length);
  313. // Flush the buffer every 1000 entries
  314. return i >= state.length;
  315. });
  316. },
  317. );
  318. });
  319. }
  320. export function storeTextEntry(text) {
  321. _appendBytesToLog(_storeTextOp(text), -5);
  322. }
  323. function _storeTextOp(text) {
  324. return (dataStream) => {
  325. dataStream.put_byte(OP_TYPE_SAVE_TEXT, null);
  326. dataStream.put_string(text, null);
  327. dataStream.put_byte(0, null); // NUL terminator
  328. return true;
  329. };
  330. }
  331. export function deleteTextEntry(id, isFavorite) {
  332. _appendBytesToLog(_deleteTextOp(id), 5);
  333. uselessOpCount += 2;
  334. if (isFavorite) {
  335. uselessOpCount++;
  336. }
  337. }
  338. function _deleteTextOp(id) {
  339. return (dataStream) => {
  340. dataStream.put_byte(OP_TYPE_DELETE_TEXT, null);
  341. dataStream.put_uint32(id, null);
  342. return true;
  343. };
  344. }
  345. export function updateFavoriteStatus(id, favorite) {
  346. _appendBytesToLog(_updateFavoriteStatusOp(id, favorite));
  347. if (!favorite) {
  348. uselessOpCount += 2;
  349. }
  350. }
  351. function _updateFavoriteStatusOp(id, favorite) {
  352. return (dataStream) => {
  353. dataStream.put_byte(
  354. favorite ? OP_TYPE_FAVORITE_ITEM : OP_TYPE_UNFAVORITE_ITEM,
  355. null,
  356. );
  357. dataStream.put_uint32(id, null);
  358. return true;
  359. };
  360. }
  361. export function moveEntryToEnd(id) {
  362. _appendBytesToLog(_moveToEndOp(id));
  363. uselessOpCount++;
  364. }
  365. function _moveToEndOp(id) {
  366. return (dataStream) => {
  367. dataStream.put_byte(OP_TYPE_MOVE_ITEM_TO_END, null);
  368. dataStream.put_uint32(id, null);
  369. return true;
  370. };
  371. }
  372. function _appendBytesToLog(callback, priority) {
  373. priority = priority || 0;
  374. _pushToOpQueue((resolve) => {
  375. const runUnsafe = () => {
  376. _writeToStream(writeStream, priority, resolve, callback);
  377. };
  378. if (writeStream === undefined) {
  379. Gio.File.new_for_path(DATABASE_FILE).append_to_async(
  380. Gio.FileCreateFlags.PRIVATE,
  381. priority,
  382. null,
  383. (src, res) => {
  384. writeStream = _intoDataStream(src.append_to_finish(res));
  385. runUnsafe();
  386. },
  387. );
  388. } else {
  389. runUnsafe();
  390. }
  391. });
  392. }
  393. function _writeToStream(stream, priority, resolve, callback) {
  394. _writeCallbackBytesAsyncHack(callback, stream, priority, () => {
  395. stream.flush_async(priority, null, (src, res) => {
  396. src.flush_finish(res);
  397. resolve();
  398. });
  399. });
  400. }
  401. /**
  402. * This garbage code is here to keep disk writes off the main thread. DataOutputStream doesn't have
  403. * async method variants, so we write to a memory buffer and then flush it asynchronously. We're
  404. * basically trying to balance memory allocations with disk writes.
  405. */
  406. function _writeCallbackBytesAsyncHack(
  407. dataCallback,
  408. stream,
  409. priority,
  410. callback,
  411. ) {
  412. if (dataCallback(stream)) {
  413. callback();
  414. } else {
  415. stream.flush_async(priority, null, (src, res) => {
  416. src.flush_finish(res);
  417. _writeCallbackBytesAsyncHack(dataCallback, stream, priority, callback);
  418. });
  419. }
  420. }
  421. function _intoDataStream(stream) {
  422. const bufStream = Gio.BufferedOutputStream.new(stream);
  423. bufStream.set_auto_grow(true); // Blocks flushing, needed for hack
  424. const ioStream = Gio.DataOutputStream.new(bufStream);
  425. ioStream.set_byte_order(BYTE_ORDER);
  426. return ioStream;
  427. }
  428. function _pushToOpQueue(op) {
  429. const consumeOp = () => {
  430. const resolve = () => {
  431. opInProgress = false;
  432. const next = opQueue.head;
  433. if (next) {
  434. next.detach();
  435. next.op();
  436. }
  437. };
  438. opInProgress = true;
  439. op(resolve);
  440. };
  441. if (opInProgress) {
  442. const node = new DS.LLNode();
  443. node.op = consumeOp;
  444. opQueue.append(node);
  445. } else {
  446. consumeOp();
  447. }
  448. }