<commit_before>(function () {

    //*@public
    /**
        The _enyo.Binding_ object is designed to connect and synchronize
        the state between two properties of _enyo.Object_s. It can function
        as a two-way or one-way binding (where a only changes from the source
        are propagated to the target and not vice versa). While the object
        can be used and implemented on its own, _enyo.Object_s and any subkinds
        are able to use them through an automated API.

        TODO: complete intro documentation
    */
    enyo.Binding = Binding;

    //*@protected
    enyo.Transform = Transform;

    //*@protected
    function Transform (fn, binding) {
        this.transformer = fn;
        this.binding = binding;
    }

    //*@protected
    Transform.prototype = {
        stop: function () {
            throw "stop";
        },
        transform: function (value, direction) {
            var fn = this.transformer;
            var binding = this.binding;
            var context = binding.owner || enyo.global;
            return fn.call(context, value, direction, binding);
        },
        destroy: function () {
            this.transformer = null;
            this.binding = null;
        }
    };

    //*@protected
    /**
        The constructor for a binding takes a variable number of parameters
        that are object/hashes with properties to be set on the binding. When
        multiple option-sets are provided and there are common properties the
        last property encountered will have its value used.
    */
    function Binding (/* arguments */) {
        var idx = 0;
        var len = arguments.length;
        // increment our binding counter for debugging purposes
        enyo.Binding.bindingCount++;
        // take any properties that were passed in and apply them
        // to this binding instance
        for (; idx < len; ++idx) enyo.mixin(this, arguments[idx]);
        // generate a new id for this binding
        this.bindingId = enyo.uid("binding");
        // run our initialization routines
        this.setup();
    }

    //*@public
    /**
        Keeps track of the number of bindings that are active at runtime.
        Mostly for debugging purposes.
    */
    enyo.Binding.bindingCount = 0;

    //*@protected
    /**
        Used internally as part of the getParts method.
    */
    var fromRoot = function (root, parts) {
        // check to see if the part of the path is relative to the root
        var piece = root[(parts || [])[0]];
        // if the root here is enyo.global then we need to ensure that
        // the piece is actually an object
        // this is very, very important
        if (enyo.exists(piece)) {
            if (enyo.global === root) {
                return "object" === typeof piece? root: undefined;
            } else return root;
        }
    };

    //*@protected
    /**
        Used internally to determine from the given information what the
        source and target paths and properties are. There is one exception case
        between determining parts for the source and the target in bindings so
        the optional third parameter helps it to use the correct algorithm.
    */
    var getParts = enyo.Binding.getParts = function (path, context, direction) {
        var parts;
        var idx = 0;
        var ret = {};
        var root;
        var cur;
        var prop;
        var base;
        var part;
        var owner = this.owner;
        var to = direction === "target";
        path = path[0] === "."? path.slice(1): path;
        parts = path.split(".");
        root = context || fromRoot(enyo.global, parts) || owner;
        // this is the exception case for determining parts in the target direction -
        // even if the property DID exist on the global object (e.g. _length_) if it
        // is the target it doesn't have to exist and the target has to be a subclass
        // of enyo.Object
        //if (true === to) {
        //    if (enyo.global === root) {
        //        root = owner;
        //    }
        //}
        base = root;
        ret.property = prop = parts.length > 1? parts.pop(): path;
        if (prop === path) {
            ret.base = base;
        } else {
            cur = base;
            for (; idx < parts.length; ++idx) {
                part = parts[idx];
                if (!part) continue;
                cur = cur[part];
                if (!cur || "string" === typeof cur) {
                    if (part !== prop) {
                        ret.base = null;
                    }
                    return ret;
                }
            }
            if (part !== path) base = cur;
            ret.base = base;
        }
        return ret;
    };

    //*@protected
    enyo.Binding.transform = function (value, direction) {
        var transform = this.transform;
        return transform(value, direction);
    };

    //*@protected
    /**
        The prototype of the _enyo.Binding_ object.
    */
    Binding.prototype = {
        //*@public
        source: null,
        //*@public
        target: null,
        //*@protected
        sourceProperty: null,
        //*@protected
        targetProperty: null,
        //*@protected
        sourceResponder: null,
        //*@protected
        targetResponder: null,
        //*@protected
        isConnected: false,
        //*@protected
        isRefreshing: false,
        //*@protected
        sourceConnected: false,
        //*@protected
        targetConnected: false,
        //*@public
        to: null,
        //*@public
        from: null,
        //*@public
        owner: null,
        //*@public
        autoConnect: true,
        //*@public
        autoSync: true,
        //*@public
        transform: null,
        //*@protected
        oneWay: true,
        //*@protected
        /**
            Initially called during construction to setup the properties
            of the binding appropriately exiting on specific conditions
            silently if the target or source could not be properly
            determined or found.
        */
        setup: function () {
            var connect = this.autoConnect;
            var sync = this.autoSync;
            var source = this.setupSource();
            var target = this.setupTarget();
            var refreshing = this.isRefreshing;
            // setup the transform if we can
            this.setupTransform();
            // if we are refreshing and cannot find
            // one of these parts we need to reset the targets
            // value if possible (happens frequently in proxy/model-
            // controllers who's model has been set to null)
            if (!(source && target)) {
                if (refreshing) {
                    if (target) {
                        // set the target's value to null to let
                        // it know we can't sync the real value from
                        // the source
                        this.setTargetValue(null);
                    }
                } else return;
            }
            // this will fail silently if setup went aury for
            // either the target or source
            if (connect || refreshing) this.connect();
            if (sync || refreshing) this.sync();
        },
        //*@protected
        sync: function () {
            if (true === this.isConnected) {
                this.syncFromSource();
            }
        },
        //*@protected
        refresh: function () {
            this.isRefreshing = true;
            // TODO: this needs to be reevaluated because refreshing
            // a binding as of now does more work than it should be
            this.disconnect();
            this.setup();
            this.isRefreshing = false;
        },
        //*@public
        /**
            Call this method to connect this binding to its
            source (and target). This only registers the responders
            but does not automatically synchronize the values.
        */
        connect: function () {
            if (true === this.isConnected) return;
            this.connectSource();
            this.connectTarget();
            if (this.sourceConnected && this.targetConnected) {
                this.isConnected = true;
            } else this.isConnected = false;
        },
        //*@public
        /**
            Call this method to disconnect this binding from
            its source (and target).
        */
        disconnect: function () {
            if (false === this.isConnected) return;
            this.disconnectSource();
            this.disconnectTarget();
            this.isConnected = false;
        },
        //*@protected
        setupSource: function () {
            var parts;
            var base;
            var property = this.sourceProperty;
            var source = this.source;
            var from = this.from;
            parts = getParts.call(this, from, source);
            base = parts.base;
            property = parts.property;
            if (!base || "object" !== typeof base) {
                return false;
            }
            this.source = base;
            this.sourceProperty = property;
            return true;
        },
        //*@protected
        setupTarget: function () {
            var parts;
            var base;
            var property = this.targetProperty;
            var target = this.target;
            var to = this.to;
            parts = getParts.call(this, to, target, "target");
            base = parts.base;
            property = parts.property;
            if (!base || "object" !== typeof base) {
                return false;
            }
            this.target = base;
            this.targetProperty = property;
            return true;
        },
        //*@protected
        stop: function () {
            throw "stop-binding";
        },
        //*@protected
        connectSource: function () {
            var source = this.source;
            var property = this.sourceProperty;
            var fn = this.sourceResponder;
            if (!(source instanceof enyo.Object)) return (this.sourceConnected = false);
            // only create the responder if it doesn't already exist
            if (!enyo.exists(fn) || "function" !== typeof fn) {
                fn = enyo.bind(this, this.syncFromSource);
                this.sourceResponder = fn;
            }
            // if it is already connected don't do anything
            if (true === this.sourceConnected) return true;
            if (!enyo.exists(source)) return (this.sourceConnected = false);
            // assign the binding's id to the responder for debugging
            fn.bindingId = this.bindingId;
            // add the observer for the property on the source object
            source.addObserver(property, fn);
            return (this.sourceConnected = true);
        },
        //*@protected
        connectTarget: function () {
            var target = this.target;
            var property = this.targetProperty;
            var fn = this.targetResponder;
            var oneWay = this.oneWay;
            if (!(target instanceof enyo.Object)) return (this.targetConnected = false);
            // if this is a one way binding there is nothing to do
            if (true === oneWay) return (this.targetConnected = true);
            // only create the responder if it doesn't already exist
            if (!enyo.exists(fn) || "function" !== typeof fn) {
                fn = enyo.bind(this, this.syncFromTarget);
                this.targetResponder = fn;
            }
            // if it is already connected don't do anything else
            if (true === this.targetConnected) return true;
            if (!enyo.exists(target)) return (this.targetConnected = false);
            fn.bindingId = this.bindingId;
            target.addObserver(property, fn);
            return (this.targetConnected = true);
        },
        //*@protected
        syncFromSource: function () {
            var twoWay = !this.oneWay;
            var value = this.getSourceValue();
            var transformer = this.transform;
            // if this is a two way binding we need to
            // disconnect from the target first to ensure
            // we don't catch the update response
            // TODO: rethink this approach as try/catch are
            // costly in general...
            try {
                value = transformer.transform(value, "source");
            } catch (err) {
                // the transform was interrupted, do not complete
                if ("stop-binding" === err) return;
                else throw err;
            }
            if (twoWay) this.disconnectTarget();
            this.setTargetValue(value);
            if (twoWay) this.connectTarget();
        },
        //*@protected
        syncFromTarget: function () {
            var value = this.getTargetValue();
            var transformer = this.transform;
            // TODO: same as for syncFromSource
            try {
                value = transformer.transform(value, "target");
            } catch (err) {
                // the transform was interrupted, do not complete
                if ("stop-binding" === err) return;
                else throw err;
            }
            this.disconnectSource();
            this.setSourceValue(value);
            this.connectSource();
        },
        //*@protected
        disconnectSource: function () {
            var source = this.source;
            var property = this.sourceProperty;
            var fn = this.sourceResponder;
            if (!enyo.exists(source)) return;
            source.removeObserver(property, fn);
            this.sourceConnected = false;
        },
        //*@protected
        disconnectTarget: function () {
            var target = this.target;
            var fn = this.targetResponder;
            var property = this.targetProperty;
            if (!enyo.exists(target)) return;
            if ("function" === typeof fn) target.removeObserver(property, fn);
            this.targetConnected = false;
        },
        //*@protected
        setSourceValue: function (value) {
            var source = this.source;
            var property = this.sourceProperty;
            source.set(property, value);
        },
        //*@protected
        setTargetValue: function (value) {
            var target = this.target;
            var property = this.targetProperty;
            target.set(property, value);
        },
        //*@protected
        getSourceValue: function () {
            var source = this.source;
            var property = this.sourceProperty;
            return source.get(property);
        },
        //*@protected
        getTargetValue: function () {
            var target = this.target;
            var property = this.targetProperty;
            return target.get(property);
        },
        //*@protected
        setupTransform: function () {
            var transform = this.transform;
            var owner = this.owner || {};
            // if it is a string we try and locate it on the owner
            // or as a global method
            if ("string" === typeof transform) {
                transform = owner[transform] || enyo.getPath(transform);
            } else if ("function" === typeof transform) {
                transform = this.transform;
            }
            // if we couldn't find anything go ahead and setup a default
            // to simply return the value
            if ("function" !== typeof transform) {
                transform = this.transform = function(value) {return value};
            }
            if (!(transform instanceof Transform)) {
                this.transform = new Transform(transform, this);
            }
        },
        //*@public
        /**
            Call this method to prepare this object to be
            cleaned up by the garbage collector.
        */
        destroy: function () {
            this.disconnect();
            this.source = null;
            this.target = null;
            this.sourceResponder = null;
            this.targetResponder = null;
            this.isDestroyed = true;
            enyo.Binding.bindingCount--;
            if (this.transform) {
                this.transform.destroy();
                this.transform = null;
            }
            if (this.owner) this.owner.removeBinding(this);
        }
    };

}());<commit_msg>bindings now more efficiently handle relative paths explicitly notated via a leading '.'<commit_after>(function () {

    //*@public
    /**
        The _enyo.Binding_ object is designed to connect and synchronize
        the state between two properties of _enyo.Object_s. It can function
        as a two-way or one-way binding (where a only changes from the source
        are propagated to the target and not vice versa). While the object
        can be used and implemented on its own, _enyo.Object_s and any subkinds
        are able to use them through an automated API.

        TODO: complete intro documentation
    */
    enyo.Binding = Binding;

    //*@protected
    enyo.Transform = Transform;

    //*@protected
    function Transform (fn, binding) {
        this.transformer = fn;
        this.binding = binding;
    }

    //*@protected
    Transform.prototype = {
        stop: function () {
            throw "stop";
        },
        transform: function (value, direction) {
            var fn = this.transformer;
            var binding = this.binding;
            var context = binding.owner || enyo.global;
            return fn.call(context, value, direction, binding);
        },
        destroy: function () {
            this.transformer = null;
            this.binding = null;
        }
    };

    //*@protected
    /**
        The constructor for a binding takes a variable number of parameters
        that are object/hashes with properties to be set on the binding. When
        multiple option-sets are provided and there are common properties the
        last property encountered will have its value used.
    */
    function Binding (/* arguments */) {
        var idx = 0;
        var len = arguments.length;
        // increment our binding counter for debugging purposes
        enyo.Binding.bindingCount++;
        // take any properties that were passed in and apply them
        // to this binding instance
        for (; idx < len; ++idx) enyo.mixin(this, arguments[idx]);
        // generate a new id for this binding
        this.bindingId = enyo.uid("binding");
        // run our initialization routines
        this.setup();
    }

    //*@public
    /**
        Keeps track of the number of bindings that are active at runtime.
        Mostly for debugging purposes.
    */
    enyo.Binding.bindingCount = 0;

    //*@protected
    /**
        Used internally as part of the getParts method.
    */
    var fromRoot = function (root, parts) {
        // check to see if the part of the path is relative to the root
        var piece = root[(parts || [])[0]];
        // if the root here is enyo.global then we need to ensure that
        // the piece is actually an object
        // this is very, very important
        if (enyo.exists(piece)) {
            if (enyo.global === root) {
                return "object" === typeof piece? root: undefined;
            } else return root;
        }
    };

    //*@protected
    /**
        Used internally to determine from the given information what the
        source and target paths and properties are. There is one exception case
        between determining parts for the source and the target in bindings so
        the optional third parameter helps it to use the correct algorithm.
    */
    var getParts = enyo.Binding.getParts = function (path, context, direction) {
        var parts;
        var idx = 0;
        var ret = {};
        var root;
        var cur;
        var prop;
        var base;
        var part;
        var owner = this.owner;
        var local = path[0] === "."? true: false;
        var to = direction === "target";
        path = path[0] === "."? path.slice(1): path;
        parts = path.split(".");
        root = local? owner: context || fromRoot(enyo.global, parts) || owner;
        // this is the exception case for determining parts in the target direction -
        // even if the property DID exist on the global object (e.g. _length_) if it
        // is the target it doesn't have to exist and the target has to be a subclass
        // of enyo.Object
        //if (true === to) {
        //    if (enyo.global === root) {
        //        root = owner;
        //    }
        //}
        base = root;
        ret.property = prop = parts.length > 1? parts.pop(): path;
        if (prop === path) {
            ret.base = base;
        } else {
            cur = base;
            for (; idx < parts.length; ++idx) {
                part = parts[idx];
                if (!part) continue;
                cur = cur[part];
                if (!cur || "string" === typeof cur) {
                    if (part !== prop) {
                        ret.base = null;
                    }
                    return ret;
                }
            }
            if (part !== path) base = cur;
            ret.base = base;
        }
        return ret;
    };

    //*@protected
    enyo.Binding.transform = function (value, direction) {
        var transform = this.transform;
        return transform(value, direction);
    };

    //*@protected
    /**
        The prototype of the _enyo.Binding_ object.
    */
    Binding.prototype = {
        //*@public
        source: null,
        //*@public
        target: null,
        //*@protected
        sourceProperty: null,
        //*@protected
        targetProperty: null,
        //*@protected
        sourceResponder: null,
        //*@protected
        targetResponder: null,
        //*@protected
        isConnected: false,
        //*@protected
        isRefreshing: false,
        //*@protected
        sourceConnected: false,
        //*@protected
        targetConnected: false,
        //*@public
        to: null,
        //*@public
        from: null,
        //*@public
        owner: null,
        //*@public
        autoConnect: true,
        //*@public
        autoSync: true,
        //*@public
        transform: null,
        //*@protected
        oneWay: true,
        //*@protected
        /**
            Initially called during construction to setup the properties
            of the binding appropriately exiting on specific conditions
            silently if the target or source could not be properly
            determined or found.
        */
        setup: function () {
            var connect = this.autoConnect;
            var sync = this.autoSync;
            var source = this.setupSource();
            var target = this.setupTarget();
            var refreshing = this.isRefreshing;
            // setup the transform if we can
            this.setupTransform();
            // if we are refreshing and cannot find
            // one of these parts we need to reset the targets
            // value if possible (happens frequently in proxy/model-
            // controllers who's model has been set to null)
            if (!(source && target)) {
                if (refreshing) {
                    if (target) {
                        // set the target's value to null to let
                        // it know we can't sync the real value from
                        // the source
                        this.setTargetValue(null);
                    }
                } else return;
            }
            // this will fail silently if setup went aury for
            // either the target or source
            if (connect || refreshing) this.connect();
            if (sync || refreshing) this.sync();
        },
        //*@protected
        sync: function () {
            if (true === this.isConnected) {
                this.syncFromSource();
            }
        },
        //*@protected
        refresh: function () {
            this.isRefreshing = true;
            // TODO: this needs to be reevaluated because refreshing
            // a binding as of now does more work than it should be
            this.disconnect();
            this.setup();
            this.isRefreshing = false;
        },
        //*@public
        /**
            Call this method to connect this binding to its
            source (and target). This only registers the responders
            but does not automatically synchronize the values.
        */
        connect: function () {
            if (true === this.isConnected) return;
            this.connectSource();
            this.connectTarget();
            if (this.sourceConnected && this.targetConnected) {
                this.isConnected = true;
            } else this.isConnected = false;
        },
        //*@public
        /**
            Call this method to disconnect this binding from
            its source (and target).
        */
        disconnect: function () {
            if (false === this.isConnected) return;
            this.disconnectSource();
            this.disconnectTarget();
            this.isConnected = false;
        },
        //*@protected
        setupSource: function () {
            var parts;
            var base;
            var property = this.sourceProperty;
            var source = this.source;
            var from = this.from;
            parts = getParts.call(this, from, source);
            base = parts.base;
            property = parts.property;
            if (!base || "object" !== typeof base) {
                return false;
            }
            this.source = base;
            this.sourceProperty = property;
            return true;
        },
        //*@protected
        setupTarget: function () {
            var parts;
            var base;
            var property = this.targetProperty;
            var target = this.target;
            var to = this.to;
            parts = getParts.call(this, to, target, "target");
            base = parts.base;
            property = parts.property;
            if (!base || "object" !== typeof base) {
                return false;
            }
            this.target = base;
            this.targetProperty = property;
            return true;
        },
        //*@protected
        stop: function () {
            throw "stop-binding";
        },
        //*@protected
        connectSource: function () {
            var source = this.source;
            var property = this.sourceProperty;
            var fn = this.sourceResponder;
            if (!(source instanceof enyo.Object)) return (this.sourceConnected = false);
            // only create the responder if it doesn't already exist
            if (!enyo.exists(fn) || "function" !== typeof fn) {
                fn = enyo.bind(this, this.syncFromSource);
                this.sourceResponder = fn;
            }
            // if it is already connected don't do anything
            if (true === this.sourceConnected) return true;
            if (!enyo.exists(source)) return (this.sourceConnected = false);
            // assign the binding's id to the responder for debugging
            fn.bindingId = this.bindingId;
            // add the observer for the property on the source object
            source.addObserver(property, fn);
            return (this.sourceConnected = true);
        },
        //*@protected
        connectTarget: function () {
            var target = this.target;
            var property = this.targetProperty;
            var fn = this.targetResponder;
            var oneWay = this.oneWay;
            if (!(target instanceof enyo.Object)) return (this.targetConnected = false);
            // if this is a one way binding there is nothing to do
            if (true === oneWay) return (this.targetConnected = true);
            // only create the responder if it doesn't already exist
            if (!enyo.exists(fn) || "function" !== typeof fn) {
                fn = enyo.bind(this, this.syncFromTarget);
                this.targetResponder = fn;
            }
            // if it is already connected don't do anything else
            if (true === this.targetConnected) return true;
            if (!enyo.exists(target)) return (this.targetConnected = false);
            fn.bindingId = this.bindingId;
            target.addObserver(property, fn);
            return (this.targetConnected = true);
        },
        //*@protected
        syncFromSource: function () {
            var twoWay = !this.oneWay;
            var value = this.getSourceValue();
            var transformer = this.transform;
            // if this is a two way binding we need to
            // disconnect from the target first to ensure
            // we don't catch the update response
            // TODO: rethink this approach as try/catch are
            // costly in general...
            try {
                value = transformer.transform(value, "source");
            } catch (err) {
                // the transform was interrupted, do not complete
                if ("stop-binding" === err) return;
                else throw err;
            }
            if (twoWay) this.disconnectTarget();
            this.setTargetValue(value);
            if (twoWay) this.connectTarget();
        },
        //*@protected
        syncFromTarget: function () {
            var value = this.getTargetValue();
            var transformer = this.transform;
            // TODO: same as for syncFromSource
            try {
                value = transformer.transform(value, "target");
            } catch (err) {
                // the transform was interrupted, do not complete
                if ("stop-binding" === err) return;
                else throw err;
            }
            this.disconnectSource();
            this.setSourceValue(value);
            this.connectSource();
        },
        //*@protected
        disconnectSource: function () {
            var source = this.source;
            var property = this.sourceProperty;
            var fn = this.sourceResponder;
            if (!enyo.exists(source)) return;
            source.removeObserver(property, fn);
            this.sourceConnected = false;
        },
        //*@protected
        disconnectTarget: function () {
            var target = this.target;
            var fn = this.targetResponder;
            var property = this.targetProperty;
            if (!enyo.exists(target)) return;
            if ("function" === typeof fn) target.removeObserver(property, fn);
            this.targetConnected = false;
        },
        //*@protected
        setSourceValue: function (value) {
            var source = this.source;
            var property = this.sourceProperty;
            source.set(property, value);
        },
        //*@protected
        setTargetValue: function (value) {
            var target = this.target;
            var property = this.targetProperty;
            target.set(property, value);
        },
        //*@protected
        getSourceValue: function () {
            var source = this.source;
            var property = this.sourceProperty;
            return source.get(property);
        },
        //*@protected
        getTargetValue: function () {
            var target = this.target;
            var property = this.targetProperty;
            return target.get(property);
        },
        //*@protected
        setupTransform: function () {
            var transform = this.transform;
            var owner = this.owner || {};
            // if it is a string we try and locate it on the owner
            // or as a global method
            if ("string" === typeof transform) {
                transform = owner[transform] || enyo.getPath(transform);
            } else if ("function" === typeof transform) {
                transform = this.transform;
            }
            // if we couldn't find anything go ahead and setup a default
            // to simply return the value
            if ("function" !== typeof transform) {
                transform = this.transform = function(value) {return value};
            }
            if (!(transform instanceof Transform)) {
                this.transform = new Transform(transform, this);
            }
        },
        //*@public
        /**
            Call this method to prepare this object to be
            cleaned up by the garbage collector.
        */
        destroy: function () {
            this.disconnect();
            this.source = null;
            this.target = null;
            this.sourceResponder = null;
            this.targetResponder = null;
            this.isDestroyed = true;
            enyo.Binding.bindingCount--;
            if (this.transform) {
                this.transform.destroy();
                this.transform = null;
            }
            if (this.owner) this.owner.removeBinding(this);
        }
    };

}());<|endoftext|>


<commit_before>import React, { Component } from 'react';
import ToolBarButtonGroup from './ToolBarButtonGroup.js';
import Helper from '../helper.js';
import uniqid from 'uniqid';

class BodyToolBar extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchInfo: '',
    };
  }

  handleInputFocus(event) {
    event.target.placeholder = '';
  }

  handleInputBlur(event) {
    if (event.target.name === 'searchInfo') {
      event.target.placeholder = '输入文件名';
    }
  }

  handleSearchInfoChange(event) {
    const value = event.target.value;
    if (event.target.name === 'searchInfo') {
      this.setState({
        searchInfo: value,
      });
    }
  }

  handleRemoveIconClick(event) {
    this.setState({
      searchInfo: '',
    }, this.props.onClearSearchInfo);
  }

  handleSearchButtonClick(event) {
    this.props.onToolBarSearchInfoChange(this.state.searchInfo);
  }

  handleUploadFileButtonClick(event) {
    const fileInput = document.getElementById('uploadFile');
    fileInput.click();
  }

  handleUploadFileChange(event) {
    // Current, One file; Todo, more files.
    const file = event.target.files[0];
    console.log(file);
    let newItem = {
      id: uniqid(),
      parentId: this.props.bodyContent.currentDirId,
      title: file.name,
      size: Helper.getFileSize(file.size),
      updatedAt: Helper.dateFormat(new Date()),
      type: 'file',
      isEdit: false,
      files: file,
    }
    console.log(newItem);

    let params = new FormData();
    for (let prop in newItem) {
      params.append(prop, newItem[prop]);
    }

    //Todo, upLoadFile; Just add a item in the database.
    const fetchLink = Helper.fetchLinkHeader + 'addItem';
    fetch(fetchLink, {
      method: 'POST',
      body: params,
      credentials: 'include'
    }).then((response) => response.json())
      .then((json) => {
        if (json.success === '1' || json.success === 1) {
          this.props.onFetchData();
          Helper.notifyBox('上传文件成功', 'success');
        } else {
          Helper.notifyBox('上传失败, 请重试', 'danger');
        }
      }).catch((ex) => {
        console.log(ex);
        Helper.notifyBox('上传失败, 请重试', 'danger');
      })
  }

  handleDownloadButtonClick(event) {
    const listCheckedIds = this.props.bodyContent.listCheckedIds;
    const activeLists = this.props.bodyContent.activeLists;
    let listCheckedIdsArray = [];
    listCheckedIds.forEach((_id) => {
      for (let obj of activeLists) {
        if (obj._id === _id) {
          let res = {_id: obj._id, filePath: obj.filePath};
          listCheckedIdsArray.push(res);
        }
      }
    });

    if (listCheckedIdsArray.length === 1) {
      if (listCheckedIdsArray[0].filePath) {
        window.location = Helper.fetchLinkHeader + 'download/' + listCheckedIdsArray[0].filePath;
      } else {
        Helper.notifyBox('抱歉, 请选择可下载的文件(目前不支持文件夹下载)', 'danger');
      }
    } else if (listCheckedIdsArray.length > 1){
      Helper.notifyBox('抱歉, 目前仅支持单个文件下载, 请选择一个可下载文件', 'danger');
    }

    // const fetchLink = Helper.fetchLinkHeader + 'download';
    // const params = {
    //   ids: listCheckedIdsArray,
    // }
    // fetch(fetchLink, {
    //   method: 'POST',
    //   headers: {
    //     'Content-Type': 'application/json',
    //   },
    //   body: JSON.stringify(params),
    //   credentials: 'include'
    // }).then((response) => {
    //   console.log(response);
    // }).catch((ex) => {
    //   console.log(ex);
    // })
  }

  isShowButtonGroup() {
    const currentDir = this.props.bodyContent.currentDir;
    if (currentDir.substr(0, 4) === '全部文件' || currentDir.substr(0, 5) === '/全部文件') {
      return true;
    }

    return false;
  }

  isTrashContent() {
    return this.props.menuAside.buttonActiveIndex === 5;
  }

  render() {
    const removeIconStyle = {
      position: 'absolute',
      left: '172px',
      top: '10.5px',
      cursor: 'pointer',
    }

    return (

          {!this.isTrashContent() &&
              <button name="upload" type="button" className="btn btn-primary-outline" onClick={(e) => this.handleUploadFileButtonClick(e)}>
               上传文件
              <input type="file" id="uploadFile" name="uploadfile" style={{display: 'none'}}
                onChange={(e) => this.handleUploadFileChange(e)}/>
            </button>
          }
          {this.isShowButtonGroup() &&
            <button name="newDirectory" type="button" className="btn btn-primary-outline" onClick={this.props.onToolBarButtonClick}>
               新建文件夹</button>
          }
          {!this.isTrashContent() &&
            <button name="download" type="button" className="btn btn-primary-outline" onClick={(e) => this.handleDownloadButtonClick(e)}>
               下载</button>
          }
          {this.props.isItemsChecked &&
            <ToolBarButtonGroup
             bodyContent={this.props.bodyContent}
             menuAside={this.props.menuAside}
             onUpdateListItemContent={this.props.onUpdateListItemContent}
             onUpdateActiveLists={this.props.onUpdateActiveLists}
             onFetchData={this.props.onFetchData}/>}

          <input name="searchInfo"
            type="text"
            placeholder="输入文件名"
            value={this.state.searchInfo}
            onFocus={(e) => this.handleInputFocus(e)}
            onBlur={(e) => this.handleInputBlur(e)}
            onChange={(e) => this.handleSearchInfoChange(e)}></input>
          {this.state.searchInfo !== '' &&
            this.handleRemoveIconClick(e)}>
             }
          <button name="searchButton" type="button" className="btn btn-success-outline"
            onClick={(e) => this.handleSearchButtonClick(e)}>
             搜索</button>

    );
  }
}

export default BodyToolBar;
<commit_msg>add file type.<commit_after>import React, { Component } from 'react';
import ToolBarButtonGroup from './ToolBarButtonGroup.js';
import Helper from '../helper.js';
import uniqid from 'uniqid';

class BodyToolBar extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchInfo: '',
    };
  }

  handleInputFocus(event) {
    event.target.placeholder = '';
  }

  handleInputBlur(event) {
    if (event.target.name === 'searchInfo') {
      event.target.placeholder = '输入文件名';
    }
  }

  handleSearchInfoChange(event) {
    const value = event.target.value;
    if (event.target.name === 'searchInfo') {
      this.setState({
        searchInfo: value,
      });
    }
  }

  handleRemoveIconClick(event) {
    this.setState({
      searchInfo: '',
    }, this.props.onClearSearchInfo);
  }

  handleSearchButtonClick(event) {
    this.props.onToolBarSearchInfoChange(this.state.searchInfo);
  }

  handleUploadFileButtonClick(event) {
    const fileInput = document.getElementById('uploadFile');
    fileInput.click();
  }

  handleUploadFileChange(event) {
    // Current, One file; Todo, more files.
    const file = event.target.files[0];
    console.log(file);
    const fileType = Helper.getFileType(file.name);
    let newItem = {
      id: uniqid(),
      parentId: this.props.bodyContent.currentDirId,
      title: file.name,
      size: Helper.getFileSize(file.size),
      updatedAt: Helper.dateFormat(new Date()),
      type: fileType,
      isEdit: false,
      files: file,
    }
    console.log(newItem);

    let params = new FormData();
    for (let prop in newItem) {
      params.append(prop, newItem[prop]);
    }

    //Todo, upLoadFile; Just add a item in the database.
    const fetchLink = Helper.fetchLinkHeader + 'addItem';
    fetch(fetchLink, {
      method: 'POST',
      body: params,
      credentials: 'include'
    }).then((response) => response.json())
      .then((json) => {
        if (json.success === '1' || json.success === 1) {
          this.props.onFetchData();
          Helper.notifyBox('上传文件成功', 'success');
        } else {
          Helper.notifyBox('上传失败, 请重试', 'danger');
        }
      }).catch((ex) => {
        console.log(ex);
        Helper.notifyBox('上传失败, 请重试', 'danger');
      })
  }

  handleDownloadButtonClick(event) {
    const listCheckedIds = this.props.bodyContent.listCheckedIds;
    const activeLists = this.props.bodyContent.activeLists;
    let listCheckedIdsArray = [];
    listCheckedIds.forEach((_id) => {
      for (let obj of activeLists) {
        if (obj._id === _id) {
          let res = {_id: obj._id, filePath: obj.filePath};
          listCheckedIdsArray.push(res);
        }
      }
    });

    if (listCheckedIdsArray.length === 1) {
      if (listCheckedIdsArray[0].filePath) {
        window.location = Helper.fetchLinkHeader + 'download/' + listCheckedIdsArray[0].filePath;
      } else {
        Helper.notifyBox('抱歉, 请选择可下载的文件(目前不支持文件夹下载)', 'danger');
      }
    } else if (listCheckedIdsArray.length > 1){
      Helper.notifyBox('抱歉, 目前仅支持单个文件下载, 请选择一个可下载文件', 'danger');
    }

    // const fetchLink = Helper.fetchLinkHeader + 'download';
    // const params = {
    //   ids: listCheckedIdsArray,
    // }
    // fetch(fetchLink, {
    //   method: 'POST',
    //   headers: {
    //     'Content-Type': 'application/json',
    //   },
    //   body: JSON.stringify(params),
    //   credentials: 'include'
    // }).then((response) => {
    //   console.log(response);
    // }).catch((ex) => {
    //   console.log(ex);
    // })
  }

  isShowButtonGroup() {
    const currentDir = this.props.bodyContent.currentDir;
    if (currentDir.substr(0, 4) === '全部文件' || currentDir.substr(0, 5) === '/全部文件') {
      return true;
    }

    return false;
  }

  isTrashContent() {
    return this.props.menuAside.buttonActiveIndex === 5;
  }

  render() {
    const removeIconStyle = {
      position: 'absolute',
      left: '172px',
      top: '10.5px',
      cursor: 'pointer',
    }

    return (

          {!this.isTrashContent() &&
              <button name="upload" type="button" className="btn btn-primary-outline" onClick={(e) => this.handleUploadFileButtonClick(e)}>
               上传文件
              <input type="file" id="uploadFile" name="uploadfile" style={{display: 'none'}}
                onChange={(e) => this.handleUploadFileChange(e)}/>
            </button>
          }
          {this.isShowButtonGroup() &&
            <button name="newDirectory" type="button" className="btn btn-primary-outline" onClick={this.props.onToolBarButtonClick}>
               新建文件夹</button>
          }
          {!this.isTrashContent() &&
            <button name="download" type="button" className="btn btn-primary-outline" onClick={(e) => this.handleDownloadButtonClick(e)}>
               下载</button>
          }
          {this.props.isItemsChecked &&
            <ToolBarButtonGroup
             bodyContent={this.props.bodyContent}
             menuAside={this.props.menuAside}
             onUpdateListItemContent={this.props.onUpdateListItemContent}
             onUpdateActiveLists={this.props.onUpdateActiveLists}
             onFetchData={this.props.onFetchData}/>}

          <input name="searchInfo"
            type="text"
            placeholder="输入文件名"
            value={this.state.searchInfo}
            onFocus={(e) => this.handleInputFocus(e)}
            onBlur={(e) => this.handleInputBlur(e)}
            onChange={(e) => this.handleSearchInfoChange(e)}></input>
          {this.state.searchInfo !== '' &&
            this.handleRemoveIconClick(e)}>
             }
          <button name="searchButton" type="button" className="btn btn-success-outline"
            onClick={(e) => this.handleSearchButtonClick(e)}>
             搜索</button>

    );
  }
}

export default BodyToolBar;
<|endoftext|>


<commit_before>
import styled from 'styled-components'

const Column = styled.div`
  flex: 1 1 auto;
  padding: 0 0.5em;
  max-width: ${({cols}) => cols / 12 * 100}%;
`

export default Column
<commit_msg>removed gutters on first and last grid column<commit_after>
import styled from 'styled-components'

const Column = styled.div`
  flex: 1 1 auto;
  padding: 0 0.5em;
  max-width: ${({cols}) => cols / 12 * 100}%;
  &:first-child {
    padding-left: 0;
  }
  &:last-child {
    padding-right: 0;
  }
`

export default Column
<|endoftext|>


<commit_before>import CSSModules from 'react-css-modules';
import React from 'react';

import styles from './input.css';
import Header from '../Header';

type Props = {
  /** default text to display inside the input */
  children?: string,
  /** html element, div,span,button */
  component?: string,
  /** function to capture the state change outside the component */
  onChange?: Function,
  /** error message to show to the user */
  errorMessage?: string,
  /** make the input required */
  required?: boolean,
  /** change state of input when true */
  error?: boolean,
  /** disable the input */
  disabled?: boolean,
  css: Object,
  /** add any other props to the component */
  other?: Object,
  /** placeholder text */
  placeholder?: string,
  /** reference funciton */
  handleRef?: Function,
  ref?: Function,
  /** used to link the label element with the input */
  id: string
}

class Input extends React.Component<void, Props, void> {

  constructor(props: Props) {
    super(props);
  }

  render() {
    const { component: Component, onChange, id, handleRef, disabled, required, error, errorMessage, placeholder, children, ref, css, ...other } = this.props;
    const styleName: string = error ? 'error' : 'input';

    return (

        <Component
          id={id}
          ref={(el) => {
            handleRef(el);
          }}
          onChange={onChange}
          disabled={disabled}
          styleName={styleName}
          aria-disabled={disabled}
          aria-required={required}
          aria-invalid={error}
          placeholder={placeholder}
          defaultValue={children}
          {...other} />
        {error && errorMessage && {errorMessage} }

    );
  }
}

Input.defaultProps = {
  component: 'input',
  disabled: false,
  required: false,
  error: false,
  onChange: function noop() {},
  handleRef: function noop() {}
};

export default CSSModules(Input, styles, { allowMultiple: true });
<commit_msg>input accessiblity change<commit_after>import CSSModules from 'react-css-modules';
import React from 'react';

import styles from './input.css';
import Header from '../Header';

type Props = {
  /** default text to display inside the input */
  children?: string,
  /** html element, div,span,button */
  component?: string,
  /** function to capture the state change outside the component */
  onChange?: Function,
  /** error message to show to the user */
  errorMessage?: string,
  /** make the input required */
  required?: boolean,
  /** change state of input when true */
  error?: boolean,
  /** disable the input */
  disabled?: boolean,
  css: Object,
  /** add any other props to the component */
  other?: Object,
  /** placeholder text */
  placeholder?: string,
  /** reference funciton */
  handleRef?: Function,
  ref?: Function,
  /** used to link the label element with the input */
  id: string,
  /** used for the label element */
  label: string
}

class Input extends React.Component<void, Props, void> {

  constructor(props: Props) {
    super(props);
  }

  render() {
    const { component: Component, onChange, id, label, handleRef, disabled, required, error, errorMessage, placeholder, children, ref, css, ...other } = this.props;
    const styleName: string = error ? 'error' : 'input';

    return (

        {label}
        <Component
          id={id}
          ref={(el) => {
            handleRef(el);
          }}
          onChange={onChange}
          disabled={disabled}
          styleName={styleName}
          aria-disabled={disabled}
          aria-required={required}
          aria-invalid={error}
          placeholder={placeholder}
          defaultValue={children}
          {...other} />
        {error && errorMessage && {errorMessage} }

    );
  }
}

Input.defaultProps = {
  component: 'input',
  disabled: false,
  required: false,
  error: false,
  onChange: function noop() {},
  handleRef: function noop() {}
};

export default CSSModules(Input, styles, { allowMultiple: true });
<|endoftext|>


<commit_before>function save_options() {
  var emailIssuesList = document.getElementById('emailIssuesList').checked;
  var emailIssue = document.getElementById('emailIssue').checked;
  var emailPullRequestList = document.getElementById('emailPullRequestList').checked;
  var emailPullRequest = document.getElementById('emailPullRequest').checked;

  var jenkinsOpenDetailsLinksInNewTab = document.getElementById('jenkinsOpenDetailsLinksInNewTab').checked;
  var jenkinsShowRunTime = document.getElementById('jenkinsShowRunTime').checked;
  var jenkinsShowFailureIndications = document.getElementById('jenkinsShowFailureIndications').checked;
  var jenkinsShowTestFailures = document.getElementById('jenkinsShowTestFailures').checked;
  var jenkinsShowBugFilingButton = document.getElementById('jenkinsShowBugFilingButton').checked;

  chrome.storage.sync.set({
    emailIssuesList: emailIssuesList,
    emailIssue: emailIssue,
    emailPullRequestList: emailPullRequestList,
    emailPullRequest: emailPullRequest,
    jenkinsOpenDetailsLinksInNewTab: jenkinsOpenDetailsLinksInNewTab,
    jenkinsShowRunTime: jenkinsShowRunTime,
    jenkinsShowFailureIndications: jenkinsShowFailureIndications,
    jenkinsShowTestFailures: jenkinsShowTestFailures,
    jenkinsShowBugFilingButton: jenkinsShowBugFilingButton
  }, function() {
    // Update status to let user know options were saved.
    var status = document.getElementById('status');
    status.textContent = 'Options saved.';
    setTimeout(function() {
      status.textContent = '';
    }, 750);
  });
}

function restore_options() {
  chrome.storage.sync.get({
    emailIssuesList: true,
    emailIssue: true,
    emailPullRequestList: true,
    emailPullRequest: true,
    jenkinsOpenDetailsLinksInNewTab: true,
    jenkinsShowRunTime: true,
    jenkinsShowFailureIndications: true,
    jenkinsShowTestFailures: true,
    jenkinsShowBugFilingButton: true
  }, function(items) {
    document.getElementById('emailIssuesList').checked = items.emailIssuesList;
    document.getElementById('emailIssue').checked = items.emailIssue;
    document.getElementById('emailPullRequestList').checked = items.emailPullRequestList;
    document.getElementById('emailPullRequest').checked = items.emailPullRequest;
    document.getElementById('jenkinsOpenDetailsLinksInNewTab').checked = items.jenkinsOpenDetailsLinksInNewTab;
    document.getElementById('jenkinsShowRunTime').checked = items.jenkinsShowRunTime;
    document.getElementById('jenkinsShowFailureIndications').checked = items.jenkinsShowFailureIndications;
    document.getElementById('jenkinsShowTestFailures').checked = items.jenkinsShowTestFailures;
    document.getElementById('jenkinsShowBugFilingButton').checked = items.jenkinsShowBugFilingButton;
  });
}
document.addEventListener('DOMContentLoaded', restore_options);
document.getElementById('save').addEventListener('click',
    save_options);<commit_msg>Format options.js<commit_after>function save_options() {
    var emailIssuesList = document.getElementById('emailIssuesList').checked;
    var emailIssue = document.getElementById('emailIssue').checked;
    var emailPullRequestList = document.getElementById('emailPullRequestList').checked;
    var emailPullRequest = document.getElementById('emailPullRequest').checked;

    var jenkinsOpenDetailsLinksInNewTab = document.getElementById('jenkinsOpenDetailsLinksInNewTab').checked;
    var jenkinsShowRunTime = document.getElementById('jenkinsShowRunTime').checked;
    var jenkinsShowFailureIndications = document.getElementById('jenkinsShowFailureIndications').checked;
    var jenkinsShowTestFailures = document.getElementById('jenkinsShowTestFailures').checked;
    var jenkinsShowBugFilingButton = document.getElementById('jenkinsShowBugFilingButton').checked;

    chrome.storage.sync.set({
        emailIssuesList: emailIssuesList,
        emailIssue: emailIssue,
        emailPullRequestList: emailPullRequestList,
        emailPullRequest: emailPullRequest,
        jenkinsOpenDetailsLinksInNewTab: jenkinsOpenDetailsLinksInNewTab,
        jenkinsShowRunTime: jenkinsShowRunTime,
        jenkinsShowFailureIndications: jenkinsShowFailureIndications,
        jenkinsShowTestFailures: jenkinsShowTestFailures,
        jenkinsShowBugFilingButton: jenkinsShowBugFilingButton
    }, function () {
        // Update status to let user know options were saved.
        var status = document.getElementById('status');
        status.textContent = 'Options saved.';
        setTimeout(function () {
            status.textContent = '';
        }, 750);
    });
}

function restore_options() {
    chrome.storage.sync.get({
        emailIssuesList: true,
        emailIssue: true,
        emailPullRequestList: true,
        emailPullRequest: true,
        jenkinsOpenDetailsLinksInNewTab: true,
        jenkinsShowRunTime: true,
        jenkinsShowFailureIndications: true,
        jenkinsShowTestFailures: true,
        jenkinsShowBugFilingButton: true
    }, function (items) {
        document.getElementById('emailIssuesList').checked = items.emailIssuesList;
        document.getElementById('emailIssue').checked = items.emailIssue;
        document.getElementById('emailPullRequestList').checked = items.emailPullRequestList;
        document.getElementById('emailPullRequest').checked = items.emailPullRequest;
        document.getElementById('jenkinsOpenDetailsLinksInNewTab').checked = items.jenkinsOpenDetailsLinksInNewTab;
        document.getElementById('jenkinsShowRunTime').checked = items.jenkinsShowRunTime;
        document.getElementById('jenkinsShowFailureIndications').checked = items.jenkinsShowFailureIndications;
        document.getElementById('jenkinsShowTestFailures').checked = items.jenkinsShowTestFailures;
        document.getElementById('jenkinsShowBugFilingButton').checked = items.jenkinsShowBugFilingButton;
    });
}
document.addEventListener('DOMContentLoaded', restore_options);
document.getElementById('save').addEventListener('click',
    save_options);<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { connect } from 'react-redux'
import { updateMatchReq, selectMatch } from '../actions/matches-actions'
import base from '../base'

class MatchDetail extends Component {
  constructor(props) {
    super(props)

    this.ticketAvailable = this.ticketAvailable.bind(this)
  }

  componentWillMount() {
    this.props.selectMatch(this.props.params.matchId)
  }

  ticketAvailable(match) {
    if (match.claimedUser || !match.available) return false
    return true
  }

  render() {
    const { match } = this.props
    return (

{ match ? match.homeTeam.name : '' }

        <button onClick={(e) => this.props.claimTicket(this.props.params.matchId)}>Claim Ticket</button>

    )
  }
}

const mapStateToProps = (state) => {
  return {
    match: state.matches.data[state.matches.selectedMatch],
    user: state.user
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    claimTicket: (matchId, userId='xxx') => {
      dispatch(updateMatchReq(matchId, {
        claimedUserId: userId,
        available: false
      }))
    },
    selectMatch: (matchId) => {
      dispatch(selectMatch(matchId))
    }
  }
}

const MatchDetailContainer = connect(mapStateToProps, mapDispatchToProps)(MatchDetail)
export default MatchDetailContainer
<commit_msg>nullify selected match field when unmounting<commit_after>import React, { Component } from 'react'
import { connect } from 'react-redux'
import { updateMatchReq, selectMatch } from '../actions/matches-actions'
import base from '../base'

class MatchDetail extends Component {
  constructor(props) {
    super(props)

    this.ticketAvailable = this.ticketAvailable.bind(this)
  }

  componentWillMount() {
    this.props.selectMatch(this.props.params.matchId)
  }

  componentWillUnmount() {
    this.props.selectMatch(null)
  }

  ticketAvailable(match) {
    if (match.claimedUser || !match.available) return false
    return true
  }

  render() {
    const { match } = this.props
    return (

{ match ? match.homeTeam.name : '' }

        <button onClick={(e) => this.props.claimTicket(this.props.params.matchId)}>Claim Ticket</button>

    )
  }
}

const mapStateToProps = (state) => {
  return {
    match: state.matches.data[state.matches.selectedMatch],
    user: state.user
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    claimTicket: (matchId, userId='xxx') => {
      dispatch(updateMatchReq(matchId, {
        claimedUserId: userId,
        available: false
      }))
    },
    selectMatch: (matchId) => {
      dispatch(selectMatch(matchId))
    }
  }
}

const MatchDetailContainer = connect(mapStateToProps, mapDispatchToProps)(MatchDetail)
export default MatchDetailContainer
<|endoftext|>


<commit_before>import child_process from 'child_process';

export default class ADB {

  constructor() {
    this.device = [];
    this.selected_device;
  }

  devices() {

    let child = child_process.spawnSync("adb", ["devices"]);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
    }

    let output = child.stdout.toString();
    let match_devices = output.match(/[\w\d]+\s+device\n/ig);

    if(!match_devices.length) return this.device;

    match_devices = match_devices[0].split(/\n/);
    for(let i in match_devices) {
      if(match_devices[i] == "") continue;
      if(!/device/ig.test(match_devices[i])) continue;
      let did = match_devices[i].replace(/\tdevice/ig, "");
      if(this.device.indexOf(did) != -1) continue;
      this.device.push(did);
    }

    this.selected_device = this.device[0];
    return this.device;
  }

  selectDevice(device) {
    this.selected_device = device;
  }

  isPackageInstalled(_package_) {

    let params = ["shell" ,"pm", "list", "packages", "|", "grep", _package_];
    if(this.selected_device) {
      params.unshift(this.selected_device);
      params.unshift("-s");
    }

    let child = child_process.spawnSync("adb", params);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
    }

    let output = child.stdout.toString();
        output = output.replace(/[\n\t\s\r]*/ig, "");

    return output == "package:"+_package_ ? true : false;
  }

  listPackages() {

    let params = ["shell" ,"pm", "list", "packages"];
    if(this.selected_device) {
      params.unshift(this.selected_device);
      params.unshift("-s");
    }

    let child = child_process.spawnSync("adb", params);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
    }

    let output = child.stdout.toString();
    let list = output.split(/\n/);

    let packages = [];
    if(!list.length) return packages;
    for(let i in list) {

      if(list[i] == "") continue;

      let pkg = list[i];
          pkg = pkg.replace("package:","");
          pkg = pkg.replace(/\r/,"");

      packages.push(pkg);
    }

    return packages;
  }

};
<commit_msg>add 2 new methods: closeApp, isAppRunning<commit_after>import child_process from 'child_process';

export default class ADB {

  constructor() {
    this.device = [];
    this.selected_device;
  }

  devices() {

    let child = child_process.spawnSync("adb", ["devices"]);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
    }

    let output = child.stdout.toString();
    let match_devices = output.match(/[\w\d]+\s+device\n/ig);

    if(!match_devices.length) return this.device;

    match_devices = match_devices[0].split(/\n/);
    for(let i in match_devices) {
      if(match_devices[i] == "") continue;
      if(!/device/ig.test(match_devices[i])) continue;
      let did = match_devices[i].replace(/\tdevice/ig, "");
      if(this.device.indexOf(did) != -1) continue;
      this.device.push(did);
    }

    this.selected_device = this.device[0];
    return this.device;
  }

  selectDevice(device) {
    this.selected_device = device;
  }

  isPackageInstalled(_package_) {

    let params = ["shell" ,"pm", "list", "packages", "|", "grep", _package_];
    if(this.selected_device) {
      params.unshift(this.selected_device);
      params.unshift("-s");
    }

    let child = child_process.spawnSync("adb", params);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
    }

    let output = child.stdout.toString();
        output = output.replace(/[\n\t\s\r]*/ig, "");

    return output == "package:"+_package_ ? true : false;
  }

  isAppRunning(_package_) {

    let params = ["shell" ,"ps", "|", "grep", _package_];
    if(this.selected_device) {
      params.unshift(this.selected_device);
      params.unshift("-s");
    }

    let child = child_process.spawnSync("adb", params);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
    }

    let output = child.stdout.toString();
    return output.indexOf(_package_) != -1 ? true : false;

  }

  closeApp(_package_) {

    let params = ["shell" ,"am", "force-stop", _package_];
    if(this.selected_device) {
      params.unshift(this.selected_device);
      params.unshift("-s");
    }

    let child = child_process.spawnSync("adb", params);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
    }
  }

  listPackages() {

    let params = ["shell" ,"pm", "list", "packages"];
    if(this.selected_device) {
      params.unshift(this.selected_device);
      params.unshift("-s");
    }

    let child = child_process.spawnSync("adb", params);
    if(child.stderr && child.stderr.toString() !="") {
      throw new Error(" "+child.stderr);
    }

    let output = child.stdout.toString();
    let list = output.split(/\n/);

    let packages = [];
    if(!list.length) return packages;
    for(let i in list) {

      if(list[i] == "") continue;

      let pkg = list[i];
          pkg = pkg.replace("package:","");
          pkg = pkg.replace(/\r/,"");

      packages.push(pkg);
    }

    return packages;
  }

};
<|endoftext|>


<commit_before>var d = require ('dequeue');
var seatStateStore = require("./SeatStateStore");
var redis = require("redis");
var rClient = redis.createClient();
var dgram = require("dgram");

var FIFO = new d();

fetcher();

var udpserver = dgram.createSocket("udp4");

udpserver.on("message",
    function (msg, rinfo) {
        console.log("MSG", msg);
        FIFO.push(msg);
    }
);

udpserver.bind(4444);

function fetcher () {
    while (FIFO.length > 0) {

        var msg = FIFO.shift();
        console.log("Goi tin: ", msg);
        //rClient.hset("raw", "data"+index, msg);
        seatStateStore.parseMessage(msg);
        process.nextTick(fetcher);
    }
}

///<commit_msg>Update UDPefef<commit_after>var d = require ('dequeue');
var seatStateStore = require("./SeatStateStore");
var redis = require("redis");
var rClient = redis.createClient();
var dgram = require("dgram");

var FIFO = new d();

fetcher();

var udpserver = dgram.createSocket("udp4");

udpserver.on("message",
    function (msg, rinfo) {
        console.log("sida", FIFO);
        console.log("MSG", msg);
        FIFO.push(msg);
    }
);

udpserver.bind(4444);

function fetcher () {
    while (FIFO.length > 0) {

        var msg = FIFO.shift();
        console.log("Goi tin: ", msg);
        //rClient.hset("raw", "data"+index, msg);
        seatStateStore.parseMessage(msg);
        process.nextTick(fetcher);
    }
}

///<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2018 The FOAM Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
  Accessible through browser at location path static/foam2/src/foam/nanos/controller/index.html
  Available on browser console as ctrl. (exports axiom)
*/
foam.CLASS({
  package: 'foam.nanos.controller',
  name: 'ApplicationController',
  extends: 'foam.u2.Element',

  documentation: 'FOAM Application Controller.',

  implements: [
    'foam.box.Context',
    'foam.nanos.controller.AppStyles'
  ],

  requires: [
    'foam.nanos.client.ClientBuilder',
    'foam.nanos.auth.Group',
    'foam.nanos.auth.ResendVerificationEmail',
    'foam.nanos.auth.SignInView',
    'foam.nanos.auth.User',
    'foam.nanos.auth.resetPassword.ResetView',
    'foam.nanos.u2.navigation.TopNavigation',
    'foam.u2.stack.Stack',
    'foam.u2.stack.StackView'
  ],

  imports: [
    'getElementById',
    'installCSS',
    'sessionSuccess',
    'window'
  ],

  exports: [
    'as ctrl',
    'group',
    'loginSuccess',
    'logo',
    'requestLogin',
    'signUpEnabled',
    'stack',
    'currentMenu',
    'lastMenuLaunched',
    'menuListener',
    'lastMenuLaunchedListener',
    'user',
    'webApp',
    'wrapCSS as installCSS'
  ],

  constants: {
    MACROS: [ 'primaryColor', 'secondaryColor', 'tableColor', 'tableHoverColor', 'accentColor' ]
  },

  css: `
    body {
      font-family: 'Roboto', sans-serif;
      font-size: 14px;
      letter-spacing: 0.2px;
      color: #373a3c;
      background: #edf0f5;
      margin: 0;
    }

    .stack-wrapper {
      margin-bottom: -10px;
      min-height: calc(80% - 60px);
    }

    .stack-wrapper:after {
      content: "";
      display: block;
    }
  `,

  properties: [
    {
      name: 'clientPromise',
      factory: function() {
        var self = this;
        return self.ClientBuilder.create().promise.then(function(cls) {
          return cls.create(null, self);
        });
      },
    },
    {
      name: 'stack',
      factory: function() { return this.Stack.create(null, this.__subSubContext__); }
    },
    {
      class: 'foam.core.FObjectProperty',
      of: 'foam.nanos.auth.User',
      name: 'user',
      factory: function() { return this.User.create(null, this.__subSubContext__); }
    },
    {
      class: 'foam.core.FObjectProperty',
      of: 'foam.nanos.auth.Group',
      name: 'group',
      factory: function() { return this.Group.create(null, this.__subSubContext__); }
    },
    {
      class: 'Boolean',
      name: 'signUpEnabled',
      adapt: function(_, v) {
        return foam.String.isInstance(v) ? v !== 'false' : v;
      }
    },
    {
      class: 'Boolean',
      name: 'loginSuccess'
    },
    { class: 'URL', name: 'logo' },
    'currentMenu',
    'lastMenuLaunched',
    'webApp',
    'primaryColor',
    'secondaryColor',
    'tableColor',
    'tableHoverColor',
    'accentColor'
  ],

  methods: [
    function init() {
      this.SUPER();

      var self = this;
      self.clientPromise.then(function(client) {
        self.__subSubContext__ = client.__subContext__;
        self.getCurrentUser();

        window.onpopstate = function(event) {
          if ( location.hash != null ) {
            var hid = location.hash.substr(1);

            hid && self.__subSubContext__.menuDAO.find(hid).then(function(menu) {
              menu && menu.launch(this, null);
            });
          }
        };

        window.onpopstate();
      });
    },

    function initE() {
      var self = this;
      self.clientPromise.then(function() {
        self
          .addClass(self.myClass())
          .tag({class: 'foam.nanos.u2.navigation.TopNavigation'})
          .start('div').addClass('stack-wrapper')
            .tag({class: 'foam.u2.stack.StackView', data: self.stack, showActions: false})
          .end();
      });
    },

    function setDefaultMenu() {
      // Don't select default if menu already set
      if ( this.window.location.hash || ! this.user.group ) return;

      this.__subSubContext__.groupDAO.find(this.user.group).then(function (group) {
        this.group.copyFrom(group);

        for ( var i = 0 ; i < this.MACROS.length ; i++ ) {
          var m = this.MACROS[i];
          if ( group[m] ) this[m] = group[m];
        }

        // Don't select default if menu already set
        if ( group && ! this.window.location.hash ) {
          this.window.location.hash = group.defaultMenu;
        }
      }.bind(this));
    },

    function getCurrentUser() {
      var self = this;

      // get current user, else show login
      this.__subSubContext__.auth.getCurrentUser(null).then(function (result) {
        self.loginSuccess = !! result;
        if ( result ) {
          self.user.copyFrom(result);
          if ( ! self.user.emailVerified ) {
            self.stack.push({ class: 'foam.nanos.auth.ResendVerificationEmail' });
            return;
          }
          self.onUserUpdate();
        }
      })
      .catch(function (err) {
        self.requestLogin().then(function() {
          self.getCurrentUser();
        });
      });
    },

    function expandShortFormMacro(css, m) {
      /* A short-form macros is of the form %PRIMARY_COLOR%. */
      var M = m.toUpperCase();

      return css.replace(
        new RegExp("%" + M + "%", 'g'),
        '/*%' + M + '%*/ ' + this[m]);
    },

    function expandLongFormMacro(css, m) {
      // A long-form macros is of the form "/*%PRIMARY_COLOR%*/ blue".
      var M = m.toUpperCase();

      return css.replace(
        new RegExp('/\\*%' + M + '%\\*/[^;]*', 'g'),
        '/*%' + M + '%*/ ' + this[m]);
    },

    // CSS preprocessor, works on classes instantiated in subContext
    function wrapCSS(text, id) {
      if ( text ) {
        if ( ! this.accentColor ) {
          var self = this;

          this.accentColor$.sub(function(s) {
            self.wrapCSS(text, id);
            s.detach();
          });
        }

        let eid = foam.u2.Element.NEXT_ID();

        for ( var i = 0 ; i < this.MACROS.length ; i++ ) {
          let m     = this.MACROS[i];
          var text2 = this.expandShortFormMacro(this.expandLongFormMacro(text, m), m);

            // If the macro was found, then listen for changes to the property
            // and update the CSS if it changes.
            if ( text != text2 ) {
              text = text2;
              this.slot(m).sub(function() {
                var el = this.getElementById(eid);
                el.innerText = this.expandLongFormMacro(el.innerText, m);
              }.bind(this));
            }
        }

        this.installCSS(text, id, eid);
      }
    },

    function requestLogin() {
      var self = this;

      // don't go to log in screen if going to reset password screen
      if ( location.hash != null && location.hash === '#reset')
        return new Promise(function (resolve, reject) {
          self.stack.push({ class: 'foam.nanos.auth.resetPassword.ResetView' });
          self.loginSuccess$.sub(resolve);
        });

      return new Promise(function(resolve, reject) {
        self.stack.push({ class: 'foam.nanos.auth.SignInView' });
        self.loginSuccess$.sub(resolve);
      });
    }
  ],

  listeners: [
    function onUserUpdate() {
      this.setDefaultMenu();
    },

    // This listener should be triggered when a Menu item has been launched AND
    // navigates to a new screen.
    function menuListener(m) {
      this.currentMenu = m;
    },

    // This listener should be triggered when a Menu has been launched but does
    // not navigate to a new screen. Typically for SubMenus
    function lastMenuLaunchedListener(m) {
      this.lastMenuLaunched = m;
    }
  ]
});
<commit_msg>Switch the __subContext__ of ApplicationController when the client is finished being created.<commit_after>/**
 * @license
 * Copyright 2018 The FOAM Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
  Accessible through browser at location path static/foam2/src/foam/nanos/controller/index.html
  Available on browser console as ctrl. (exports axiom)
*/
foam.CLASS({
  package: 'foam.nanos.controller',
  name: 'ApplicationController',
  extends: 'foam.u2.Element',

  documentation: 'FOAM Application Controller.',

  implements: [
    'foam.box.Context',
    'foam.nanos.controller.AppStyles'
  ],

  requires: [
    'foam.nanos.client.ClientBuilder',
    'foam.nanos.auth.Group',
    'foam.nanos.auth.ResendVerificationEmail',
    'foam.nanos.auth.SignInView',
    'foam.nanos.auth.User',
    'foam.nanos.auth.resetPassword.ResetView',
    'foam.nanos.u2.navigation.TopNavigation',
    'foam.u2.stack.Stack',
    'foam.u2.stack.StackView'
  ],

  imports: [
    'getElementById',
    'installCSS',
    'sessionSuccess',
    'window'
  ],

  exports: [
    'as ctrl',
    'group',
    'loginSuccess',
    'logo',
    'requestLogin',
    'signUpEnabled',
    'stack',
    'currentMenu',
    'lastMenuLaunched',
    'menuListener',
    'lastMenuLaunchedListener',
    'user',
    'webApp',
    'wrapCSS as installCSS'
  ],

  constants: {
    MACROS: [ 'primaryColor', 'secondaryColor', 'tableColor', 'tableHoverColor', 'accentColor' ]
  },

  css: `
    body {
      font-family: 'Roboto', sans-serif;
      font-size: 14px;
      letter-spacing: 0.2px;
      color: #373a3c;
      background: #edf0f5;
      margin: 0;
    }

    .stack-wrapper {
      margin-bottom: -10px;
      min-height: calc(80% - 60px);
    }

    .stack-wrapper:after {
      content: "";
      display: block;
    }
  `,

  properties: [
    {
      name: 'clientPromise',
      factory: function() {
        var self = this;
        return self.ClientBuilder.create().promise.then(function(cls) {
          self.client = cls.create(null, self);
          return self.client;
        });
      },
    },
    {
      name: 'client',
    },
    {
      name: 'stack',
      factory: function() { return this.Stack.create(); }
    },
    {
      class: 'foam.core.FObjectProperty',
      of: 'foam.nanos.auth.User',
      name: 'user',
      factory: function() { return this.User.create(); }
    },
    {
      class: 'foam.core.FObjectProperty',
      of: 'foam.nanos.auth.Group',
      name: 'group',
      factory: function() { return this.Group.create(); }
    },
    {
      class: 'Boolean',
      name: 'signUpEnabled',
      adapt: function(_, v) {
        return foam.String.isInstance(v) ? v !== 'false' : v;
      }
    },
    {
      class: 'Boolean',
      name: 'loginSuccess'
    },
    { class: 'URL', name: 'logo' },
    'currentMenu',
    'lastMenuLaunched',
    'webApp',
    'primaryColor',
    'secondaryColor',
    'tableColor',
    'tableHoverColor',
    'accentColor'
  ],

  methods: [
    function init() {
      this.SUPER();

      var self = this;
      self.clientPromise.then(function(client) {
        self.setPrivate_('__subContext__', client.__subContext__);
        self.getCurrentUser();

        window.onpopstate = function(event) {
          if ( location.hash != null ) {
            var hid = location.hash.substr(1);

            hid && self.client.menuDAO.find(hid).then(function(menu) {
              menu && menu.launch(this, null);
            });
          }
        };

        window.onpopstate();
      });
    },

    function initE() {
      var self = this;
      self.clientPromise.then(function() {
        self
          .addClass(self.myClass())
          .tag({class: 'foam.nanos.u2.navigation.TopNavigation'})
          .start('div').addClass('stack-wrapper')
            .tag({class: 'foam.u2.stack.StackView', data: self.stack, showActions: false})
          .end();
      });
    },

    function setDefaultMenu() {
      // Don't select default if menu already set
      if ( this.window.location.hash || ! this.user.group ) return;

      this.client.groupDAO.find(this.user.group).then(function (group) {
        this.group.copyFrom(group);

        for ( var i = 0 ; i < this.MACROS.length ; i++ ) {
          var m = this.MACROS[i];
          if ( group[m] ) this[m] = group[m];
        }

        // Don't select default if menu already set
        if ( group && ! this.window.location.hash ) {
          this.window.location.hash = group.defaultMenu;
        }
      }.bind(this));
    },

    function getCurrentUser() {
      var self = this;

      // get current user, else show login
      this.client.auth.getCurrentUser(null).then(function (result) {
        self.loginSuccess = !! result;
        if ( result ) {
          self.user.copyFrom(result);
          if ( ! self.user.emailVerified ) {
            self.stack.push({ class: 'foam.nanos.auth.ResendVerificationEmail' });
            return;
          }
          self.onUserUpdate();
        }
      })
      .catch(function (err) {
        self.requestLogin().then(function() {
          self.getCurrentUser();
        });
      });
    },

    function expandShortFormMacro(css, m) {
      /* A short-form macros is of the form %PRIMARY_COLOR%. */
      var M = m.toUpperCase();

      return css.replace(
        new RegExp("%" + M + "%", 'g'),
        '/*%' + M + '%*/ ' + this[m]);
    },

    function expandLongFormMacro(css, m) {
      // A long-form macros is of the form "/*%PRIMARY_COLOR%*/ blue".
      var M = m.toUpperCase();

      return css.replace(
        new RegExp('/\\*%' + M + '%\\*/[^;]*', 'g'),
        '/*%' + M + '%*/ ' + this[m]);
    },

    // CSS preprocessor, works on classes instantiated in subContext
    function wrapCSS(text, id) {
      if ( text ) {
        if ( ! this.accentColor ) {
          var self = this;

          this.accentColor$.sub(function(s) {
            self.wrapCSS(text, id);
            s.detach();
          });
        }

        let eid = foam.u2.Element.NEXT_ID();

        for ( var i = 0 ; i < this.MACROS.length ; i++ ) {
          let m     = this.MACROS[i];
          var text2 = this.expandShortFormMacro(this.expandLongFormMacro(text, m), m);

            // If the macro was found, then listen for changes to the property
            // and update the CSS if it changes.
            if ( text != text2 ) {
              text = text2;
              this.slot(m).sub(function() {
                var el = this.getElementById(eid);
                el.innerText = this.expandLongFormMacro(el.innerText, m);
              }.bind(this));
            }
        }

        this.installCSS(text, id, eid);
      }
    },

    function requestLogin() {
      var self = this;

      // don't go to log in screen if going to reset password screen
      if ( location.hash != null && location.hash === '#reset')
        return new Promise(function (resolve, reject) {
          self.stack.push({ class: 'foam.nanos.auth.resetPassword.ResetView' });
          self.loginSuccess$.sub(resolve);
        });

      return new Promise(function(resolve, reject) {
        self.stack.push({ class: 'foam.nanos.auth.SignInView' });
        self.loginSuccess$.sub(resolve);
      });
    }
  ],

  listeners: [
    function onUserUpdate() {
      this.setDefaultMenu();
    },

    // This listener should be triggered when a Menu item has been launched AND
    // navigates to a new screen.
    function menuListener(m) {
      this.currentMenu = m;
    },

    // This listener should be triggered when a Menu has been launched but does
    // not navigate to a new screen. Typically for SubMenus
    function lastMenuLaunchedListener(m) {
      this.lastMenuLaunched = m;
    }
  ]
});
<|endoftext|>


<commit_before>// Saves options to chrome sync storage.
function saveOps() {

	chrome.storage.sync.set({
		"select_new_created": document.getElementById("select_new_created").checked,
		"close_second_tab": document.getElementById("close_second_tab").checked,
		"auto_pin": document.getElementById("auto_pin").checked,
		"open_custom_page": document.getElementById("open_custom_page").checked,
		"custom_page_url": document.getElementById("custom_page_url").value
	});

	// Update status to let user know options were saved.
	var status = document.getElementById("status");
	status.innerHTML = "Options Saved.";
	setTimeout(function() {
		status.innerHTML = "";
	}, 750);
}

// Restores select box state to saved value from chrome sync storage.
function loadOps() {
	chrome.storage.sync.get(["select_new_created", "close_second_tab", "auto_pin", "open_custom_page", "custom_page_url"],
		function(items) {

			document.getElementById("select_new_created").checked = items["select_new_created"];
			document.getElementById("close_second_tab").checked = items["close_second_tab"];
			document.getElementById("auto_pin").checked = items["auto_pin"];
			document.getElementById("open_custom_page").checked = items["open_custom_page"];
			document.getElementById("custom_page_url").value = items["custom_page_url"];

		}
	);
}

// Add the events to load/save from this page.
document.addEventListener('DOMContentLoaded', loadOps);
document.querySelector('#save').addEventListener('click', saveOps);<commit_msg>set HTML elements value properly for new installs<commit_after>// Saves options to chrome sync storage.
function saveOps() {

	chrome.storage.sync.set({
		"select_new_created": document.getElementById("select_new_created").checked,
		"close_second_tab": document.getElementById("close_second_tab").checked,
		"auto_pin": document.getElementById("auto_pin").checked,
		"open_custom_page": document.getElementById("open_custom_page").checked,
		"custom_page_url": document.getElementById("custom_page_url").value
	});

	// Update status to let user know options were saved.
	var status = document.getElementById("status");
	status.innerHTML = "Options Saved.";
	setTimeout(function() {
		status.innerHTML = "";
	}, 750);
}

// Restores select box state to saved value from chrome sync storage.
function loadOps() {
	chrome.storage.sync.get(["select_new_created", "close_second_tab", "auto_pin", "open_custom_page", "custom_page_url"],
		function(items) {

			document.getElementById("select_new_created").checked = !!items["select_new_created"];
			document.getElementById("close_second_tab").checked = !!items["close_second_tab"];
			document.getElementById("auto_pin").checked = !!items["auto_pin"];
			document.getElementById("open_custom_page").checked = !!items["open_custom_page"];
			document.getElementById("custom_page_url").value = items["custom_page_url"] || '';

		}
	);
}

// Add the events to load/save from this page.
document.addEventListener('DOMContentLoaded', loadOps);
document.querySelector('#save').addEventListener('click', saveOps);
<|endoftext|>