2
0

tools.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * JavaScript code in this page
  4. *
  5. * Copyright 2022 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * JavaScript code in this page
  21. */
  22. "use strict";
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.KeyboardManager = exports.CommandManager = exports.ColorManager = exports.AnnotationEditorUIManager = void 0;
  27. exports.bindEvents = bindEvents;
  28. exports.opacityToHex = opacityToHex;
  29. var _util = require("../../shared/util.js");
  30. var _display_utils = require("../display_utils.js");
  31. function bindEvents(obj, element, names) {
  32. for (const name of names) {
  33. element.addEventListener(name, obj[name].bind(obj));
  34. }
  35. }
  36. function opacityToHex(opacity) {
  37. return Math.round(Math.min(255, Math.max(1, 255 * opacity))).toString(16).padStart(2, "0");
  38. }
  39. class IdManager {
  40. #id = 0;
  41. getId() {
  42. return `${_util.AnnotationEditorPrefix}${this.#id++}`;
  43. }
  44. }
  45. class CommandManager {
  46. #commands = [];
  47. #locked = false;
  48. #maxSize;
  49. #position = -1;
  50. constructor(maxSize = 128) {
  51. this.#maxSize = maxSize;
  52. }
  53. add({
  54. cmd,
  55. undo,
  56. mustExec,
  57. type = NaN,
  58. overwriteIfSameType = false,
  59. keepUndo = false
  60. }) {
  61. if (mustExec) {
  62. cmd();
  63. }
  64. if (this.#locked) {
  65. return;
  66. }
  67. const save = {
  68. cmd,
  69. undo,
  70. type
  71. };
  72. if (this.#position === -1) {
  73. if (this.#commands.length > 0) {
  74. this.#commands.length = 0;
  75. }
  76. this.#position = 0;
  77. this.#commands.push(save);
  78. return;
  79. }
  80. if (overwriteIfSameType && this.#commands[this.#position].type === type) {
  81. if (keepUndo) {
  82. save.undo = this.#commands[this.#position].undo;
  83. }
  84. this.#commands[this.#position] = save;
  85. return;
  86. }
  87. const next = this.#position + 1;
  88. if (next === this.#maxSize) {
  89. this.#commands.splice(0, 1);
  90. } else {
  91. this.#position = next;
  92. if (next < this.#commands.length) {
  93. this.#commands.splice(next);
  94. }
  95. }
  96. this.#commands.push(save);
  97. }
  98. undo() {
  99. if (this.#position === -1) {
  100. return;
  101. }
  102. this.#locked = true;
  103. this.#commands[this.#position].undo();
  104. this.#locked = false;
  105. this.#position -= 1;
  106. }
  107. redo() {
  108. if (this.#position < this.#commands.length - 1) {
  109. this.#position += 1;
  110. this.#locked = true;
  111. this.#commands[this.#position].cmd();
  112. this.#locked = false;
  113. }
  114. }
  115. hasSomethingToUndo() {
  116. return this.#position !== -1;
  117. }
  118. hasSomethingToRedo() {
  119. return this.#position < this.#commands.length - 1;
  120. }
  121. destroy() {
  122. this.#commands = null;
  123. }
  124. }
  125. exports.CommandManager = CommandManager;
  126. class KeyboardManager {
  127. constructor(callbacks) {
  128. this.buffer = [];
  129. this.callbacks = new Map();
  130. this.allKeys = new Set();
  131. const isMac = KeyboardManager.platform.isMac;
  132. for (const [keys, callback] of callbacks) {
  133. for (const key of keys) {
  134. const isMacKey = key.startsWith("mac+");
  135. if (isMac && isMacKey) {
  136. this.callbacks.set(key.slice(4), callback);
  137. this.allKeys.add(key.split("+").at(-1));
  138. } else if (!isMac && !isMacKey) {
  139. this.callbacks.set(key, callback);
  140. this.allKeys.add(key.split("+").at(-1));
  141. }
  142. }
  143. }
  144. }
  145. static get platform() {
  146. const platform = typeof navigator !== "undefined" ? navigator.platform : "";
  147. return (0, _util.shadow)(this, "platform", {
  148. isWin: platform.includes("Win"),
  149. isMac: platform.includes("Mac")
  150. });
  151. }
  152. #serialize(event) {
  153. if (event.altKey) {
  154. this.buffer.push("alt");
  155. }
  156. if (event.ctrlKey) {
  157. this.buffer.push("ctrl");
  158. }
  159. if (event.metaKey) {
  160. this.buffer.push("meta");
  161. }
  162. if (event.shiftKey) {
  163. this.buffer.push("shift");
  164. }
  165. this.buffer.push(event.key);
  166. const str = this.buffer.join("+");
  167. this.buffer.length = 0;
  168. return str;
  169. }
  170. exec(self, event) {
  171. if (!this.allKeys.has(event.key)) {
  172. return;
  173. }
  174. const callback = this.callbacks.get(this.#serialize(event));
  175. if (!callback) {
  176. return;
  177. }
  178. callback.bind(self)();
  179. event.stopPropagation();
  180. event.preventDefault();
  181. }
  182. }
  183. exports.KeyboardManager = KeyboardManager;
  184. class ColorManager {
  185. static _colorsMapping = new Map([["CanvasText", [0, 0, 0]], ["Canvas", [255, 255, 255]]]);
  186. get _colors() {
  187. if (typeof document === "undefined") {
  188. return (0, _util.shadow)(this, "_colors", ColorManager._colorsMapping);
  189. }
  190. const colors = new Map([["CanvasText", null], ["Canvas", null]]);
  191. (0, _display_utils.getColorValues)(colors);
  192. return (0, _util.shadow)(this, "_colors", colors);
  193. }
  194. convert(color) {
  195. const rgb = (0, _display_utils.getRGB)(color);
  196. if (!window.matchMedia("(forced-colors: active)").matches) {
  197. return rgb;
  198. }
  199. for (const [name, RGB] of this._colors) {
  200. if (RGB.every((x, i) => x === rgb[i])) {
  201. return ColorManager._colorsMapping.get(name);
  202. }
  203. }
  204. return rgb;
  205. }
  206. getHexCode(name) {
  207. const rgb = this._colors.get(name);
  208. if (!rgb) {
  209. return name;
  210. }
  211. return _util.Util.makeHexColor(...rgb);
  212. }
  213. }
  214. exports.ColorManager = ColorManager;
  215. class AnnotationEditorUIManager {
  216. #activeEditor = null;
  217. #allEditors = new Map();
  218. #allLayers = new Map();
  219. #commandManager = new CommandManager();
  220. #currentPageIndex = 0;
  221. #editorTypes = null;
  222. #eventBus = null;
  223. #idManager = new IdManager();
  224. #isEnabled = false;
  225. #mode = _util.AnnotationEditorType.NONE;
  226. #selectedEditors = new Set();
  227. #boundCopy = this.copy.bind(this);
  228. #boundCut = this.cut.bind(this);
  229. #boundPaste = this.paste.bind(this);
  230. #boundKeydown = this.keydown.bind(this);
  231. #boundOnEditingAction = this.onEditingAction.bind(this);
  232. #boundOnPageChanging = this.onPageChanging.bind(this);
  233. #previousStates = {
  234. isEditing: false,
  235. isEmpty: true,
  236. hasSomethingToUndo: false,
  237. hasSomethingToRedo: false,
  238. hasSelectedEditor: false
  239. };
  240. #container = null;
  241. static _keyboardManager = new KeyboardManager([[["ctrl+a", "mac+meta+a"], AnnotationEditorUIManager.prototype.selectAll], [["ctrl+z", "mac+meta+z"], AnnotationEditorUIManager.prototype.undo], [["ctrl+y", "ctrl+shift+Z", "mac+meta+shift+Z"], AnnotationEditorUIManager.prototype.redo], [["Backspace", "alt+Backspace", "ctrl+Backspace", "shift+Backspace", "mac+Backspace", "mac+alt+Backspace", "mac+ctrl+Backspace", "Delete", "ctrl+Delete", "shift+Delete"], AnnotationEditorUIManager.prototype.delete], [["Escape", "mac+Escape"], AnnotationEditorUIManager.prototype.unselectAll]]);
  242. constructor(container, eventBus) {
  243. this.#container = container;
  244. this.#eventBus = eventBus;
  245. this.#eventBus._on("editingaction", this.#boundOnEditingAction);
  246. this.#eventBus._on("pagechanging", this.#boundOnPageChanging);
  247. }
  248. destroy() {
  249. this.#removeKeyboardManager();
  250. this.#eventBus._off("editingaction", this.#boundOnEditingAction);
  251. this.#eventBus._off("pagechanging", this.#boundOnPageChanging);
  252. for (const layer of this.#allLayers.values()) {
  253. layer.destroy();
  254. }
  255. this.#allLayers.clear();
  256. this.#allEditors.clear();
  257. this.#activeEditor = null;
  258. this.#selectedEditors.clear();
  259. this.#commandManager.destroy();
  260. }
  261. onPageChanging({
  262. pageNumber
  263. }) {
  264. this.#currentPageIndex = pageNumber - 1;
  265. }
  266. focusMainContainer() {
  267. this.#container.focus();
  268. }
  269. #addKeyboardManager() {
  270. this.#container.addEventListener("keydown", this.#boundKeydown);
  271. }
  272. #removeKeyboardManager() {
  273. this.#container.removeEventListener("keydown", this.#boundKeydown);
  274. }
  275. #addCopyPasteListeners() {
  276. document.addEventListener("copy", this.#boundCopy);
  277. document.addEventListener("cut", this.#boundCut);
  278. document.addEventListener("paste", this.#boundPaste);
  279. }
  280. #removeCopyPasteListeners() {
  281. document.removeEventListener("copy", this.#boundCopy);
  282. document.removeEventListener("cut", this.#boundCut);
  283. document.removeEventListener("paste", this.#boundPaste);
  284. }
  285. copy(event) {
  286. event.preventDefault();
  287. if (this.#activeEditor) {
  288. this.#activeEditor.commitOrRemove();
  289. }
  290. if (!this.hasSelection) {
  291. return;
  292. }
  293. const editors = [];
  294. for (const editor of this.#selectedEditors) {
  295. if (!editor.isEmpty()) {
  296. editors.push(editor.serialize());
  297. }
  298. }
  299. if (editors.length === 0) {
  300. return;
  301. }
  302. event.clipboardData.setData("application/pdfjs", JSON.stringify(editors));
  303. }
  304. cut(event) {
  305. this.copy(event);
  306. this.delete();
  307. }
  308. paste(event) {
  309. event.preventDefault();
  310. let data = event.clipboardData.getData("application/pdfjs");
  311. if (!data) {
  312. return;
  313. }
  314. try {
  315. data = JSON.parse(data);
  316. } catch (ex) {
  317. (0, _util.warn)(`paste: "${ex.message}".`);
  318. return;
  319. }
  320. if (!Array.isArray(data)) {
  321. return;
  322. }
  323. this.unselectAll();
  324. const layer = this.#allLayers.get(this.#currentPageIndex);
  325. try {
  326. const newEditors = [];
  327. for (const editor of data) {
  328. const deserializedEditor = layer.deserialize(editor);
  329. if (!deserializedEditor) {
  330. return;
  331. }
  332. newEditors.push(deserializedEditor);
  333. }
  334. const cmd = () => {
  335. for (const editor of newEditors) {
  336. this.#addEditorToLayer(editor);
  337. }
  338. this.#selectEditors(newEditors);
  339. };
  340. const undo = () => {
  341. for (const editor of newEditors) {
  342. editor.remove();
  343. }
  344. };
  345. this.addCommands({
  346. cmd,
  347. undo,
  348. mustExec: true
  349. });
  350. } catch (ex) {
  351. (0, _util.warn)(`paste: "${ex.message}".`);
  352. }
  353. }
  354. keydown(event) {
  355. if (!this.getActive()?.shouldGetKeyboardEvents()) {
  356. AnnotationEditorUIManager._keyboardManager.exec(this, event);
  357. }
  358. }
  359. onEditingAction(details) {
  360. if (["undo", "redo", "delete", "selectAll"].includes(details.name)) {
  361. this[details.name]();
  362. }
  363. }
  364. #dispatchUpdateStates(details) {
  365. const hasChanged = Object.entries(details).some(([key, value]) => this.#previousStates[key] !== value);
  366. if (hasChanged) {
  367. this.#eventBus.dispatch("annotationeditorstateschanged", {
  368. source: this,
  369. details: Object.assign(this.#previousStates, details)
  370. });
  371. }
  372. }
  373. #dispatchUpdateUI(details) {
  374. this.#eventBus.dispatch("annotationeditorparamschanged", {
  375. source: this,
  376. details
  377. });
  378. }
  379. setEditingState(isEditing) {
  380. if (isEditing) {
  381. this.#addKeyboardManager();
  382. this.#addCopyPasteListeners();
  383. this.#dispatchUpdateStates({
  384. isEditing: this.#mode !== _util.AnnotationEditorType.NONE,
  385. isEmpty: this.#isEmpty(),
  386. hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
  387. hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
  388. hasSelectedEditor: false
  389. });
  390. } else {
  391. this.#removeKeyboardManager();
  392. this.#removeCopyPasteListeners();
  393. this.#dispatchUpdateStates({
  394. isEditing: false
  395. });
  396. }
  397. }
  398. registerEditorTypes(types) {
  399. if (this.#editorTypes) {
  400. return;
  401. }
  402. this.#editorTypes = types;
  403. for (const editorType of this.#editorTypes) {
  404. this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate);
  405. }
  406. }
  407. getId() {
  408. return this.#idManager.getId();
  409. }
  410. addLayer(layer) {
  411. this.#allLayers.set(layer.pageIndex, layer);
  412. if (this.#isEnabled) {
  413. layer.enable();
  414. } else {
  415. layer.disable();
  416. }
  417. }
  418. removeLayer(layer) {
  419. this.#allLayers.delete(layer.pageIndex);
  420. }
  421. updateMode(mode) {
  422. this.#mode = mode;
  423. if (mode === _util.AnnotationEditorType.NONE) {
  424. this.setEditingState(false);
  425. this.#disableAll();
  426. } else {
  427. this.setEditingState(true);
  428. this.#enableAll();
  429. for (const layer of this.#allLayers.values()) {
  430. layer.updateMode(mode);
  431. }
  432. }
  433. }
  434. updateToolbar(mode) {
  435. if (mode === this.#mode) {
  436. return;
  437. }
  438. this.#eventBus.dispatch("switchannotationeditormode", {
  439. source: this,
  440. mode
  441. });
  442. }
  443. updateParams(type, value) {
  444. if (!this.#editorTypes) {
  445. return;
  446. }
  447. for (const editor of this.#selectedEditors) {
  448. editor.updateParams(type, value);
  449. }
  450. for (const editorType of this.#editorTypes) {
  451. editorType.updateDefaultParams(type, value);
  452. }
  453. }
  454. #enableAll() {
  455. if (!this.#isEnabled) {
  456. this.#isEnabled = true;
  457. for (const layer of this.#allLayers.values()) {
  458. layer.enable();
  459. }
  460. }
  461. }
  462. #disableAll() {
  463. this.unselectAll();
  464. if (this.#isEnabled) {
  465. this.#isEnabled = false;
  466. for (const layer of this.#allLayers.values()) {
  467. layer.disable();
  468. }
  469. }
  470. }
  471. getEditors(pageIndex) {
  472. const editors = [];
  473. for (const editor of this.#allEditors.values()) {
  474. if (editor.pageIndex === pageIndex) {
  475. editors.push(editor);
  476. }
  477. }
  478. return editors;
  479. }
  480. getEditor(id) {
  481. return this.#allEditors.get(id);
  482. }
  483. addEditor(editor) {
  484. this.#allEditors.set(editor.id, editor);
  485. }
  486. removeEditor(editor) {
  487. this.#allEditors.delete(editor.id);
  488. this.unselect(editor);
  489. }
  490. #addEditorToLayer(editor) {
  491. const layer = this.#allLayers.get(editor.pageIndex);
  492. if (layer) {
  493. layer.addOrRebuild(editor);
  494. } else {
  495. this.addEditor(editor);
  496. }
  497. }
  498. setActiveEditor(editor) {
  499. if (this.#activeEditor === editor) {
  500. return;
  501. }
  502. this.#activeEditor = editor;
  503. if (editor) {
  504. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  505. }
  506. }
  507. toggleSelected(editor) {
  508. if (this.#selectedEditors.has(editor)) {
  509. this.#selectedEditors.delete(editor);
  510. editor.unselect();
  511. this.#dispatchUpdateStates({
  512. hasSelectedEditor: this.hasSelection
  513. });
  514. return;
  515. }
  516. this.#selectedEditors.add(editor);
  517. editor.select();
  518. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  519. this.#dispatchUpdateStates({
  520. hasSelectedEditor: true
  521. });
  522. }
  523. setSelected(editor) {
  524. for (const ed of this.#selectedEditors) {
  525. if (ed !== editor) {
  526. ed.unselect();
  527. }
  528. }
  529. this.#selectedEditors.clear();
  530. this.#selectedEditors.add(editor);
  531. editor.select();
  532. this.#dispatchUpdateUI(editor.propertiesToUpdate);
  533. this.#dispatchUpdateStates({
  534. hasSelectedEditor: true
  535. });
  536. }
  537. isSelected(editor) {
  538. return this.#selectedEditors.has(editor);
  539. }
  540. unselect(editor) {
  541. editor.unselect();
  542. this.#selectedEditors.delete(editor);
  543. this.#dispatchUpdateStates({
  544. hasSelectedEditor: this.hasSelection
  545. });
  546. }
  547. get hasSelection() {
  548. return this.#selectedEditors.size !== 0;
  549. }
  550. undo() {
  551. this.#commandManager.undo();
  552. this.#dispatchUpdateStates({
  553. hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(),
  554. hasSomethingToRedo: true,
  555. isEmpty: this.#isEmpty()
  556. });
  557. }
  558. redo() {
  559. this.#commandManager.redo();
  560. this.#dispatchUpdateStates({
  561. hasSomethingToUndo: true,
  562. hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(),
  563. isEmpty: this.#isEmpty()
  564. });
  565. }
  566. addCommands(params) {
  567. this.#commandManager.add(params);
  568. this.#dispatchUpdateStates({
  569. hasSomethingToUndo: true,
  570. hasSomethingToRedo: false,
  571. isEmpty: this.#isEmpty()
  572. });
  573. }
  574. #isEmpty() {
  575. if (this.#allEditors.size === 0) {
  576. return true;
  577. }
  578. if (this.#allEditors.size === 1) {
  579. for (const editor of this.#allEditors.values()) {
  580. return editor.isEmpty();
  581. }
  582. }
  583. return false;
  584. }
  585. delete() {
  586. this.commitOrRemove();
  587. if (!this.hasSelection) {
  588. return;
  589. }
  590. const editors = [...this.#selectedEditors];
  591. const cmd = () => {
  592. for (const editor of editors) {
  593. editor.remove();
  594. }
  595. };
  596. const undo = () => {
  597. for (const editor of editors) {
  598. this.#addEditorToLayer(editor);
  599. }
  600. };
  601. this.addCommands({
  602. cmd,
  603. undo,
  604. mustExec: true
  605. });
  606. }
  607. commitOrRemove() {
  608. this.#activeEditor?.commitOrRemove();
  609. }
  610. #selectEditors(editors) {
  611. this.#selectedEditors.clear();
  612. for (const editor of editors) {
  613. if (editor.isEmpty()) {
  614. continue;
  615. }
  616. this.#selectedEditors.add(editor);
  617. editor.select();
  618. }
  619. this.#dispatchUpdateStates({
  620. hasSelectedEditor: true
  621. });
  622. }
  623. selectAll() {
  624. for (const editor of this.#selectedEditors) {
  625. editor.commit();
  626. }
  627. this.#selectEditors(this.#allEditors.values());
  628. }
  629. unselectAll() {
  630. if (this.#activeEditor) {
  631. this.#activeEditor.commitOrRemove();
  632. return;
  633. }
  634. if (this.#selectedEditors.size === 0) {
  635. return;
  636. }
  637. for (const editor of this.#selectedEditors) {
  638. editor.unselect();
  639. }
  640. this.#selectedEditors.clear();
  641. this.#dispatchUpdateStates({
  642. hasSelectedEditor: false
  643. });
  644. }
  645. isActive(editor) {
  646. return this.#activeEditor === editor;
  647. }
  648. getActive() {
  649. return this.#activeEditor;
  650. }
  651. getMode() {
  652. return this.#mode;
  653. }
  654. }
  655. exports.AnnotationEditorUIManager = AnnotationEditorUIManager;