@summary Handle XZ compressed images
@function
@public
@memberof handlers

@param {String} file - file path
@fulfil {Object} - image metadata
@returns {Promise}
964333
function(file) {
    return fs.openAsync(file, 'r').then((fileDescriptor) => {
      return lzma.parseFileIndexFDAsync(fileDescriptor).tap(() => {
        return fs.closeAsync(fileDescriptor);
      });
    }).then((metadata) => {
      return {
        stream: fs.createReadStream(file)
          .pipe(lzma.createDecompressor()),
        size: metadata.uncompressedSize,
        transform: new PassThroughStream()
      };
    });
  }
248676
function safegetzipfile(zip, file) {
	var k = keys(zip.files);
	var f = file.toLowerCase(), g = f.replace(/\//g,'\\');
	for(var i=0; i<k.length; ++i) {
		var n = k[i].toLowerCase();
		if(f == n || g == n) return zip.files[k[i]];
	}
	return null;
}
47550
function processFile(rootPath, log) {
  return (file, callback) => {
    const filePath = path.join(rootPath, file.path);
    const writeMode = isStream(file.data) ? WriteMode.STREAM : WriteMode.UTF8;
    write(filePath, file.data, writeMode, (error) => {
      if (log === true && !error) {
        console.log(`Successfully wrote file '${file.path}'`);
      }

      async.nextTick(callback, error, file);
    });
  };
}
295275
function readYamlFile(file) {
  return new Promise((resolve, reject) => {
    readFile(file, 'utf8')
      .then(data => resolve(fromYaml(data)))
      .catch(reject);
  });
}
592794
function readPNG(file) {
    const deferred = Q.defer();
    const onerror = deferred.reject.bind(deferred);
    const stream = fs.createReadStream(file);
    stream.on("error", onerror);
    pngparse.parseStream(stream, function(err, image) {
        if (err) {
            console.log("Failed to load " + file);
            onerror(err);
            return;
        }
        deferred.resolve(image);
    });
    return deferred.promise;
}
1082432
function compress() {
  return through.obj(function(file, enc, cb) {
    new CleanCSS().minify(file.contents, function (err, minified) {
      file.contents = new Buffer(minified.styles);
      cb(err, file);
    });
  });
}
20923
function mustUnzip(file, mode){
  if (mode){
    return mode === 'tgz';
  }
  var extension = path.extname(file);
  return contains(['.tgz', '.gz'], extension);
}
1372115
function processFile(extension) {
  return (file, callback) => {
    let filePath;
    if (file.meta !== undefined && file.meta.filePath !== undefined) {
      const ext = extension === null
        ? file.meta.filePath.ext
        : extension;
      filePath = path.format(Object.assign({}, file.meta.filePath, { ext }));
    } else {
      filePath = extension === undefined
        ? file.path
        : `${trimExtension(file.path)}${extension}`;
    }

    async.nextTick(callback, null, Object.assign({}, file, { path: filePath }));
  };
}
822456
function handleImageLoad(canvas, filename, e) {
        e.preventDefault();

        downloadCanvas(drawImageOnCanvas(this, canvas), filename);
    }
1123544
function(file, callback) {
        var number = arguments[2] || 0;
        var location = url.parse(file);
        var protocol = location.protocol === 'http:' ? http : https;
        var timeoutEventId;
        var that = this;
        var REDIRECTION_MAX = 3;

        var done = function(errors, data) {
            clearTimeout(timeoutEventId);
            callback(errors, data);
        }


        var request = protocol.request({
                method: 'GET',
                host: location.host,
                hostname: location.hostname,
                path: location.path,
                port: location.port,
                headers: this.adapter.resourceRequestHeaders(file)
            }, function(res) {

                var encoding = res.headers['content-encoding'];
                var type = res.headers['content-type'];
                var statusCode = res.statusCode;
                var errors = null;

                if (/3\d\d/.test(statusCode) && res.headers.location && number < REDIRECTION_MAX) {
                    clearTimeout(timeoutEventId);
                    var file = res.headers.location;
                    number++;
                    that.loadRemoteFile(file, callback, number);
                    return;
                } else if (!/2\d\d/.test(statusCode)) {
                    errors = new Error(res.statusMessage);
                }

                if (type.indexOf('text/') !== 0) {
                    errors = new Error('only supports `text/*` resources');
                }


                if (errors) {
                    done(errors);
                } else {

                    var buffer = new Buffer([]);


                    if (encoding === 'undefined') {
                        res.setEncoding('utf-8');
                    }


                    res.on('data', function(chunk) {
                        buffer = Buffer.concat([buffer, chunk]);
                    });

                    res.on('end', function() {

                        if (encoding === 'gzip') {

                            zlib.unzip(buffer, function(errors, buffer) {
                                if (errors) {
                                    done(errors);
                                } else {
                                    done(null, buffer);
                                }
                            });

                        } else if (encoding == 'deflate') {

                            zlib.inflate(buffer, function(errors, decoded) {
                                if (errors) {
                                    done(errors);
                                } else {
                                    done(null, decoded);
                                }
                            });

                        } else {
                            done(null, buffer);
                        }

                    });

                }

            })
            .on('error', done)
            .on('timeout', function(errors) {
                request.abort();
                done(errors);
            });


        timeoutEventId = setTimeout(function() {
            request.emit('timeout', new Error('have been timeout'));
        }, this.adapter.resourceTimeout);


        request.end();

    }
465708
function tryFile(file) {
	return new Promise((resolve, reject) => {
		fs.stat(file, (err, stat) => {
			if (err) {
				return reject(err);
			}

			if (!stat.isFile()) {
				return reject(new Error(`${file} is not a file`));
			}

			resolve(file);
		});
	});
}
506326
function(file, $canvas, callback) {
            this.newImage();
            if (!file)
                return;

            var reader = new FileReader();
            reader.onload = function (fileReaderEvent) {
                image.onload = function () { readImageToCanvasOnLoad(this, $canvas, callback); };
                image.src = fileReaderEvent.target.result;      // The URL from FileReader

            };
            reader.readAsDataURL(file);
        }
925108
function _compress(command, outputFile) {
    return qexec(command)
        .then(function () {
            return outputFile.loadSize();
        })
        .fail(function (err) {
            // Before using of 'advpng' a raw file has to be copied
            // This algorithm can not compress a file and write a result to another file
            return qfs.exists(outputFile.name)
                .then(function (exists) {
                    if (exists) {
                        outputFile.remove();
                    }

                    throw err;
                });
        });
}
530320
function deliverImage(path, res) {
  var stream = lib.fs.createReadStream(path);
  /* @todo: set headers 'n stuff */
  lib.util.pump(stream, res, function (err) {
    if (err) {
      /* @todo: handle errors. */
      console.log('errors', err);
    }
  });
}
1062754
function load(file) {

    let contents = null;

    file = path.resolve(file);

    // handle .env files
    if (constants.REGEX.envfile.test(file)) {
        contents = util.parse(fs.readFileSync(file, 'utf8'));

    // handle .js/.json files
    } else {
        contents = require(file);
    }

    return env(contents);

}
1202287
function (file) {
                var _this = this;
                return new Promise(function (resolve, reject) {
                    return __awaiter(_this, void 0, void 0, function () {
                        var err_1, err_2;
                        var _this = this;
                        return __generator(this, function (_a) {
                            switch (_a.label) {
                                case 0:
                                    this.processing.emit(true);
                                    _a.label = 1;
                                case 1:
                                    _a.trys.push([1, 3, , 4]);
                                    return [4 /*yield*/, this.readImage(file)];
                                case 2:
                                    _a.sent();
                                    return [3 /*break*/, 4];
                                case 3:
                                    err_1 = _a.sent();
                                    console.error(err_1);
                                    this.error.emit(new Error(err_1));
                                    return [3 /*break*/, 4];
                                case 4:
                                    _a.trys.push([4, 6, , 7]);
                                    return [4 /*yield*/, this.showPreview()];
                                case 5:
                                    _a.sent();
                                    return [3 /*break*/, 7];
                                case 6:
                                    err_2 = _a.sent();
                                    console.error(err_2);
                                    this.error.emit(new Error(err_2));
                                    return [3 /*break*/, 7];
                                case 7:
                                    // set pane limits
                                    // show points
                                    this.imageLoaded = true;
                                    return [4 /*yield*/, this.limitsService.setPaneDimensions({ width: this.previewDimensions.width, height: this.previewDimensions.height })];
                                case 8:
                                    _a.sent();
                                    setTimeout(function () {
                                        return __awaiter(_this, void 0, void 0, function () {
                                            return __generator(this, function (_a) {
                                                switch (_a.label) {
                                                    case 0: return [4 /*yield*/, this.detectContours()];
                                                    case 1:
                                                        _a.sent();
                                                        this.processing.emit(false);
                                                        resolve();
                                                        return [2 /*return*/];
                                                }
                                            });
                                        });
                                    }, 15);
                                    return [2 /*return*/];
                            }
                        });
                    });
                });
            }
867388
function getImageSizeFromFile(file) {
	return new Promise((resolve, reject) => {
		const isDataUrl = file.match(/^data:.+?;base64,/);

		if (isDataUrl) {
			// NB should use sync version of `sizeOf()` for buffers
			try {
				const data = Buffer.from(file.slice(isDataUrl[0].length), 'base64');
				return resolve(sizeForFileName('', sizeOf(data)));
			} catch (err) {
				return reject(err);
			}
		}

		sizeOf(file, (err, size) => {
			if (err) {
				reject(err);
			} else {
				resolve(sizeForFileName(path.basename(file), size));
			}
		});
	});
}