<commit_before>import Modernizr from 'modernizr';
import React from 'react';
import ReactDOM from 'react-dom';
import {Button, Grid, Row, Col, Modal, Alert} from 'react-bootstrap';
import '../assets/css/main.css';
import SavegameParser from './savegame_parser';

import Spellbook from './components/Spellbook';
import CharacterProfile from './components/CharacterProfile';
import OutdatedBrowserWarning from './components/OutdatedBrowserWarning';

import './google_analytics';

const browserSupported = Modernizr.typedarrays && Modernizr.xhrresponsetypearraybuffer;

var FileInput = React.createClass({
	propTypes: {
		onChange: React.PropTypes.func.isRequired,
		onLoadExample: React.PropTypes.func.isRequired,
	},
	clear() {
		if(this.fileInput !== null){
			this.fileInput.value = null;
		}
	},
	render() {
		return (
			<fieldset>
				<legend>Select a savegame file</legend>
				<Row>
					<Col md={5}><input ref={(ref) => this.fileInput = ref} type='file' id='file' onChange={this.props.onChange} /></Col>
					<Col md={1}>or</Col>
					<Col md={5}><Button bsStyle="primary" onClick={this.props.onLoadExample}>Use example savegame</Button></Col>
				</Row>

Remember to backup your original savegame file.

			</fieldset>
		);
	}
});

var MainEditor = React.createClass({
	getInitialState() {
		return {spellBook: {}, showModal: false, modalText: '', validationMsg: ''};
	},
	informError(error) {
		let text = error.message;
		if(error instanceof RangeError){
			text = 'The file is not a valid Castle of the Winds savegame.';
		}
		this.refs.fileinput.clear();
		this.setState({showModal: true, modalText: text});
	},
	closeModal() {
		this.setState({showModal: false});
	},
	savefileSelected(e) {
		SavegameParser.parse(e.target.files[0], (state) => this.setState(state), this.informError);
	},
	downloadSavefile(e) {
		e.preventDefault();
		var form = document.getElementsByTagName('form')[0];
		if(form.checkValidity()){
			this.setState({validationMsg: ''});
			SavegameParser.write(this.state);
		} else {
			this.setState({validationMsg: 'All input fields should contain numbers'});
		}
	},
	handleChange(attribute, event) {
		this.setState({[attribute]: event.target.value});
	},
	handleSpellChange(spell, event) {
		//source: 2nd comment of http://stackoverflow.com/a/18934259
		this.setState({spellBook: { ...this.state.spellBook, [spell]: event.target.value}});
	},
	isLoaded() {
		return !!this.state.level;
	},
	loadExample(){
		var xhr = new XMLHttpRequest();
		xhr.open('GET', 'build/example.cwg');
		xhr.setRequestHeader('Content-Type', 'application/octet-stream');
		xhr.responseType = 'arraybuffer';
		xhr.onload = () => {
			if (xhr.status === 200) {
				this.refs.fileinput.clear();
				SavegameParser.parse(xhr.response, (state) => this.setState(state), this.informError);
			}else {
				alert('Error loading the example file. Returned status of ' + xhr.status);
			}
		};
		xhr.send();

	},
	render() {
		return (
			<Grid>
				<OutdatedBrowserWarning initialShow={!browserSupported}/>

Castle of the Winds Editor

					View on Github

				<FileInput ref="fileinput" onChange={this.savefileSelected} onLoadExample={this.loadExample}/>
				<form>
					<Row className={this.isLoaded() ? '' : 'hidden'}>
						<Col md={4}>
							<CharacterProfile
								str={this.state.str} int={this.state.int} con={this.state.con} dex={this.state.dex}
								hp={this.state.hp} maxHp={this.state.maxHp}
								mp={this.state.mp} maxMp={this.state.maxMp}
								exp={this.state.exp} armorClass={this.state.armorClass} level={this.state.level}
								bulk={this.state.bulk} maxBulk={this.state.maxBulk} name={this.state.name}
								weight={this.state.weight} maxWeight={this.state.maxWeight} gender={this.state.gender}
								handleChange={this.handleChange}
								/>
						</Col>
						<Col md={8}>
							<Spellbook spells={this.state.spellBook} handleChange={this.handleSpellChange}/>
						</Col>
					</Row>
					<fieldset className={this.isLoaded() ? '' : 'hidden'}>
						<legend>Download savegame file</legend>
						{ this.state.validationMsg !== '' ? <Alert bsStyle="danger">{this.state.validationMsg}</Alert> : '' }
						<Button type="submit" bsStyle="primary" disabled={!this.isLoaded()} onClick={this.downloadSavefile}>Download savegame</Button>
					</fieldset>
				</form>

				<Modal show={this.state.showModal} onHide={this.closeModal}>
					<Modal.Header closeButton>
						<Modal.Title>Error</Modal.Title>
					</Modal.Header>
					<Modal.Body>

Error reading file: {this.state.modalText}

					</Modal.Body>
					<Modal.Footer>
						<Button onClick={this.closeModal}>Close</Button>
					</Modal.Footer>
				</Modal>
			</Grid>
		);
	}
});

ReactDOM.render(<MainEditor />, document.getElementById('react-app'));<commit_msg>Filter .cwg files on file input<commit_after>import Modernizr from 'modernizr';
import React from 'react';
import ReactDOM from 'react-dom';
import {Button, Grid, Row, Col, Modal, Alert} from 'react-bootstrap';
import '../assets/css/main.css';
import SavegameParser from './savegame_parser';

import Spellbook from './components/Spellbook';
import CharacterProfile from './components/CharacterProfile';
import OutdatedBrowserWarning from './components/OutdatedBrowserWarning';

import './google_analytics';

const browserSupported = Modernizr.typedarrays && Modernizr.xhrresponsetypearraybuffer;

var FileInput = React.createClass({
	propTypes: {
		onChange: React.PropTypes.func.isRequired,
		onLoadExample: React.PropTypes.func.isRequired,
	},
	clear() {
		if(this.fileInput !== null){
			this.fileInput.value = null;
		}
	},
	render() {
		return (
			<fieldset>
				<legend>Select a savegame file</legend>
				<Row>
					<Col md={5}><input ref={(ref) => this.fileInput = ref} type='file' id='file' accept=".cwg" onChange={this.props.onChange} /></Col>
					<Col md={1}>or</Col>
					<Col md={5}><Button bsStyle="primary" onClick={this.props.onLoadExample}>Use example savegame</Button></Col>
				</Row>

Remember to backup your original savegame file.

			</fieldset>
		);
	}
});

var MainEditor = React.createClass({
	getInitialState() {
		return {spellBook: {}, showModal: false, modalText: '', validationMsg: ''};
	},
	informError(error) {
		let text = error.message;
		if(error instanceof RangeError){
			text = 'The file is not a valid Castle of the Winds savegame.';
		}
		this.refs.fileinput.clear();
		this.setState({showModal: true, modalText: text});
	},
	closeModal() {
		this.setState({showModal: false});
	},
	savefileSelected(e) {
		SavegameParser.parse(e.target.files[0], (state) => this.setState(state), this.informError);
	},
	downloadSavefile(e) {
		e.preventDefault();
		var form = document.getElementsByTagName('form')[0];
		if(form.checkValidity()){
			this.setState({validationMsg: ''});
			SavegameParser.write(this.state);
		} else {
			this.setState({validationMsg: 'All input fields should contain numbers'});
		}
	},
	handleChange(attribute, event) {
		this.setState({[attribute]: event.target.value});
	},
	handleSpellChange(spell, event) {
		//source: 2nd comment of http://stackoverflow.com/a/18934259
		this.setState({spellBook: { ...this.state.spellBook, [spell]: event.target.value}});
	},
	isLoaded() {
		return !!this.state.level;
	},
	loadExample(){
		var xhr = new XMLHttpRequest();
		xhr.open('GET', 'build/example.cwg');
		xhr.setRequestHeader('Content-Type', 'application/octet-stream');
		xhr.responseType = 'arraybuffer';
		xhr.onload = () => {
			if (xhr.status === 200) {
				this.refs.fileinput.clear();
				SavegameParser.parse(xhr.response, (state) => this.setState(state), this.informError);
			}else {
				alert('Error loading the example file. Returned status of ' + xhr.status);
			}
		};
		xhr.send();

	},
	render() {
		return (
			<Grid>
				<OutdatedBrowserWarning initialShow={!browserSupported}/>

Castle of the Winds Editor

					View on Github

				<FileInput ref="fileinput" onChange={this.savefileSelected} onLoadExample={this.loadExample}/>
				<form>
					<Row className={this.isLoaded() ? '' : 'hidden'}>
						<Col md={4}>
							<CharacterProfile
								str={this.state.str} int={this.state.int} con={this.state.con} dex={this.state.dex}
								hp={this.state.hp} maxHp={this.state.maxHp}
								mp={this.state.mp} maxMp={this.state.maxMp}
								exp={this.state.exp} armorClass={this.state.armorClass} level={this.state.level}
								bulk={this.state.bulk} maxBulk={this.state.maxBulk} name={this.state.name}
								weight={this.state.weight} maxWeight={this.state.maxWeight} gender={this.state.gender}
								handleChange={this.handleChange}
								/>
						</Col>
						<Col md={8}>
							<Spellbook spells={this.state.spellBook} handleChange={this.handleSpellChange}/>
						</Col>
					</Row>
					<fieldset className={this.isLoaded() ? '' : 'hidden'}>
						<legend>Download savegame file</legend>
						{ this.state.validationMsg !== '' ? <Alert bsStyle="danger">{this.state.validationMsg}</Alert> : '' }
						<Button type="submit" bsStyle="primary" disabled={!this.isLoaded()} onClick={this.downloadSavefile}>Download savegame</Button>
					</fieldset>
				</form>

				<Modal show={this.state.showModal} onHide={this.closeModal}>
					<Modal.Header closeButton>
						<Modal.Title>Error</Modal.Title>
					</Modal.Header>
					<Modal.Body>

Error reading file: {this.state.modalText}

					</Modal.Body>
					<Modal.Footer>
						<Button onClick={this.closeModal}>Close</Button>
					</Modal.Footer>
				</Modal>
			</Grid>
		);
	}
});

ReactDOM.render(<MainEditor />, document.getElementById('react-app'));<|endoftext|>


<commit_before>//MAIN
// Parameters optimized according to tests.
function writeMsgToCanvas(canvasid,msg,pass,mode){
    mode=(mode=== undefined)?0:parseInt(mode);
    switch (mode) {
        case 1: return writeMsgToCanvas_block(canvasid,msg,pass,5,4,350);
        case 2: return writeMsgToCanvas_single(canvasid,msg,pass,true,5,3,160);
        case 3: return writeMsgToCanvas_single(canvasid,msg,pass,true,5,2,80);
        case 4: return writeMsgToCanvas_single(canvasid,msg,pass,true,9,2,350);
        case 5: return writeMsgToCanvas_single(canvasid,msg,pass,true,3,3,1300);

        //case : return writeMsgToCanvas_AVG(canvasid,msg,pass,3,2,300); --FAIL
        case 0:
        default: return writeMsgToCanvas_single(canvasid,msg,pass);
    }
}

//Read msg from the image in canvasid.
//Return msg (null -> fail)
function readMsgFromCanvas(canvasid,pass,mode){
    mode=(mode=== undefined)?0:parseInt(mode);
    switch (mode) {
        case 1: return readMsgFromCanvas_block(canvasid,pass,5,4,350);
        case 2: return readMsgFromCanvas_single(canvasid,pass,true,5,3,160);
        case 3: return readMsgFromCanvas_single(canvasid,pass,true,5,2,80);
        case 4: return readMsgFromCanvas_single(canvasid,pass,true,9,2,350);
        case 5: return readMsgFromCanvas_single(canvasid,pass,true,3,3,1300);
        //case : return readMsgFromCanvas_AVG(canvasid,pass,3,2,300); --FAIL
        case 0:
        default: return readMsgFromCanvas_single(canvasid,pass);
    }
}

//load image from html5 input and execute callback() if successful
function loadIMGtoCanvas(inputid, canvasid, callback, maxsize) {
    maxsize=(maxsize=== undefined)?0:maxsize;
    var input = document.getElementById(inputid);
    if (input.files && input.files[0]) {
        var f = input.files[0];
        var reader = new FileReader();
        reader.onload = function(e) {
            var data = e.target.result;
            var image = new Image();
            image.onload = function() {
                var w=image.width;
                var h=image.height;
                if(maxsize>0){
                    if(w>maxsize){
                        h=h*(maxsize/w);
                        w=maxsize;
                    }
                    if(h>maxsize){
                        w=w*(maxsize/h);
                        h=maxsize;
                    }
                    w=Math.floor(w);
                    h=Math.floor(h);
                }
                var canvas = document.createElement('canvas');
                canvas.id = canvasid;
                canvas.width = w;
                canvas.height = h;
                canvas.style.display = "none";
                var body = document.getElementsByTagName("body")[0];
                body.appendChild(canvas);
                var context = canvas.getContext('2d');
                context.drawImage(image, 0, 0,image.width,image.height,0,0,w,h);
                callback();
                document.body.removeChild(canvas);
            };
            image.src = data;
        };
        reader.readAsDataURL(f);
    } else {
        alert('NO IMG FILE SELECTED');
        return 'ERROR PROCESSING IMAGE!';
    }
}<commit_msg>block write doesn't work, remove<commit_after>//MAIN
// Parameters optimized according to tests.
function writeMsgToCanvas(canvasid,msg,pass,mode){
    mode=(mode=== undefined)?0:parseInt(mode);
    switch (mode) {
        //case 1: return writeMsgToCanvas_block(canvasid,msg,pass,5,4,350); -NOT WORKING WELL
        case 1: return writeMsgToCanvas_single(canvasid,msg,pass,true,19,3,160);
        case 2: return writeMsgToCanvas_single(canvasid,msg,pass,true,5,3,160);
        case 3: return writeMsgToCanvas_single(canvasid,msg,pass,true,5,2,80);
        case 4: return writeMsgToCanvas_single(canvasid,msg,pass,true,9,2,350);
        case 5: return writeMsgToCanvas_single(canvasid,msg,pass,true,3,3,1300);

        //case : return writeMsgToCanvas_AVG(canvasid,msg,pass,3,2,300); --FAIL
        case 0:
        default: return writeMsgToCanvas_single(canvasid,msg,pass);
    }
}

//Read msg from the image in canvasid.
//Return msg (null -> fail)
function readMsgFromCanvas(canvasid,pass,mode){
    mode=(mode=== undefined)?0:parseInt(mode);
    switch (mode) {
        //case 1: return readMsgFromCanvas_block(canvasid,pass,5,4,350); -NOT WORKING WELL
        case 1: return readMsgFromCanvas_single(canvasid,pass,true,19,3,160);
        case 2: return readMsgFromCanvas_single(canvasid,pass,true,5,3,160);
        case 3: return readMsgFromCanvas_single(canvasid,pass,true,5,2,80);
        case 4: return readMsgFromCanvas_single(canvasid,pass,true,9,2,350);
        case 5: return readMsgFromCanvas_single(canvasid,pass,true,3,3,1300);
        //case : return readMsgFromCanvas_AVG(canvasid,pass,3,2,300); --FAIL
        case 0:
        default: return readMsgFromCanvas_single(canvasid,pass);
    }
}

//load image from html5 input and execute callback() if successful
function loadIMGtoCanvas(inputid, canvasid, callback, maxsize) {
    maxsize=(maxsize=== undefined)?0:maxsize;
    var input = document.getElementById(inputid);
    if (input.files && input.files[0]) {
        var f = input.files[0];
        var reader = new FileReader();
        reader.onload = function(e) {
            var data = e.target.result;
            var image = new Image();
            image.onload = function() {
                var w=image.width;
                var h=image.height;
                if(maxsize>0){
                    if(w>maxsize){
                        h=h*(maxsize/w);
                        w=maxsize;
                    }
                    if(h>maxsize){
                        w=w*(maxsize/h);
                        h=maxsize;
                    }
                    w=Math.floor(w);
                    h=Math.floor(h);
                }
                var canvas = document.createElement('canvas');
                canvas.id = canvasid;
                canvas.width = w;
                canvas.height = h;
                canvas.style.display = "none";
                var body = document.getElementsByTagName("body")[0];
                body.appendChild(canvas);
                var context = canvas.getContext('2d');
                context.drawImage(image, 0, 0,image.width,image.height,0,0,w,h);
                callback();
                document.body.removeChild(canvas);
            };
            image.src = data;
        };
        reader.readAsDataURL(f);
    } else {
        alert('NO IMG FILE SELECTED');
        return 'ERROR PROCESSING IMAGE!';
    }
}<|endoftext|>


<commit_before>
var game = new Phaser.Game(window.screen.width, window.screen.height, Phaser.AUTO, '', {
    preload: preload,
    create: create,
    update: update
});

var player;
var backgroundTileSprite;

var ACCLERATION = 900;
var DRAG = 400;
var MAXSPEED = 400;
var BASE_TEXTURE_ROTATION = 90 * (Math.PI/180);

function preload() {
    game.load.image('background', 'assets/background/background2.jpg');
    game.load.image('player', 'assets/ship.png');
}

function create() {
    game.physics.startSystem(Phaser.Physics.ARCADE);

    //  Resize our game world to be a 2000 x 2000 square
    game.world.setBounds(-1000, -1000, 2000, 2000);
    backgroundTileSprite = game.add.tileSprite(0, 0, game.width, game.height, 'background');
    backgroundTileSprite.fixedToCamera = true;

    // Player stuff
    player = game.add.sprite(0, 0, 'player');
    player.anchor.setTo(0.5, 0.5);
    player.scale.x = 0.3;
    player.scale.y = 0.3;
    game.physics.enable(player, Phaser.Physics.ARCADE);
    player.body.maxVelocity.setTo(MAXSPEED, MAXSPEED);
    player.body.drag.setTo(DRAG, DRAG);
    player.body.collideWorldBounds = true;

    cursors = game.input.keyboard.createCursorKeys();

    game.camera.follow(player);
    game.camera.deadzone = new Phaser.Rectangle(150, 150, 500, 300);
    game.camera.focusOnXY(0, 0);
}

function update() {
    backgroundTileSprite.tilePosition.x = -game.camera.x;
    backgroundTileSprite.tilePosition.y = -game.camera.y;

    if (cursors.left.isDown)
    {
        //backgroundTileSprite.tilePosition.x += 8;
        //player.body.rotation -= 3;
        player.body.angularVelocity = -250;
    }
    else if (cursors.right.isDown)
    {
        //backgroundTileSprite.tilePosition.x -= 8;
        //player.body.rotation += 3;
        player.body.angularVelocity = 250;
    } else {
        player.body.angularVelocity = 0;
    }

    if (cursors.up.isDown)
    {
        //backgroundTileSprite.tilePosition.y += 8;
        //var acceleration = game.physics.arcade.accelerationFromRotation(player.body.rotation, ACCLERATION, player.acceleration);
        game.physics.arcade.accelerationFromRotation(player.rotation - BASE_TEXTURE_ROTATION, ACCLERATION, player.body.acceleration);
    } else {
        player.body.acceleration.set(0);
    }
}<commit_msg>Minor cleanup<commit_after>
var game = new Phaser.Game(window.screen.width, window.screen.height, Phaser.AUTO, '', {
    preload: preload,
    create: create,
    update: update
});

var player;
var backgroundTileSprite;

var ACCLERATION = 900;
var DRAG = 400;
var MAXSPEED = 400;
var BASE_TEXTURE_ROTATION = 90 * (Math.PI/180);

function preload() {
    game.load.image('background', 'assets/background/background2.jpg');
    game.load.image('player', 'assets/ship.png');
}

function create() {
    game.physics.startSystem(Phaser.Physics.ARCADE);

    //  Resize our game world to be a 2000 x 2000 square
    game.world.setBounds(-1000, -1000, 2000, 2000);
    backgroundTileSprite = game.add.tileSprite(0, 0, game.width, game.height, 'background');
    backgroundTileSprite.fixedToCamera = true;

    // Player stuff
    player = game.add.sprite(0, 0, 'player');
    player.anchor.setTo(0.5, 0.5);
    player.scale.x = 0.3;
    player.scale.y = 0.3;
    game.physics.enable(player, Phaser.Physics.ARCADE);
    player.body.maxVelocity.setTo(MAXSPEED, MAXSPEED);
    player.body.drag.setTo(DRAG, DRAG);
    player.body.collideWorldBounds = true;

    cursors = game.input.keyboard.createCursorKeys();

    game.camera.follow(player);
    game.camera.deadzone = new Phaser.Rectangle(150, 150, 500, 300);
    game.camera.focusOnXY(0, 0);
}

function update() {
    backgroundTileSprite.tilePosition.x = -game.camera.x;
    backgroundTileSprite.tilePosition.y = -game.camera.y;

    if (cursors.left.isDown)
    {
        player.body.angularVelocity = -250;
    }
    else if (cursors.right.isDown)
    {
        player.body.angularVelocity = 250;
    } else {
        player.body.angularVelocity = 0;
    }

    if (cursors.up.isDown)
    {
        game.physics.arcade.accelerationFromRotation(player.rotation - BASE_TEXTURE_ROTATION, ACCLERATION, player.body.acceleration);
    } else {
        player.body.acceleration.set(0);
    }
}<|endoftext|>


<commit_before>/**
 * Created by Thomas on 1/25/14.
 */

// Initialization functions
loadFiles();

window.onload=function(){
    setTimeout(function(){mainPhaser()}, 3000);
};

// JS file preloader
function loadFiles(){
    var head = document.getElementsByTagName("head")[0];
    for( var i=0; i<files.length; i++ ){
        var js = document.createElement("script");
        js.type = "text/javascript";
        js.src = "src/"+files[i];
        head.appendChild(js);
    }
}

function mainPhaser(){
    var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'gameCanvas', { preload: preload, create: create, update: update, render: render });
    var map;
    var camera;
    var player,inputsKeyboard, inputsMouse;

    function preload() {
        game.load.image('h_red','img/h_red.png');
        game.load.image('w_red','img/wave_red.png')
        map = createMap(game);
    }

    function create() {
        player = new Player('red',game);
        player.setSprite(game.add.sprite(200,200,'h_red'));

        game.camera.follow(player.sprite);

//        var stream = new Stream(45, 10, 100, 500, 10);
//        stream.create(game);
        var a = new Obstacle(game, 400, 400, "w_red", COLORS.RED);

        inputsKeyboard = game.input.keyboard.createCursorKeys(); // bind the keyboard/mouse to inputs
        inputsMouse = game.input.mousePointer; // bind the keyboard/mouse to inputsb
        player.sonar(game,map.obstacles);
    }

    function update () {
<<<<<<< HEAD
        //player.checkSector(map.getSectors());
=======
        // player.checkSector(map.getSectors());
>>>>>>> 97b41760aa169c3e39dfeeae9e45bc3f029e059e
        player.moveK(inputsKeyboard);
        player.moveM(inputsMouse);

        // game.physics.collide(player, this.box, collideHandler, null, this);

        // check for collision over the player's sonar
        game.physics.collide(player.sonarPts,map.obstacles,function(pt,ob){
            pt.body.velocity = new Phaser.Point(0,0); //  we stop the point
            pt.lifespan = pt.lifespan + Math.random()*100; // add a little delay
        });

        game.physics.collide(player.sprite,map.obstacles,function(){});
    }

    function collideHandler() {
        console.log("coucou");
    }

    function render (){
        // map.obstacles.forEachAlive(function(ob){
        //     // console.log(ob);
        //    game.debug.renderRectangle(ob,'#022ff22');
        // },this)
        // // console.log(map.obstacles);
        // // for(var i = 0; i < map.obstacles.lenght; ++i){
        // //     console.log(i);
        // // }

        var m = map.getObstacles();

//         console.log("size = " + m.total);
//        console.debug(m);

        for (var i = 0; i < m.total; i++) {
            {
//                console.log("obs = " + i);
//                console.log(m.getAt(i));
                game.debug.renderSpriteBody(m.getAt(i), '#022ff22');
            }

        }
    }
}

<commit_msg>Correct merge issue<commit_after>/**
 * Created by Thomas on 1/25/14.
 */

// Initialization functions
loadFiles();

window.onload=function(){
    setTimeout(function(){mainPhaser()}, 3000);
};

// JS file preloader
function loadFiles(){
    var head = document.getElementsByTagName("head")[0];
    for( var i=0; i<files.length; i++ ){
        var js = document.createElement("script");
        js.type = "text/javascript";
        js.src = "src/"+files[i];
        head.appendChild(js);
    }
}

function mainPhaser(){
    var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'gameCanvas', { preload: preload, create: create, update: update, render: render });
    var map;
    var camera;
    var player,inputsKeyboard, inputsMouse;

    function preload() {
        game.load.image('h_red','img/h_red.png');
        game.load.image('w_red','img/wave_red.png')
        map = createMap(game);
    }

    function create() {
        player = new Player('red',game);
        player.setSprite(game.add.sprite(200,200,'h_red'));

        game.camera.follow(player.sprite);

//        var stream = new Stream(45, 10, 100, 500, 10);
//        stream.create(game);
        var a = new Obstacle(game, 400, 400, "w_red", COLORS.RED);

        inputsKeyboard = game.input.keyboard.createCursorKeys(); // bind the keyboard/mouse to inputs
        inputsMouse = game.input.mousePointer; // bind the keyboard/mouse to inputsb
        player.sonar(game,map.obstacles);
    }

    function update () {
        player.moveK(inputsKeyboard);
        player.moveM(inputsMouse);

        // game.physics.collide(player, this.box, collideHandler, null, this);

        // check for collision over the player's sonar
        game.physics.collide(player.sonarPts,map.obstacles,function(pt,ob){
            pt.body.velocity = new Phaser.Point(0,0); //  we stop the point
            pt.lifespan = pt.lifespan + Math.random()*100; // add a little delay
        });

        game.physics.collide(player.sprite,map.obstacles,function(){});
    }

    function collideHandler() {
        console.log("coucou");
    }

    function render (){
        // map.obstacles.forEachAlive(function(ob){
        //     // console.log(ob);
        //    game.debug.renderRectangle(ob,'#022ff22');
        // },this)
        // // console.log(map.obstacles);
        // // for(var i = 0; i < map.obstacles.lenght; ++i){
        // //     console.log(i);
        // // }

        var m = map.getObstacles();

//         console.log("size = " + m.total);
//        console.debug(m);

        for (var i = 0; i < m.total; i++) {
            {
//                console.log("obs = " + i);
//                console.log(m.getAt(i));
                game.debug.renderSpriteBody(m.getAt(i), '#022ff22');
            }

        }
    }
}

<|endoftext|>


<commit_before>import 'riot'
import './less/main.less'
import './flex.scss'
import './js/components/event/edit/event-create.html'
import './js/components/user/user-register.html'
import './js/components/user/user-profile-dropdown.html'
import './js/components/user/user-profile.html'
import './js/components/user/user-profile-list.html'
import './js/components/user/user-messages.html'
import './js/components/event/event-list-short.html'
import './js/components/user/user-club-list.html'
import './js/components/user/user-filter.html'
import './js/components/user/user-message-send.html'

window.riot = riot
window.api = window.api || {}
window.api.google = {}
window.api.user.track = {}
riot.observable(window.api.google)
riot.observable(window.api.user.track)
riot.mount('*')

import './images/logo.png'
<commit_msg>Added floating header using waypoints<commit_after>import 'riot'
import fittier from 'fitter-happier-text'
import 'waypoints/lib/noframework.waypoints'
import './less/main.less'
import './flex.scss'
import './js/components/page/page-editor.html'
import './js/components/ssf-carousel.html'
import './js/components/ssf-countdown.html'
import './js/components/ssf-chart.html'
import './js/components/ssf-location-distance.html'
import './js/components/user/user-register.html'
import './js/components/user/user-login.html'
import './js/components/user/user-profile-dropdown.html'
import './js/components/user/user-profile-card.html'
import './js/components/user/user-profile-list.html'
import './js/components/user/user-messages.html'
import './js/components/user/user-club-list.html'
import './js/components/user/user-filter.html'
import './js/components/user/user-message-send.html'
import './js/components/event/edit/event-update.html'
import './js/components/event/edit/event-create.html'
import './js/components/event/event-register.html'
import './js/components/event/manage/manage-registrations.html'
import './js/components/event/event-list-short.html'
import './images/logo.png'
import './images/navigation/events.svg'
import './images/navigation/verein.svg'
import './images/navigation/users.svg'
import './images/navigation/home.svg'
import './images/navigation/kontakt.svg'
import './images/navigation/login.svg'

fittier(document.querySelectorAll('.js-fitty'))

function floatHeaderOnWaypoint () {
    let offset = document.querySelector('.site__nav').offsetHeight
    new Waypoint({
        element: document.querySelector('.site__content'),
        offset: offset,
        handler: direction=>{
            let offset = document.querySelector('.site__nav').offsetHeight
            if (direction == 'down') {
                if (document.body.clientWidth > 600) {
                    document.querySelector('.site__nav').classList.add('site__nav--floating')
                    document.querySelector('.site__content').style.marginTop = offset+16+'px'
                }
            } else {
                document.querySelector('.site__nav').classList.remove('site__nav--floating')
                document.querySelector('.site__content').style.marginTop = 0
            }
        }
    })
}

window.riot = riot
window.api = window.api || {}
window.api.google = {}
window.api.user.track = {}
riot.observable(window.api.google)
riot.observable(window.api.user.track)
riot.mount('*')

floatHeaderOnWaypoint()
<|endoftext|>


<commit_before>var Position = Class(function(x, y) {
	if (typeof x === 'number') {
		this.x = x;
	}
	if (typeof y === 'number') {
		this.y = y;
	}
},{
	x: 0,
	y: 0
});

var GraphNode = Class(function(data) {
	this.data = data;

	this.position = new Position();
	this.parentStack = [];
},{
	state: 'none',
	parentStack: []
});

/**
 * Create a diagram.
 *
 * @param {Object} [configuration] - Diagram configuration.
 * configurations: {
 * 	inputAdapter: {}
 * 	positioningStrategy: {},
 * 	rendeEngine: {},
 * 	outputAdapter: {},
 * 	renderingProperties: {
 * 		styles: 'file.css',
 * 		nodeDimensions: {
 * 			width: 0,
 * 			height: 0
 * 		},
 * 		spacing: {
 * 			horizontal: 0,
 * 			vertical: 0
 * 		},
 * 		text: {
 * 			dx: 0,
 * 			dy: 0,
 * 			'text-anchor': 'middle'
 * 		}
 * 	}
 * }
 */
var Diagram = Class(function(configurations) {
	if (configurations) {
		if (configurations.inputAdapter) {
			this._inputAdapter = configurations.inputAdapter.bind(this);
		}

		if (configurations.positioningStategy) {
			this._positioningStrategy = configurations.positioningStrategy.bind(this);
		}

		if (configurations.renderEngine) {
			this._renderEngine = configurations.renderEngine.bind(this);
		}

		if (configurations.outputAdapter) {
			this._outputAdapter = configurations.outputAdapter.bind(this);
		}

		if (configurations.renderingProperties) {
			this._renderingOptions = configurations.renderingProperties;
		}
	}
}, {
	build: function() {
		this._inputAdapter(this._data);
		this._positioningStrategy();
		this._renderEngine();
		this._outputAdapter();
	},

	_inputAdapter: function() {
	},
	_positioningStrategy: function() {
	},
	_renderEngine: function() {
	},
	_outputAdapter: function() {
	},
	_renderingProperties: {}
});
<commit_msg>init: connect all parts and do the processing<commit_after>var Class = require('class-wrapper').Class;
var fs = require('fs');

var InputAdapter = require('./inputAdapter');
var Position = require('./position');
var Rendering = require('./rendering');
var outputAdapter = require('./outputAdapter');

global.document = require('jsdom').jsdom('<body>');

var Diagram = Class(function(noiName, nodeMap, css) {
	this.inAdapter.setNodeMap(nodeMap);
	var noi = this.inAdapter.prepareNOI(noiName);
	this.inAdapter.prepareOtherNodes();

	this.position.setNOI(noi);
	var nodes = this.position.position();

	var domElement = this.rendering.render(nodes);

	var out = this.outAdapter(domElement, css);

	fs.writeFile('out.svg', out, err => {
		if (err) {
			throw err;
		}

		console.log('Done.');
	});
}, {
	inAdapter: new InputAdapter(),
	position: new Position(),
	rendering: new Rendering(),
	outAdapter: outputAdapter
});

module.exports = Diagram;
<|endoftext|>


<commit_before>const HTML = DOM.find("html");
const DEFAULT_LANGUAGE = HTML.get("lang") || void 0;
const globalFormatters = DOM.findAll("meta[name^='data-format:']").reduce((globalFormatters, meta) => {
    const key = meta.get("name").split(":")[1];
    const formatOptions = JSON.parse(meta.get("content"));
    if (key) {
        try {
            globalFormatters[key] = new window.Intl.DateTimeFormat(DEFAULT_LANGUAGE, formatOptions);
        } catch(err) {}
    }
    return globalFormatters;
}, {});

DOM.extend("local-time", {
    constructor() {
        const lang = this.get("lang") || DEFAULT_LANGUAGE;
        const dateValue = new Date(this.get("datetime"));
        const formatOptions = this.get("data-format");

        this.value(this._formatDate(dateValue, lang, formatOptions));
    },
    _formatDate(dateValue, lang, formatOptions) {
        const formatter = globalFormatters[formatOptions];

        try {
            if (formatter && lang === DEFAULT_LANGUAGE) {
                return formatter.format(dateValue);
            } else {
                return dateValue.toLocaleString(lang, formatOptions ? JSON.parse(formatOptions) : {});
            }
        } catch (err) {
            return dateValue.toLocaleString();
        }
    }
});
<commit_msg>trim global formatter keys<commit_after>const HTML = DOM.find("html");
const DEFAULT_LANGUAGE = HTML.get("lang") || void 0;
const globalFormatters = DOM.findAll("meta[name^='data-format:']").reduce((globalFormatters, meta) => {
    const key = meta.get("name").split(":")[1].trim();
    const formatOptions = JSON.parse(meta.get("content"));
    if (key) {
        try {
            globalFormatters[key] = new window.Intl.DateTimeFormat(DEFAULT_LANGUAGE, formatOptions);
        } catch(err) {}
    }
    return globalFormatters;
}, {});

DOM.extend("local-time", {
    constructor() {
        const lang = this.get("lang") || DEFAULT_LANGUAGE;
        const dateValue = new Date(this.get("datetime"));
        const formatOptions = this.get("data-format");

        this.value(this._formatDate(dateValue, lang, formatOptions));
    },
    _formatDate(dateValue, lang, formatOptions) {
        const formatter = globalFormatters[formatOptions];

        try {
            if (formatter && lang === DEFAULT_LANGUAGE) {
                return formatter.format(dateValue);
            } else {
                return dateValue.toLocaleString(lang, formatOptions ? JSON.parse(formatOptions) : {});
            }
        } catch (err) {
            return dateValue.toLocaleString();
        }
    }
});
<|endoftext|>


<commit_before>'use strict'

/**
 * plugin.js
 *
 * Released under LGPL License.
 * Copyright (c) 2017 SIRAP Group All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/**
 * plugin.js Tinymce plugin headersfooters
 * @file plugin.js
 * @module
 * @name tinycmce-plugin-headersfooters
 * @description
 * A plugin for tinymce WYSIWYG HTML editor that allow to insert headers and footers
 * @see https://github.com/sirap-group/tinymce-plugin-headersfooters
 * @author Rémi Becheras
 * @author Groupe SIRAP
 * @license GNU GPL-v2 http://www.tinymce.com/license
 */

/**
 * Tinymce library - injected by the plugin loader.
 * @external tinymce
 * @see {@link https://www.tinymce.com/docs/api/class/tinymce/|Tinymce API Reference}
 */
var tinymce = window.tinymce

var menuItems = require('./components/menu-items')

var units = require('./utils/units')
var events = require('./utils/events')
var uiUtils = require('./utils/ui')

var eventHandlers = require('./event-handlers')
var Format = require('./classes/Format')
var editFormatOpenMainWin = require('./components/edit-format-window')

// Add the plugin to the tinymce PluginManager
tinymce.PluginManager.add('headersfooters', tinymcePluginHeadersFooters)

/**
 * Tinymce plugin headers/footers
 * @function
 * @global
 * @param {tinymce.Editor} editor - The injected tinymce editor.
 * @returns void
 */
function tinymcePluginHeadersFooters (editor, url) {
  var thisPlugin = this

  this.type = editor.settings.headersfooters_type
  this.bodyClass = editor.settings.body_class

  // bind plugin methods
  this.enable = enable
  this.disable = disable
  this.setFormat = setFormat
  this.parseParamList = parseParamList

  this.isMaster = this.type === 'body'
  this.isSlave = !this.isMaster

  if (this.isMaster) {
    tinymce.getMasterHeadersFootersPlugin = function () {
      return thisPlugin
    }
  }
  this.getMaster = function () {
    return tinymce.getMasterHeadersFootersPlugin()
  }

  if (this.isMaster && window.env === 'development') {
    window.mceHF = this
  }

  this.headerFooterFactory = null

  this.units = units
  this.editor = editor

  this.documentBody = null
  this.documentBodies = {
    app: null,
    mce: {
      header: null,
      body: null,
      footer: null
    }
  }
  this.stackedLayout = {
    root: null,
    wrapper: null,
    layout: null,
    menubar: null,
    toolbar: null,
    editarea: null,
    statusbar: null
  }

  if (this.isMaster) {
    this.pageLayout = {
      pageWrapper: null,
      pagePanel: null,
      headerWrapper: null,
      headerPanel: null,
      bodyPanel: null,
      footerWrapper: null,
      footerPanel: null
    }
  }

  this.availableFormats = {}
  this.formats = []
  this.customFormats = []
  this.defaultFormat = null
  this.currentFormat = null

  _setAvailableFormats.call(this)

  this.menuItemsList = menuItems.create(editor)
  uiUtils.autoAddMenuItems.call(this)

  editor.addCommand('insertPageNumberCmd', function () {
    editor.insertContent('{{page}}')
  })
  editor.addCommand('insertNumberOfPagesCmd', function () {
    editor.insertContent('{{pages}}')
  })
  editor.addCommand('editFormatCmd', function () {
    editFormatOpenMainWin(editor)(thisPlugin.currentFormat)
  })

  events.autoBindImplementedEventCallbacks.call(this, editor, eventHandlers)

  if (window.env === 'development' && this.isMaster) {
    setTimeout(function () {
      editor.execCommand('editFormatCmd')
    })
  }
}

function enable () {
  this.stackedLayout.menubar.show()
  this.stackedLayout.toolbar.show()
  this.stackedLayout.statusbar.wrapper.show()
  this.stackedLayout.statusbar.path.show()
  this.stackedLayout.statusbar.wordcount.show()
  this.stackedLayout.statusbar.resizehandle.show()

  this.stackedLayout.statusbar.wrapper.css({left: 0, right: 0, zIndex: 9999})

  this.editor.$('body').css({opacity: 1})
}

function disable () {
  this.stackedLayout.menubar.hide()
  this.stackedLayout.toolbar.hide()
  this.stackedLayout.statusbar.wrapper.hide()
  this.stackedLayout.statusbar.path.hide()
  this.stackedLayout.statusbar.wordcount.hide()
  this.stackedLayout.statusbar.resizehandle.hide()

  if (!this.editor.selection.isCollapsed()) {
    this.editor.selection.collapse()
  }
  this.editor.$('body').css({opacity: 0.25})
}

function _setAvailableFormats () {
  var that = this
  var settings = this.editor.settings

  // set enabled default formats
  var userEnabledDefaultFormats = this.parseParamList(settings.headersfooters_formats)
  .map(function (formatName) {
    return Format.defaults[formatName]
  })
  .filter(function (v) {
    return !!v
  })
  if (userEnabledDefaultFormats.length) {
    this.formats = userEnabledDefaultFormats
  } else {
    this.formats = []
    for (var name in Format.defaults) {
      that.formats.push(Format.defaults[name])
    }
  }

  // set user custom formats
  this.customFormats = (settings.headersfooters_custom_formats || [])
  .map(function (f) {
    return new Format(f.name, f.config)
  })

  // set the formats available for the editor
  this.availableFormats = {}
  // use enabled default formats
  this.formats.map(function (f) {
    that.availableFormats[f.name] = f
  })
  // add or override custom formats
  this.customFormats.map(function (f) {
    that.availableFormats[f.name] = f
  })

  // select a default format for new doc
  this.defaultFormat = this.availableFormats[settings.headersfooters_default_format] || this.formats[0] || this.customFormats[0]

  // current format is set on editor init callback
}

function setFormat (format) {
  this.currentFormat = new Format(format.name, format)
  this.editor.fire('HeadersFooters:SetFormat')
}

function parseParamList (paramValue) {
  if (paramValue === undefined) {
    return []
  }
  if (typeof paramValue !== 'string') {
    throw new TypeError('paramValue must be a String, ' + typeof paramValue + ' given.')
  }
  return paramValue.split(' ')
}
<commit_msg>disable auto exec command 'editFormatCmd'<commit_after>'use strict'

/**
 * plugin.js
 *
 * Released under LGPL License.
 * Copyright (c) 2017 SIRAP Group All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/**
 * plugin.js Tinymce plugin headersfooters
 * @file plugin.js
 * @module
 * @name tinycmce-plugin-headersfooters
 * @description
 * A plugin for tinymce WYSIWYG HTML editor that allow to insert headers and footers
 * @see https://github.com/sirap-group/tinymce-plugin-headersfooters
 * @author Rémi Becheras
 * @author Groupe SIRAP
 * @license GNU GPL-v2 http://www.tinymce.com/license
 */

/**
 * Tinymce library - injected by the plugin loader.
 * @external tinymce
 * @see {@link https://www.tinymce.com/docs/api/class/tinymce/|Tinymce API Reference}
 */
var tinymce = window.tinymce

var menuItems = require('./components/menu-items')

var units = require('./utils/units')
var events = require('./utils/events')
var uiUtils = require('./utils/ui')

var eventHandlers = require('./event-handlers')
var Format = require('./classes/Format')
var editFormatOpenMainWin = require('./components/edit-format-window')

// Add the plugin to the tinymce PluginManager
tinymce.PluginManager.add('headersfooters', tinymcePluginHeadersFooters)

/**
 * Tinymce plugin headers/footers
 * @function
 * @global
 * @param {tinymce.Editor} editor - The injected tinymce editor.
 * @returns void
 */
function tinymcePluginHeadersFooters (editor, url) {
  var thisPlugin = this

  this.type = editor.settings.headersfooters_type
  this.bodyClass = editor.settings.body_class

  // bind plugin methods
  this.enable = enable
  this.disable = disable
  this.setFormat = setFormat
  this.parseParamList = parseParamList

  this.isMaster = this.type === 'body'
  this.isSlave = !this.isMaster

  if (this.isMaster) {
    tinymce.getMasterHeadersFootersPlugin = function () {
      return thisPlugin
    }
  }
  this.getMaster = function () {
    return tinymce.getMasterHeadersFootersPlugin()
  }

  if (this.isMaster && window.env === 'development') {
    window.mceHF = this
  }

  this.headerFooterFactory = null

  this.units = units
  this.editor = editor

  this.documentBody = null
  this.documentBodies = {
    app: null,
    mce: {
      header: null,
      body: null,
      footer: null
    }
  }
  this.stackedLayout = {
    root: null,
    wrapper: null,
    layout: null,
    menubar: null,
    toolbar: null,
    editarea: null,
    statusbar: null
  }

  if (this.isMaster) {
    this.pageLayout = {
      pageWrapper: null,
      pagePanel: null,
      headerWrapper: null,
      headerPanel: null,
      bodyPanel: null,
      footerWrapper: null,
      footerPanel: null
    }
  }

  this.availableFormats = {}
  this.formats = []
  this.customFormats = []
  this.defaultFormat = null
  this.currentFormat = null

  _setAvailableFormats.call(this)

  this.menuItemsList = menuItems.create(editor)
  uiUtils.autoAddMenuItems.call(this)

  editor.addCommand('insertPageNumberCmd', function () {
    editor.insertContent('{{page}}')
  })
  editor.addCommand('insertNumberOfPagesCmd', function () {
    editor.insertContent('{{pages}}')
  })
  editor.addCommand('editFormatCmd', function () {
    editFormatOpenMainWin(editor)(thisPlugin.currentFormat)
  })

  events.autoBindImplementedEventCallbacks.call(this, editor, eventHandlers)

  // if (window.env === 'development' && this.isMaster) {
  //   setTimeout(function () {
  //     editor.execCommand('editFormatCmd')
  //   })
  // }
}

function enable () {
  this.stackedLayout.menubar.show()
  this.stackedLayout.toolbar.show()
  this.stackedLayout.statusbar.wrapper.show()
  this.stackedLayout.statusbar.path.show()
  this.stackedLayout.statusbar.wordcount.show()
  this.stackedLayout.statusbar.resizehandle.show()

  this.stackedLayout.statusbar.wrapper.css({left: 0, right: 0, zIndex: 9999})

  this.editor.$('body').css({opacity: 1})
}

function disable () {
  this.stackedLayout.menubar.hide()
  this.stackedLayout.toolbar.hide()
  this.stackedLayout.statusbar.wrapper.hide()
  this.stackedLayout.statusbar.path.hide()
  this.stackedLayout.statusbar.wordcount.hide()
  this.stackedLayout.statusbar.resizehandle.hide()

  if (!this.editor.selection.isCollapsed()) {
    this.editor.selection.collapse()
  }
  this.editor.$('body').css({opacity: 0.25})
}

function _setAvailableFormats () {
  var that = this
  var settings = this.editor.settings

  // set enabled default formats
  var userEnabledDefaultFormats = this.parseParamList(settings.headersfooters_formats)
  .map(function (formatName) {
    return Format.defaults[formatName]
  })
  .filter(function (v) {
    return !!v
  })
  if (userEnabledDefaultFormats.length) {
    this.formats = userEnabledDefaultFormats
  } else {
    this.formats = []
    for (var name in Format.defaults) {
      that.formats.push(Format.defaults[name])
    }
  }

  // set user custom formats
  this.customFormats = (settings.headersfooters_custom_formats || [])
  .map(function (f) {
    return new Format(f.name, f.config)
  })

  // set the formats available for the editor
  this.availableFormats = {}
  // use enabled default formats
  this.formats.map(function (f) {
    that.availableFormats[f.name] = f
  })
  // add or override custom formats
  this.customFormats.map(function (f) {
    that.availableFormats[f.name] = f
  })

  // select a default format for new doc
  this.defaultFormat = this.availableFormats[settings.headersfooters_default_format] || this.formats[0] || this.customFormats[0]

  // current format is set on editor init callback
}

function setFormat (format) {
  this.currentFormat = new Format(format.name, format)
  this.editor.fire('HeadersFooters:SetFormat')
}

function parseParamList (paramValue) {
  if (paramValue === undefined) {
    return []
  }
  if (typeof paramValue !== 'string') {
    throw new TypeError('paramValue must be a String, ' + typeof paramValue + ' given.')
  }
  return paramValue.split(' ')
}
<|endoftext|>


<commit_before>/**
 * @file mdjs
 * @author xiaowu
 * @email fe.xiaowu@gmail.com
 */

'use strict';

import template from 'art-template/node/template-native';

import express from 'express';
import serve_static from 'serve-static';

import fs from 'fs';
import url from 'url';
import path from 'path';

import Key_cache from 'key-cache';

import marked from 'marked';
import highlight from 'highlight.js';

export default class Mdjs {
    static options = {
        /**
         * 文档名
         *
         * @type {String}
         */
        name: 'mdjs',

        /**
         * 监听的端口
         *
         * @type {Number}
         */
        port: 8091,

        /**
         * 文档根目录
         *
         * @type {String}
         */
        root: './',

        /**
         * 缓存文件目录
         *
         * @type {String}
         */
        cache_path: './.cache/',

        /**
         * 目录别名
         *
         * @type {Object}
         */
        dir_alias: {},

        /**
         * mdjs静态资源前缀
         *
         * @description 监听内置的静态资源，配置是为了解决与别的名冲突
         * @type {String}
         */
        static_prefix: 'static',

        /**
         * 忽略的目录
         *
         * @type {Array}
         */
        ignore_dir: [
            '.svn',
            '.git',
            'node_modules'
        ],

        /**
         * 导航里额外追加的链接
         *
         * @example
         *     [
         *         {
         *             "text": "链接名称-默认往导航之前插件",
         *             "url": "链接"
         *         },
         *         {
         *             "text": "链接名称-往导航之后追加",
         *             "url": "链接",
         *             "type": "after"
         *         }
         *     ]
         * @type {Array}
         */
        links: [
        ],

        /**
         * 调试模式
         *
         * @description 开启后不使用缓存
         * @type {Boolean}
         */
        debug: false
    }

    /**
     * 构造器
     *
     * @param  {Object} options 配置参数
     */
    constructor(options = {}) {
        let package_options;
        try {
            package_options = require(path.resolve('./package.json')).mdjs;
        }
        catch (e) {
            package_options = {};
        }

        // 合并默认配置
        // 合并的顺序是： 参数 > package.mdjs > 默认 （由左向右合并）
        options = this.options = Object.assign({}, Mdjs.options, package_options, options);

        options.root = path.resolve(options.root);
        options.cache_path = path.resolve(options.cache_path);

        // 缓存当前运行的目录
        this.__dirname = path.dirname(__dirname);

        // 缓存express
        this.express = express();

        // 初始化express
        this._init_express();
    }

    /**
     * 获取渲染后的导航html代码
     *
     * @param  {string|undefined} uri 当前高亮的路径，如果为空则全不高亮， 高亮即展开
     *
     * @return {string}     html代码
     */
    get_render_nav(uri) {
        let data = this.get_list();
        let str = '';

        if (!data || !data.length) {
            return str;
        }

        if (uri) {
            uri = decodeURIComponent(uri);
        }

        let filter = (filepath, type) => {
            if (!uri) {
                return false;
            }

            if (type === 'dir') {
                return uri.indexOf(filepath + '/') === 0;
            }
            return uri === filepath;
        };

        let fn = (res) => {
            let html = '';

            res.forEach((val) => {
                if (!val.children || !val.children.length) {
                    if (filter(val.uri, 'file')) {
                        html += `<li class="nav-tree-file nav-tree-current">`;
                    }
                    else {
                        html += `<li class="nav-tree-file">`;
                    }
                    html += `

                                    ${val.text}

                    `;
                }
                else {
                    if (filter(val.uri, 'dir')) {
                        html += `<li class="nav-tree-dir nav-tree-dir-open">`;
                    }
                    else {
                        html += `<li class="nav-tree-dir">`;
                    }
                    html += `

                                    ${val.text}

                            ${fn(val.children)}

                    `;
                }
            });

            return '
' + html + '
';
        };

        return fn(data);
    }

    /**
     * 清空缓存
     *
     * @return {Object} this
     */
    clear_cache() {
        // 调用缓存对象清空缓存
        new Key_cache({
            dir: this.options.cache_path
        }).remove();

        return this;
    }

    /**
     * 获取navtree使用数据，会追加options.links
     *
     * @description 会先读取缓存
     * @return {Array} 数组
     */
    get_list() {
        return this.cache('nav_data', () => {
            let data = this._get_list();

            if (!data.children) {
                data.children = [];
            }

            // 如果有链接，则追加
            if (this.options.links && this.options.links.length) {
                this.options.links.forEach(val => {
                    if (val.type === 'after') {
                        data.children.push(val);
                    }
                    else {
                        data.children.unshift(val);
                    }
                });
            }

            return data.children;
        });
    }

    /**
     * 渲染md文件
     *
     * @param  {string} content md源码
     *
     * @return {Object}         {content:html代码, catalog: h2,3分类}
     */
    renderMarkdown(content = '') {
        let renderer = new marked.Renderer();
        let cachekey = {};

        let catalog = [];

        // 渲染标题
        renderer.heading = (text, level) => {
            let key;

            if (level !== 2 && level !== 3) {
                return `<h${level}>${text}</h${level}>`;
            }

            if (cachekey[level] === undefined) {
                cachekey[level] = 0;
            }

            key = ++cachekey[level];

            catalog.push({
                text: text,
                level: level,
                id: `h${level}-${key}`
            });

            return `
                <h${level}>

                        ${text}

                </h${level}>
            `;
        };

        // 渲染代码
        renderer.code = (data, lang) => {
            data = highlight.highlightAuto(data).value;

            // 有语言时
            if (lang) {

                // 超过3行有提示
                if (data.split(/\n/).length >= 3) {
                    let html = `<pre><code class="hljs lang-${lang}"><span class="hljs-lang-tips">${lang}</span>`;
                    return html + `${data}</code></pre>`;
                }

                return `<pre><code class="hljs lang-${lang}">${data}</code></pre>`;
            }

            return `<pre><code class="hljs">${data}</code></pre>`;
        };

        // md => html
        content = marked(content, {
            renderer: renderer
        });

        // 兼容todo
        content = content.replace(/
\s*\[ \]\s*/g, '
<input type="checkbox" class="ui-todo" disabled>');
        content = content.replace(/
\s*\[x\]\s*/g, '
<input type="checkbox" disabled checked class="ui-todo">');

        return {
            content: content,
            catalog: catalog
        };
    }

    /**
     * 运行
     *
     * @return {Object} this
     */
    run() {
        this.express.listen(this.options.port);
        return this;
    }

    /**
     * 缓存
     *
     * @description 如果开启了debug，则忽略缓存
     * @param  {string}   key  缓存key
     * @param {Function} fn 当没有缓存时执行的回调
     * @return {Object|undefined} 缓存数据或者回调返回值
     */
    cache(key, fn = () => {}) {
        // 如果没有key则返回空
        if (!key) {
            return undefined;
        }

        // 如果有debug
        if (this.options.debug) {
            return fn();
        }

        let cache = new Key_cache({
            dir: this.options.cache_path
        });
        let value = cache.get(key);
        if (value) {
            return value;
        }

        value = fn();

        // 如果不为空则设置缓存
        if (value !== undefined) {
            cache.set(key, value);
        }

        return value;
    }

    /**
     * 初始化express
     *
     * @private
     */
    _init_express() {
        let app = this.express;

        template.config('base', '');
        template.config('extname', '.html');

        app.engine('.html', template.__express);
        app.set('views', path.resolve(this.__dirname, './views/'));
        app.set('view engine', 'html');

        // 写入变量
        app.use((req, res, next) => {
            // 写入变量
            res.locals.options = this.options;

            return next();
        });

        // 绑定.md文档
        app.get(/([\s\S]+?)\.md$/, this._md.bind(this));

        // 监听以目录结束的，其实是为了解决默认主页为md文档问题
        app.get(/(^\/$|\/$)/, (req, res, next) => {
            let parseUrl = url.parse(req.url, true);
            let pathname = parseUrl.pathname;

            // 相对文件的路径,用来判断文件是否存在
            let filepath = decodeURIComponent('.' + pathname);

            // 默认主页
            let default_index = [
                'readme.md',
                'README.md'
            ];
            let flag = false;
            for (let i = 0, len = default_index.length; i < len; i++) {
                if (fs.existsSync(path.resolve(this.options.root, filepath, default_index[i]))) {
                    flag = default_index[i];
                    break;
                }
            }

            if (flag) {
                req.url = url.format({
                    hash: parseUrl.hash,
                    search: parseUrl.search,
                    pathname: pathname + flag,
                    query: parseUrl.query
                });

                return this._md(req, res, next);
            }

            next();
        });

        // 委托静态资源
        app.use('/' + this.options.static_prefix, serve_static(path.resolve(this.__dirname, './static/')));

        // 委托源目录
        app.use('/', serve_static(this.options.root));
    }

    /**
     * 内部获取列表数据
     *
     * @private
     * @param  {string|undefined} dir 目录
     *
     * @return {Object}     {path:'', children:[]}
     */
    _get_list(dir) {
        let options = this.options;
        let result;

        dir = dir || options.root;

        let basename = path.basename(dir);

        result = {
            uri: dir.replace(options.root, '') || '/',
            children: [],
            text: options.dir_alias[basename] || basename
        };

        let data = fs.readdirSync(dir);

        data.forEach(file => {
            let filepath = path.resolve(dir, file);
            let stat = fs.statSync(filepath);

            if (stat.isDirectory()) {
                if (options.ignore_dir && options.ignore_dir.indexOf(file) !== -1) {
                    return;
                }

                let res = this._get_list(filepath);

                if (res.children && res.children.length) {
                    result.children.push(res);
                }
            }
            else {
                if (path.extname(file) !== '.md') {
                    return;
                }

                result.children.push({
                    text: this._get_md_title(dir + '/' + file),
                    uri: (dir + '/' + file).replace(options.root, '')
                });
            }
        });

        return result;
    }

    /**
     * 渲染md文档
     *
     * @private
     * @param  {Object}   req  express.req
     * @param  {Object}   res  express.res
     * @param  {Function} next 下一个路由
     * @return {Object} res
     */
    _md(req, res, next) {
        let parseUrl = url.parse(req.url, true);

        // 如果要读取源码
        if (parseUrl.query.source) {
            return next();
        }

        // 加.是为了变成相对路径
        let filepath = path.resolve(this.options.root, '.' + parseUrl.pathname);

        // 为了中文
        filepath = decodeURIComponent(filepath);

        // 如果md文件不存在
        if (!fs.existsSync(filepath)) {
            return next();
        }

        let htmldata = this.renderMarkdown(fs.readFileSync(filepath).toString()).content;

        // 如果是pjax
        if (parseUrl.query.pjax) {
            return res.end(htmldata);
        }

        // 渲染md
        return res.render('markdown', {
            nav_data: this.get_render_nav(parseUrl.pathname),
            markdown_data: htmldata,
            title: `${this._get_md_title(filepath)} - ${this.options.name}`
        });
    }

    /**
     * 内部获取md文档的标题
     *
     * @private
     * @param  {string} filepath 文件路径
     *
     * @return {string}     标题
     */
    _get_md_title(filepath) {
        // 如果是md扩展
        if (path.extname(filepath) === '.md') {
            // 获取文件内容
            let filedata = fs.readFileSync(filepath).toString();

            // 正则取出#标题的文字
            if (filedata.match(/^\#+\s?(.+)/)) {
                return String(RegExp.$1).trim();
            }
        }

        return path.basename(filepath);
    }
}
<commit_msg>添加空目录测试<commit_after>/**
 * @file mdjs
 * @author xiaowu
 * @email fe.xiaowu@gmail.com
 */

'use strict';

import template from 'art-template/node/template-native';

import express from 'express';
import serve_static from 'serve-static';

import fs from 'fs';
import url from 'url';
import path from 'path';

import Key_cache from 'key-cache';

import marked from 'marked';
import highlight from 'highlight.js';

export default class Mdjs {
    static options = {
        /**
         * 文档名
         *
         * @type {String}
         */
        name: 'mdjs',

        /**
         * 监听的端口
         *
         * @type {Number}
         */
        port: 8091,

        /**
         * 文档根目录
         *
         * @type {String}
         */
        root: './',

        /**
         * 缓存文件目录
         *
         * @type {String}
         */
        cache_path: './.cache/',

        /**
         * 目录别名
         *
         * @type {Object}
         */
        dir_alias: {},

        /**
         * mdjs静态资源前缀
         *
         * @description 监听内置的静态资源，配置是为了解决与别的名冲突
         * @type {String}
         */
        static_prefix: 'static',

        /**
         * 忽略的目录
         *
         * @type {Array}
         */
        ignore_dir: [
            '.svn',
            '.git',
            'node_modules'
        ],

        /**
         * 导航里额外追加的链接
         *
         * @example
         *     [
         *         {
         *             "text": "链接名称-默认往导航之前插件",
         *             "url": "链接"
         *         },
         *         {
         *             "text": "链接名称-往导航之后追加",
         *             "url": "链接",
         *             "type": "after"
         *         }
         *     ]
         * @type {Array}
         */
        links: [
        ],

        /**
         * 调试模式
         *
         * @description 开启后不使用缓存
         * @type {Boolean}
         */
        debug: false
    }

    /**
     * 构造器
     *
     * @param  {Object} options 配置参数
     */
    constructor(options = {}) {
        let package_options;
        try {
            package_options = require(path.resolve('./package.json')).mdjs;
        }
        catch (e) {
            package_options = {};
        }

        // 合并默认配置
        // 合并的顺序是： 参数 > package.mdjs > 默认 （由左向右合并）
        options = this.options = Object.assign({}, Mdjs.options, package_options, options);

        options.root = path.resolve(options.root);
        options.cache_path = path.resolve(options.cache_path);

        // 缓存当前运行的目录
        this.__dirname = path.dirname(__dirname);

        // 缓存express
        this.express = express();

        // 初始化express
        this._init_express();
    }

    /**
     * 获取渲染后的导航html代码
     *
     * @param  {string|undefined} uri 当前高亮的路径，如果为空则全不高亮， 高亮即展开
     *
     * @return {string}     html代码
     */
    get_render_nav(uri) {
        let data = this.get_list();
        let str = '';

        if (!data || !data.length) {
            return str;
        }

        if (uri) {
            uri = decodeURIComponent(uri);
        }

        let filter = (filepath, type) => {
            if (!uri) {
                return false;
            }

            if (type === 'dir') {
                return uri.indexOf(filepath + '/') === 0;
            }
            return uri === filepath;
        };

        let fn = (res) => {
            let html = '';

            res.forEach((val) => {
                if (!val.children || !val.children.length) {
                    if (filter(val.uri, 'file')) {
                        html += `<li class="nav-tree-file nav-tree-current">`;
                    }
                    else {
                        html += `<li class="nav-tree-file">`;
                    }
                    html += `

                                    ${val.text}

                    `;
                }
                else {
                    if (filter(val.uri, 'dir')) {
                        html += `<li class="nav-tree-dir nav-tree-dir-open">`;
                    }
                    else {
                        html += `<li class="nav-tree-dir">`;
                    }
                    html += `

                                    ${val.text}

                            ${fn(val.children)}

                    `;
                }
            });

            return '
' + html + '
';
        };

        return fn(data);
    }

    /**
     * 清空缓存
     *
     * @return {Object} this
     */
    clear_cache() {
        // 调用缓存对象清空缓存
        new Key_cache({
            dir: this.options.cache_path
        }).remove();

        return this;
    }

    /**
     * 获取navtree使用数据，会追加options.links
     *
     * @description 会先读取缓存
     * @return {Array} 数组
     */
    get_list() {
        return this.cache('nav_data', () => {
            let data = this._get_list();

            if (!data.children) {
                data.children = [];
            }

            // 如果有链接，则追加
            if (this.options.links && this.options.links.length) {
                this.options.links.forEach(val => {
                    if (val.type === 'after') {
                        data.children.push(val);
                    }
                    else {
                        data.children.unshift(val);
                    }
                });
            }

            return data.children;
        });
    }

    /**
     * 渲染md文件
     *
     * @param  {string} content md源码
     *
     * @return {Object}         {content:html代码, catalog: h2,3分类}
     */
    renderMarkdown(content = '') {
        let renderer = new marked.Renderer();
        let cachekey = {};

        let catalog = [];

        // 渲染标题
        renderer.heading = (text, level) => {
            let key;

            if (level !== 2 && level !== 3) {
                return `<h${level}>${text}</h${level}>`;
            }

            if (cachekey[level] === undefined) {
                cachekey[level] = 0;
            }

            key = ++cachekey[level];

            catalog.push({
                text: text,
                level: level,
                id: `h${level}-${key}`
            });

            return `
                <h${level}>

                        ${text}

                </h${level}>
            `;
        };

        // 渲染代码
        renderer.code = (data, lang) => {
            data = highlight.highlightAuto(data).value;

            // 有语言时
            if (lang) {

                // 超过3行有提示
                if (data.split(/\n/).length >= 3) {
                    let html = `<pre><code class="hljs lang-${lang}"><span class="hljs-lang-tips">${lang}</span>`;
                    return html + `${data}</code></pre>`;
                }

                return `<pre><code class="hljs lang-${lang}">${data}</code></pre>`;
            }

            return `<pre><code class="hljs">${data}</code></pre>`;
        };

        // md => html
        content = marked(content, {
            renderer: renderer
        });

        // 兼容todo
        content = content.replace(/
\s*\[ \]\s*/g, '
<input type="checkbox" class="ui-todo" disabled>');
        content = content.replace(/
\s*\[x\]\s*/g, '
<input type="checkbox" disabled checked class="ui-todo">');

        return {
            content: content,
            catalog: catalog
        };
    }

    /**
     * 运行
     *
     * @return {Object} this
     */
    run() {
        this.express.listen(this.options.port);
        return this;
    }

    /**
     * 缓存
     *
     * @description 如果开启了debug，则忽略缓存
     * @param  {string}   key  缓存key
     * @param {Function} fn 当没有缓存时执行的回调
     * @return {Object|undefined} 缓存数据或者回调返回值
     */
    cache(key, fn = () => {}) {
        // 如果没有key则返回空
        if (!key) {
            return undefined;
        }

        // 如果有debug
        if (this.options.debug) {
            return fn();
        }

        let cache = new Key_cache({
            dir: this.options.cache_path
        });
        let value = cache.get(key);
        if (value) {
            return value;
        }

        value = fn();

        // 如果不为空则设置缓存
        if (value !== undefined) {
            cache.set(key, value);
        }

        return value;
    }

    /**
     * 初始化express
     *
     * @private
     */
    _init_express() {
        let app = this.express;

        template.config('base', '');
        template.config('extname', '.html');

        app.engine('.html', template.__express);
        app.set('views', path.resolve(this.__dirname, './views/'));
        app.set('view engine', 'html');

        // 写入变量
        app.use((req, res, next) => {
            // 写入变量
            res.locals.options = this.options;

            return next();
        });

        // 绑定.md文档
        app.get(/([\s\S]+?)\.md$/, this._md.bind(this));

        // 监听以目录结束的，其实是为了解决默认主页为md文档问题
        app.get(/(^\/$|\/$)/, (req, res, next) => {
            let parseUrl = url.parse(req.url, true);
            let pathname = parseUrl.pathname;

            // 相对文件的路径,用来判断文件是否存在
            let filepath = decodeURIComponent('.' + pathname);

            // 默认主页
            let default_index = [
                'readme.md',
                'README.md'
            ];
            let flag = false;
            for (let i = 0, len = default_index.length; i < len; i++) {
                if (fs.existsSync(path.resolve(this.options.root, filepath, default_index[i]))) {
                    flag = default_index[i];
                    break;
                }
            }

            if (flag) {
                req.url = url.format({
                    hash: parseUrl.hash,
                    search: parseUrl.search,
                    pathname: pathname + flag,
                    query: parseUrl.query
                });

                return this._md(req, res, next);
            }

            next();
        });

        // 委托静态资源
        app.use('/' + this.options.static_prefix, serve_static(path.resolve(this.__dirname, './static/')));

        // 委托源目录
        app.use('/', serve_static(this.options.root));
    }

    /**
     * 内部获取列表数据
     *
     * @private
     * @param  {string|undefined} dir 目录
     *
     * @return {Object}     {path:'', children:[]}
     */
    _get_list(dir) {
        let options = this.options;
        let result;

        dir = dir || options.root;

        let basename = path.basename(dir);

        result = {
            uri: dir.replace(options.root, '') || '/',
            children: [],
            text: options.dir_alias[basename] || basename
        };

        // 如果目录不存在
        if (!fs.existsSync(dir)) {
            return result;
        }

        let data = fs.readdirSync(dir);

        data.forEach(file => {
            let filepath = path.resolve(dir, file);
            let stat = fs.statSync(filepath);

            if (stat.isDirectory()) {
                if (options.ignore_dir && options.ignore_dir.indexOf(file) !== -1) {
                    return;
                }

                let res = this._get_list(filepath);

                if (res.children && res.children.length) {
                    result.children.push(res);
                }
            }
            else {
                if (path.extname(file) !== '.md') {
                    return;
                }

                result.children.push({
                    text: this._get_md_title(dir + '/' + file),
                    uri: (dir + '/' + file).replace(options.root, '')
                });
            }
        });

        return result;
    }

    /**
     * 渲染md文档
     *
     * @private
     * @param  {Object}   req  express.req
     * @param  {Object}   res  express.res
     * @param  {Function} next 下一个路由
     * @return {Object} res
     */
    _md(req, res, next) {
        let parseUrl = url.parse(req.url, true);

        // 如果要读取源码
        if (parseUrl.query.source) {
            return next();
        }

        // 加.是为了变成相对路径
        let filepath = path.resolve(this.options.root, '.' + parseUrl.pathname);

        // 为了中文
        filepath = decodeURIComponent(filepath);

        // 如果md文件不存在
        if (!fs.existsSync(filepath)) {
            return next();
        }

        let htmldata = this.renderMarkdown(fs.readFileSync(filepath).toString()).content;

        // 如果是pjax
        if (parseUrl.query.pjax) {
            return res.end(htmldata);
        }

        // 渲染md
        return res.render('markdown', {
            nav_data: this.get_render_nav(parseUrl.pathname),
            markdown_data: htmldata,
            title: `${this._get_md_title(filepath)} - ${this.options.name}`
        });
    }

    /**
     * 内部获取md文档的标题
     *
     * @private
     * @param  {string} filepath 文件路径
     *
     * @return {string}     标题
     */
    _get_md_title(filepath) {
        // 如果是md扩展
        if (path.extname(filepath) === '.md') {
            // 获取文件内容
            let filedata = fs.readFileSync(filepath).toString();

            // 正则取出#标题的文字
            if (filedata.match(/^\#+\s?(.+)/)) {
                return String(RegExp.$1).trim();
            }
        }

        return path.basename(filepath);
    }
}
<|endoftext|>


<commit_before>function gltf_rv(canvasId, index, headless = false, onRendererReady = undefined)
{
    let canvas = document.getElementById(canvasId);
    if (!canvas)
    {
        console.warn("Failed to retrieve the WebGL canvas!");
        return null;
    }

    gl = getWebGlContext();
    if (!gl)
    {
        console.warn("Failed to get an WebGL rendering context!");
        return null;
    }

    let viewer = new gltfViewer(canvas, index, headless, onRendererReady);

    canvas.onmousedown = viewer.onMouseDown.bind(viewer);
    document.onmouseup = viewer.onMouseUp.bind(viewer);
    document.onmousemove = viewer.onMouseMove.bind(viewer);
    canvas.onwheel = viewer.onMouseWheel.bind(viewer);
    canvas.ontouchstart = viewer.onTouchStart.bind(viewer);
    document.ontouchend = viewer.onTouchEnd.bind(viewer);
    document.ontouchmove = viewer.onTouchMove.bind(viewer);

    canvas.ondrop = viewer.dropEventHandler.bind(viewer);
    canvas.ondragover = viewer.dragOverHandler.bind(viewer);

    return viewer; // Succeeded in creating a glTF viewer!
}

function getWebGlContext()
{
    const parameters = { alpha: false, antialias: false };
    const names = [ "webgl", "experimental-webgl" ];
    let context;
    for (const name of names)
    {
        context = canvas.getContext(name, parameters);
        if (context)
        {
            return context;
        }
    }
}
<commit_msg>Added such that anti-aliasing is on by default.<commit_after>function gltf_rv(canvasId, index, headless = false, onRendererReady = undefined)
{
    let canvas = document.getElementById(canvasId);
    if (!canvas)
    {
        console.warn("Failed to retrieve the WebGL canvas!");
        return null;
    }

    gl = getWebGlContext();
    if (!gl)
    {
        console.warn("Failed to get an WebGL rendering context!");
        return null;
    }

    let viewer = new gltfViewer(canvas, index, headless, onRendererReady);

    canvas.onmousedown = viewer.onMouseDown.bind(viewer);
    document.onmouseup = viewer.onMouseUp.bind(viewer);
    document.onmousemove = viewer.onMouseMove.bind(viewer);
    canvas.onwheel = viewer.onMouseWheel.bind(viewer);
    canvas.ontouchstart = viewer.onTouchStart.bind(viewer);
    document.ontouchend = viewer.onTouchEnd.bind(viewer);
    document.ontouchmove = viewer.onTouchMove.bind(viewer);

    canvas.ondrop = viewer.dropEventHandler.bind(viewer);
    canvas.ondragover = viewer.dragOverHandler.bind(viewer);

    return viewer; // Succeeded in creating a glTF viewer!
}

function getWebGlContext()
{
    const parameters = { alpha: false, antialias: true };
    const type = [ "webgl", "experimental-webgl" ];

    let context;

    for (const name of names)
    {
        context = canvas.getContext(type, parameters);
        if (context)
        {
            return context;
        }
    }
}
<|endoftext|>


<commit_before>var prePageTag = '<pb id="prePage"/>\n';
var emptyPrePageRegex = new RegExp(prePageTag + '\\s*', 'g');
var delim = '~!iamdelim~!';
var sutraRegex = /<sutra id="[^<>]*(\d+)[^<>\d]*"\/>/;

function notEmptyPrePage(str) {
  var rmPbNl = str.replace(emptyPrePageRegex, '')
    .replace(/\s/g, '');
  return rmPbNl !== '';
}

function getTextsAndSplit(texts, noBampoTag) {
  var wholeText = prePageTag + texts.join(prePageTag);
  var pages = wholeText.replace(/(<pb)/g, delim + '$1')
    .split(delim)
    .filter(notEmptyPrePage);

  if (noBampoTag) {

  }
}

module.exports = getTextsAndSplit;<commit_msg>add paging<commit_after>var prePageTag = '<pb id="prePage"/>\n';
var emptyPrePageRegex = new RegExp(prePageTag + '\\s*', 'g');
var delim = '~!iamdelim~!';
var sutraRegex = /<sutra id="[^<>]*(\d+)[^<>\d]*"\/>/;

function split20Page(pages) {
  var results = [];
  pages.forEach(function(page) {

  });
}

function notEmptyPrePage(str) {
  var rmPbNl = str.replace(emptyPrePageRegex, '')
    .replace(/\s/g, '');
  return rmPbNl !== '';
}

function paging(strs) {
  return (prePageTag + strs.join(prePageTag))
    .replace(/(<pb)/g, delim + '$1')
    .split(delim)
    .filter(notEmptyPrePage);
}

function getTextsAndSplit(texts, noBampoTag) {
  var pages = paging(texts);

  if (noBampoTag) {

  }
}

module.exports = getTextsAndSplit;<|endoftext|>


<commit_before>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

if (process.argv.indexOf('--prof-startup') >= 0) {
	var profiler = require('v8-profiler');
	var prefix = require('crypto').randomBytes(2).toString('hex');
	process.env.VSCODE_PROFILES_PREFIX = prefix;
	profiler.startProfiling('main', true);
}

// Workaround for https://github.com/electron/electron/issues/9225. Chrome has an issue where
// in certain locales (e.g. PL), image metrics are wrongly computed. We explicitly set the
// LC_NUMERIC to prevent this from happening (selects the numeric formatting category of the
// C locale, http://en.cppreference.com/w/cpp/locale/LC_categories).
process.env.LC_NUMERIC = 'C';

// Perf measurements
global.perfStartTime = Date.now();

var app = require('electron').app;
var fs = require('fs');
var path = require('path');
var minimist = require('minimist');
var paths = require('./paths');

var args = minimist(process.argv, {
	string: ['user-data-dir', 'locale']
});

function stripComments(content) {
	var regexp = /("(?:[^\\\"]*(?:\\.)?)*")|('(?:[^\\\']*(?:\\.)?)*')|(\/\*(?:\r?\n|.)*?\*\/)|(\/{2,}.*?(?:(?:\r?\n)|$))/g;
	var result = content.replace(regexp, function (match, m1, m2, m3, m4) {
		// Only one of m1, m2, m3, m4 matches
		if (m3) {
			// A block comment. Replace with nothing
			return '';
		}
		else if (m4) {
			// A line comment. If it ends in \r?\n then keep it.
			var length_1 = m4.length;
			if (length_1 > 2 && m4[length_1 - 1] === '\n') {
				return m4[length_1 - 2] === '\r' ? '\r\n' : '\n';
			}
			else {
				return '';
			}
		}
		else {
			// We match a string
			return match;
		}
	});
	return result;
}

function getNLSConfiguration() {
	var locale = args['locale'];

	if (!locale) {
		var userData = app.getPath('userData');
		var localeConfig = path.join(userData, 'User', 'locale.json');
		if (fs.existsSync(localeConfig)) {
			try {
				var content = stripComments(fs.readFileSync(localeConfig, 'utf8'));
				var value = JSON.parse(content).locale;
				if (value && typeof value === 'string') {
					locale = value;
				}
			} catch (e) {
				// noop
			}
		}
	}

	var appLocale = app.getLocale();
	locale = locale || appLocale;
	// Language tags are case insensitve however an amd loader is case sensitive
	// To make this work on case preserving & insensitive FS we do the following:
	// the language bundles have lower case language tags and we always lower case
	// the locale we receive from the user or OS.
	locale = locale ? locale.toLowerCase() : locale;
	if (locale === 'pseudo') {
		return { locale: locale, availableLanguages: {}, pseudo: true };
	}
	var initialLocale = locale;
	if (process.env['VSCODE_DEV']) {
		return { locale: locale, availableLanguages: {} };
	}

	// We have a built version so we have extracted nls file. Try to find
	// the right file to use.

	// Check if we have an English locale. If so fall to default since that is our
	// English translation (we don't ship *.nls.en.json files)
	if (locale && (locale == 'en' || locale.startsWith('en-'))) {
		return { locale: locale, availableLanguages: {} };
	}

	function resolveLocale(locale) {
		while (locale) {
			var candidate = path.join(__dirname, 'vs', 'code', 'electron-main', 'main.nls.') + locale + '.js';
			if (fs.existsSync(candidate)) {
				return { locale: initialLocale, availableLanguages: { '*': locale } };
			} else {
				var index = locale.lastIndexOf('-');
				if (index > 0) {
					locale = locale.substring(0, index);
				} else {
					locale = null;
				}
			}
		}
		return null;
	}

	var resolvedLocale = resolveLocale(locale);
	if (!resolvedLocale && appLocale && appLocale !== locale) {
		resolvedLocale = resolveLocale(appLocale);
	}
	return resolvedLocale ? resolvedLocale : { locale: initialLocale, availableLanguages: {} };
}

function getNodeCachedDataDir() {

	// IEnvironmentService.isBuilt
	if (process.env['VSCODE_DEV']) {
		return Promise.resolve(undefined);
	}

	// find commit id
	var productJson = require(path.join(__dirname, '../product.json'));
	if (!productJson.commit) {
		return Promise.resolve(undefined);
	}

	var dir = path.join(app.getPath('userData'), 'CachedData', productJson.commit);

	return mkdirp(dir).then(undefined, function (err) { /*ignore*/ });
}

function mkdirp(dir) {
	return mkdir(dir)
		.then(null, function (err) {
			if (err && err.code === 'ENOENT') {
				var parent = path.dirname(dir);
				if (parent !== dir) { // if not arrived at root
					return mkdirp(parent)
						.then(function () {
							return mkdir(dir);
						});
				}
			}
			throw err;
		});
}

function mkdir(dir) {
	return new Promise(function (resolve, reject) {
		fs.mkdir(dir, function (err) {
			if (err && err.code !== 'EEXIST') {
				reject(err);
			} else {
				resolve(dir);
			}
		});
	});
}

// Set userData path before app 'ready' event and call to process.chdir
var userData = path.resolve(args['user-data-dir'] || paths.getDefaultUserDataPath(process.platform));
app.setPath('userData', userData);

// Update cwd based on environment and platform
try {
	if (process.platform === 'win32') {
		process.env['VSCODE_CWD'] = process.cwd(); // remember as environment variable
		process.chdir(path.dirname(app.getPath('exe'))); // always set application folder as cwd
	} else if (process.env['VSCODE_CWD']) {
		process.chdir(process.env['VSCODE_CWD']);
	}
} catch (err) {
	console.error(err);
}

// Mac: when someone drops a file to the not-yet running VSCode, the open-file event fires even before
// the app-ready event. We listen very early for open-file and remember this upon startup as path to open.
global.macOpenFiles = [];
app.on('open-file', function (event, path) {
	global.macOpenFiles.push(path);
});

var openUrls = [];
var onOpenUrl = function (event, url) {
	event.preventDefault();
	openUrls.push(url);
};

app.on('will-finish-launching', function () {
	app.on('open-url', onOpenUrl);
});

global.getOpenUrls = function () {
	app.removeListener('open-url', onOpenUrl);
	return openUrls;
};

// use '<UserData>/CachedData'-directory to store
// node/v8 cached data.
var nodeCachedDataDir = getNodeCachedDataDir().then(function (value) {
	if (value) {
		// store the data directory
		process.env['VSCODE_NODE_CACHED_DATA_DIR_' + process.pid] = value;

		// tell v8 to not be lazy when parsing JavaScript. Generally this makes startup slower
		// but because we generate cached data it makes subsequent startups much faster
		app.commandLine.appendSwitch('--js-flags', '--nolazy');
	}
});

// Load our code once ready
app.once('ready', function () {
	global.perfAppReady = Date.now();
	var nlsConfig = getNLSConfiguration();
	process.env['VSCODE_NLS_CONFIG'] = JSON.stringify(nlsConfig);

	nodeCachedDataDir.then(function () {
		require('./bootstrap-amd').bootstrap('vs/code/electron-main/main');
	}, console.error);
});
<commit_msg>add todo for electron update related workaround<commit_after>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

if (process.argv.indexOf('--prof-startup') >= 0) {
	var profiler = require('v8-profiler');
	var prefix = require('crypto').randomBytes(2).toString('hex');
	process.env.VSCODE_PROFILES_PREFIX = prefix;
	profiler.startProfiling('main', true);
}

// Workaround for https://github.com/electron/electron/issues/9225. Chrome has an issue where
// in certain locales (e.g. PL), image metrics are wrongly computed. We explicitly set the
// LC_NUMERIC to prevent this from happening (selects the numeric formatting category of the
// C locale, http://en.cppreference.com/w/cpp/locale/LC_categories). TODO@Ben temporary.
process.env.LC_NUMERIC = 'C';

// Perf measurements
global.perfStartTime = Date.now();

var app = require('electron').app;
var fs = require('fs');
var path = require('path');
var minimist = require('minimist');
var paths = require('./paths');

var args = minimist(process.argv, {
	string: ['user-data-dir', 'locale']
});

function stripComments(content) {
	var regexp = /("(?:[^\\\"]*(?:\\.)?)*")|('(?:[^\\\']*(?:\\.)?)*')|(\/\*(?:\r?\n|.)*?\*\/)|(\/{2,}.*?(?:(?:\r?\n)|$))/g;
	var result = content.replace(regexp, function (match, m1, m2, m3, m4) {
		// Only one of m1, m2, m3, m4 matches
		if (m3) {
			// A block comment. Replace with nothing
			return '';
		}
		else if (m4) {
			// A line comment. If it ends in \r?\n then keep it.
			var length_1 = m4.length;
			if (length_1 > 2 && m4[length_1 - 1] === '\n') {
				return m4[length_1 - 2] === '\r' ? '\r\n' : '\n';
			}
			else {
				return '';
			}
		}
		else {
			// We match a string
			return match;
		}
	});
	return result;
}

function getNLSConfiguration() {
	var locale = args['locale'];

	if (!locale) {
		var userData = app.getPath('userData');
		var localeConfig = path.join(userData, 'User', 'locale.json');
		if (fs.existsSync(localeConfig)) {
			try {
				var content = stripComments(fs.readFileSync(localeConfig, 'utf8'));
				var value = JSON.parse(content).locale;
				if (value && typeof value === 'string') {
					locale = value;
				}
			} catch (e) {
				// noop
			}
		}
	}

	var appLocale = app.getLocale();
	locale = locale || appLocale;
	// Language tags are case insensitve however an amd loader is case sensitive
	// To make this work on case preserving & insensitive FS we do the following:
	// the language bundles have lower case language tags and we always lower case
	// the locale we receive from the user or OS.
	locale = locale ? locale.toLowerCase() : locale;
	if (locale === 'pseudo') {
		return { locale: locale, availableLanguages: {}, pseudo: true };
	}
	var initialLocale = locale;
	if (process.env['VSCODE_DEV']) {
		return { locale: locale, availableLanguages: {} };
	}

	// We have a built version so we have extracted nls file. Try to find
	// the right file to use.

	// Check if we have an English locale. If so fall to default since that is our
	// English translation (we don't ship *.nls.en.json files)
	if (locale && (locale == 'en' || locale.startsWith('en-'))) {
		return { locale: locale, availableLanguages: {} };
	}

	function resolveLocale(locale) {
		while (locale) {
			var candidate = path.join(__dirname, 'vs', 'code', 'electron-main', 'main.nls.') + locale + '.js';
			if (fs.existsSync(candidate)) {
				return { locale: initialLocale, availableLanguages: { '*': locale } };
			} else {
				var index = locale.lastIndexOf('-');
				if (index > 0) {
					locale = locale.substring(0, index);
				} else {
					locale = null;
				}
			}
		}
		return null;
	}

	var resolvedLocale = resolveLocale(locale);
	if (!resolvedLocale && appLocale && appLocale !== locale) {
		resolvedLocale = resolveLocale(appLocale);
	}
	return resolvedLocale ? resolvedLocale : { locale: initialLocale, availableLanguages: {} };
}

function getNodeCachedDataDir() {

	// IEnvironmentService.isBuilt
	if (process.env['VSCODE_DEV']) {
		return Promise.resolve(undefined);
	}

	// find commit id
	var productJson = require(path.join(__dirname, '../product.json'));
	if (!productJson.commit) {
		return Promise.resolve(undefined);
	}

	var dir = path.join(app.getPath('userData'), 'CachedData', productJson.commit);

	return mkdirp(dir).then(undefined, function (err) { /*ignore*/ });
}

function mkdirp(dir) {
	return mkdir(dir)
		.then(null, function (err) {
			if (err && err.code === 'ENOENT') {
				var parent = path.dirname(dir);
				if (parent !== dir) { // if not arrived at root
					return mkdirp(parent)
						.then(function () {
							return mkdir(dir);
						});
				}
			}
			throw err;
		});
}

function mkdir(dir) {
	return new Promise(function (resolve, reject) {
		fs.mkdir(dir, function (err) {
			if (err && err.code !== 'EEXIST') {
				reject(err);
			} else {
				resolve(dir);
			}
		});
	});
}

// Set userData path before app 'ready' event and call to process.chdir
var userData = path.resolve(args['user-data-dir'] || paths.getDefaultUserDataPath(process.platform));
app.setPath('userData', userData);

// Update cwd based on environment and platform
try {
	if (process.platform === 'win32') {
		process.env['VSCODE_CWD'] = process.cwd(); // remember as environment variable
		process.chdir(path.dirname(app.getPath('exe'))); // always set application folder as cwd
	} else if (process.env['VSCODE_CWD']) {
		process.chdir(process.env['VSCODE_CWD']);
	}
} catch (err) {
	console.error(err);
}

// Mac: when someone drops a file to the not-yet running VSCode, the open-file event fires even before
// the app-ready event. We listen very early for open-file and remember this upon startup as path to open.
global.macOpenFiles = [];
app.on('open-file', function (event, path) {
	global.macOpenFiles.push(path);
});

var openUrls = [];
var onOpenUrl = function (event, url) {
	event.preventDefault();
	openUrls.push(url);
};

app.on('will-finish-launching', function () {
	app.on('open-url', onOpenUrl);
});

global.getOpenUrls = function () {
	app.removeListener('open-url', onOpenUrl);
	return openUrls;
};

// use '<UserData>/CachedData'-directory to store
// node/v8 cached data.
var nodeCachedDataDir = getNodeCachedDataDir().then(function (value) {
	if (value) {
		// store the data directory
		process.env['VSCODE_NODE_CACHED_DATA_DIR_' + process.pid] = value;

		// tell v8 to not be lazy when parsing JavaScript. Generally this makes startup slower
		// but because we generate cached data it makes subsequent startups much faster
		app.commandLine.appendSwitch('--js-flags', '--nolazy');
	}
});

// Load our code once ready
app.once('ready', function () {
	global.perfAppReady = Date.now();
	var nlsConfig = getNLSConfiguration();
	process.env['VSCODE_NLS_CONFIG'] = JSON.stringify(nlsConfig);

	nodeCachedDataDir.then(function () {
		require('./bootstrap-amd').bootstrap('vs/code/electron-main/main');
	}, console.error);
});
<|endoftext|>


<commit_before>import fs from 'fs';
import path from 'path';
import chalk from 'chalk';
import * as injectDebugger from './injectDebugger';
import * as injectServer from './injectServer';
import runServer from './runServer';

const bundleCode = fs.readFileSync(path.join(__dirname, '../bundle.js'), 'utf-8');

const getModuleName = (type) => {
  switch (type) {
    case 'macos':
      return 'react-native-macos';
    // react-native-macos is renamed from react-native-desktop
    case 'desktop':
      return 'react-native-desktop';
    default:
      return 'react-native';
  }
};
const getModulePath = moduleName => path.join(process.cwd(), 'node_modules', moduleName);
const getModule = (type) => {
  let moduleName = getModuleName(type);
  let modulePath = getModulePath(moduleName);
  if (type === 'desktop' && !fs.existsSync(modulePath)) {
    moduleName = getModuleName('macos');
    modulePath = getModulePath(moduleName);
  }
  return { moduleName, modulePath };
};

const log = (pass, msg) => {
  const prefix = pass ? chalk.green.bgBlack('PASS') : chalk.red.bgBlack('FAIL');
  const color = pass ? chalk.blue : chalk.red;
  console.log(prefix, color(msg));
};

const getFullPath = filePath => path.resolve(process.cwd(), filePath);
const assignSecureOptions = (options, { secure, key, cert, passphrase }) => ({
  ...options,
  ...(secure
    ? {
      protocol: 'https',
      key: key ? getFullPath(key) : null,
      cert: cert ? getFullPath(cert) : null,
      passphrase: passphrase || null,
    }
    : null),
});

module.exports = (argv) => {
  const type = argv.desktop ? 'desktop' : argv.macos && 'macos';
  const { moduleName, modulePath } = getModule(type);
  const serverPath = path.join(moduleName, injectServer.fullPath);
  const debuggerPath = path.join(moduleName, injectDebugger.fullPath);

  // Revert all injection
  if (argv.revert) {
    const passServ = injectServer.revert(modulePath, moduleName);
    let msg = 'Revert injection of RemoteDev server from React Native local server';
    log(passServ, msg + (!passServ ? `, the file '${serverPath}' not found.` : '.'));

    const passDbg = injectDebugger.revert(modulePath);
    msg = 'Revert injection of RemoteDev monitor from React Native debugger';
    log(passDbg, msg + (!passDbg ? `, the file '${debuggerPath}' not found.` : '.'));

    return passServ && passDbg;
  }

  const options =
    argv.hostname || argv.port
      ? {
        secure: argv.secure,
        hostname: argv.hostname || 'localhost',
        port: argv.port || 8000,
        showtips: argv.showtips,
      }
      : null;

  // Inject server
  if (argv.injectserver) {
    const pass = injectServer.inject(modulePath, assignSecureOptions(options, argv), moduleName);
    const msg = 'Inject RemoteDev server into React Native local server';
    log(pass, msg + (pass ? '.' : `, the file '${serverPath}' not found.`));
    if (!pass) return false;
  }

  // Inject debugger
  if (argv.injectdebugger) {
    const pass = injectDebugger.inject(modulePath, bundleCode, options);
    const msg = 'Inject RemoteDev monitor into React Native debugger';
    log(pass, msg + (pass ? '.' : `, the file '${debuggerPath}' not found.`));
    if (!pass) return false;
  }

  // Run RemoteDev server
  if (argv.runserver) {
    return runServer(assignSecureOptions(options || { secure: argv.secure, port: 8000 }, argv));
  }
  return true;
};
<commit_msg>Fix options for injectDebugger, closes #24<commit_after>import fs from 'fs';
import path from 'path';
import chalk from 'chalk';
import * as injectDebugger from './injectDebugger';
import * as injectServer from './injectServer';
import runServer from './runServer';

const bundleCode = fs.readFileSync(path.join(__dirname, '../bundle.js'), 'utf-8');

const getModuleName = (type) => {
  switch (type) {
    case 'macos':
      return 'react-native-macos';
    // react-native-macos is renamed from react-native-desktop
    case 'desktop':
      return 'react-native-desktop';
    default:
      return 'react-native';
  }
};
const getModulePath = moduleName => path.join(process.cwd(), 'node_modules', moduleName);
const getModule = (type) => {
  let moduleName = getModuleName(type);
  let modulePath = getModulePath(moduleName);
  if (type === 'desktop' && !fs.existsSync(modulePath)) {
    moduleName = getModuleName('macos');
    modulePath = getModulePath(moduleName);
  }
  return { moduleName, modulePath };
};

const log = (pass, msg) => {
  const prefix = pass ? chalk.green.bgBlack('PASS') : chalk.red.bgBlack('FAIL');
  const color = pass ? chalk.blue : chalk.red;
  console.log(prefix, color(msg));
};

const getFullPath = filePath => path.resolve(process.cwd(), filePath);
const assignSecureOptions = (options, { secure, key, cert, passphrase }) => ({
  ...options,
  ...(secure
    ? {
      protocol: 'https',
      key: key ? getFullPath(key) : null,
      cert: cert ? getFullPath(cert) : null,
      passphrase: passphrase || null,
    }
    : null),
});

module.exports = (argv) => {
  const type = argv.desktop ? 'desktop' : argv.macos && 'macos';
  const { moduleName, modulePath } = getModule(type);
  const serverPath = path.join(moduleName, injectServer.fullPath);
  const debuggerPath = path.join(moduleName, injectDebugger.fullPath);

  // Revert all injection
  if (argv.revert) {
    const passServ = injectServer.revert(modulePath, moduleName);
    let msg = 'Revert injection of RemoteDev server from React Native local server';
    log(passServ, msg + (!passServ ? `, the file '${serverPath}' not found.` : '.'));

    const passDbg = injectDebugger.revert(modulePath);
    msg = 'Revert injection of RemoteDev monitor from React Native debugger';
    log(passDbg, msg + (!passDbg ? `, the file '${debuggerPath}' not found.` : '.'));

    return passServ && passDbg;
  }

  const defaultOptions = { showtips: argv.showtips };
  const options =
    argv.hostname || argv.port
      ? {
        secure: argv.secure,
        hostname: argv.hostname || 'localhost',
        port: argv.port || 8000,
        ...defaultOptions,
      }
      : defaultOptions;

  // Inject server
  if (argv.injectserver) {
    const pass = injectServer.inject(modulePath, assignSecureOptions(options, argv), moduleName);
    const msg = 'Inject RemoteDev server into React Native local server';
    log(pass, msg + (pass ? '.' : `, the file '${serverPath}' not found.`));
    if (!pass) return false;
  }

  // Inject debugger
  if (argv.injectdebugger) {
    const pass = injectDebugger.inject(modulePath, bundleCode, options);
    const msg = 'Inject RemoteDev monitor into React Native debugger';
    log(pass, msg + (pass ? '.' : `, the file '${debuggerPath}' not found.`));
    if (!pass) return false;
  }

  // Run RemoteDev server
  if (argv.runserver) {
    return runServer(assignSecureOptions({ secure: argv.secure, port: 8000, ...options }, argv));
  }
  return true;
};
<|endoftext|>