browser/devtools/styleeditor/StyleSheetEditor.jsm

Wed, 31 Dec 2014 06:09:35 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 06:09:35 +0100
changeset 0
6474c204b198
permissions
-rw-r--r--

Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.

michael@0 1 /* vim:set ts=2 sw=2 sts=2 et: */
michael@0 2 /* This Source Code Form is subject to the terms of the Mozilla Public
michael@0 3 * License, v. 2.0. If a copy of the MPL was not distributed with this
michael@0 4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
michael@0 5
michael@0 6 "use strict";
michael@0 7
michael@0 8 this.EXPORTED_SYMBOLS = ["StyleSheetEditor"];
michael@0 9
michael@0 10 const Cc = Components.classes;
michael@0 11 const Ci = Components.interfaces;
michael@0 12 const Cu = Components.utils;
michael@0 13
michael@0 14 const require = Cu.import("resource://gre/modules/devtools/Loader.jsm", {}).devtools.require;
michael@0 15 const Editor = require("devtools/sourceeditor/editor");
michael@0 16 const {Promise: promise} = Cu.import("resource://gre/modules/Promise.jsm", {});
michael@0 17 const {CssLogic} = require("devtools/styleinspector/css-logic");
michael@0 18 const AutoCompleter = require("devtools/sourceeditor/autocomplete");
michael@0 19
michael@0 20 Cu.import("resource://gre/modules/Services.jsm");
michael@0 21 Cu.import("resource://gre/modules/FileUtils.jsm");
michael@0 22 Cu.import("resource://gre/modules/NetUtil.jsm");
michael@0 23 Cu.import("resource://gre/modules/osfile.jsm");
michael@0 24 Cu.import("resource://gre/modules/devtools/event-emitter.js");
michael@0 25 Cu.import("resource:///modules/devtools/StyleEditorUtil.jsm");
michael@0 26
michael@0 27 const LOAD_ERROR = "error-load";
michael@0 28 const SAVE_ERROR = "error-save";
michael@0 29
michael@0 30 // max update frequency in ms (avoid potential typing lag and/or flicker)
michael@0 31 // @see StyleEditor.updateStylesheet
michael@0 32 const UPDATE_STYLESHEET_THROTTLE_DELAY = 500;
michael@0 33
michael@0 34 // Pref which decides if CSS autocompletion is enabled in Style Editor or not.
michael@0 35 const AUTOCOMPLETION_PREF = "devtools.styleeditor.autocompletion-enabled";
michael@0 36
michael@0 37 // How long to wait to update linked CSS file after original source was saved
michael@0 38 // to disk. Time in ms.
michael@0 39 const CHECK_LINKED_SHEET_DELAY=500;
michael@0 40
michael@0 41 // How many times to check for linked file changes
michael@0 42 const MAX_CHECK_COUNT=10;
michael@0 43
michael@0 44 /**
michael@0 45 * StyleSheetEditor controls the editor linked to a particular StyleSheet
michael@0 46 * object.
michael@0 47 *
michael@0 48 * Emits events:
michael@0 49 * 'property-change': A property on the underlying stylesheet has changed
michael@0 50 * 'source-editor-load': The source editor for this editor has been loaded
michael@0 51 * 'error': An error has occured
michael@0 52 *
michael@0 53 * @param {StyleSheet|OriginalSource} styleSheet
michael@0 54 * Stylesheet or original source to show
michael@0 55 * @param {DOMWindow} win
michael@0 56 * panel window for style editor
michael@0 57 * @param {nsIFile} file
michael@0 58 * Optional file that the sheet was imported from
michael@0 59 * @param {boolean} isNew
michael@0 60 * Optional whether the sheet was created by the user
michael@0 61 * @param {Walker} walker
michael@0 62 * Optional walker used for selectors autocompletion
michael@0 63 */
michael@0 64 function StyleSheetEditor(styleSheet, win, file, isNew, walker) {
michael@0 65 EventEmitter.decorate(this);
michael@0 66
michael@0 67 this.styleSheet = styleSheet;
michael@0 68 this._inputElement = null;
michael@0 69 this.sourceEditor = null;
michael@0 70 this._window = win;
michael@0 71 this._isNew = isNew;
michael@0 72 this.walker = walker;
michael@0 73
michael@0 74 this._state = { // state to use when inputElement attaches
michael@0 75 text: "",
michael@0 76 selection: {
michael@0 77 start: {line: 0, ch: 0},
michael@0 78 end: {line: 0, ch: 0}
michael@0 79 },
michael@0 80 topIndex: 0 // the first visible line
michael@0 81 };
michael@0 82
michael@0 83 this._styleSheetFilePath = null;
michael@0 84 if (styleSheet.href &&
michael@0 85 Services.io.extractScheme(this.styleSheet.href) == "file") {
michael@0 86 this._styleSheetFilePath = this.styleSheet.href;
michael@0 87 }
michael@0 88
michael@0 89 this._onPropertyChange = this._onPropertyChange.bind(this);
michael@0 90 this._onError = this._onError.bind(this);
michael@0 91 this.checkLinkedFileForChanges = this.checkLinkedFileForChanges.bind(this);
michael@0 92 this.markLinkedFileBroken = this.markLinkedFileBroken.bind(this);
michael@0 93
michael@0 94 this._focusOnSourceEditorReady = false;
michael@0 95
michael@0 96 let relatedSheet = this.styleSheet.relatedStyleSheet;
michael@0 97 if (relatedSheet) {
michael@0 98 relatedSheet.on("property-change", this._onPropertyChange);
michael@0 99 }
michael@0 100 this.styleSheet.on("property-change", this._onPropertyChange);
michael@0 101 this.styleSheet.on("error", this._onError);
michael@0 102
michael@0 103 this.savedFile = file;
michael@0 104 this.linkCSSFile();
michael@0 105 }
michael@0 106
michael@0 107 StyleSheetEditor.prototype = {
michael@0 108 /**
michael@0 109 * Whether there are unsaved changes in the editor
michael@0 110 */
michael@0 111 get unsaved() {
michael@0 112 return this.sourceEditor && !this.sourceEditor.isClean();
michael@0 113 },
michael@0 114
michael@0 115 /**
michael@0 116 * Whether the editor is for a stylesheet created by the user
michael@0 117 * through the style editor UI.
michael@0 118 */
michael@0 119 get isNew() {
michael@0 120 return this._isNew;
michael@0 121 },
michael@0 122
michael@0 123 get savedFile() {
michael@0 124 return this._savedFile;
michael@0 125 },
michael@0 126
michael@0 127 set savedFile(name) {
michael@0 128 this._savedFile = name;
michael@0 129
michael@0 130 this.linkCSSFile();
michael@0 131 },
michael@0 132
michael@0 133 /**
michael@0 134 * Get a user-friendly name for the style sheet.
michael@0 135 *
michael@0 136 * @return string
michael@0 137 */
michael@0 138 get friendlyName() {
michael@0 139 if (this.savedFile) {
michael@0 140 return this.savedFile.leafName;
michael@0 141 }
michael@0 142
michael@0 143 if (this._isNew) {
michael@0 144 let index = this.styleSheet.styleSheetIndex + 1;
michael@0 145 return _("newStyleSheet", index);
michael@0 146 }
michael@0 147
michael@0 148 if (!this.styleSheet.href) {
michael@0 149 let index = this.styleSheet.styleSheetIndex + 1;
michael@0 150 return _("inlineStyleSheet", index);
michael@0 151 }
michael@0 152
michael@0 153 if (!this._friendlyName) {
michael@0 154 let sheetURI = this.styleSheet.href;
michael@0 155 this._friendlyName = CssLogic.shortSource({ href: sheetURI });
michael@0 156 try {
michael@0 157 this._friendlyName = decodeURI(this._friendlyName);
michael@0 158 } catch (ex) {
michael@0 159 }
michael@0 160 }
michael@0 161 return this._friendlyName;
michael@0 162 },
michael@0 163
michael@0 164 /**
michael@0 165 * If this is an original source, get the path of the CSS file it generated.
michael@0 166 */
michael@0 167 linkCSSFile: function() {
michael@0 168 if (!this.styleSheet.isOriginalSource) {
michael@0 169 return;
michael@0 170 }
michael@0 171
michael@0 172 let relatedSheet = this.styleSheet.relatedStyleSheet;
michael@0 173
michael@0 174 let path;
michael@0 175 let href = removeQuery(relatedSheet.href);
michael@0 176 let uri = NetUtil.newURI(href);
michael@0 177
michael@0 178 if (uri.scheme == "file") {
michael@0 179 let file = uri.QueryInterface(Ci.nsIFileURL).file;
michael@0 180 path = file.path;
michael@0 181 }
michael@0 182 else if (this.savedFile) {
michael@0 183 let origHref = removeQuery(this.styleSheet.href);
michael@0 184 let origUri = NetUtil.newURI(origHref);
michael@0 185 path = findLinkedFilePath(uri, origUri, this.savedFile);
michael@0 186 }
michael@0 187 else {
michael@0 188 // we can't determine path to generated file on disk
michael@0 189 return;
michael@0 190 }
michael@0 191
michael@0 192 if (this.linkedCSSFile == path) {
michael@0 193 return;
michael@0 194 }
michael@0 195
michael@0 196 this.linkedCSSFile = path;
michael@0 197
michael@0 198 this.linkedCSSFileError = null;
michael@0 199
michael@0 200 // save last file change time so we can compare when we check for changes.
michael@0 201 OS.File.stat(path).then((info) => {
michael@0 202 this._fileModDate = info.lastModificationDate.getTime();
michael@0 203 }, this.markLinkedFileBroken);
michael@0 204
michael@0 205 this.emit("linked-css-file");
michael@0 206 },
michael@0 207
michael@0 208 /**
michael@0 209 * Start fetching the full text source for this editor's sheet.
michael@0 210 */
michael@0 211 fetchSource: function(callback) {
michael@0 212 this.styleSheet.getText().then((longStr) => {
michael@0 213 longStr.string().then((source) => {
michael@0 214 let ruleCount = this.styleSheet.ruleCount;
michael@0 215 this._state.text = prettifyCSS(source, ruleCount);
michael@0 216 this.sourceLoaded = true;
michael@0 217
michael@0 218 callback(source);
michael@0 219 });
michael@0 220 }, e => {
michael@0 221 this.emit("error", LOAD_ERROR, this.styleSheet.href);
michael@0 222 })
michael@0 223 },
michael@0 224
michael@0 225 /**
michael@0 226 * Forward property-change event from stylesheet.
michael@0 227 *
michael@0 228 * @param {string} event
michael@0 229 * Event type
michael@0 230 * @param {string} property
michael@0 231 * Property that has changed on sheet
michael@0 232 */
michael@0 233 _onPropertyChange: function(property, value) {
michael@0 234 this.emit("property-change", property, value);
michael@0 235 },
michael@0 236
michael@0 237 /**
michael@0 238 * Forward error event from stylesheet.
michael@0 239 *
michael@0 240 * @param {string} event
michael@0 241 * Event type
michael@0 242 * @param {string} errorCode
michael@0 243 */
michael@0 244 _onError: function(event, errorCode) {
michael@0 245 this.emit("error", errorCode);
michael@0 246 },
michael@0 247
michael@0 248 /**
michael@0 249 * Create source editor and load state into it.
michael@0 250 * @param {DOMElement} inputElement
michael@0 251 * Element to load source editor in
michael@0 252 *
michael@0 253 * @return {Promise}
michael@0 254 * Promise that will resolve when the style editor is loaded.
michael@0 255 */
michael@0 256 load: function(inputElement) {
michael@0 257 this._inputElement = inputElement;
michael@0 258
michael@0 259 let config = {
michael@0 260 value: this._state.text,
michael@0 261 lineNumbers: true,
michael@0 262 mode: Editor.modes.css,
michael@0 263 readOnly: false,
michael@0 264 autoCloseBrackets: "{}()[]",
michael@0 265 extraKeys: this._getKeyBindings(),
michael@0 266 contextMenu: "sourceEditorContextMenu"
michael@0 267 };
michael@0 268 let sourceEditor = new Editor(config);
michael@0 269
michael@0 270 sourceEditor.on("dirty-change", this._onPropertyChange);
michael@0 271
michael@0 272 return sourceEditor.appendTo(inputElement).then(() => {
michael@0 273 if (Services.prefs.getBoolPref(AUTOCOMPLETION_PREF)) {
michael@0 274 sourceEditor.extend(AutoCompleter);
michael@0 275 sourceEditor.setupAutoCompletion(this.walker);
michael@0 276 }
michael@0 277 sourceEditor.on("save", () => {
michael@0 278 this.saveToFile();
michael@0 279 });
michael@0 280
michael@0 281 if (this.styleSheet.update) {
michael@0 282 sourceEditor.on("change", () => {
michael@0 283 this.updateStyleSheet();
michael@0 284 });
michael@0 285 }
michael@0 286
michael@0 287 this.sourceEditor = sourceEditor;
michael@0 288
michael@0 289 if (this._focusOnSourceEditorReady) {
michael@0 290 this._focusOnSourceEditorReady = false;
michael@0 291 sourceEditor.focus();
michael@0 292 }
michael@0 293
michael@0 294 sourceEditor.setFirstVisibleLine(this._state.topIndex);
michael@0 295 sourceEditor.setSelection(this._state.selection.start,
michael@0 296 this._state.selection.end);
michael@0 297
michael@0 298 this.emit("source-editor-load");
michael@0 299 });
michael@0 300 },
michael@0 301
michael@0 302 /**
michael@0 303 * Get the source editor for this editor.
michael@0 304 *
michael@0 305 * @return {Promise}
michael@0 306 * Promise that will resolve with the editor.
michael@0 307 */
michael@0 308 getSourceEditor: function() {
michael@0 309 let deferred = promise.defer();
michael@0 310
michael@0 311 if (this.sourceEditor) {
michael@0 312 return promise.resolve(this);
michael@0 313 }
michael@0 314 this.on("source-editor-load", () => {
michael@0 315 deferred.resolve(this);
michael@0 316 });
michael@0 317 return deferred.promise;
michael@0 318 },
michael@0 319
michael@0 320 /**
michael@0 321 * Focus the Style Editor input.
michael@0 322 */
michael@0 323 focus: function() {
michael@0 324 if (this.sourceEditor) {
michael@0 325 this.sourceEditor.focus();
michael@0 326 } else {
michael@0 327 this._focusOnSourceEditorReady = true;
michael@0 328 }
michael@0 329 },
michael@0 330
michael@0 331 /**
michael@0 332 * Event handler for when the editor is shown.
michael@0 333 */
michael@0 334 onShow: function() {
michael@0 335 if (this.sourceEditor) {
michael@0 336 this.sourceEditor.setFirstVisibleLine(this._state.topIndex);
michael@0 337 }
michael@0 338 this.focus();
michael@0 339 },
michael@0 340
michael@0 341 /**
michael@0 342 * Toggled the disabled state of the underlying stylesheet.
michael@0 343 */
michael@0 344 toggleDisabled: function() {
michael@0 345 this.styleSheet.toggleDisabled();
michael@0 346 },
michael@0 347
michael@0 348 /**
michael@0 349 * Queue a throttled task to update the live style sheet.
michael@0 350 *
michael@0 351 * @param boolean immediate
michael@0 352 * Optional. If true the update is performed immediately.
michael@0 353 */
michael@0 354 updateStyleSheet: function(immediate) {
michael@0 355 if (this._updateTask) {
michael@0 356 // cancel previous queued task not executed within throttle delay
michael@0 357 this._window.clearTimeout(this._updateTask);
michael@0 358 }
michael@0 359
michael@0 360 if (immediate) {
michael@0 361 this._updateStyleSheet();
michael@0 362 } else {
michael@0 363 this._updateTask = this._window.setTimeout(this._updateStyleSheet.bind(this),
michael@0 364 UPDATE_STYLESHEET_THROTTLE_DELAY);
michael@0 365 }
michael@0 366 },
michael@0 367
michael@0 368 /**
michael@0 369 * Update live style sheet according to modifications.
michael@0 370 */
michael@0 371 _updateStyleSheet: function() {
michael@0 372 if (this.styleSheet.disabled) {
michael@0 373 return; // TODO: do we want to do this?
michael@0 374 }
michael@0 375
michael@0 376 this._updateTask = null; // reset only if we actually perform an update
michael@0 377 // (stylesheet is enabled) so that 'missed' updates
michael@0 378 // while the stylesheet is disabled can be performed
michael@0 379 // when it is enabled back. @see enableStylesheet
michael@0 380
michael@0 381 if (this.sourceEditor) {
michael@0 382 this._state.text = this.sourceEditor.getText();
michael@0 383 }
michael@0 384
michael@0 385 this.styleSheet.update(this._state.text, true);
michael@0 386 },
michael@0 387
michael@0 388 /**
michael@0 389 * Save the editor contents into a file and set savedFile property.
michael@0 390 * A file picker UI will open if file is not set and editor is not headless.
michael@0 391 *
michael@0 392 * @param mixed file
michael@0 393 * Optional nsIFile or string representing the filename to save in the
michael@0 394 * background, no UI will be displayed.
michael@0 395 * If not specified, the original style sheet URI is used.
michael@0 396 * To implement 'Save' instead of 'Save as', you can pass savedFile here.
michael@0 397 * @param function(nsIFile aFile) callback
michael@0 398 * Optional callback called when the operation has finished.
michael@0 399 * aFile has the nsIFile object for saved file or null if the operation
michael@0 400 * has failed or has been canceled by the user.
michael@0 401 * @see savedFile
michael@0 402 */
michael@0 403 saveToFile: function(file, callback) {
michael@0 404 let onFile = (returnFile) => {
michael@0 405 if (!returnFile) {
michael@0 406 if (callback) {
michael@0 407 callback(null);
michael@0 408 }
michael@0 409 return;
michael@0 410 }
michael@0 411
michael@0 412 if (this.sourceEditor) {
michael@0 413 this._state.text = this.sourceEditor.getText();
michael@0 414 }
michael@0 415
michael@0 416 let ostream = FileUtils.openSafeFileOutputStream(returnFile);
michael@0 417 let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
michael@0 418 .createInstance(Ci.nsIScriptableUnicodeConverter);
michael@0 419 converter.charset = "UTF-8";
michael@0 420 let istream = converter.convertToInputStream(this._state.text);
michael@0 421
michael@0 422 NetUtil.asyncCopy(istream, ostream, function onStreamCopied(status) {
michael@0 423 if (!Components.isSuccessCode(status)) {
michael@0 424 if (callback) {
michael@0 425 callback(null);
michael@0 426 }
michael@0 427 this.emit("error", SAVE_ERROR);
michael@0 428 return;
michael@0 429 }
michael@0 430 FileUtils.closeSafeFileOutputStream(ostream);
michael@0 431
michael@0 432 this.onFileSaved(returnFile);
michael@0 433
michael@0 434 if (callback) {
michael@0 435 callback(returnFile);
michael@0 436 }
michael@0 437 }.bind(this));
michael@0 438 };
michael@0 439
michael@0 440 let defaultName;
michael@0 441 if (this._friendlyName) {
michael@0 442 defaultName = OS.Path.basename(this._friendlyName);
michael@0 443 }
michael@0 444 showFilePicker(file || this._styleSheetFilePath, true, this._window,
michael@0 445 onFile, defaultName);
michael@0 446 },
michael@0 447
michael@0 448 /**
michael@0 449 * Called when this source has been successfully saved to disk.
michael@0 450 */
michael@0 451 onFileSaved: function(returnFile) {
michael@0 452 this._friendlyName = null;
michael@0 453 this.savedFile = returnFile;
michael@0 454
michael@0 455 this.sourceEditor.setClean();
michael@0 456
michael@0 457 this.emit("property-change");
michael@0 458
michael@0 459 // TODO: replace with file watching
michael@0 460 this._modCheckCount = 0;
michael@0 461 this._window.clearTimeout(this._timeout);
michael@0 462
michael@0 463 if (this.linkedCSSFile && !this.linkedCSSFileError) {
michael@0 464 this._timeout = this._window.setTimeout(this.checkLinkedFileForChanges,
michael@0 465 CHECK_LINKED_SHEET_DELAY);
michael@0 466 }
michael@0 467 },
michael@0 468
michael@0 469 /**
michael@0 470 * Check to see if our linked CSS file has changed on disk, and
michael@0 471 * if so, update the live style sheet.
michael@0 472 */
michael@0 473 checkLinkedFileForChanges: function() {
michael@0 474 OS.File.stat(this.linkedCSSFile).then((info) => {
michael@0 475 let lastChange = info.lastModificationDate.getTime();
michael@0 476
michael@0 477 if (this._fileModDate && lastChange != this._fileModDate) {
michael@0 478 this._fileModDate = lastChange;
michael@0 479 this._modCheckCount = 0;
michael@0 480
michael@0 481 this.updateLinkedStyleSheet();
michael@0 482 return;
michael@0 483 }
michael@0 484
michael@0 485 if (++this._modCheckCount > MAX_CHECK_COUNT) {
michael@0 486 this.updateLinkedStyleSheet();
michael@0 487 return;
michael@0 488 }
michael@0 489
michael@0 490 // try again in a bit
michael@0 491 this._timeout = this._window.setTimeout(this.checkLinkedFileForChanges,
michael@0 492 CHECK_LINKED_SHEET_DELAY);
michael@0 493 }, this.markLinkedFileBroken);
michael@0 494 },
michael@0 495
michael@0 496 /**
michael@0 497 * Notify that the linked CSS file (if this is an original source)
michael@0 498 * doesn't exist on disk in the place we think it does.
michael@0 499 *
michael@0 500 * @param string error
michael@0 501 * The error we got when trying to access the file.
michael@0 502 */
michael@0 503 markLinkedFileBroken: function(error) {
michael@0 504 this.linkedCSSFileError = error || true;
michael@0 505 this.emit("linked-css-file-error");
michael@0 506
michael@0 507 error += " querying " + this.linkedCSSFile +
michael@0 508 " original source location: " + this.savedFile.path
michael@0 509 Cu.reportError(error);
michael@0 510 },
michael@0 511
michael@0 512 /**
michael@0 513 * For original sources (e.g. Sass files). Fetch contents of linked CSS
michael@0 514 * file from disk and live update the stylesheet object with the contents.
michael@0 515 */
michael@0 516 updateLinkedStyleSheet: function() {
michael@0 517 OS.File.read(this.linkedCSSFile).then((array) => {
michael@0 518 let decoder = new TextDecoder();
michael@0 519 let text = decoder.decode(array);
michael@0 520
michael@0 521 let relatedSheet = this.styleSheet.relatedStyleSheet;
michael@0 522 relatedSheet.update(text, true);
michael@0 523 }, this.markLinkedFileBroken);
michael@0 524 },
michael@0 525
michael@0 526 /**
michael@0 527 * Retrieve custom key bindings objects as expected by Editor.
michael@0 528 * Editor action names are not displayed to the user.
michael@0 529 *
michael@0 530 * @return {array} key binding objects for the source editor
michael@0 531 */
michael@0 532 _getKeyBindings: function() {
michael@0 533 let bindings = {};
michael@0 534
michael@0 535 bindings[Editor.accel(_("saveStyleSheet.commandkey"))] = () => {
michael@0 536 this.saveToFile(this.savedFile);
michael@0 537 };
michael@0 538
michael@0 539 bindings["Shift-" + Editor.accel(_("saveStyleSheet.commandkey"))] = () => {
michael@0 540 this.saveToFile();
michael@0 541 };
michael@0 542
michael@0 543 return bindings;
michael@0 544 },
michael@0 545
michael@0 546 /**
michael@0 547 * Clean up for this editor.
michael@0 548 */
michael@0 549 destroy: function() {
michael@0 550 if (this.sourceEditor) {
michael@0 551 this.sourceEditor.destroy();
michael@0 552 }
michael@0 553 this.styleSheet.off("property-change", this._onPropertyChange);
michael@0 554 this.styleSheet.off("error", this._onError);
michael@0 555 }
michael@0 556 }
michael@0 557
michael@0 558
michael@0 559 const TAB_CHARS = "\t";
michael@0 560
michael@0 561 const CURRENT_OS = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime).OS;
michael@0 562 const LINE_SEPARATOR = CURRENT_OS === "WINNT" ? "\r\n" : "\n";
michael@0 563
michael@0 564 /**
michael@0 565 * Prettify minified CSS text.
michael@0 566 * This prettifies CSS code where there is no indentation in usual places while
michael@0 567 * keeping original indentation as-is elsewhere.
michael@0 568 *
michael@0 569 * @param string text
michael@0 570 * The CSS source to prettify.
michael@0 571 * @return string
michael@0 572 * Prettified CSS source
michael@0 573 */
michael@0 574 function prettifyCSS(text, ruleCount)
michael@0 575 {
michael@0 576 // remove initial and terminating HTML comments and surrounding whitespace
michael@0 577 text = text.replace(/(?:^\s*<!--[\r\n]*)|(?:\s*-->\s*$)/g, "");
michael@0 578
michael@0 579 // don't attempt to prettify if there's more than one line per rule.
michael@0 580 let lineCount = text.split("\n").length - 1;
michael@0 581 if (ruleCount !== null && lineCount >= ruleCount) {
michael@0 582 return text;
michael@0 583 }
michael@0 584
michael@0 585 let parts = []; // indented parts
michael@0 586 let partStart = 0; // start offset of currently parsed part
michael@0 587 let indent = "";
michael@0 588 let indentLevel = 0;
michael@0 589
michael@0 590 for (let i = 0; i < text.length; i++) {
michael@0 591 let c = text[i];
michael@0 592 let shouldIndent = false;
michael@0 593
michael@0 594 switch (c) {
michael@0 595 case "}":
michael@0 596 if (i - partStart > 1) {
michael@0 597 // there's more than just } on the line, add line
michael@0 598 parts.push(indent + text.substring(partStart, i));
michael@0 599 partStart = i;
michael@0 600 }
michael@0 601 indent = TAB_CHARS.repeat(--indentLevel);
michael@0 602 /* fallthrough */
michael@0 603 case ";":
michael@0 604 case "{":
michael@0 605 shouldIndent = true;
michael@0 606 break;
michael@0 607 }
michael@0 608
michael@0 609 if (shouldIndent) {
michael@0 610 let la = text[i+1]; // one-character lookahead
michael@0 611 if (!/\n/.test(la) || /^\s+$/.test(text.substring(i+1, text.length))) {
michael@0 612 // following character should be a new line, but isn't,
michael@0 613 // or it's whitespace at the end of the file
michael@0 614 parts.push(indent + text.substring(partStart, i + 1));
michael@0 615 if (c == "}") {
michael@0 616 parts.push(""); // for extra line separator
michael@0 617 }
michael@0 618 partStart = i + 1;
michael@0 619 } else {
michael@0 620 return text; // assume it is not minified, early exit
michael@0 621 }
michael@0 622 }
michael@0 623
michael@0 624 if (c == "{") {
michael@0 625 indent = TAB_CHARS.repeat(++indentLevel);
michael@0 626 }
michael@0 627 }
michael@0 628 return parts.join(LINE_SEPARATOR);
michael@0 629 }
michael@0 630
michael@0 631 /**
michael@0 632 * Find a path on disk for a file given it's hosted uri, the uri of the
michael@0 633 * original resource that generated it (e.g. Sass file), and the location of the
michael@0 634 * local file for that source.
michael@0 635 *
michael@0 636 * @param {nsIURI} uri
michael@0 637 * The uri of the resource
michael@0 638 * @param {nsIURI} origUri
michael@0 639 * The uri of the original source for the resource
michael@0 640 * @param {nsIFile} file
michael@0 641 * The local file for the resource on disk
michael@0 642 *
michael@0 643 * @return {string}
michael@0 644 * The path of original file on disk
michael@0 645 */
michael@0 646 function findLinkedFilePath(uri, origUri, file) {
michael@0 647 let { origBranch, branch } = findUnsharedBranches(origUri, uri);
michael@0 648 let project = findProjectPath(file, origBranch);
michael@0 649
michael@0 650 let parts = project.concat(branch);
michael@0 651 let path = OS.Path.join.apply(this, parts);
michael@0 652
michael@0 653 return path;
michael@0 654 }
michael@0 655
michael@0 656 /**
michael@0 657 * Find the path of a project given a file in the project and its branch
michael@0 658 * off the root. e.g.:
michael@0 659 * /Users/moz/proj/src/a.css" and "src/a.css"
michael@0 660 * would yield ["Users", "moz", "proj"]
michael@0 661 *
michael@0 662 * @param {nsIFile} file
michael@0 663 * file for that resource on disk
michael@0 664 * @param {array} branch
michael@0 665 * path parts for branch to chop off file path.
michael@0 666 * @return {array}
michael@0 667 * array of path parts
michael@0 668 */
michael@0 669 function findProjectPath(file, branch) {
michael@0 670 let path = OS.Path.split(file.path).components;
michael@0 671
michael@0 672 for (let i = 2; i <= branch.length; i++) {
michael@0 673 // work backwards until we find a differing directory name
michael@0 674 if (path[path.length - i] != branch[branch.length - i]) {
michael@0 675 return path.slice(0, path.length - i + 1);
michael@0 676 }
michael@0 677 }
michael@0 678
michael@0 679 // if we don't find a differing directory, just chop off the branch
michael@0 680 return path.slice(0, path.length - branch.length);
michael@0 681 }
michael@0 682
michael@0 683 /**
michael@0 684 * Find the parts of a uri past the root it shares with another uri. e.g:
michael@0 685 * "http://localhost/built/a.scss" and "http://localhost/src/a.css"
michael@0 686 * would yield ["built", "a.scss"] and ["src", "a.css"]
michael@0 687 *
michael@0 688 * @param {nsIURI} origUri
michael@0 689 * uri to find unshared branch of. Usually is uri for original source.
michael@0 690 * @param {nsIURI} uri
michael@0 691 * uri to compare against to get a shared root
michael@0 692 * @return {object}
michael@0 693 * object with 'branch' and 'origBranch' array of path parts for branch
michael@0 694 */
michael@0 695 function findUnsharedBranches(origUri, uri) {
michael@0 696 origUri = OS.Path.split(origUri.path).components;
michael@0 697 uri = OS.Path.split(uri.path).components;
michael@0 698
michael@0 699 for (let i = 0; i < uri.length - 1; i++) {
michael@0 700 if (uri[i] != origUri[i]) {
michael@0 701 return {
michael@0 702 branch: uri.slice(i),
michael@0 703 origBranch: origUri.slice(i)
michael@0 704 };
michael@0 705 }
michael@0 706 }
michael@0 707 return {
michael@0 708 branch: uri,
michael@0 709 origBranch: origUri
michael@0 710 };
michael@0 711 }
michael@0 712
michael@0 713 /**
michael@0 714 * Remove the query string from a url.
michael@0 715 *
michael@0 716 * @param {string} href
michael@0 717 * Url to remove query string from
michael@0 718 * @return {string}
michael@0 719 * Url without query string
michael@0 720 */
michael@0 721 function removeQuery(href) {
michael@0 722 return href.replace(/\?.*/, "");
michael@0 723 }

mercurial