Converts the png to a temporary directory which will be cleaned up on process exit
@param {string} pngSrc
@param {pngToIcnsCallback} callback
558068
function convertToIcnsTmp(pngSrc, callback) {
  const tempIconDirObj = tmp.dirSync({ unsafeCleanup: true });
  const tempIconDirPath = tempIconDirObj.name;
  convertToIcns(pngSrc, `${tempIconDirPath}/icon.icns`, callback);
}
979896
function(callback) {
    //process first all directories and then all files.
    async.mapSeries(['getDirectories', 'getFiles'], (nodeSource, cbMap) => {
      syncDb[nodeSource]((err, nodes) => {
        async.eachSeries(nodes, (node, cb) => {

          // If a node has to be redownloaded do not delete it remotely
          // See: https://github.com/gyselroth/balloon-node-sync/issues/17
          if(node.downloadOriginal) return cb();

          var nodePath = utility.joinPath(node.parent, node.name);

          process.nextTick(() => {
            var nodePath = utility.joinPath(node.parent, node.name);

            if(fsWrap.existsSync(nodePath) === false) {
              //Node doesn't exist localy -> delete it remotely
              deleteNode(node, false, cb);
            } else {
              try {
                var stat = fsWrap.lstatSync(nodePath);
              } catch(e) {
                logger.warning('findDeletedNodes got lstat error on node', {category: 'sync-local-delta', nodePath, code: e.code});
                throw new BlnDeltaError(e.message);
              }

              if(stat.ino === node.ino) {
                //node still exists at given path
                return cb();
              } else {
                deleteNode(node, true, cb);
              }
            }
          });
        }, cbMap);
      });
    }, callback);
  }
359246
function( options, callback ) {
            var me = this;
            var error = function(e) { fail(e); if ( callback ) me.fn( me.name, callback ).call( me, me ); };
            requestFileSystem( (options.storage === 'TEMPORARY' ? TEMPORARY : PERSISTENT), (options.size || 1024*1024*1024), function( fs ) {
                fs.root.getDirectory( options.name, {create:true}, function( directory ) {
                    filesystems[options.name] = directory;
                    if ( callback ) me.fn( me.name, callback ).call( me, me );
                }, error );
            }, error );
        }
734290
function convertInlinePNG(source, dest) {
    if (!/^data\:image\/png/.test(source)) return Promise.reject(new Error('Source is not a PNG data-uri'));

    var base64data = source.split('data:image/png;base64,')[1];
    var buf = new Buffer(base64data, 'base64');

    return fs.writeFile(dest, buf)
    .then(function() {
        if (fs.existsSync(dest)) return;

        throw new Error('Error converting '+source+' into '+dest);
    });
}
939989
function (el, evalScripts, pngFallback, callback) {

    // Grab the src or data-src attribute
    var imgUrl = el.getAttribute('data-src') || el.getAttribute('src');

    // We can only inject SVG
    if (!(/\.svg/i).test(imgUrl)) {
      callback('Attempted to inject a file with a non-svg extension: ' + imgUrl);
      return;
    }

    // If we don't have SVG support try to fall back to a png,
    // either defined per-element via data-fallback or data-png,
    // or globally via the pngFallback directory setting
    if (!hasSvgSupport) {
      var perElementFallback = el.getAttribute('data-fallback') || el.getAttribute('data-png');

      // Per-element specific PNG fallback defined, so use that
      if (perElementFallback) {
        el.setAttribute('src', perElementFallback);
        callback(null);
      }
      // Global PNG fallback directoriy defined, use the same-named PNG
      else if (pngFallback) {
        el.setAttribute('src', pngFallback + '/' + imgUrl.split('/').pop().replace('.svg', '.png'));
        callback(null);
      }
      // um...
      else {
        callback('This browser does not support SVG and no PNG fallback was defined.');
      }

      return;
    }

    // Make sure we aren't already in the process of injecting this element to
    // avoid a race condition if multiple injections for the same element are run.
    // :NOTE: Using indexOf() only _after_ we check for SVG support and bail,
    // so no need for IE8 indexOf() polyfill
    if (injectedElements.indexOf(el) !== -1) {
      return;
    }

    // Remember the request to inject this element, in case other injection
    // calls are also trying to replace this element before we finish
    injectedElements.push(el);

    // Try to avoid loading the orginal image src if possible.
    el.setAttribute('src', '');

    // Load it up
    loadSvg(imgUrl, function (svg) {

      if (typeof svg === 'undefined' || typeof svg === 'string') {
        callback(svg);
        return false;
      }

      var imgId = el.getAttribute('id');
      if (imgId) {
        svg.setAttribute('id', imgId);
      }

      var imgTitle = el.getAttribute('title');
      if (imgTitle) {
        svg.setAttribute('title', imgTitle);
      }

      // Concat the SVG classes + 'injected-svg' + the img classes
      var classMerge = [].concat(svg.getAttribute('class') || [], 'injected-svg', el.getAttribute('class') || []).join(' ');
      svg.setAttribute('class', uniqueClasses(classMerge));

      var imgStyle = el.getAttribute('style');
      if (imgStyle) {
        svg.setAttribute('style', imgStyle);
      }

      // Copy all the data elements to the svg
      var imgData = [].filter.call(el.attributes, function (at) {
        return (/^data-\w[\w\-]*$/).test(at.name);
      });
      forEach.call(imgData, function (dataAttr) {
        if (dataAttr.name && dataAttr.value) {
          svg.setAttribute(dataAttr.name, dataAttr.value);
        }
      });

      // Make sure any internally referenced clipPath ids and their
      // clip-path references are unique.
      //
      // This addresses the issue of having multiple instances of the
      // same SVG on a page and only the first clipPath id is referenced.
      //
      // Browsers often shortcut the SVG Spec and don't use clipPaths
      // contained in parent elements that are hidden, so if you hide the first
      // SVG instance on the page, then all other instances lose their clipping.
      // Reference: https://bugzilla.mozilla.org/show_bug.cgi?id=376027

      // Handle all defs elements that have iri capable attributes as defined by w3c: http://www.w3.org/TR/SVG/linking.html#processingIRI
      // Mapping IRI addressable elements to the properties that can reference them:
      var iriElementsAndProperties = {
        'clipPath': ['clip-path'],
        'color-profile': ['color-profile'],
        'cursor': ['cursor'],
        'filter': ['filter'],
        'linearGradient': ['fill', 'stroke'],
        'marker': ['marker', 'marker-start', 'marker-mid', 'marker-end'],
        'mask': ['mask'],
        'pattern': ['fill', 'stroke'],
        'radialGradient': ['fill', 'stroke']
      };

      var element, elementDefs, properties, currentId, newId;
      Object.keys(iriElementsAndProperties).forEach(function (key) {
        element = key;
        properties = iriElementsAndProperties[key];

        elementDefs = svg.querySelectorAll('defs ' + element + '[id]');
        for (var i = 0, elementsLen = elementDefs.length; i < elementsLen; i++) {
          currentId = elementDefs[i].id;
          newId = currentId + '-' + injectCount;

          // All of the properties that can reference this element type
          var referencingElements;
          forEach.call(properties, function (property) {
            // :NOTE: using a substring match attr selector here to deal with IE "adding extra quotes in url() attrs"
            referencingElements = svg.querySelectorAll('[' + property + '*="' + currentId + '"]');
            for (var j = 0, referencingElementLen = referencingElements.length; j < referencingElementLen; j++) {
              referencingElements[j].setAttribute(property, 'url(#' + newId + ')');
            }
          });

          elementDefs[i].id = newId;
        }
      });

      // Remove any unwanted/invalid namespaces that might have been added by SVG editing tools
      svg.removeAttribute('xmlns:a');

      // Post page load injected SVGs don't automatically have their script
      // elements run, so we'll need to make that happen, if requested

      // Find then prune the scripts
      var scripts = svg.querySelectorAll('script');
      var scriptsToEval = [];
      var script, scriptType;

      for (var k = 0, scriptsLen = scripts.length; k < scriptsLen; k++) {
        scriptType = scripts[k].getAttribute('type');

        // Only process javascript types.
        // SVG defaults to 'application/ecmascript' for unset types
        if (!scriptType || scriptType === 'application/ecmascript' || scriptType === 'application/javascript') {

          // innerText for IE, textContent for other browsers
          script = scripts[k].innerText || scripts[k].textContent;

          // Stash
          scriptsToEval.push(script);

          // Tidy up and remove the script element since we don't need it anymore
          svg.removeChild(scripts[k]);
        }
      }

      // Run/Eval the scripts if needed
      if (scriptsToEval.length > 0 && (evalScripts === 'always' || (evalScripts === 'once' && !ranScripts[imgUrl]))) {
        for (var l = 0, scriptsToEvalLen = scriptsToEval.length; l < scriptsToEvalLen; l++) {

          // :NOTE: Yup, this is a form of eval, but it is being used to eval code
          // the caller has explictely asked to be loaded, and the code is in a caller
          // defined SVG file... not raw user input.
          //
          // Also, the code is evaluated in a closure and not in the global scope.
          // If you need to put something in global scope, use 'window'
          new Function(scriptsToEval[l])(window); // jshint ignore:line
        }

        // Remember we already ran scripts for this svg
        ranScripts[imgUrl] = true;
      }

      // :WORKAROUND:
      // IE doesn't evaluate <style> tags in SVGs that are dynamically added to the page.
      // This trick will trigger IE to read and use any existing SVG <style> tags.
      //
      // Reference: https://github.com/iconic/SVGInjector/issues/23
      var styleTags = svg.querySelectorAll('style');
      forEach.call(styleTags, function (styleTag) {
        styleTag.textContent += '';
      });

      // Replace the image with the svg
      el.parentNode.replaceChild(svg, el);

      // Now that we no longer need it, drop references
      // to the original element so it can be GC'd
      delete injectedElements[injectedElements.indexOf(el)];
      el = null;

      // Increment the injected count
      injectCount++;

      callback(svg);
    });
  }
1149134
function(callback) {
      var asyncFunctions = [];

      for (var i = 0; i < numberOfRows; i++) {
        var rowsImagesPaths = imagesPaths.slice(i * numberOfColumns, i * numberOfColumns + numberOfColumns);
        var lineWidth = width;
        var lineHeight = height;
        var linePath = path.join(temporaryDirectoryPath, 'line-' + i);

        linesPaths.push(linePath);
        asyncFunctions.push(createLine(rowsImagesPaths, linePath, lineWidth, lineHeight, true, 100));
      }

      async.parallel(asyncFunctions, function(error, results) {
        if (error) return callback(error);

        results.forEach(function(line) {
          line.forEach(function(image) {
            if (image.image === path.join(temporaryDirectoryPath, 'transparent.png')) return;

            var spritePathChunks = path.parse(image.sprite).name.match(/-([0-9]+)$/);
            var lineIndex = (spritePathChunks && parseInt(spritePathChunks[1])) || 0;

            image.y = image.y + (lineIndex * height);
            image.sprite = destinationPath;
            images.push(image);
          });
        });

        callback();
      });
    }
594656
function convertToIcns(pngSrc, icnsDest, callback) {
  if (!isOSX()) {
    callback('OSX is required to convert .png to .icns icon', pngSrc);
    return;
  }

  shell.exec(
    `"${PNG_TO_ICNS_BIN_PATH}" "${pngSrc}" "${icnsDest}"`,
    { silent: true },
    (exitCode, stdOut, stdError) => {
      if (stdOut.includes('icon.iconset:error') || exitCode) {
        if (exitCode) {
          callback(
            {
              stdOut,
              stdError,
            },
            pngSrc,
          );
          return;
        }

        callback(stdOut, pngSrc);
        return;
      }

      callback(null, icnsDest);
    },
  );
}
1120029
function(callback) {
        var headers     = this._formatHeaders(this.headers, this.params);
        if (this.payload != null) {
            headers['content-length'] = new Buffer(this.payload).length;
        } else if (this.method == 'POST' || this.method == 'DELETE' || this.method == 'PUT') {
            headers['content-length'] = 0;
        }
        var client = this.httpClient.http;
        if (this.scheme == 'https') client = this.httpClient.https;
        var httpRequest = client.request({port    : this.port,
                                          host    : this.host,
                                          method  : this.method,
                                          path    : this.uri,
                                          headers : headers},
                                         function(response) {
                                             var data = "";
                                             response.on('data', function(chunk) {
                                                 data += chunk;
                                             });
                                             response.on('end', function() {
                                                 var c = {
                                                     status  : response.statusCode,
                                                     headers : response.headers,
                                                     body    : data
                                                 };
                                                 callback(null, c);
                                             });
                                         });
        httpRequest.on('error', function(e) {
            callback(e, null);
        });
        if (this.payload !== null)
            httpRequest.write(this.payload);
        httpRequest.end();
    }
768119
function (callback) {
		fs.mkdir("./dist", function (err) {
			if (err && err.code !== "EEXIST") {
				callback(err);
				return;
			}

			callback(null);
		});
	}
56363
function (base, res) {
  base.stream('png', function (err, stdout) {
    if (err) {
      throw err;
    }
    res.setHeader('Expires', new Date(Date.now() + 600000));
    res.setHeader('Content-Type', 'image/png');
    stdout.pipe(res);
  });
}
611271
function toDataURL (image, options) {
  var src = '';
  var async, callback;

  options = options || {};

  async = typeof options.callback === 'function';

  callback = async ? options.callback : function (err, data) {
    if (err) {
      throw err;
    }
    return data;
  };

  function _convert (err, img) {
    if (err) {
      return callback(err);
    }
    var result;
    cors(img);
    result = convert(img, options.width, options.height);
    return callback(null, (options.purify ? purify(result) : result));
  }

  if (isImage(image)) {
    src = image.src || '';
  } else if (typeof image === 'string') {
    if (!async) {
      return callback(new Error('the url mode should be called with a callback'));
    }
    src = image;
  } else {
    return callback(new Error('image should be an Image Object or a string'));
  }

  return async ? createImage(src, _convert) : _convert(null, image);
}
949908
function( grunt, options, callback ) {
  this.callback          = callback;
  this.diffCount         = 0;
  this.grunt             = grunt;
  this.options           = options;
  this.options.indexPath = this.getIndexPath();
  this.pictureCount      = 0;

  if ( typeof options.template === 'string' ) {
    this.template = options.template;
  } else if ( typeof options.template === 'object' ) {
    this.template = options.template.name;
  }

  this.movePictures();
  this.pictures = this.getPreparedPictures();
}
739712
function loadImage ($imageElement, newSource, callback) {
        $imageElement.fadeOut(function () {
            $imageElement.attr("src", newSource);
            imgLoad($imageElement, function () {
                $imageElement.removeClass("loading");
                $imageElement.fadeIn();
                if (typeof callback === "function") {
                    callback();
                }
            });
        });
    }
953991
function(cb){
      this.toCanvas(function(canvas){
        var canvasData = canvas.toDataURL("image/png");
        var img = document.createElement('img');

        img.onload = function(){
          cb(img);
        };

        // Make pngImg's source the canvas data.
        img.setAttribute('src', canvasData);
      });
    }
1165847
function inlineAssets(rootFolder, currentFile) {
    return function($) {
        return Promise()

        // Resolving images and fetching external images should be
        // done before svg conversion
        .then(resolveImages.bind(null, currentFile, $))
        .then(fetchRemoteImages.bind(null, rootFolder, currentFile, $))

        .then(svgToImg.bind(null, rootFolder, currentFile, $))
        .then(svgToPng.bind(null, rootFolder, currentFile, $))
        .then(inlinePng.bind(null, rootFolder, currentFile, $));
    };
}
852363
function(callback) {
      if (imagesPaths.length >= numberOfColumns * numberOfRows) return callback();

      var transparentImagePath = path.join(temporaryDirectoryPath, 'transparent.png');
      gm(width, height, '#00000000').write(transparentImagePath, function(error) {

        // Add as many as needed transparent images to the list of images
        var totalMissingImages = numberOfColumns * numberOfRows - imagesPaths.length;

        for (var i = 0; i < totalMissingImages; i++)
          imagesPaths.push(transparentImagePath);

        callback(error);
      });
    }
844210
function fetchRemoteImages(rootFolder, currentFile, $) {
    var currentDirectory = path.dirname(currentFile);

    return editHTMLElement($, 'img', function($img) {
        var src = $img.attr('src');
        var extension = path.extname(src);

        if (!LocationUtils.isExternal(src)) {
            return;
        }

        // We avoid generating twice the same PNG
        var hash = crc.crc32(src).toString(16);
        var fileName = hash + extension;
        var filePath = path.join(rootFolder, fileName);

        return fs.assertFile(filePath, function() {
            return fs.download(src, filePath);
        })
        .then(function() {
            // Convert to relative
            src = LocationUtils.relative(currentDirectory, fileName);

            $img.replaceWith('<img src="' + src + '" />');
        });
    });
}