<commit_before>/*!

   hlsjs engine plugin for Flowplayer HTML5

   Copyright (c) 2015, Flowplayer Oy

   Released under the MIT License:
   http://www.opensource.org/licenses/mit-license.php

   Includes hls.min.js
   Copyright (c) 2015 Dailymotion (http://www.dailymotion.com)
   https://github.com/dailymotion/hls.js/blob/master/LICENSE

   requires:
   - Flowplayer HTML5 version 6.x or greater
   - hls.js https://github.com/dailymotion/hls.js

*/

(function () {
    var win = window,
        engineName = "hlsjs",
        support = flowplayer.support,
        clientSupport = support.video && win.MediaSource,
        extend = flowplayer.extend,

        engineImpl = function hlsjsEngine(player, root) {
            var bean = flowplayer.bean,
                common = flowplayer.common,
                videoTag,
                hls = new Hls({
                    debug: player.conf.debug
                });

                engine = {
                    engineName: engineName,

                    pick: function (sources) {
                        var i,
                            source;

                        for (i = 0; i < sources.length; i = i + 1) {
                            source = sources[i];
                            if (/mpegurl/i.test(source.type) && (!source.engine || source.engine == "hlsjs")) {
                                return source;
                            }
                        }
                    },

                    load: function (video) {
                        common.removeNode(common.findDirect("video", root)[0] || common.find(".fp-player > video", root)[0]);
                        videoTag = common.createElement("video");

                        bean.on(videoTag, "play", function () {
                            player.trigger('resume', [player]);
                        });
                        bean.on(videoTag, "pause", function () {
                            player.trigger('pause', [player]);
                        });
                        bean.on(videoTag, "timeupdate", function () {
                            player.trigger('progress', [player, videoTag.currentTime]);
                        });
                        bean.on(videoTag, "loadeddata", function () {
                            extend(video, {
                                duration: videoTag.duration,
                                seekable: videoTag.seekable.end(null),
                                width: videoTag.videoWidth,
                                height: videoTag.videoHeight,
                                url: videoTag.currentSrc
                            });
                            player.trigger('ready', [player, video]);

                            // fix timing for poster class
                            var poster = "is-poster";
                            if (common.hasClass(root, poster)) {
                                player.on("stop.hlsjs", function () {
                                    setTimeout(function () {
                                        common.addClass(root, poster);
                                        bean.one(videoTag, "play.hlsjs", function () {
                                            common.removeClass(root, poster);
                                        });
                                    }, 0);
                                });
                            }

                            if (player.conf.autoplay) {
                                // let the fp API take care of autoplay
                                videoTag.play();
                            }
                        });
                        bean.on(videoTag, "seeked", function () {
                            player.trigger('seek', [player, videoTag.currentTime]);
                        });
                        bean.on(videoTag, "progress", function (e) {
                            try {
                                var buffered = videoTag.buffered,
                                    buffer = buffered.end(null), // first loaded buffer
                                    ct = videoTag.currentTime,
                                    buffend = 0,
                                    i;

                                // buffered.end(null) will not always return the current buffer
                                // so we cycle through the time ranges to obtain it
                                if (ct) {
                                    for (i = 1; i < buffered.length; i = i + 1) {
                                        buffend = buffered.end(i);

                                        if (buffend >= ct && buffered.start(i) <= ct) {
                                            buffer = buffend;
                                        }
                                    }
                                }
                                video.buffer = buffer;
                            } catch (ignored) {}
                            player.trigger('buffer', [player, e]);
                        });
                        bean.on(videoTag, "ended", function () {
                            player.trigger('finish', [player]);
                            /*
                            if (support.browser.safari && !player.conf.autoplay) {
                                bean.one(videoTag, "seeked.hlsjsreplay", function () {
                                    if (!videoTag.currentTime) {
                                        videoTag.play();
                                    }
                                });
                            }
                            */
                        });
                        bean.on(videoTag, "volumechange", function () {
                            player.trigger('volume', [player, videoTag.volume]);
                        });

                        videoTag.className = 'fp-engine hlsjs-engine';
                        common.prepend(common.find(".fp-player", root)[0], videoTag);

                        hls.on(Hls.Events.ERROR, function (e, data) {
                            var fperr,
                                errtypes = Hls.ErrorTypes,
                                errobj;

                            if (data.fatal) {
                                // try recovery?
                                switch (data.type) {
                                case Hls.ErrorTypes.NETWORK_ERROR:
                                    // in theory should be 3 (Network error)
                                    fperr = 4;
                                    break;
                                case Hls.ErrorTypes.MEDIA_ERROR:
                                    fperr = 3;
                                    break;
                                default:
                                    fperr = 5;
                                    break;
                                }
                                errobj = {code: fperr};
                                if (fperr > 2) {
                                    errobj.video = extend(video, {
                                        src: video.src,
                                        url: video.src
                                    });
                                }
                                player.trigger('error', [player, errobj]);
                            }
                            /* TODO: */
                            // log non fatals
                        });

                        player.on("error", function () {
                            hls.destroy();
                        });

                        hls.attachVideo(videoTag);
                        hls.on(Hls.Events.MSE_ATTACHED, function () {
                            hls.loadSource(video.src);
                        });
                    },

                    resume: function () {
                        videoTag.play();
                    },

                    pause: function () {
                        videoTag.pause();
                    },

                    seek: function (time) {
                        videoTag.currentTime = time;
                    },

                    volume: function (level) {
                        if (videoTag) {
                            videoTag.volume = level;
                        }
                    },

                    speed: function (val) {
                        videoTag.playbackRate = val;
                        player.trigger('speed', [player, val]);
                    },

                    unload: function () {
                        /*
                        if (player.video.live && player.paused) {
                            videoTag.play();
                        }
                        */
                        if (player.conf.splash) {
                            hls.detachVideo();
                        }
                        player.trigger('unload', [player]);
                    }
                };

            return engine;
        };

    if (clientSupport) {
        // only load engine if it can be used
        engineImpl.engineName = engineName; // must be exposed
        engineImpl.canPlay = function (type, conf) {
            var hlsjsconf = conf.hlsjs;

            /*
              WARNING: MediaSource.isTypeSupported very inconsistent!
              e.g. Safari ignores codecs entirely, even bogus, like codecs="XYZ"
              example avc3 main level 3.1 + aac_he: avc3.4d401f; mp4a.40.5
              example avc1 high level 4.1 + aac_lc: avc1.640029; mp4a.40.2
              default: avc1 baseline level 3.0 + aac_lc
            */
            conf.hlsjs = extend({
                type: "video/mp4",
                codecs: "avc1.42c00d, mp4a.40.2"
            }, hlsjsconf);
            if (/mpegurl/i.test(type)) {
                return win.MediaSource.isTypeSupported(conf.hlsjs.type + '; codecs="' + conf.hlsjs.codecs + '"');
            }
            return false;
        };

        // put on top of engine stack
        // so hlsjs is tested before html5
        flowplayer.engines.unshift(engineImpl);
    }

}());
<commit_msg>Correct codecs examples<commit_after>/*!

   hlsjs engine plugin for Flowplayer HTML5

   Copyright (c) 2015, Flowplayer Oy

   Released under the MIT License:
   http://www.opensource.org/licenses/mit-license.php

   Includes hls.min.js
   Copyright (c) 2015 Dailymotion (http://www.dailymotion.com)
   https://github.com/dailymotion/hls.js/blob/master/LICENSE

   requires:
   - Flowplayer HTML5 version 6.x or greater
   - hls.js https://github.com/dailymotion/hls.js

*/

(function () {
    var win = window,
        engineName = "hlsjs",
        support = flowplayer.support,
        clientSupport = support.video && win.MediaSource,
        extend = flowplayer.extend,

        engineImpl = function hlsjsEngine(player, root) {
            var bean = flowplayer.bean,
                common = flowplayer.common,
                videoTag,
                hls = new Hls({
                    debug: player.conf.debug
                });

                engine = {
                    engineName: engineName,

                    pick: function (sources) {
                        var i,
                            source;

                        for (i = 0; i < sources.length; i = i + 1) {
                            source = sources[i];
                            if (/mpegurl/i.test(source.type) && (!source.engine || source.engine == "hlsjs")) {
                                return source;
                            }
                        }
                    },

                    load: function (video) {
                        common.removeNode(common.findDirect("video", root)[0] || common.find(".fp-player > video", root)[0]);
                        videoTag = common.createElement("video");

                        bean.on(videoTag, "play", function () {
                            player.trigger('resume', [player]);
                        });
                        bean.on(videoTag, "pause", function () {
                            player.trigger('pause', [player]);
                        });
                        bean.on(videoTag, "timeupdate", function () {
                            player.trigger('progress', [player, videoTag.currentTime]);
                        });
                        bean.on(videoTag, "loadeddata", function () {
                            extend(video, {
                                duration: videoTag.duration,
                                seekable: videoTag.seekable.end(null),
                                width: videoTag.videoWidth,
                                height: videoTag.videoHeight,
                                url: videoTag.currentSrc
                            });
                            player.trigger('ready', [player, video]);

                            // fix timing for poster class
                            var poster = "is-poster";
                            if (common.hasClass(root, poster)) {
                                player.on("stop.hlsjs", function () {
                                    setTimeout(function () {
                                        common.addClass(root, poster);
                                        bean.one(videoTag, "play.hlsjs", function () {
                                            common.removeClass(root, poster);
                                        });
                                    }, 0);
                                });
                            }

                            if (player.conf.autoplay) {
                                // let the fp API take care of autoplay
                                videoTag.play();
                            }
                        });
                        bean.on(videoTag, "seeked", function () {
                            player.trigger('seek', [player, videoTag.currentTime]);
                        });
                        bean.on(videoTag, "progress", function (e) {
                            try {
                                var buffered = videoTag.buffered,
                                    buffer = buffered.end(null), // first loaded buffer
                                    ct = videoTag.currentTime,
                                    buffend = 0,
                                    i;

                                // buffered.end(null) will not always return the current buffer
                                // so we cycle through the time ranges to obtain it
                                if (ct) {
                                    for (i = 1; i < buffered.length; i = i + 1) {
                                        buffend = buffered.end(i);

                                        if (buffend >= ct && buffered.start(i) <= ct) {
                                            buffer = buffend;
                                        }
                                    }
                                }
                                video.buffer = buffer;
                            } catch (ignored) {}
                            player.trigger('buffer', [player, e]);
                        });
                        bean.on(videoTag, "ended", function () {
                            player.trigger('finish', [player]);
                            /*
                            if (support.browser.safari && !player.conf.autoplay) {
                                bean.one(videoTag, "seeked.hlsjsreplay", function () {
                                    if (!videoTag.currentTime) {
                                        videoTag.play();
                                    }
                                });
                            }
                            */
                        });
                        bean.on(videoTag, "volumechange", function () {
                            player.trigger('volume', [player, videoTag.volume]);
                        });

                        videoTag.className = 'fp-engine hlsjs-engine';
                        common.prepend(common.find(".fp-player", root)[0], videoTag);

                        hls.on(Hls.Events.ERROR, function (e, data) {
                            var fperr,
                                errtypes = Hls.ErrorTypes,
                                errobj;

                            if (data.fatal) {
                                // try recovery?
                                switch (data.type) {
                                case Hls.ErrorTypes.NETWORK_ERROR:
                                    // in theory should be 3 (Network error)
                                    fperr = 4;
                                    break;
                                case Hls.ErrorTypes.MEDIA_ERROR:
                                    fperr = 3;
                                    break;
                                default:
                                    fperr = 5;
                                    break;
                                }
                                errobj = {code: fperr};
                                if (fperr > 2) {
                                    errobj.video = extend(video, {
                                        src: video.src,
                                        url: video.src
                                    });
                                }
                                player.trigger('error', [player, errobj]);
                            }
                            /* TODO: */
                            // log non fatals
                        });

                        player.on("error", function () {
                            hls.destroy();
                        });

                        hls.attachVideo(videoTag);
                        hls.on(Hls.Events.MSE_ATTACHED, function () {
                            hls.loadSource(video.src);
                        });
                    },

                    resume: function () {
                        videoTag.play();
                    },

                    pause: function () {
                        videoTag.pause();
                    },

                    seek: function (time) {
                        videoTag.currentTime = time;
                    },

                    volume: function (level) {
                        if (videoTag) {
                            videoTag.volume = level;
                        }
                    },

                    speed: function (val) {
                        videoTag.playbackRate = val;
                        player.trigger('speed', [player, val]);
                    },

                    unload: function () {
                        /*
                        if (player.video.live && player.paused) {
                            videoTag.play();
                        }
                        */
                        if (player.conf.splash) {
                            hls.detachVideo();
                        }
                        player.trigger('unload', [player]);
                    }
                };

            return engine;
        };

    if (clientSupport) {
        // only load engine if it can be used
        engineImpl.engineName = engineName; // must be exposed
        engineImpl.canPlay = function (type, conf) {
            var hlsjsconf = conf.hlsjs;

            /*
              WARNING: MediaSource.isTypeSupported very inconsistent!
              e.g. Safari ignores codecs entirely, even bogus, like codecs="XYZ"
              example avc1 main level 3.1 + aac_he: avc1.4d401e, mp4a.40.5
              example avc1 high level 4.1 + aac_lc: avc1.640029; mp4a.40.2
              hls.js check (extended baseline): avc1.42e01e, mp4a.40.2

              default: avc1 constrained baseline level 3.0 + aac_lc
            */
            conf.hlsjs = extend({
                type: "video/mp4",
                codecs: "avc1.42c00d, mp4a.40.2"
            }, hlsjsconf);
            if (/mpegurl/i.test(type)) {
                return win.MediaSource.isTypeSupported(conf.hlsjs.type + '; codecs="' + conf.hlsjs.codecs + '"');
            }
            return false;
        };

        // put on top of engine stack
        // so hlsjs is tested before html5
        flowplayer.engines.unshift(engineImpl);
    }

}());
<|endoftext|>


<commit_before>/**
 * The examples provided by Facebook are for non-commercial testing and
 * evaluation purposes only.
 *
 * Facebook reserves all rights not expressly granted.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
 * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * @flow
 */
'use strict';

var React = require('react-native');
var {
  AppRegistry,
  ListView,
  PixelRatio,
  Platform,
  StyleSheet,
  Text,
  TextInput,
  TouchableHighlight,
  View,
} = React;

var { TestModule } = React.addons;
var Settings = require('Settings');

import type { ExampleModule } from 'ExampleTypes';

var createExamplePage = require('./createExamplePage');

var COMMON_COMPONENTS = [
  require('./ViewExample'),
  require('./WebViewExample'),
];

var COMMON_APIS = [
  require('./GeolocationExample'),
  require('./LayoutExample'),
  require('./PanResponderExample'),
];

if (Platform.OS === 'ios') {
  var COMPONENTS = COMMON_COMPONENTS.concat([
    require('./ActivityIndicatorIOSExample'),
    require('./DatePickerIOSExample'),
    require('./ImageExample'),
    require('./ListViewExample'),
    require('./ListViewPagingExample'),
    require('./MapViewExample'),
    require('./Navigator/NavigatorExample'),
    require('./NavigatorIOSColorsExample'),
    require('./NavigatorIOSExample'),
    require('./PickerIOSExample'),
    require('./ProgressViewIOSExample'),
    require('./ScrollViewExample'),
    require('./SegmentedControlIOSExample'),
    require('./SliderIOSExample'),
    require('./SwitchIOSExample'),
    require('./TabBarIOSExample'),
    require('./TextExample.ios'),
    require('./TextInputExample'),
    require('./TouchableExample'),
  ]);

  var APIS = COMMON_APIS.concat([
    require('./AccessibilityIOSExample'),
    require('./ActionSheetIOSExample'),
    require('./AdSupportIOSExample'),
    require('./AlertIOSExample'),
    require('./AppStateIOSExample'),
    require('./AsyncStorageExample'),
    require('./BorderExample'),
    require('./CameraRollExample.ios'),
    require('./LayoutEventsExample'),
    require('./NetInfoExample'),
    require('./PointerEventsExample'),
    require('./PushNotificationIOSExample'),
    require('./StatusBarIOSExample'),
    require('./TimerExample'),
    require('./VibrationIOSExample'),
    require('./XHRExample'),
  ]);

} else if (Platform.OS === 'android') {
  var COMPONENTS = COMMON_COMPONENTS.concat([
    require('ToolbarAndroidSampleApp'),
  ]);

  var APIS = COMMON_APIS.concat([
  ]);
}

var ds = new ListView.DataSource({
  rowHasChanged: (r1, r2) => r1 !== r2,
  sectionHeaderHasChanged: (h1, h2) => h1 !== h2,
});

function makeRenderable(example: any): ReactClass<any, any, any> {
  return example.examples ?
    createExamplePage(null, example) :
    example;
}

// Register suitable examples for snapshot tests
COMPONENTS.concat(APIS).forEach((Example) => {
  if (Example.displayName) {
    var Snapshotter = React.createClass({
      componentDidMount: function() {
        // View is still blank after first RAF :\
        global.requestAnimationFrame(() =>
          global.requestAnimationFrame(() => TestModule.verifySnapshot(
            TestModule.markTestCompleted
          )
        ));
      },
      render: function() {
        var Renderable = makeRenderable(Example);
        return <Renderable />;
      },
    });
    AppRegistry.registerComponent(Example.displayName, () => Snapshotter);
  }
});

if (Platform.OS === 'ios') {
  type Props = {
    navigator: Array<{title: string, component: ReactClass<any,any,any>}>,
    onExternalExampleRequested: Function,
  };
} else if (Platform.OS === 'android') {
  type Props = {
    onSelectExample: Function,
    isInDrawer: bool,
  };
}

class UIExplorerList extends React.Component {
  props: Props;

  constructor(props: Props) {
    super(props);
    this.state = {
      dataSource: ds.cloneWithRowsAndSections({
        components: COMPONENTS,
        apis: APIS,
      }),
      searchText: Platform.OS === 'ios' ? Settings.get('searchText') : '',
    };
  }

  componentDidMount() {
    this._search(this.state.searchText);
  }

  render() {
    if (Platform.OS === 'ios' ||
      (Platform.OS === 'android' && !this.props.isInDrawer)) {
      var platformTextInputStyle =
        Platform.OS === 'ios' ? styles.searchTextInputIOS :
        Platform.OS === 'android' ? styles.searchTextInputAndroid : {};
      var textInput = (
        <View style={styles.searchRow}>
          <TextInput
            autoCapitalize="none"
            autoCorrect={false}
            clearButtonMode="always"
            onChangeText={this._search.bind(this)}
            placeholder="Search..."
            style={[styles.searchTextInput, platformTextInputStyle]}
            value={this.state.searchText}
          />
        </View>);
    }

    var homePage;
    if (Platform.OS === 'android' && this.props.isInDrawer) {
      homePage = this._renderRow({
        title: 'UIExplorer',
        description: 'List of examples',
      }, -1);
    }

    return (
      <View style={styles.listContainer}>
        {textInput}
        {homePage}
        <ListView
          style={styles.list}
          dataSource={this.state.dataSource}
          renderRow={this._renderRow.bind(this)}
          renderSectionHeader={this._renderSectionHeader}
          keyboardShouldPersistTaps={true}
          automaticallyAdjustContentInsets={false}
          keyboardDismissMode="on-drag"
        />
      </View>
    );
  }

  _renderSectionHeader(data: any, section: string) {
    return (
      <View style={styles.sectionHeader}>
        <Text style={styles.sectionHeaderTitle}>
          {section.toUpperCase()}
        </Text>
      </View>
    );
  }

  _renderRow(example: ExampleModule, i: number) {
    return (
      <View key={i}>
        <TouchableHighlight onPress={() => this._onPressRow(example)}>
          <View style={styles.row}>
            <Text style={styles.rowTitleText}>
              {example.title}
            </Text>
            <Text style={styles.rowDetailText}>
              {example.description}
            </Text>
          </View>
        </TouchableHighlight>
        <View style={styles.separator} />
      </View>
    );
  }

  _search(text: mixed) {
    var regex = new RegExp(text, 'i');
    var filter = (component) => regex.test(component.title);

    this.setState({
      dataSource: ds.cloneWithRowsAndSections({
        components: COMPONENTS.filter(filter),
        apis: APIS.filter(filter),
      }),
      searchText: text,
    });
    Settings.set({searchText: text});
  }

  _onPressRow(example: ExampleModule) {
    if (example.external) {
      this.props.onExternalExampleRequested(example);
      return;
    }
    var Component = makeRenderable(example);
    if (Platform.OS === 'ios') {
      this.props.navigator.push({
        title: Component.title,
        component: Component,
      });
    } else if (Platform.OS === 'android') {
      this.props.onSelectExample({
        title: Component.title,
        component: Component,
      });
    }
  }
}

var styles = StyleSheet.create({
  listContainer: {
    flex: 1,
  },
  list: {
    backgroundColor: '#eeeeee',
  },
  sectionHeader: {
    padding: 5,
  },
  group: {
    backgroundColor: 'white',
  },
  sectionHeaderTitle: {
    fontWeight: '500',
    fontSize: 11,
  },
  row: {
    backgroundColor: 'white',
    justifyContent: 'center',
    paddingHorizontal: 15,
    paddingVertical: 8,
  },
  separator: {
    height: 1 / PixelRatio.get(),
    backgroundColor: '#bbbbbb',
    marginLeft: 15,
  },
  rowTitleText: {
    fontSize: 17,
    fontWeight: '500',
  },
  rowDetailText: {
    fontSize: 15,
    color: '#888888',
    lineHeight: 20,
  },
  searchRow: {
    backgroundColor: '#eeeeee',
    paddingTop: 75,
    paddingLeft: 10,
    paddingRight: 10,
    paddingBottom: 10,
  },
  searchTextInput: {
    backgroundColor: 'white',
    borderColor: '#cccccc',
    borderRadius: 3,
    borderWidth: 1,
    paddingLeft: 8,
  },
  searchTextInputIOS: {
    height: 30,
  },
  searchTextInputAndroid: {
    padding: 2,
  },
});

module.exports = UIExplorerList;
<commit_msg>[react_native] Fix UIExplorer<commit_after>/**
 * The examples provided by Facebook are for non-commercial testing and
 * evaluation purposes only.
 *
 * Facebook reserves all rights not expressly granted.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
 * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * @flow
 */
'use strict';

var React = require('react-native');
var {
  AppRegistry,
  ListView,
  PixelRatio,
  Platform,
  StyleSheet,
  Text,
  TextInput,
  TouchableHighlight,
  View,
} = React;

var { TestModule } = React.addons;
var Settings = require('Settings');

import type { ExampleModule } from 'ExampleTypes';

var createExamplePage = require('./createExamplePage');

var COMMON_COMPONENTS = [
  require('./ViewExample'),
  require('./WebViewExample'),
];

var COMMON_APIS = [
  require('./GeolocationExample'),
  require('./LayoutExample'),
  require('./PanResponderExample'),
];

if (Platform.OS === 'ios') {
  var COMPONENTS = COMMON_COMPONENTS.concat([
    require('./ActivityIndicatorIOSExample'),
    require('./DatePickerIOSExample'),
    require('./ImageExample'),
    require('./ListViewExample'),
    require('./ListViewPagingExample'),
    require('./MapViewExample'),
    require('./Navigator/NavigatorExample'),
    require('./NavigatorIOSColorsExample'),
    require('./NavigatorIOSExample'),
    require('./PickerIOSExample'),
    require('./ProgressViewIOSExample'),
    require('./ScrollViewExample'),
    require('./SegmentedControlIOSExample'),
    require('./SliderIOSExample'),
    require('./SwitchIOSExample'),
    require('./TabBarIOSExample'),
    require('./TextExample.ios'),
    require('./TextInputExample'),
    require('./TouchableExample'),
  ]);

  var APIS = COMMON_APIS.concat([
    require('./AccessibilityIOSExample'),
    require('./ActionSheetIOSExample'),
    require('./AdSupportIOSExample'),
    require('./AlertIOSExample'),
    require('./AppStateIOSExample'),
    require('./AsyncStorageExample'),
    require('./BorderExample'),
    require('./CameraRollExample.ios'),
    require('./LayoutEventsExample'),
    require('./NetInfoExample'),
    require('./PointerEventsExample'),
    require('./PushNotificationIOSExample'),
    require('./StatusBarIOSExample'),
    require('./TimerExample'),
    require('./VibrationIOSExample'),
    require('./XHRExample'),
  ]);

} else if (Platform.OS === 'android') {
  var COMPONENTS = COMMON_COMPONENTS.concat([
  ]);

  var APIS = COMMON_APIS.concat([
  ]);
}

var ds = new ListView.DataSource({
  rowHasChanged: (r1, r2) => r1 !== r2,
  sectionHeaderHasChanged: (h1, h2) => h1 !== h2,
});

function makeRenderable(example: any): ReactClass<any, any, any> {
  return example.examples ?
    createExamplePage(null, example) :
    example;
}

// Register suitable examples for snapshot tests
COMPONENTS.concat(APIS).forEach((Example) => {
  if (Example.displayName) {
    var Snapshotter = React.createClass({
      componentDidMount: function() {
        // View is still blank after first RAF :\
        global.requestAnimationFrame(() =>
          global.requestAnimationFrame(() => TestModule.verifySnapshot(
            TestModule.markTestCompleted
          )
        ));
      },
      render: function() {
        var Renderable = makeRenderable(Example);
        return <Renderable />;
      },
    });
    AppRegistry.registerComponent(Example.displayName, () => Snapshotter);
  }
});

type Props = {
  navigator: Array<{title: string, component: ReactClass<any,any,any>}>,
  onExternalExampleRequested: Function,
  onSelectExample: Function,
  isInDrawer: bool,
};

class UIExplorerList extends React.Component {
  props: Props;

  constructor(props: Props) {
    super(props);
    this.state = {
      dataSource: ds.cloneWithRowsAndSections({
        components: COMPONENTS,
        apis: APIS,
      }),
      searchText: Platform.OS === 'ios' ? Settings.get('searchText') : '',
    };
  }

  componentDidMount() {
    this._search(this.state.searchText);
  }

  render() {
    if (Platform.OS === 'ios' ||
      (Platform.OS === 'android' && !this.props.isInDrawer)) {
      var platformTextInputStyle =
        Platform.OS === 'ios' ? styles.searchTextInputIOS :
        Platform.OS === 'android' ? styles.searchTextInputAndroid : {};
      var textInput = (
        <View style={styles.searchRow}>
          <TextInput
            autoCapitalize="none"
            autoCorrect={false}
            clearButtonMode="always"
            onChangeText={this._search.bind(this)}
            placeholder="Search..."
            style={[styles.searchTextInput, platformTextInputStyle]}
            value={this.state.searchText}
          />
        </View>);
    }

    var homePage;
    if (Platform.OS === 'android' && this.props.isInDrawer) {
      homePage = this._renderRow({
        title: 'UIExplorer',
        description: 'List of examples',
      }, -1);
    }

    return (
      <View style={styles.listContainer}>
        {textInput}
        {homePage}
        <ListView
          style={styles.list}
          dataSource={this.state.dataSource}
          renderRow={this._renderRow.bind(this)}
          renderSectionHeader={this._renderSectionHeader}
          keyboardShouldPersistTaps={true}
          automaticallyAdjustContentInsets={false}
          keyboardDismissMode="on-drag"
        />
      </View>
    );
  }

  _renderSectionHeader(data: any, section: string) {
    return (
      <View style={styles.sectionHeader}>
        <Text style={styles.sectionHeaderTitle}>
          {section.toUpperCase()}
        </Text>
      </View>
    );
  }

  _renderRow(example: any, i: number) {
    return (
      <View key={i}>
        <TouchableHighlight onPress={() => this._onPressRow(example)}>
          <View style={styles.row}>
            <Text style={styles.rowTitleText}>
              {example.title}
            </Text>
            <Text style={styles.rowDetailText}>
              {example.description}
            </Text>
          </View>
        </TouchableHighlight>
        <View style={styles.separator} />
      </View>
    );
  }

  _search(text: mixed) {
    var regex = new RegExp(text, 'i');
    var filter = (component) => regex.test(component.title);

    this.setState({
      dataSource: ds.cloneWithRowsAndSections({
        components: COMPONENTS.filter(filter),
        apis: APIS.filter(filter),
      }),
      searchText: text,
    });
    Settings.set({searchText: text});
  }

  _onPressRow(example: any) {
    if (example.external) {
      this.props.onExternalExampleRequested(example);
      return;
    }
    var Component = makeRenderable(example);
    if (Platform.OS === 'ios') {
      this.props.navigator.push({
        title: Component.title,
        component: Component,
      });
    } else if (Platform.OS === 'android') {
      this.props.onSelectExample({
        title: Component.title,
        component: Component,
      });
    }
  }
}

var styles = StyleSheet.create({
  listContainer: {
    flex: 1,
  },
  list: {
    backgroundColor: '#eeeeee',
  },
  sectionHeader: {
    padding: 5,
  },
  group: {
    backgroundColor: 'white',
  },
  sectionHeaderTitle: {
    fontWeight: '500',
    fontSize: 11,
  },
  row: {
    backgroundColor: 'white',
    justifyContent: 'center',
    paddingHorizontal: 15,
    paddingVertical: 8,
  },
  separator: {
    height: 1 / PixelRatio.get(),
    backgroundColor: '#bbbbbb',
    marginLeft: 15,
  },
  rowTitleText: {
    fontSize: 17,
    fontWeight: '500',
  },
  rowDetailText: {
    fontSize: 15,
    color: '#888888',
    lineHeight: 20,
  },
  searchRow: {
    backgroundColor: '#eeeeee',
    paddingTop: 75,
    paddingLeft: 10,
    paddingRight: 10,
    paddingBottom: 10,
  },
  searchTextInput: {
    backgroundColor: 'white',
    borderColor: '#cccccc',
    borderRadius: 3,
    borderWidth: 1,
    paddingLeft: 8,
  },
  searchTextInputIOS: {
    height: 30,
  },
  searchTextInputAndroid: {
    padding: 2,
  },
});

module.exports = UIExplorerList;
<|endoftext|>


<commit_before>//
// Editing/detail page for ward round episodes
//
angular.module('opal.controllers').controller(
   'PatientDetailCtrl', function($rootScope, $scope, $cookieStore,
                                episodes, options, profile, recordLoader,
                                EpisodeDetailMixin
                                   ){

        microEpisodes = _.filter(episodes, function(e){
           return e.microbiology_input && e.microbiology_input.length;
       });
       $scope.episodes = _.sortBy(microEpisodes, function(e){
           var significantDate = e.date_of_discharge || e.date_of_episode || e.date_of_admission;
           if(significantDate){
               return significantDate.unix * -1;
           }
       });

       $scope.profile = profile;
       $scope.options = options;

       if($scope.episodes.length){
           $scope.episode = $scope.episodes[0];
           EpisodeDetailMixin($scope);
       }

       $scope.patient = episodes[0].demographics[0];
       $scope.lastInputId = _.last(_.last($scope.episodes).microbiology_input).id;

       $scope.getEpisodeLink = function(episode){
           return "/#/episode/" + episode.id
       }
   }
);
<commit_msg>only get last input id if we have episodes<commit_after>//
// Editing/detail page for ward round episodes
//
angular.module('opal.controllers').controller(
   'PatientDetailCtrl', function($rootScope, $scope, $cookieStore,
                                episodes, options, profile, recordLoader,
                                EpisodeDetailMixin
                                   ){

        microEpisodes = _.filter(episodes, function(e){
           return e.microbiology_input && e.microbiology_input.length;
       });
       $scope.episodes = _.sortBy(microEpisodes, function(e){
           var significantDate = e.date_of_discharge || e.date_of_episode || e.date_of_admission;
           if(significantDate){
               return significantDate.unix * -1;
           }
       });

       $scope.profile = profile;
       $scope.options = options;

       if($scope.episodes.length){
           $scope.episode = $scope.episodes[0];
           EpisodeDetailMixin($scope);
           $scope.lastInputId = _.last(_.last($scope.episodes).microbiology_input).id;
       }

       $scope.patient = episodes[0].demographics[0];

       $scope.getEpisodeLink = function(episode){
           return "/#/episode/" + episode.id
       }
   }
);
<|endoftext|>


<commit_before>const deepAssign = require('deep-assign');
const path = require('path');

function getOptionsForPath(filePath, options) {
  const absolutePath =
    filePath.charAt(0) === '/' ? path : path.resolve(process.cwd(), filePath);

  if (absolutePath.indexOf('packages') === -1) {
    // non lerna package
    return {
      marlint: {
        ignores: [],
      },
      eslint: {
        useEslintrc: false,
        baseConfig: {
          extends: 'marlint',
        },
        quiet: Boolean(options.quiet),
        fix: Boolean(options.fix),
      },
    };
  }

  let packageConfig = {};
  let rootConfig = {};

  // /User/fatih/work/web/packages/path/to/file.js
  const splitPath = absolutePath.split('/packages/');

  try {
    const packageName = splitPath[1].split('/')[0];
    const packageJsonPath = `${splitPath[0]}/packages/${packageName}/package.json`;
    const json = require(packageJsonPath);
    packageConfig = json.marlint || {};
  } catch (err) {}

  try {
    const rootJsonPath = `${splitPath[0]}/package.json`;
    const json = require(rootJsonPath);
    rootConfig = json.marlint || {};
  } catch (err) {}

  const mergedConfig = deepAssign(packageConfig, rootConfig);

  return {
    marlint: {
      ignores: mergedConfig.ignores,
    },
    eslint: {
      useEslintrc: false,
      baseConfig: {
        extends: 'marlint',
      },
      rules: mergedConfig.rules || {},
      globals: mergedConfig.globals || [],
      quiet: Boolean(options.quiet),
      fix: Boolean(options.fix),
    },
  };
}

module.exports = getOptionsForPath;
<commit_msg>fix path parser in getOptionsForPath<commit_after>const deepAssign = require('deep-assign');
const path = require('path');

function getOptionsForPath(filePath, options) {
  const cwd = options.cwd || process.cwd();
  const absolutePath =
    filePath.charAt(0) === '/' ? filePath : path.resolve(cwd, filePath);

  if (absolutePath.indexOf('packages') === -1) {
    // non lerna package
    return {
      marlint: {
        ignores: [],
      },
      eslint: {
        useEslintrc: false,
        baseConfig: {
          extends: 'marlint',
        },
        quiet: Boolean(options.quiet),
        fix: Boolean(options.fix),
      },
    };
  }

  let packageConfig = {};
  let rootConfig = {};

  // /User/fatih/work/web/packages/path/to/file.js
  const splitPath = absolutePath.split('/packages/');

  try {
    const packageName = splitPath[1].split('/')[0];
    const packageJsonPath = `${splitPath[0]}/packages/${packageName}/package.json`;
    const json = require(packageJsonPath);
    packageConfig = json.marlint || {};
  } catch (err) {}

  try {
    const rootJsonPath = `${splitPath[0]}/package.json`;
    const json = require(rootJsonPath);
    rootConfig = json.marlint || {};
  } catch (err) {}

  const mergedConfig = deepAssign(packageConfig, rootConfig);

  return {
    marlint: {
      ignores: mergedConfig.ignores,
    },
    eslint: {
      useEslintrc: false,
      baseConfig: {
        extends: 'marlint',
      },
      rules: mergedConfig.rules || {},
      globals: mergedConfig.globals || [],
      quiet: Boolean(options.quiet),
      fix: Boolean(options.fix),
    },
  };
}

module.exports = getOptionsForPath;
<|endoftext|>


<commit_before>import $ from 'nodobjc'
import Logger from '../log/logger'

// Load Cocoa framework
$.framework('cocoa')

export const getBackground = () => {
  try {
    const url = $.NSWorkspace('sharedWorkspace')(
      'desktopImageURLForScreen',
      $.NSScreen('mainScreen')
    )

    return url.toString()
  } catch (e) {
    Logger.error('Failed to get desktop background image.', e)

    return null
  }
}
<commit_msg>More Obj-C bridge safety<commit_after>
import Logger from '../log/logger'

let $

try {
  // Load Obj-C bridge
  $ = require('nodobjc')

  // Load Cocoa framework
  $.framework('cocoa')
} catch (e) {
  Logger.error('Failed to load nodobjc.', e)
}

export const getBackground = () => {
  try {
    const url = $.NSWorkspace('sharedWorkspace')(
      'desktopImageURLForScreen',
      $.NSScreen('mainScreen')
    )

    return url.toString()
  } catch (e) {
    Logger.error('Failed to get desktop background image.', e)

    return null
  }
}
<|endoftext|>


<commit_before>var _ = require('lodash');
//TODO remove from package.json var toId = require('to-js-identifier');
var mkTree = require('estree-builder');
var wrapKRLType = require('./wrapKRLType');

var mkDbCall = function(e, method, args){
  return e('call', e('id', 'ctx.persistent.' + method), args);
};

var comp_by_type = {
  'String': function(ast, comp, e){
    return wrapKRLType(e, 'String', [e('string', ast.value)]);
  },
  'Number': function(ast, comp, e){
    return wrapKRLType(e, 'Number', [e('number', ast.value)]);
  },
  'Identifier': function(ast, comp, e){
    return e('call', e('id', 'ctx.scope.get'), [e('str', ast.value)]);
  },
  'Chevron': function(ast, comp, e){
    if(ast.value.length < 1){
      return wrapKRLType(e, 'String', []);
    }
    var compElm = function(elm){
      if(elm.type === 'String'){
        return e('string', elm.value, elm.loc);
      }
      return e('call', e('get', e('id', 'ctx.krl.stdlib'), e('string', 'beesting', elm.loc), elm.loc), [comp(elm)], elm.loc);
    };
    var curr = compElm(ast.value[0]);
    var i = 1;
    while(i < ast.value.length){
      curr = e('+', curr, compElm(ast.value[i]));
      i++;
    }
    return wrapKRLType(e, 'String', [curr]);
  },
  'Boolean': function(ast, comp, e){
    return wrapKRLType(e, 'Boolean', [e(ast.value ? 'true' : 'false')]);
  },
  'RegExp': function(ast, comp, e){
    var flags = '';
    if(ast.value.global){
      flags += 'g';
    }
    if(ast.value.ignoreCase){
      flags += 'i';
    }
    return e('new', e('id', 'RegExp'), [
      e('str', ast.value.source),
      e('str', flags)
    ]);
  },
  'DomainIdentifier': function(ast, comp, e){
    if(ast.domain === 'ent'){
      return mkDbCall(e, 'getEnt', [
        e('str', ast.value)
      ]);
    }else if(ast.domain === 'app'){
      return mkDbCall(e, 'getApp', [
        e('str', ast.value)
      ]);
    }
    throw new Error('Only ent:* and app:* DomainIdentifiers are supported');
  },
  'MemberExpression': function(ast, comp, e){
    if(ast.method === 'dot'){
      if(ast.property.type === 'Identifier'){
        //using 'get' rather than . b/c we don't want to mess
        //with reserved javascript properties i.e. "prototype"
        return e('get', comp(ast.object), e('str', ast.property.value, ast.property.loc));
      }
      return e('get', comp(ast.object), comp(ast.property));
    }
    throw new Error('Unsupported MemberExpression method: ' + ast.method);
  },
  'Map': function(ast, comp, e){
    return e('obj-raw', comp(ast.value));
  },
  'MapKeyValuePair': function(ast, comp, e){
    return e('obj-prop', e('string', ast.key.value + '', ast.key.loc), comp(ast.value));
  },
  'Application': function(ast, comp, e){
    return e('call', comp(ast.callee), [
      e('id', 'ctx'),
      e('array', comp(ast.args))
    ]);
  },
  'InfixOperator': function(ast, comp, e){
    return e('call', e('get', e('id', 'ctx.krl.stdlib'), e('string', ast.op)), [
      comp(ast.left),
      comp(ast.right)
    ]);
  },
  'Function': function(ast, comp, e){
    var body = _.map(ast.params, function(param, i){
      var loc = param.loc;
      return e(';', e('call', e('id', 'ctx.scope.set', loc), [
        e('str', param.value, loc),
        e('call',
          e('id', 'ctx.getArg', loc),
          [
            e('id', 'ctx.args', loc),
            e('string', param.value, loc),
            e('number', i, loc)
          ],
          loc
        )
      ], loc), loc);
    });
    _.each(ast.body, function(part, i){
      if(i < (ast.body.length - 1)){
        return body.push(comp(part));
      }
      if(part.type === 'ExpressionStatement'){
        part = part.expression;
      }
      return body.push(e('return', comp(part)));
    });
    return e('call', e('id', 'ctx.krl.Closure'), [
      e('id', 'ctx'),
      e('fn', ['ctx'], body)
    ]);
  },
  'Declaration': function(ast, comp, e){
    if(ast.op === '='){
      if(ast.left
          && ast.left.type === 'DomainIdentifier'
          && ast.left.domain === 'ent'
        ){
        return e(';', mkDbCall(e, 'putEnt', [
          e('str', ast.left.value, ast.left.loc),
          comp(ast.right)
        ]));
      }else if(ast.left
          && ast.left.type === 'DomainIdentifier'
          && ast.left.domain === 'app'
        ){
        return e(';', mkDbCall(e, 'putApp', [
          e('str', ast.left.value, ast.left.loc),
          comp(ast.right)
        ]));
      }
      return e(';', e('call', e('id', 'ctx.scope.set'), [
        e('str', ast.left.value, ast.left.loc),
        comp(ast.right)
      ]));
    }
    throw new Error('Unsuported Declaration.op: ' + ast.op);
  },
  'ExpressionStatement': function(ast, comp, e){
    return e(';', comp(ast.expression));
  },
  'Ruleset': function(ast, comp, e){
    var rules_obj = {};
    _.each(ast.rules, function(rule){
      rules_obj[rule.name.value] = comp(rule);
    });
    var rs = {
      name: comp(ast.name),
      meta: e('obj-raw', comp(ast.meta))
    };
    if(!_.isEmpty(ast.global)){
      rs.global = e('fn', ['ctx'], comp(ast.global));
    }
    rs.rules = e('obj', rules_obj);
    return [
      e(';', e('=', e('id', 'module.exports'), e('obj', rs)))
    ];
  },
  'RulesetName': function(ast, comp, e){
    return e('string', ast.value);
  },
  'RulesetMetaProperty': function(ast, comp, e){
    var key = ast.key.value;
    var val = e('nil');
    if(key === 'shares'){
      val = e('arr', _.map(ast.value.ids, function(id){
        return e('str', id.value, id.loc);
      }));
    }else if(ast.value.type === 'String'){
      val = e('string', ast.value.value, ast.value.loc);
    }else if(ast.value.type === 'Chevron'){
      val = e('string', ast.value.value[0].value, ast.value.value[0].loc);
    }else if(ast.value.type === 'Boolean'){
      val = e(ast.value.value ? 'true' : 'false', ast.value.loc);
    }
    return e('obj-prop', e('str', key, ast.key.loc), val);
  },
  'Rule': function(ast, comp, e){
    var rule = {
      name: e('string', ast.name.value, ast.name.loc)
    };
    if(ast.rule_state !== 'active'){
      rule.rule_state = e('string', ast.rule_state);
    }
    if(ast.select){
      rule.select = comp(ast.select);
    }
    if(!_.isEmpty(ast.prelude)){
      rule.prelude = e('fn', ['ctx'], comp(ast.prelude));
    }
    if(ast.action_block){
      rule.action_block = comp(ast.action_block);
    }
    if(ast.postlude){
      rule.postlude = comp(ast.postlude);
    }
    return e('obj', rule);
  },
  'RuleSelect': require('./c/RuleSelect'),
  'EventExpression': require('./c/EventExpression'),
  'RuleActionBlock': function(ast, comp, e){
    var block = {};
    //TODO "condition": COND,
    //TODO "block_type": "choose",
    block.actions = e('arr', _.map(ast.actions, function(action){
      return comp(action);
    }));
    return e('obj', block);
  },
  'RuleAction': function(ast, comp, e){
    var fn_body = [];
    fn_body.push(e('return', e('obj', {
      type: e('str', 'directive'),
      name: e('str', ast.args[0].value),
      options: e('obj', _.fromPairs(_.map(ast['with'], function(dec){
        return [dec.left.value, comp(dec.right)];
      })))
    })));
    return e('fn', ['ctx'], fn_body);
  },
  'RulePostlude': require('./c/RulePostlude')
};

var isKRL_loc = function(loc){
  return _.isPlainObject(loc) && _.has(loc, 'start') && _.has(loc, 'end');
};

module.exports = function(ast, options){
  options = options || {};

  var toLoc = options.toLoc || _.noop;

  var mkE = function(default_krl_loc){
    var default_loc = toLoc(default_krl_loc.start, default_krl_loc.end);

    return function(){
      var args = Array.prototype.slice.call(arguments);
      var last_i = args.length - 1;
      var last = args[last_i];
      if(isKRL_loc(last)){
        args[last_i] = toLoc(last.start, last.end);
      }else{
        args.push(default_loc);
      }
      return mkTree.apply(null, args);
    };
  };

  var compile = function compile(ast){
    if(_.isArray(ast)){
      return _.map(ast, function(a){
        return compile(a);
      });
    }else if(!_.has(ast, 'type')){
      throw new Error('Invalid ast node: ' + JSON.stringify(ast));
    }else if(!_.has(comp_by_type, ast.type)){
      throw new Error('Unsupported ast node type: ' + ast.type);
    }
    return comp_by_type[ast.type](ast, compile, mkE(ast.loc));
  };

  return compile(ast, 0);
};
<commit_msg>starting ctx.krl.RegExp<commit_after>var _ = require('lodash');
//TODO remove from package.json var toId = require('to-js-identifier');
var mkTree = require('estree-builder');
var wrapKRLType = require('./wrapKRLType');

var mkDbCall = function(e, method, args){
  return e('call', e('id', 'ctx.persistent.' + method), args);
};

var comp_by_type = {
  'String': function(ast, comp, e){
    return wrapKRLType(e, 'String', [e('string', ast.value)]);
  },
  'Number': function(ast, comp, e){
    return wrapKRLType(e, 'Number', [e('number', ast.value)]);
  },
  'Identifier': function(ast, comp, e){
    return e('call', e('id', 'ctx.scope.get'), [e('str', ast.value)]);
  },
  'Chevron': function(ast, comp, e){
    if(ast.value.length < 1){
      return wrapKRLType(e, 'String', []);
    }
    var compElm = function(elm){
      if(elm.type === 'String'){
        return e('string', elm.value, elm.loc);
      }
      return e('call', e('get', e('id', 'ctx.krl.stdlib'), e('string', 'beesting', elm.loc), elm.loc), [comp(elm)], elm.loc);
    };
    var curr = compElm(ast.value[0]);
    var i = 1;
    while(i < ast.value.length){
      curr = e('+', curr, compElm(ast.value[i]));
      i++;
    }
    return wrapKRLType(e, 'String', [curr]);
  },
  'Boolean': function(ast, comp, e){
    return wrapKRLType(e, 'Boolean', [e(ast.value ? 'true' : 'false')]);
  },
  'RegExp': function(ast, comp, e){
    var flags = '';
    if(ast.value.global){
      flags += 'g';
    }
    if(ast.value.ignoreCase){
      flags += 'i';
    }
    return wrapKRLType(e, 'RegExp', [
      e('str', ast.value.source),
      e('str', flags)
    ]);
  },
  'DomainIdentifier': function(ast, comp, e){
    if(ast.domain === 'ent'){
      return mkDbCall(e, 'getEnt', [
        e('str', ast.value)
      ]);
    }else if(ast.domain === 'app'){
      return mkDbCall(e, 'getApp', [
        e('str', ast.value)
      ]);
    }
    throw new Error('Only ent:* and app:* DomainIdentifiers are supported');
  },
  'MemberExpression': function(ast, comp, e){
    if(ast.method === 'dot'){
      if(ast.property.type === 'Identifier'){
        //using 'get' rather than . b/c we don't want to mess
        //with reserved javascript properties i.e. "prototype"
        return e('get', comp(ast.object), e('str', ast.property.value, ast.property.loc));
      }
      return e('get', comp(ast.object), comp(ast.property));
    }
    throw new Error('Unsupported MemberExpression method: ' + ast.method);
  },
  'Map': function(ast, comp, e){
    return e('obj-raw', comp(ast.value));
  },
  'MapKeyValuePair': function(ast, comp, e){
    return e('obj-prop', e('string', ast.key.value + '', ast.key.loc), comp(ast.value));
  },
  'Application': function(ast, comp, e){
    return e('call', comp(ast.callee), [
      e('id', 'ctx'),
      e('array', comp(ast.args))
    ]);
  },
  'InfixOperator': function(ast, comp, e){
    return e('call', e('get', e('id', 'ctx.krl.stdlib'), e('string', ast.op)), [
      comp(ast.left),
      comp(ast.right)
    ]);
  },
  'Function': function(ast, comp, e){
    var body = _.map(ast.params, function(param, i){
      var loc = param.loc;
      return e(';', e('call', e('id', 'ctx.scope.set', loc), [
        e('str', param.value, loc),
        e('call',
          e('id', 'ctx.getArg', loc),
          [
            e('id', 'ctx.args', loc),
            e('string', param.value, loc),
            e('number', i, loc)
          ],
          loc
        )
      ], loc), loc);
    });
    _.each(ast.body, function(part, i){
      if(i < (ast.body.length - 1)){
        return body.push(comp(part));
      }
      if(part.type === 'ExpressionStatement'){
        part = part.expression;
      }
      return body.push(e('return', comp(part)));
    });
    return e('call', e('id', 'ctx.krl.Closure'), [
      e('id', 'ctx'),
      e('fn', ['ctx'], body)
    ]);
  },
  'Declaration': function(ast, comp, e){
    if(ast.op === '='){
      if(ast.left
          && ast.left.type === 'DomainIdentifier'
          && ast.left.domain === 'ent'
        ){
        return e(';', mkDbCall(e, 'putEnt', [
          e('str', ast.left.value, ast.left.loc),
          comp(ast.right)
        ]));
      }else if(ast.left
          && ast.left.type === 'DomainIdentifier'
          && ast.left.domain === 'app'
        ){
        return e(';', mkDbCall(e, 'putApp', [
          e('str', ast.left.value, ast.left.loc),
          comp(ast.right)
        ]));
      }
      return e(';', e('call', e('id', 'ctx.scope.set'), [
        e('str', ast.left.value, ast.left.loc),
        comp(ast.right)
      ]));
    }
    throw new Error('Unsuported Declaration.op: ' + ast.op);
  },
  'ExpressionStatement': function(ast, comp, e){
    return e(';', comp(ast.expression));
  },
  'Ruleset': function(ast, comp, e){
    var rules_obj = {};
    _.each(ast.rules, function(rule){
      rules_obj[rule.name.value] = comp(rule);
    });
    var rs = {
      name: comp(ast.name),
      meta: e('obj-raw', comp(ast.meta))
    };
    if(!_.isEmpty(ast.global)){
      rs.global = e('fn', ['ctx'], comp(ast.global));
    }
    rs.rules = e('obj', rules_obj);
    return [
      e(';', e('=', e('id', 'module.exports'), e('obj', rs)))
    ];
  },
  'RulesetName': function(ast, comp, e){
    return e('string', ast.value);
  },
  'RulesetMetaProperty': function(ast, comp, e){
    var key = ast.key.value;
    var val = e('nil');
    if(key === 'shares'){
      val = e('arr', _.map(ast.value.ids, function(id){
        return e('str', id.value, id.loc);
      }));
    }else if(ast.value.type === 'String'){
      val = e('string', ast.value.value, ast.value.loc);
    }else if(ast.value.type === 'Chevron'){
      val = e('string', ast.value.value[0].value, ast.value.value[0].loc);
    }else if(ast.value.type === 'Boolean'){
      val = e(ast.value.value ? 'true' : 'false', ast.value.loc);
    }
    return e('obj-prop', e('str', key, ast.key.loc), val);
  },
  'Rule': function(ast, comp, e){
    var rule = {
      name: e('string', ast.name.value, ast.name.loc)
    };
    if(ast.rule_state !== 'active'){
      rule.rule_state = e('string', ast.rule_state);
    }
    if(ast.select){
      rule.select = comp(ast.select);
    }
    if(!_.isEmpty(ast.prelude)){
      rule.prelude = e('fn', ['ctx'], comp(ast.prelude));
    }
    if(ast.action_block){
      rule.action_block = comp(ast.action_block);
    }
    if(ast.postlude){
      rule.postlude = comp(ast.postlude);
    }
    return e('obj', rule);
  },
  'RuleSelect': require('./c/RuleSelect'),
  'EventExpression': require('./c/EventExpression'),
  'RuleActionBlock': function(ast, comp, e){
    var block = {};
    //TODO "condition": COND,
    //TODO "block_type": "choose",
    block.actions = e('arr', _.map(ast.actions, function(action){
      return comp(action);
    }));
    return e('obj', block);
  },
  'RuleAction': function(ast, comp, e){
    var fn_body = [];
    fn_body.push(e('return', e('obj', {
      type: e('str', 'directive'),
      name: e('str', ast.args[0].value),
      options: e('obj', _.fromPairs(_.map(ast['with'], function(dec){
        return [dec.left.value, comp(dec.right)];
      })))
    })));
    return e('fn', ['ctx'], fn_body);
  },
  'RulePostlude': require('./c/RulePostlude')
};

var isKRL_loc = function(loc){
  return _.isPlainObject(loc) && _.has(loc, 'start') && _.has(loc, 'end');
};

module.exports = function(ast, options){
  options = options || {};

  var toLoc = options.toLoc || _.noop;

  var mkE = function(default_krl_loc){
    var default_loc = toLoc(default_krl_loc.start, default_krl_loc.end);

    return function(){
      var args = Array.prototype.slice.call(arguments);
      var last_i = args.length - 1;
      var last = args[last_i];
      if(isKRL_loc(last)){
        args[last_i] = toLoc(last.start, last.end);
      }else{
        args.push(default_loc);
      }
      return mkTree.apply(null, args);
    };
  };

  var compile = function compile(ast){
    if(_.isArray(ast)){
      return _.map(ast, function(a){
        return compile(a);
      });
    }else if(!_.has(ast, 'type')){
      throw new Error('Invalid ast node: ' + JSON.stringify(ast));
    }else if(!_.has(comp_by_type, ast.type)){
      throw new Error('Unsupported ast node type: ' + ast.type);
    }
    return comp_by_type[ast.type](ast, compile, mkE(ast.loc));
  };

  return compile(ast, 0);
};
<|endoftext|>


<commit_before>/*
 * ***** BEGIN LICENSE BLOCK *****
 * OpenPGP Zimbra Secure is the open source digital signature and encrypt for Zimbra Collaboration Open Source Edition software
 * Copyright (C) 2016-present OpenPGP Zimbra Secure

 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>
 * ***** END LICENSE BLOCK *****
 *
 * OpenPGP MIME Secure Email Zimlet
 *
 * Written by nguyennv1981@gmail.com
 */

OpenPGPSecureKeyStore = function(handler) {
    this._handler = handler;
    this._fingerprints = [];
    this._addCallbacks = [];
    this._removeCallbacks = [];
    this._userId = this._handler.getUserID();

    this.passphrase = '';
    this.privateKey = false;
    this.publicKey = false;
    this.publicKeys = [];
};

OpenPGPSecureKeyStore.ADD_CALLBACK = 'add';
OpenPGPSecureKeyStore.REMOVE_CALLBACK = 'remove';

OpenPGPSecureKeyStore.prototype = new Object();
OpenPGPSecureKeyStore.prototype.constructor = OpenPGPSecureKeyStore;

OpenPGPSecureKeyStore.prototype.init = function() {
    var self = this;
    var pgpKey = openpgp.key;

    var sequence = Promise.resolve();
    return sequence.then(function() {
        var publicKeys = [];
        if (localStorage['openpgp_secure_public_keys_' + self._userId]) {
            publicKeys = JSON.parse(localStorage['openpgp_secure_public_keys_' + self._userId]);
        }

        publicKeys.forEach(function(armoredKey) {
            var pubKey = pgpKey.readArmored(armoredKey);
            pubKey.keys.forEach(function(key) {
                var fingerprint = key.primaryKey.fingerprint;
                if (!self._fingerprints[fingerprint]) {
                    self.publicKeys.push(key);
                    self._fingerprints[fingerprint] = fingerprint;
                }
            });
        });

        if (localStorage['openpgp_secure_public_key_' + self._userId]) {
            var publicKey = localStorage['openpgp_secure_public_key_' + self._userId];
            self.setPublicKey(publicKey);
        }
        return self;
    })
    .then(function() {
        return OpenPGPUtils.localStorageRead(
            'openpgp_secure_passphrase_' + self._userId,
            self._handler.getSecurePassword()
        )
        .then(function(passphrase) {
            return passphrase;
        });
    })
    .then(function(passphrase) {
        if (passphrase) {
            return OpenPGPUtils.localStorageRead(
                'openpgp_secure_private_key_' + self._userId,
                self._handler.getSecurePassword()
            )
            .then(function(privateKey) {
                if (privateKey) {
                    var privKey = pgpKey.readArmored(privateKey);
                    privKey.keys.forEach(function(key) {
                        if (key.decrypt(passphrase)) {
                            self.privateKey = key;
                            self.passphrase = passphrase;
                        }
                        else {
                            throw new Error(self._handler.getMessage('decryptPrivateKeyError'));
                        }
                    });
                }
                return privateKey;
            });
        }
        else {
            return self.privateKey;
        }
    });
};

OpenPGPSecureKeyStore.prototype.addPublicKey = function(key) {
    var self = this;
    var added = false;

    var fingerprint = key.primaryKey.fingerprint;
    if (!self._fingerprints[fingerprint]) {
        self._fingerprints[fingerprint] = fingerprint;
        self.publicKeys.push(key);
        added = true;
    }

    if (added) {
        this._addCallbacks.forEach(function(callback) {
            callback.run(key);
        });
        this._storePublicKeys();
    }
};

OpenPGPSecureKeyStore.prototype.removePublicKey = function(fingerprint) {
    var self = this;
    var removed = false;
    this.publicKeys.forEach(function(key, index) {
        if (fingerprint == key.primaryKey.fingerprint) {
            self.publicKeys.splice(index, 1);
            delete self._fingerprints[fingerprint];
            removed = true;
        }
    });

    if (removed) {
        this._removeCallbacks.forEach(function(callback) {
            callback.run(fingerprint);
        });
        this._storePublicKeys();
    }
};

OpenPGPSecureKeyStore.prototype.addCallback = function(callback, type) {
    if (type === OpenPGPSecureKeyStore.REMOVE_CALLBACK) {
        this._removeCallbacks.push(callback);
    }
    else {
        this._addCallbacks.push(callback);
    }
};

OpenPGPSecureKeyStore.prototype.getPassphrase = function() {
    return this.passphrase;
};

OpenPGPSecureKeyStore.prototype.getPrivateKey = function() {
    return this.privateKey;
};

OpenPGPSecureKeyStore.prototype.setPrivateKey = function(privateKey, passphrase) {
    var self = this;
    var privKey = openpgp.key.readArmored(privateKey);
    privKey.keys.forEach(function(key) {
        if (key.decrypt(passphrase)) {
            self.privateKey = key;
            self.passphrase = passphrase;

            OpenPGPUtils.localStorageSave(
                'openpgp_secure_private_key_' + self._userId,
                self._handler.getSecurePassword(),
                privateKey
            );
            OpenPGPUtils.localStorageSave(
                'openpgp_secure_passphrase_' + self._userId,
                self._handler.getSecurePassword(),
                passphrase
            );
        }
        else {
            throw new Error(this._handler.getMessage('decryptPrivateKeyError'));
        }
    });
};

OpenPGPSecureKeyStore.prototype.getPublicKeys = function() {
    return this.publicKeys;
};

OpenPGPSecureKeyStore.prototype.getPublicKey = function() {
    return this.publicKey;
};

OpenPGPSecureKeyStore.prototype.setPublicKey = function(publicKey) {
    var self = this;
    var pubKey = openpgp.key.readArmored(publicKey);
    pubKey.keys.forEach(function(key) {
        self.publicKey = key;
        localStorage['openpgp_secure_public_key_' + self._userId] = self.publicKey.armor();
        self.addPublicKey(self.publicKey);
    });
};

OpenPGPSecureKeyStore.prototype.havingPublicKeys = function(addresses) {
    var dupes = [];
    var publicKeys = [];
    this.publicKeys.forEach(function(key) {
        addresses.foreach(function(address) {
            for (i = 0; i < key.users.length; i++) {
                var uid = key.users[i].userId.userid;
                var fingerprint = key.primaryKey.fingerprint;
                if (uid.indexOf(address) >= 0 && !dupes[fingerprint + uid]) {
                    publicKeys.push(key);
                    dupes[fingerprint + uid] = fingerprint + uid;
                }
            }
        });
    });
    return publicKeys;
};

OpenPGPSecureKeyStore.prototype.publicKeyMissing = function(addresses) {
    var uidAddresses = [];
    this.publicKeys.forEach(function(key) {
        for (i = 0; i < key.users.length; i++) {
            var addr = AjxEmailAddress.parse(key.users[i].userId.userid);
            if (addr) {
                uidAddresses[addr.getAddress()] = addr.getAddress();
            }
        }
    });

    var missing = [];
    addresses.forEach(function(address) {
        if (!uidAddresses[address]) {
            missing.push(address);
        }
    });
    return missing;
}

OpenPGPSecureKeyStore.prototype.publicKeyExisted = function(fingerprint) {
    return this._fingerprints[fingerprint] ? true : false;
}

OpenPGPSecureKeyStore.keyInfo = function(key) {
    var uids = [];
    key.users.forEach(function(user) {
        uids.push(AjxStringUtil.htmlEncode(user.userId.userid));
    });
    var priKey = key.primaryKey;
    var keyLength = '';
    if (priKey.mpi.length > 0) {
        keyLength = (priKey.mpi[0].byteLength() * 8);
    }
    return {
        value: key.armor(),
        uids: uids,
        fingerprint: priKey.fingerprint,
        keyid: priKey.keyid.toHex(),
        algorithm: priKey.algorithm,
        keyLength: keyLength,
        created: priKey.created
    };
}

OpenPGPSecureKeyStore.prototype._storePublicKeys = function() {
    var publicKeys = [];
    this.publicKeys.forEach(function(key) {
        publicKeys.push(key.armor());
    });
    var storeKey = 'openpgp_secure_public_keys_' + this._userId;
    localStorage[storeKey] = JSON.stringify(publicKeys);
};
<commit_msg>Refactor key store<commit_after>/*
 * ***** BEGIN LICENSE BLOCK *****
 * OpenPGP Zimbra Secure is the open source digital signature and encrypt for Zimbra Collaboration Open Source Edition software
 * Copyright (C) 2016-present OpenPGP Zimbra Secure

 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>
 * ***** END LICENSE BLOCK *****
 *
 * OpenPGP MIME Secure Email Zimlet
 *
 * Written by nguyennv1981@gmail.com
 */

OpenPGPSecureKeyStore = function(handler) {
    this._handler = handler;
    this._fingerprints = [];
    this._addCallbacks = [];
    this._removeCallbacks = [];
    this._userId = this._handler.getUserID();

    this.passphrase = '';
    this.privateKey = false;
    this.publicKey = false;
    this.publicKeys = [];
};

OpenPGPSecureKeyStore.ADD_CALLBACK = 'add';
OpenPGPSecureKeyStore.REMOVE_CALLBACK = 'remove';

OpenPGPSecureKeyStore.prototype = new Object();
OpenPGPSecureKeyStore.prototype.constructor = OpenPGPSecureKeyStore;

OpenPGPSecureKeyStore.prototype.init = function() {
    var self = this;
    var pgpKey = openpgp.key;

    var sequence = Promise.resolve();
    return sequence.then(function() {
        self.setPublicKeys(self._readPublicKeys());

        if (localStorage['openpgp_secure_public_key_' + self._userId]) {
            var publicKey = localStorage['openpgp_secure_public_key_' + self._userId];
            self.setPublicKey(publicKey);
        }
        return self;
    })
    .then(function() {
        return OpenPGPUtils.localStorageRead(
            'openpgp_secure_passphrase_' + self._userId,
            self._handler.getSecurePassword()
        )
        .then(function(passphrase) {
            return passphrase;
        });
    })
    .then(function(passphrase) {
        if (passphrase) {
            return OpenPGPUtils.localStorageRead(
                'openpgp_secure_private_key_' + self._userId,
                self._handler.getSecurePassword()
            )
            .then(function(privateKey) {
                if (privateKey) {
                    var privKey = pgpKey.readArmored(privateKey);
                    privKey.keys.forEach(function(key) {
                        if (key.decrypt(passphrase)) {
                            self.privateKey = key;
                            self.passphrase = passphrase;
                        }
                        else {
                            throw new Error(self._handler.getMessage('decryptPrivateKeyError'));
                        }
                    });
                }
                return privateKey;
            });
        }
        else {
            return self.privateKey;
        }
    });
};

OpenPGPSecureKeyStore.prototype.addPublicKey = function(key) {
    var self = this;
    var added = false;

    var fingerprint = key.primaryKey.fingerprint;
    if (!self._fingerprints[fingerprint]) {
        self._fingerprints[fingerprint] = fingerprint;
        self.publicKeys.push(key);
        added = true;
    }

    if (added) {
        this._addCallbacks.forEach(function(callback) {
            callback.run(key);
        });
        this._storePublicKeys();
    }
};

OpenPGPSecureKeyStore.prototype.removePublicKey = function(fingerprint) {
    var self = this;
    var removed = false;
    this.publicKeys.forEach(function(key, index) {
        if (fingerprint == key.primaryKey.fingerprint) {
            self.publicKeys.splice(index, 1);
            delete self._fingerprints[fingerprint];
            removed = true;
        }
    });

    if (removed) {
        this._removeCallbacks.forEach(function(callback) {
            callback.run(fingerprint);
        });
        this._storePublicKeys();
    }
};

OpenPGPSecureKeyStore.prototype.addCallback = function(callback, type) {
    if (type === OpenPGPSecureKeyStore.REMOVE_CALLBACK) {
        this._removeCallbacks.push(callback);
    }
    else {
        this._addCallbacks.push(callback);
    }
};

OpenPGPSecureKeyStore.prototype.getPassphrase = function() {
    return this.passphrase;
};

OpenPGPSecureKeyStore.prototype.getPrivateKey = function() {
    return this.privateKey;
};

OpenPGPSecureKeyStore.prototype.setPrivateKey = function(privateKey, passphrase) {
    var self = this;
    var privKey = openpgp.key.readArmored(privateKey);
    privKey.keys.forEach(function(key) {
        if (key.decrypt(passphrase)) {
            self.privateKey = key;
            self.passphrase = passphrase;

            OpenPGPUtils.localStorageSave(
                'openpgp_secure_private_key_' + self._userId,
                self._handler.getSecurePassword(),
                privateKey
            );
            OpenPGPUtils.localStorageSave(
                'openpgp_secure_passphrase_' + self._userId,
                self._handler.getSecurePassword(),
                passphrase
            );
        }
        else {
            throw new Error(this._handler.getMessage('decryptPrivateKeyError'));
        }
    });
    return this;
};

OpenPGPSecureKeyStore.prototype.getPublicKey = function() {
    return this.publicKey;
};

OpenPGPSecureKeyStore.prototype.setPublicKey = function(publicKey) {
    var self = this;
    var pubKey = openpgp.key.readArmored(publicKey);
    pubKey.keys.forEach(function(key) {
        self.publicKey = key;
        localStorage['openpgp_secure_public_key_' + self._userId] = self.publicKey.armor();
        self.addPublicKey(self.publicKey);
    });
    return this;
};

OpenPGPSecureKeyStore.prototype.getPublicKeys = function() {
    return this.publicKeys;
};

OpenPGPSecureKeyStore.prototype.setPublicKeys = function(publicKeys) {
    var self = this;
    publicKeys.forEach(function(armoredKey) {
        var pubKey = pgpKey.readArmored(armoredKey);
        pubKey.keys.forEach(function(key) {
            var fingerprint = key.primaryKey.fingerprint;
            if (!self._fingerprints[fingerprint]) {
                self.publicKeys.push(key);
                self._fingerprints[fingerprint] = fingerprint;
            }
        });
    });
    return this;
};

OpenPGPSecureKeyStore.prototype.havingPublicKeys = function(addresses) {
    var dupes = [];
    var publicKeys = [];
    this.publicKeys.forEach(function(key) {
        addresses.foreach(function(address) {
            for (i = 0; i < key.users.length; i++) {
                var uid = key.users[i].userId.userid;
                var fingerprint = key.primaryKey.fingerprint;
                if (uid.indexOf(address) >= 0 && !dupes[fingerprint + uid]) {
                    publicKeys.push(key);
                    dupes[fingerprint + uid] = fingerprint + uid;
                }
            }
        });
    });
    return publicKeys;
};

OpenPGPSecureKeyStore.prototype.publicKeyMissing = function(addresses) {
    var uidAddresses = [];
    this.publicKeys.forEach(function(key) {
        for (i = 0; i < key.users.length; i++) {
            var addr = AjxEmailAddress.parse(key.users[i].userId.userid);
            if (addr) {
                uidAddresses[addr.getAddress()] = addr.getAddress();
            }
        }
    });

    var missing = [];
    addresses.forEach(function(address) {
        if (!uidAddresses[address]) {
            missing.push(address);
        }
    });
    return missing;
}

OpenPGPSecureKeyStore.prototype.publicKeyExisted = function(fingerprint) {
    return this._fingerprints[fingerprint] ? true : false;
}

OpenPGPSecureKeyStore.keyInfo = function(key) {
    var uids = [];
    key.users.forEach(function(user) {
        uids.push(AjxStringUtil.htmlEncode(user.userId.userid));
    });
    var priKey = key.primaryKey;
    var keyLength = '';
    if (priKey.mpi.length > 0) {
        keyLength = (priKey.mpi[0].byteLength() * 8);
    }
    return {
        value: key.armor(),
        uids: uids,
        fingerprint: priKey.fingerprint,
        keyid: priKey.keyid.toHex(),
        algorithm: priKey.algorithm,
        keyLength: keyLength,
        created: priKey.created
    };
}

OpenPGPSecureKeyStore.prototype._readPublicKeys = function() {
    var publicKeys = [];
    var storeKey = 'openpgp_secure_public_keys_' + this._userId;
    if (localStorage[storeKey]) {
        publicKeys = JSON.parse(localStorage[storeKey]);
    }
}

OpenPGPSecureKeyStore.prototype._storePublicKeys = function() {
    var publicKeys = [];
    this.publicKeys.forEach(function(key) {
        publicKeys.push(key.armor());
    });
    var storeKey = 'openpgp_secure_public_keys_' + this._userId;
    localStorage[storeKey] = JSON.stringify(publicKeys);
};
<|endoftext|>


<commit_before>"use strict";

var WebGMEGlobal = { 'version': 'x',    //will be set from Node's package.json
    'SUPPORTS_TOUCH': 'ontouchstart' in window || navigator.msMaxTouchPoints }; //touch device detection}

// let require load all the toplevel needed script and call us on domReady
define(['logManager',
    'bin/getconfig',
    'text!package.json',
    'js/client',
    'clientUtil',
    'js/Utils/GMEConcepts',
    'js/Utils/GMEVisualConcepts',
    'js/Utils/ExportManager',
    'js/Utils/ImportManager',
    'js/LayoutManager/LayoutManager',
    'js/Decorators/DecoratorManager',
    'js/KeyboardManager/KeyboardManager',
    'js/PanelManager/PanelManager',
    './WebGME.History',
    'js/Utils/METAAspectHelper',
    'js/Utils/PreferencesHelper',
    'js/ConstraintManager/ConstraintManager'], function (logManager,
                                            CONFIG,
                                            packagejson,
                                            Client,
                                            util,
                                            GMEConcepts,
                                            GMEVisualConcepts,
                                            ExportManager,
                                            ImportManager,
                                            LayoutManager,
                                            DecoratorManager,
                                            KeyboardManager,
                                            PanelManager,
                                            WebGMEHistory,
                                            METAAspectHelper,
                                            PreferencesHelper,
                                            ConstraintManager) {

    var npmJSON = JSON.parse(packagejson);
    WebGMEGlobal.version = npmJSON.version;

    var _webGMEStart = function () {
        var lm,
            client,
            loadPanels,
            layoutToLoad = util.getURLParameterByName('layout') || 'DefaultLayout',
            commitToLoad = util.getURLParameterByName('commit').toLowerCase(),
            projectToLoad = util.getURLParameterByName('project'),
            objectToLoad = util.getURLParameterByName('obj').toLowerCase(),
            logger = logManager.create('WebGME'),
            selectObject;

        lm = new LayoutManager();
        lm.loadLayout(layoutToLoad, function () {
            var panels = [],
                layoutPanels = lm._currentLayout.panels,
                len = layoutPanels ? layoutPanels.length : 0,
                i;

            client = new Client(CONFIG);

            WebGMEGlobal.ConstraintManager = new ConstraintManager(client);

            WebGMEHistory.setClient(client);

            GMEConcepts.initialize(client);
            GMEVisualConcepts.initialize(client);

            METAAspectHelper.initialize(client);
            PreferencesHelper.initialize(client);

            ExportManager.initialize(client);
            ImportManager.initialize(client);

            //hook up branch changed to set read-only mode on panels
            client.addEventListener(client.events.BRANCH_CHANGED, function (__project, branchName) {
                lm.setPanelReadOnly(client.isCommitReadOnly() || client.isProjectReadOnly());
            });
            client.addEventListener(client.events.PROJECT_OPENED, function (__project, projectName) {
                lm.setPanelReadOnly(client.isProjectReadOnly());
            });

            client.decoratorManager = new DecoratorManager();

            for (i = 0; i < len; i += 1) {
                panels.push({'panel': layoutPanels[i].panel,
                    'container': layoutPanels[i].container,
                    'control': layoutPanels[i].control,
                    'params' : {'client': client}});
            }

            //load the panels
            loadPanels(panels);

            //as of now it's a global variable just to make access to it easier
            //TODO: might need to be changed
            WebGMEGlobal.KeyboardManager = KeyboardManager;
            WebGMEGlobal.KeyboardManager.setEnabled(true);
            WebGMEGlobal.PanelManager = new PanelManager();
        });

        loadPanels = function (panels) {
            var p = panels.splice(0, 1)[0];

            lm.loadPanel(p, function () {
                if (panels.length > 0) {
                    loadPanels(panels);
                } else {
                    client.connectToDatabaseAsync({'open': true,
                                                    'project': projectToLoad || CONFIG.project}, function (err) {
                        if (err) {
                            logger.error(err);
                        } else {
                            if (commitToLoad && commitToLoad !== "") {
                                client.selectCommitAsync(commitToLoad, function (err) {
                                    if (err) {
                                        logger.error(err);
                                    } else {
                                        selectObject();
                                    }
                                });
                            } else {
                                selectObject();
                            }
                        }
                    });
                }
            });
        };

        selectObject = function () {
            if (objectToLoad && objectToLoad !== "") {
                setTimeout(function () {
                    client.setSelectedObjectId(objectToLoad);
                }, 1000);
            }
        };
    };

    return {
        start : _webGMEStart
    };
});<commit_msg>load root object if it says in the URL 'root'<commit_after>"use strict";

var WebGMEGlobal = { 'version': 'x',    //will be set from Node's package.json
    'SUPPORTS_TOUCH': 'ontouchstart' in window || navigator.msMaxTouchPoints }; //touch device detection}

// let require load all the toplevel needed script and call us on domReady
define(['logManager',
    'bin/getconfig',
    'text!package.json',
    'js/client',
    'js/Constants',
    'clientUtil',
    'js/Utils/GMEConcepts',
    'js/Utils/GMEVisualConcepts',
    'js/Utils/ExportManager',
    'js/Utils/ImportManager',
    'js/LayoutManager/LayoutManager',
    'js/Decorators/DecoratorManager',
    'js/KeyboardManager/KeyboardManager',
    'js/PanelManager/PanelManager',
    './WebGME.History',
    'js/Utils/METAAspectHelper',
    'js/Utils/PreferencesHelper',
    'js/ConstraintManager/ConstraintManager'], function (logManager,
                                            CONFIG,
                                            packagejson,
                                            Client,
                                            CONSTANTS,
                                            util,
                                            GMEConcepts,
                                            GMEVisualConcepts,
                                            ExportManager,
                                            ImportManager,
                                            LayoutManager,
                                            DecoratorManager,
                                            KeyboardManager,
                                            PanelManager,
                                            WebGMEHistory,
                                            METAAspectHelper,
                                            PreferencesHelper,
                                            ConstraintManager) {

    var npmJSON = JSON.parse(packagejson);
    WebGMEGlobal.version = npmJSON.version;

    var _webGMEStart = function () {
        var lm,
            client,
            loadPanels,
            layoutToLoad = util.getURLParameterByName('layout') || 'DefaultLayout',
            commitToLoad = util.getURLParameterByName('commit').toLowerCase(),
            projectToLoad = util.getURLParameterByName('project'),
            objectToLoad = util.getURLParameterByName('obj').toLowerCase(),
            logger = logManager.create('WebGME'),
            selectObject;

        lm = new LayoutManager();
        lm.loadLayout(layoutToLoad, function () {
            var panels = [],
                layoutPanels = lm._currentLayout.panels,
                len = layoutPanels ? layoutPanels.length : 0,
                i;

            client = new Client(CONFIG);

            WebGMEGlobal.ConstraintManager = new ConstraintManager(client);

            WebGMEHistory.setClient(client);

            GMEConcepts.initialize(client);
            GMEVisualConcepts.initialize(client);

            METAAspectHelper.initialize(client);
            PreferencesHelper.initialize(client);

            ExportManager.initialize(client);
            ImportManager.initialize(client);

            //hook up branch changed to set read-only mode on panels
            client.addEventListener(client.events.BRANCH_CHANGED, function (__project, branchName) {
                lm.setPanelReadOnly(client.isCommitReadOnly() || client.isProjectReadOnly());
            });
            client.addEventListener(client.events.PROJECT_OPENED, function (__project, projectName) {
                lm.setPanelReadOnly(client.isProjectReadOnly());
            });

            client.decoratorManager = new DecoratorManager();

            for (i = 0; i < len; i += 1) {
                panels.push({'panel': layoutPanels[i].panel,
                    'container': layoutPanels[i].container,
                    'control': layoutPanels[i].control,
                    'params' : {'client': client}});
            }

            //load the panels
            loadPanels(panels);

            //as of now it's a global variable just to make access to it easier
            //TODO: might need to be changed
            WebGMEGlobal.KeyboardManager = KeyboardManager;
            WebGMEGlobal.KeyboardManager.setEnabled(true);
            WebGMEGlobal.PanelManager = new PanelManager();
        });

        loadPanels = function (panels) {
            var p = panels.splice(0, 1)[0];

            lm.loadPanel(p, function () {
                if (panels.length > 0) {
                    loadPanels(panels);
                } else {
                    client.connectToDatabaseAsync({'open': true,
                                                    'project': projectToLoad || CONFIG.project}, function (err) {
                        if (err) {
                            logger.error(err);
                        } else {
                            if (commitToLoad && commitToLoad !== "") {
                                client.selectCommitAsync(commitToLoad, function (err) {
                                    if (err) {
                                        logger.error(err);
                                    } else {
                                        selectObject();
                                    }
                                });
                            } else {
                                selectObject();
                            }
                        }
                    });
                }
            });
        };

        selectObject = function () {
            if (objectToLoad && objectToLoad !== "") {
                if (objectToLoad.toLowerCase() === 'root') {
                    objectToLoad = CONSTANTS.PROJECT_ROOT_ID;
                }
                setTimeout(function () {
                    client.setSelectedObjectId(objectToLoad);
                }, 1000);
            }
        };
    };

    return {
        start : _webGMEStart
    };
});<|endoftext|>


<commit_before>var bounceDisabler = function(){
	var module = {};

	var track = [];

	var velocity = {
		x: 0,
		y: 0
	};

	function handleTouchStart (evt){
		evt.preventDefault();
		var point,
			touch;

		touch = evt.changedTouches[0];
		point = {
			x: touch.clientX,
			y: touch.clientY,
			timeStamp: evt.timeStamp
		};
		track = [point];
	}

	function handleTouchMove (evt){
		var point,
			touch;

		touch = evt.changedTouches[0];
		point = {
			x: touch.clientX,
			y: touch.clientY,
			timeStamp: evt.timeStamp
		};
		track.push(point);
    doScroll();
	}

	function handleTouchEnd (evt){
		if(track.length > 2){
			velocity = calcVelocity();
		}
		console.log(velocity);
	}

	function calcVelocity(){
		var p1,
			p2,
			v,
			timeDiff,
			length;

		p1 = track[0];
		p2 = track[track.length-1];
		timeDiff = p2.timeStamp - p1.timeStamp;
		v = vector.subtraction(p2, p1);
		length = vector.length(v);
		vector.unit(v);
		vector.skalarMult(v, length / timeDiff * 4);
		return v;
	}

  function doScroll(){
    var p1,
        p2,
        x,
        y;
    if(track.length > 1){
      p1 = track[track.length -1];
      p2 = track[track.length -2];
      x = p2.x - p1.x;
      y = p2.y - p1.y;
      window.scrollBy(x, y);
    }
  }

	document.addEventListener("touchstart", handleTouchStart);
	document.addEventListener("touchmove", handleTouchMove);
	document.addEventListener("touchend", handleTouchEnd);
	document.addEventListener("touchcancel", handleTouchEnd);
	document.addEventListener("touchleave", handleTouchEnd);

	return module;
}();

<commit_msg>Scrolling continues now on touchend and uses a calculated velocity for scrolling.<commit_after>var bounceDisabler = function(){
	var module = {};

	var track = [];

	var velocity = {
		x: 0,
		y: 0
	};

  var requestAnimFrame = (function(){
      return  window.requestAnimationFrame       ||
              window.webkitRequestAnimationFrame ||
              window.mozRequestAnimationFrame    ||
              window.oRequestAnimationFrame      ||
              window.msRequestAnimationFrame     ||
              function( callback ){
                window.setTimeout(callback, 1000 / 60);
              };
    })();

	function handleTouchStart (evt){
		evt.preventDefault();
		var point,
			touch;

		touch = evt.changedTouches[0];
		point = {
			x: touch.clientX,
			y: touch.clientY,
			timeStamp: evt.timeStamp
		};
		track = [point];
	}

	function handleTouchMove (evt){
		var point,
			touch;

		touch = evt.changedTouches[0];
		point = {
			x: touch.clientX,
			y: touch.clientY,
			timeStamp: evt.timeStamp
		};
		track.push(point);
    doScroll();
	}

	function handleTouchEnd (evt){
		if(track.length > 2){
			velocity = calcVelocity();
		}
		console.log(velocity);
	}

	function calcVelocity(){
		var p1,
        p2,
        v,
        timeDiff,
        length;

		p1 = track[0];
		p2 = track[track.length-1];
		timeDiff = p2.timeStamp - p1.timeStamp;
		v = vector.subtraction(p2, p1);
		length = vector.length(v);
		vector.unit(v);
		vector.skalarMult(v, length / timeDiff * 20);
		return v;
	}

  function doScroll(){
    var p1,
        p2,
        x,
        y;

    if(track.length > 1){
      p1 = track[track.length -1];
      p2 = track[track.length -2];
      x = p2.x - p1.x;
      y = p2.y - p1.y;
      window.scrollBy(x, y);
    }
  }

  function render(){
      scrollBy(-velocity.x, -velocity.y);
      vector.skalarMult(velocity, 0.95);
  }

	document.addEventListener("touchstart", handleTouchStart);
	document.addEventListener("touchmove", handleTouchMove);
	document.addEventListener("touchend", handleTouchEnd);
	document.addEventListener("touchcancel", handleTouchEnd);
	document.addEventListener("touchleave", handleTouchEnd);

  (function animloop(){
			requestAnimFrame(animloop);
			render();
		})();

	return module;
}();

<|endoftext|>