utils.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. const { Cu, Cc, Ci } = require("chrome");
  5. const { LocalizationHelper } = require("devtools/shared/l10n");
  6. const STRINGS_URI = "devtools/client/locales/memory.properties";
  7. const L10N = exports.L10N = new LocalizationHelper(STRINGS_URI);
  8. const { OS } = require("resource://gre/modules/osfile.jsm");
  9. const { assert } = require("devtools/shared/DevToolsUtils");
  10. const { Preferences } = require("resource://gre/modules/Preferences.jsm");
  11. const CUSTOM_CENSUS_DISPLAY_PREF = "devtools.memory.custom-census-displays";
  12. const CUSTOM_LABEL_DISPLAY_PREF = "devtools.memory.custom-label-displays";
  13. const CUSTOM_TREE_MAP_DISPLAY_PREF = "devtools.memory.custom-tree-map-displays";
  14. const BYTES = 1024;
  15. const KILOBYTES = Math.pow(BYTES, 2);
  16. const MEGABYTES = Math.pow(BYTES, 3);
  17. const DevToolsUtils = require("devtools/shared/DevToolsUtils");
  18. const {
  19. snapshotState: states,
  20. diffingState,
  21. censusState,
  22. treeMapState,
  23. dominatorTreeState,
  24. individualsState,
  25. } = require("./constants");
  26. /**
  27. * Takes a snapshot object and returns the localized form of its timestamp to be
  28. * used as a title.
  29. *
  30. * @param {Snapshot} snapshot
  31. * @return {String}
  32. */
  33. exports.getSnapshotTitle = function (snapshot) {
  34. if (!snapshot.creationTime) {
  35. return L10N.getStr("snapshot-title.loading");
  36. }
  37. if (snapshot.imported) {
  38. // Strip out the extension if it's the expected ".fxsnapshot"
  39. return OS.Path.basename(snapshot.path.replace(/\.fxsnapshot$/, ""));
  40. }
  41. let date = new Date(snapshot.creationTime / 1000);
  42. return date.toLocaleTimeString(void 0, {
  43. year: "2-digit",
  44. month: "2-digit",
  45. day: "2-digit",
  46. hour12: false
  47. });
  48. };
  49. function getCustomDisplaysHelper(pref) {
  50. let customDisplays = Object.create(null);
  51. try {
  52. customDisplays = JSON.parse(Preferences.get(pref)) || Object.create(null);
  53. } catch (e) {
  54. DevToolsUtils.reportException(
  55. `String stored in "${pref}" pref cannot be parsed by \`JSON.parse()\`.`);
  56. }
  57. return Object.freeze(customDisplays);
  58. }
  59. /**
  60. * Returns custom displays defined in `devtools.memory.custom-census-displays`
  61. * pref.
  62. *
  63. * @return {Object}
  64. */
  65. exports.getCustomCensusDisplays = function () {
  66. return getCustomDisplaysHelper(CUSTOM_CENSUS_DISPLAY_PREF);
  67. };
  68. /**
  69. * Returns custom displays defined in
  70. * `devtools.memory.custom-label-displays` pref.
  71. *
  72. * @return {Object}
  73. */
  74. exports.getCustomLabelDisplays = function () {
  75. return getCustomDisplaysHelper(CUSTOM_LABEL_DISPLAY_PREF);
  76. };
  77. /**
  78. * Returns custom displays defined in
  79. * `devtools.memory.custom-tree-map-displays` pref.
  80. *
  81. * @return {Object}
  82. */
  83. exports.getCustomTreeMapDisplays = function () {
  84. return getCustomDisplaysHelper(CUSTOM_TREE_MAP_DISPLAY_PREF);
  85. };
  86. /**
  87. * Returns a string representing a readable form of the snapshot's state. More
  88. * concise than `getStatusTextFull`.
  89. *
  90. * @param {snapshotState | diffingState} state
  91. * @return {String}
  92. */
  93. exports.getStatusText = function (state) {
  94. assert(state, "Must have a state");
  95. switch (state) {
  96. case diffingState.ERROR:
  97. return L10N.getStr("diffing.state.error");
  98. case states.ERROR:
  99. return L10N.getStr("snapshot.state.error");
  100. case states.SAVING:
  101. return L10N.getStr("snapshot.state.saving");
  102. case states.IMPORTING:
  103. return L10N.getStr("snapshot.state.importing");
  104. case states.SAVED:
  105. case states.READING:
  106. return L10N.getStr("snapshot.state.reading");
  107. case censusState.SAVING:
  108. return L10N.getStr("snapshot.state.saving-census");
  109. case treeMapState.SAVING:
  110. return L10N.getStr("snapshot.state.saving-tree-map");
  111. case diffingState.TAKING_DIFF:
  112. return L10N.getStr("diffing.state.taking-diff");
  113. case diffingState.SELECTING:
  114. return L10N.getStr("diffing.state.selecting");
  115. case dominatorTreeState.COMPUTING:
  116. case individualsState.COMPUTING_DOMINATOR_TREE:
  117. return L10N.getStr("dominatorTree.state.computing");
  118. case dominatorTreeState.COMPUTED:
  119. case dominatorTreeState.FETCHING:
  120. return L10N.getStr("dominatorTree.state.fetching");
  121. case dominatorTreeState.INCREMENTAL_FETCHING:
  122. return L10N.getStr("dominatorTree.state.incrementalFetching");
  123. case dominatorTreeState.ERROR:
  124. return L10N.getStr("dominatorTree.state.error");
  125. case individualsState.ERROR:
  126. return L10N.getStr("individuals.state.error");
  127. case individualsState.FETCHING:
  128. return L10N.getStr("individuals.state.fetching");
  129. // These states do not have any message to show as other content will be
  130. // displayed.
  131. case dominatorTreeState.LOADED:
  132. case diffingState.TOOK_DIFF:
  133. case states.READ:
  134. case censusState.SAVED:
  135. case treeMapState.SAVED:
  136. case individualsState.FETCHED:
  137. return "";
  138. default:
  139. assert(false, `Unexpected state: ${state}`);
  140. return "";
  141. }
  142. };
  143. /**
  144. * Returns a string representing a readable form of the snapshot's state;
  145. * more verbose than `getStatusText`.
  146. *
  147. * @param {snapshotState | diffingState} state
  148. * @return {String}
  149. */
  150. exports.getStatusTextFull = function (state) {
  151. assert(!!state, "Must have a state");
  152. switch (state) {
  153. case diffingState.ERROR:
  154. return L10N.getStr("diffing.state.error.full");
  155. case states.ERROR:
  156. return L10N.getStr("snapshot.state.error.full");
  157. case states.SAVING:
  158. return L10N.getStr("snapshot.state.saving.full");
  159. case states.IMPORTING:
  160. return L10N.getStr("snapshot.state.importing");
  161. case states.SAVED:
  162. case states.READING:
  163. return L10N.getStr("snapshot.state.reading.full");
  164. case censusState.SAVING:
  165. return L10N.getStr("snapshot.state.saving-census.full");
  166. case treeMapState.SAVING:
  167. return L10N.getStr("snapshot.state.saving-tree-map.full");
  168. case diffingState.TAKING_DIFF:
  169. return L10N.getStr("diffing.state.taking-diff.full");
  170. case diffingState.SELECTING:
  171. return L10N.getStr("diffing.state.selecting.full");
  172. case dominatorTreeState.COMPUTING:
  173. case individualsState.COMPUTING_DOMINATOR_TREE:
  174. return L10N.getStr("dominatorTree.state.computing.full");
  175. case dominatorTreeState.COMPUTED:
  176. case dominatorTreeState.FETCHING:
  177. return L10N.getStr("dominatorTree.state.fetching.full");
  178. case dominatorTreeState.INCREMENTAL_FETCHING:
  179. return L10N.getStr("dominatorTree.state.incrementalFetching.full");
  180. case dominatorTreeState.ERROR:
  181. return L10N.getStr("dominatorTree.state.error.full");
  182. case individualsState.ERROR:
  183. return L10N.getStr("individuals.state.error.full");
  184. case individualsState.FETCHING:
  185. return L10N.getStr("individuals.state.fetching.full");
  186. // These states do not have any full message to show as other content will
  187. // be displayed.
  188. case dominatorTreeState.LOADED:
  189. case diffingState.TOOK_DIFF:
  190. case states.READ:
  191. case censusState.SAVED:
  192. case treeMapState.SAVED:
  193. case individualsState.FETCHED:
  194. return "";
  195. default:
  196. assert(false, `Unexpected state: ${state}`);
  197. return "";
  198. }
  199. };
  200. /**
  201. * Return true if the snapshot is in a diffable state, false otherwise.
  202. *
  203. * @param {snapshotModel} snapshot
  204. * @returns {Boolean}
  205. */
  206. exports.snapshotIsDiffable = function snapshotIsDiffable(snapshot) {
  207. return (snapshot.census && snapshot.census.state === censusState.SAVED)
  208. || (snapshot.census && snapshot.census.state === censusState.SAVING)
  209. || snapshot.state === states.SAVED
  210. || snapshot.state === states.READ;
  211. };
  212. /**
  213. * Takes an array of snapshots and a snapshot and returns
  214. * the snapshot instance in `snapshots` that matches
  215. * the snapshot passed in.
  216. *
  217. * @param {appModel} state
  218. * @param {snapshotId} id
  219. * @return {snapshotModel|null}
  220. */
  221. exports.getSnapshot = function getSnapshot(state, id) {
  222. const found = state.snapshots.find(s => s.id === id);
  223. assert(found, `No matching snapshot found with id = ${id}`);
  224. return found;
  225. };
  226. /**
  227. * Get the ID of the selected snapshot, if one is selected, null otherwise.
  228. *
  229. * @returns {SnapshotId|null}
  230. */
  231. exports.findSelectedSnapshot = function (state) {
  232. const found = state.snapshots.find(s => s.selected);
  233. return found ? found.id : null;
  234. };
  235. /**
  236. * Creates a new snapshot object.
  237. *
  238. * @param {appModel} state
  239. * @return {Snapshot}
  240. */
  241. let ID_COUNTER = 0;
  242. exports.createSnapshot = function createSnapshot(state) {
  243. let dominatorTree = null;
  244. if (state.view.state === dominatorTreeState.DOMINATOR_TREE) {
  245. dominatorTree = Object.freeze({
  246. dominatorTreeId: null,
  247. root: null,
  248. error: null,
  249. state: dominatorTreeState.COMPUTING,
  250. });
  251. }
  252. return Object.freeze({
  253. id: ++ID_COUNTER,
  254. state: states.SAVING,
  255. dominatorTree,
  256. census: null,
  257. treeMap: null,
  258. path: null,
  259. imported: false,
  260. selected: false,
  261. error: null,
  262. });
  263. };
  264. /**
  265. * Return true if the census is up to date with regards to the current filtering
  266. * and requested display, false otherwise.
  267. *
  268. * @param {String} filter
  269. * @param {censusDisplayModel} display
  270. * @param {censusModel} census
  271. *
  272. * @returns {Boolean}
  273. */
  274. exports.censusIsUpToDate = function (filter, display, census) {
  275. return census
  276. // Filter could be null == undefined so use loose equality.
  277. && filter == census.filter
  278. && display === census.display;
  279. };
  280. /**
  281. * Check to see if the snapshot is in a state that it can take a census.
  282. *
  283. * @param {SnapshotModel} A snapshot to check.
  284. * @param {Boolean} Assert that the snapshot must be in a ready state.
  285. * @returns {Boolean}
  286. */
  287. exports.canTakeCensus = function (snapshot) {
  288. return snapshot.state === states.READ &&
  289. ((!snapshot.census || snapshot.census.state === censusState.SAVED) ||
  290. (!snapshot.treeMap || snapshot.treeMap.state === treeMapState.SAVED));
  291. };
  292. /**
  293. * Returns true if the given snapshot's dominator tree has been computed, false
  294. * otherwise.
  295. *
  296. * @param {SnapshotModel} snapshot
  297. * @returns {Boolean}
  298. */
  299. exports.dominatorTreeIsComputed = function (snapshot) {
  300. return snapshot.dominatorTree &&
  301. (snapshot.dominatorTree.state === dominatorTreeState.COMPUTED ||
  302. snapshot.dominatorTree.state === dominatorTreeState.LOADED ||
  303. snapshot.dominatorTree.state === dominatorTreeState.INCREMENTAL_FETCHING);
  304. };
  305. /**
  306. * Find the first SAVED census, either from the tree map or the normal
  307. * census.
  308. *
  309. * @param {SnapshotModel} snapshot
  310. * @returns {Object|null} Either the census, or null if one hasn't completed
  311. */
  312. exports.getSavedCensus = function (snapshot) {
  313. if (snapshot.treeMap && snapshot.treeMap.state === treeMapState.SAVED) {
  314. return snapshot.treeMap;
  315. }
  316. if (snapshot.census && snapshot.census.state === censusState.SAVED) {
  317. return snapshot.census;
  318. }
  319. return null;
  320. };
  321. /**
  322. * Takes a snapshot and returns the total bytes and total count that this
  323. * snapshot represents.
  324. *
  325. * @param {CensusModel} census
  326. * @return {Object}
  327. */
  328. exports.getSnapshotTotals = function (census) {
  329. let bytes = 0;
  330. let count = 0;
  331. let report = census.report;
  332. if (report) {
  333. bytes = report.totalBytes;
  334. count = report.totalCount;
  335. }
  336. return { bytes, count };
  337. };
  338. /**
  339. * Takes some configurations and opens up a file picker and returns
  340. * a promise to the chosen file if successful.
  341. *
  342. * @param {String} .title
  343. * The title displayed in the file picker window.
  344. * @param {Array<Array<String>>} .filters
  345. * An array of filters to display in the file picker. Each filter in the array
  346. * is a duple of two strings, one a name for the filter, and one the filter itself
  347. * (like "*.json").
  348. * @param {String} .defaultName
  349. * The default name chosen by the file picker window.
  350. * @param {String} .mode
  351. * The mode that this filepicker should open in. Can be "open" or "save".
  352. * @return {Promise<?nsILocalFile>}
  353. * The file selected by the user, or null, if cancelled.
  354. */
  355. exports.openFilePicker = function ({ title, filters, defaultName, mode }) {
  356. mode = mode === "save" ? Ci.nsIFilePicker.modeSave :
  357. mode === "open" ? Ci.nsIFilePicker.modeOpen : null;
  358. if (mode == void 0) {
  359. throw new Error("No valid mode specified for nsIFilePicker.");
  360. }
  361. let fp = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);
  362. fp.init(window, title, mode);
  363. for (let filter of (filters || [])) {
  364. fp.appendFilter(filter[0], filter[1]);
  365. }
  366. fp.defaultString = defaultName;
  367. return new Promise(resolve => {
  368. fp.open({
  369. done: result => {
  370. if (result === Ci.nsIFilePicker.returnCancel) {
  371. resolve(null);
  372. return;
  373. }
  374. resolve(fp.file);
  375. }
  376. });
  377. });
  378. };
  379. /**
  380. * Format the provided number with a space every 3 digits, and optionally
  381. * prefixed by its sign.
  382. *
  383. * @param {Number} number
  384. * @param {Boolean} showSign (defaults to false)
  385. */
  386. exports.formatNumber = function (number, showSign = false) {
  387. const rounded = Math.round(number);
  388. if (rounded === 0 || rounded === -0) {
  389. return "0";
  390. }
  391. const abs = String(Math.abs(rounded));
  392. // replace every digit followed by (sets of 3 digits) by (itself and a space)
  393. const formatted = abs.replace(/(\d)(?=(\d{3})+$)/g, "$1 ");
  394. if (showSign) {
  395. const sign = rounded < 0 ? "-" : "+";
  396. return sign + formatted;
  397. }
  398. return formatted;
  399. };
  400. /**
  401. * Format the provided percentage following the same logic as formatNumber and
  402. * an additional % suffix.
  403. *
  404. * @param {Number} percent
  405. * @param {Boolean} showSign (defaults to false)
  406. */
  407. exports.formatPercent = function (percent, showSign = false) {
  408. return exports.L10N.getFormatStr("tree-item.percent2",
  409. exports.formatNumber(percent, showSign));
  410. };
  411. /**
  412. * Change an HSL color array with values ranged 0-1 to a properly formatted
  413. * ctx.fillStyle string.
  414. *
  415. * @param {Number} h
  416. * hue values ranged between [0 - 1]
  417. * @param {Number} s
  418. * hue values ranged between [0 - 1]
  419. * @param {Number} l
  420. * hue values ranged between [0 - 1]
  421. * @return {type}
  422. */
  423. exports.hslToStyle = function (h, s, l) {
  424. h = parseInt(h * 360, 10);
  425. s = parseInt(s * 100, 10);
  426. l = parseInt(l * 100, 10);
  427. return `hsl(${h},${s}%,${l}%)`;
  428. };
  429. /**
  430. * Linearly interpolate between 2 numbers.
  431. *
  432. * @param {Number} a
  433. * @param {Number} b
  434. * @param {Number} t
  435. * A value of 0 returns a, and 1 returns b
  436. * @return {Number}
  437. */
  438. exports.lerp = function (a, b, t) {
  439. return a * (1 - t) + b * t;
  440. };
  441. /**
  442. * Format a number of bytes as human readable, e.g. 13434 => '13KiB'.
  443. *
  444. * @param {Number} n
  445. * Number of bytes
  446. * @return {String}
  447. */
  448. exports.formatAbbreviatedBytes = function (n) {
  449. if (n < BYTES) {
  450. return n + "B";
  451. } else if (n < KILOBYTES) {
  452. return Math.floor(n / BYTES) + "KiB";
  453. } else if (n < MEGABYTES) {
  454. return Math.floor(n / KILOBYTES) + "MiB";
  455. }
  456. return Math.floor(n / MEGABYTES) + "GiB";
  457. };