<commit_before>import ShadersBase from '../shaders.base';

class Unpack extends ShadersBase {

  constructor() {
    super();
    this.name = 'unpack';

    // default properties names
    this._packedData = 'packedData';
    this._offset = 'offset';
    this._unpackedData = 'unpackedData';

    this._base._uniforms ={
      uNumberOfChannels: {
        value: 1,
      },
      uBitsAllocated: {
        value: 16,
      },
      uPixelType: {
        value: 0,
      },
    };
  }

  api(baseFragment = this._base, packedData = this._packedData, offset = this._offset, unpackedData = this._unpackedData) {
    this._base = baseFragment;
    return this.compute(packedData, offset, unpackedData);
  }

  compute(packedData, offset, unpackedData) {
    this.computeDefinition();
    this._base._functions[this._name] = this._definition;
    return `${this._name}(${packedData}, ${offset}, ${unpackedData});`;
  }

  computeDefinition() {
    // fun stuff
    let content = '';
    if (this._base._uniforms.uNumberOfChannels.value === 1) {
      switch (this._base._uniforms.uBitsAllocated.value) {

        case 1:
        case 8:
          content = this.upack8();
          break;

        case 16:
          content = this.upack16();
          break;

        case 32:
          content = this.upack32();
          break;

        default:
          content = this.upackDefault();
          break;

      }
    } else {
      content = this.upackIdentity();
    }

    this._definition = `
void ${this._name}(in vec4 packedData, in int offset, out vec4 unpackedData){

${content}

}
    `;
  }

  upack8() {
    this._base._functions['uInt8'] = this.uInt8();

    return `
uInt8(
  packedData.r,
  unpackedData.x);
    `;
  }

  upack16() {
    this._base._functions['uInt16'] = this.uInt16();

    return `
uInt16(
  packedData.r * float( 1 - offset) + packedData.b * float(offset),
  packedData.g * float( 1 - offset) + packedData.a * float(offset),
  unpackedData.x);
    `;
  }

  upack32() {
    if (this._base._uniforms.uPixelType.value === 0) {
      this._base._functions['uInt32'] = this.uInt32();

      return `
uInt32(
  packedData.r,
  packedData.g,
  packedData.b,
  packedData.a,
  unpackedData.x);
      `;
    } else {
      this._base._functions['uFloat32'] = this.uFloat32();

      return `
uFloat32(
  packedData.r,
  packedData.g,
  packedData.b,
  packedData.a,
  unpackedData.x);
      `;
    }
  }

  upackIdentity() {
    return `

unpackedData = packedData;

      `;
  }

  uInt8() {
    return `
void uInt8(in float r, out float value){
  value = r * 256.;
}
    `;
  }

  uInt16() {
    return `
void uInt16(in float r, in float a, out float value){
  value = r * 256. + a * 65536.;
}
    `;
  }

  uInt32() {
    return `
void uInt32(in float r, in float g, in float b, in float a, out float value){
  value = r * 256. + g * 65536. + b * 16777216.; // + a * 4294967296.;
}
    `;
  }

  uFloat32() {
    return `
void uFloat32(in float r, in float g, in float b, in float a, out float value){

  // create arrays containing bits for rgba values
  // value between 0 and 255
  value = r * 255.;
  int bytemeR[8];
  bytemeR[0] = int(floor(value / 128.));
  value -= float(bytemeR[0] * 128);
  bytemeR[1] = int(floor(value / 64.));
  value -= float(bytemeR[1] * 64);
  bytemeR[2] = int(floor(value / 32.));
  value -= float(bytemeR[2] * 32);
  bytemeR[3] = int(floor(value / 16.));
  value -= float(bytemeR[3] * 16);
  bytemeR[4] = int(floor(value / 8.));
  value -= float(bytemeR[4] * 8);
  bytemeR[5] = int(floor(value / 4.));
  value -= float(bytemeR[5] * 4);
  bytemeR[6] = int(floor(value / 2.));
  value -= float(bytemeR[6] * 2);
  bytemeR[7] = int(floor(value));

  value = g * 255.;
  int bytemeG[8];
  bytemeG[0] = int(floor(value / 128.));
  value -= float(bytemeG[0] * 128);
  bytemeG[1] = int(floor(value / 64.));
  value -= float(bytemeG[1] * 64);
  bytemeG[2] = int(floor(value / 32.));
  value -= float(bytemeG[2] * 32);
  bytemeG[3] = int(floor(value / 16.));
  value -= float(bytemeG[3] * 16);
  bytemeG[4] = int(floor(value / 8.));
  value -= float(bytemeG[4] * 8);
  bytemeG[5] = int(floor(value / 4.));
  value -= float(bytemeG[5] * 4);
  bytemeG[6] = int(floor(value / 2.));
  value -= float(bytemeG[6] * 2);
  bytemeG[7] = int(floor(value));

  value = b * 255.;
  int bytemeB[8];
  bytemeB[0] = int(floor(value / 128.));
  value -= float(bytemeB[0] * 128);
  bytemeB[1] = int(floor(value / 64.));
  value -= float(bytemeB[1] * 64);
  bytemeB[2] = int(floor(value / 32.));
  value -= float(bytemeB[2] * 32);
  bytemeB[3] = int(floor(value / 16.));
  value -= float(bytemeB[3] * 16);
  bytemeB[4] = int(floor(value / 8.));
  value -= float(bytemeB[4] * 8);
  bytemeB[5] = int(floor(value / 4.));
  value -= float(bytemeB[5] * 4);
  bytemeB[6] = int(floor(value / 2.));
  value -= float(bytemeB[6] * 2);
  bytemeB[7] = int(floor(value));

  value = a * 255.;
  int bytemeA[8];
  bytemeA[0] = int(floor(value / 128.));
  value -= float(bytemeA[0] * 128);
  bytemeA[1] = int(floor(value / 64.));
  value -= float(bytemeA[1] * 64);
  bytemeA[2] = int(floor(value / 32.));
  value -= float(bytemeA[2] * 32);
  bytemeA[3] = int(floor(value / 16.));
  value -= float(bytemeA[3] * 16);
  bytemeA[4] = int(floor(value / 8.));
  value -= float(bytemeA[4] * 8);
  bytemeA[5] = int(floor(value / 4.));
  value -= float(bytemeA[5] * 4);
  bytemeA[6] = int(floor(value / 2.));
  value -= float(bytemeA[6] * 2);
  bytemeA[7] = int(floor(value));

  // compute float32 value from bit arrays

  // sign
  int issigned = 1 - 2 * bytemeR[0];
  //   issigned = int(pow(-1., float(bytemeR[0])));

  // exponent
  int exponent = 0;

  exponent += bytemeR[1] * int(pow(2., 7.));
  exponent += bytemeR[2] * int(pow(2., 6.));
  exponent += bytemeR[3] * int(pow(2., 5.));
  exponent += bytemeR[4] * int(pow(2., 4.));
  exponent += bytemeR[5] * int(pow(2., 3.));
  exponent += bytemeR[6] * int(pow(2., 2.));
  exponent += bytemeR[7] * int(pow(2., 1.));

  exponent += bytemeG[0];

  // fraction
  float fraction = 0.;

  fraction = float(bytemeG[1]) * pow(2., -1.);
  fraction += float(bytemeG[2]) * pow(2., -2.);
  fraction += float(bytemeG[3]) * pow(2., -3.);
  fraction += float(bytemeG[4]) * pow(2., -4.);
  fraction += float(bytemeG[5]) * pow(2., -5.);
  fraction += float(bytemeG[6]) * pow(2., -6.);
  fraction += float(bytemeG[7]) * pow(2., -7.);

  fraction += float(bytemeB[0]) * pow(2., -8.);
  fraction += float(bytemeB[1]) * pow(2., -9.);
  fraction += float(bytemeB[2]) * pow(2., -10.);
  fraction += float(bytemeB[3]) * pow(2., -11.);
  fraction += float(bytemeB[4]) * pow(2., -12.);
  fraction += float(bytemeB[5]) * pow(2., -13.);
  fraction += float(bytemeB[6]) * pow(2., -14.);
  fraction += float(bytemeB[7]) * pow(2., -15.);

  fraction += float(bytemeA[0]) * pow(2., -16.);
  fraction += float(bytemeA[1]) * pow(2., -17.);
  fraction += float(bytemeA[2]) * pow(2., -18.);
  fraction += float(bytemeA[3]) * pow(2., -19.);
  fraction += float(bytemeA[4]) * pow(2., -20.);
  fraction += float(bytemeA[5]) * pow(2., -21.);
  fraction += float(bytemeA[6]) * pow(2., -22.);
  fraction += float(bytemeA[7]) * pow(2., -23.);

  value = float(issigned) * pow( 2., float(exponent - 127)) * (1. + fraction);
}
    `;
  }

}

export default new Unpack();
<commit_msg>Fix uInt32 unpacking.<commit_after>import ShadersBase from '../shaders.base';

class Unpack extends ShadersBase {

  constructor() {
    super();
    this.name = 'unpack';

    // default properties names
    this._packedData = 'packedData';
    this._offset = 'offset';
    this._unpackedData = 'unpackedData';

    this._base._uniforms ={
      uNumberOfChannels: {
        value: 1,
      },
      uBitsAllocated: {
        value: 16,
      },
      uPixelType: {
        value: 0,
      },
    };
  }

  api(baseFragment = this._base, packedData = this._packedData, offset = this._offset, unpackedData = this._unpackedData) {
    this._base = baseFragment;
    return this.compute(packedData, offset, unpackedData);
  }

  compute(packedData, offset, unpackedData) {
    this.computeDefinition();
    this._base._functions[this._name] = this._definition;
    return `${this._name}(${packedData}, ${offset}, ${unpackedData});`;
  }

  computeDefinition() {
    // fun stuff
    let content = '';
    if (this._base._uniforms.uNumberOfChannels.value === 1) {
      switch (this._base._uniforms.uBitsAllocated.value) {

        case 1:
        case 8:
          content = this.upack8();
          break;

        case 16:
          content = this.upack16();
          break;

        case 32:
          content = this.upack32();
          break;

        default:
          content = this.upackDefault();
          break;

      }
    } else {
      content = this.upackIdentity();
    }

    this._definition = `
void ${this._name}(in vec4 packedData, in int offset, out vec4 unpackedData){

${content}

}
    `;
  }

  upack8() {
    this._base._functions['uInt8'] = this.uInt8();

    return `
uInt8(
  packedData.r,
  unpackedData.x);
    `;
  }

  upack16() {
    this._base._functions['uInt16'] = this.uInt16();

    return `
uInt16(
  packedData.r * float( 1 - offset) + packedData.b * float(offset),
  packedData.g * float( 1 - offset) + packedData.a * float(offset),
  unpackedData.x);
    `;
  }

  upack32() {
    if (this._base._uniforms.uPixelType.value === 0) {
      this._base._functions['uInt32'] = this.uInt32();

      return `
uInt32(
  packedData.r,
  packedData.g,
  packedData.b,
  packedData.a,
  unpackedData.x);
      `;
    } else {
      this._base._functions['uFloat32'] = this.uFloat32();

      return `
uFloat32(
  packedData.r,
  packedData.g,
  packedData.b,
  packedData.a,
  unpackedData.x);
      `;
    }
  }

  upackIdentity() {
    return `

unpackedData = packedData;

      `;
  }

  uInt8() {
    return `
void uInt8(in float r, out float value){
  value = r * 256.;
}
    `;
  }

  uInt16() {
    return `
void uInt16(in float r, in float a, out float value){
  value = r * 256. + a * 65536.;
}
    `;
  }

  uInt32() {
    return `
void uInt32(in float r, in float g, in float b, in float a, out float value){
  value = r * 256. + g * 65536. + b * 16777216. + a * 4294967296.;
}
    `;
  }

  uFloat32() {
    return `
void uFloat32(in float r, in float g, in float b, in float a, out float value){

  // create arrays containing bits for rgba values
  // value between 0 and 255
  value = r * 255.;
  int bytemeR[8];
  bytemeR[0] = int(floor(value / 128.));
  value -= float(bytemeR[0] * 128);
  bytemeR[1] = int(floor(value / 64.));
  value -= float(bytemeR[1] * 64);
  bytemeR[2] = int(floor(value / 32.));
  value -= float(bytemeR[2] * 32);
  bytemeR[3] = int(floor(value / 16.));
  value -= float(bytemeR[3] * 16);
  bytemeR[4] = int(floor(value / 8.));
  value -= float(bytemeR[4] * 8);
  bytemeR[5] = int(floor(value / 4.));
  value -= float(bytemeR[5] * 4);
  bytemeR[6] = int(floor(value / 2.));
  value -= float(bytemeR[6] * 2);
  bytemeR[7] = int(floor(value));

  value = g * 255.;
  int bytemeG[8];
  bytemeG[0] = int(floor(value / 128.));
  value -= float(bytemeG[0] * 128);
  bytemeG[1] = int(floor(value / 64.));
  value -= float(bytemeG[1] * 64);
  bytemeG[2] = int(floor(value / 32.));
  value -= float(bytemeG[2] * 32);
  bytemeG[3] = int(floor(value / 16.));
  value -= float(bytemeG[3] * 16);
  bytemeG[4] = int(floor(value / 8.));
  value -= float(bytemeG[4] * 8);
  bytemeG[5] = int(floor(value / 4.));
  value -= float(bytemeG[5] * 4);
  bytemeG[6] = int(floor(value / 2.));
  value -= float(bytemeG[6] * 2);
  bytemeG[7] = int(floor(value));

  value = b * 255.;
  int bytemeB[8];
  bytemeB[0] = int(floor(value / 128.));
  value -= float(bytemeB[0] * 128);
  bytemeB[1] = int(floor(value / 64.));
  value -= float(bytemeB[1] * 64);
  bytemeB[2] = int(floor(value / 32.));
  value -= float(bytemeB[2] * 32);
  bytemeB[3] = int(floor(value / 16.));
  value -= float(bytemeB[3] * 16);
  bytemeB[4] = int(floor(value / 8.));
  value -= float(bytemeB[4] * 8);
  bytemeB[5] = int(floor(value / 4.));
  value -= float(bytemeB[5] * 4);
  bytemeB[6] = int(floor(value / 2.));
  value -= float(bytemeB[6] * 2);
  bytemeB[7] = int(floor(value));

  value = a * 255.;
  int bytemeA[8];
  bytemeA[0] = int(floor(value / 128.));
  value -= float(bytemeA[0] * 128);
  bytemeA[1] = int(floor(value / 64.));
  value -= float(bytemeA[1] * 64);
  bytemeA[2] = int(floor(value / 32.));
  value -= float(bytemeA[2] * 32);
  bytemeA[3] = int(floor(value / 16.));
  value -= float(bytemeA[3] * 16);
  bytemeA[4] = int(floor(value / 8.));
  value -= float(bytemeA[4] * 8);
  bytemeA[5] = int(floor(value / 4.));
  value -= float(bytemeA[5] * 4);
  bytemeA[6] = int(floor(value / 2.));
  value -= float(bytemeA[6] * 2);
  bytemeA[7] = int(floor(value));

  // compute float32 value from bit arrays

  // sign
  int issigned = 1 - 2 * bytemeR[0];
  //   issigned = int(pow(-1., float(bytemeR[0])));

  // exponent
  int exponent = 0;

  exponent += bytemeR[1] * int(pow(2., 7.));
  exponent += bytemeR[2] * int(pow(2., 6.));
  exponent += bytemeR[3] * int(pow(2., 5.));
  exponent += bytemeR[4] * int(pow(2., 4.));
  exponent += bytemeR[5] * int(pow(2., 3.));
  exponent += bytemeR[6] * int(pow(2., 2.));
  exponent += bytemeR[7] * int(pow(2., 1.));

  exponent += bytemeG[0];

  // fraction
  float fraction = 0.;

  fraction = float(bytemeG[1]) * pow(2., -1.);
  fraction += float(bytemeG[2]) * pow(2., -2.);
  fraction += float(bytemeG[3]) * pow(2., -3.);
  fraction += float(bytemeG[4]) * pow(2., -4.);
  fraction += float(bytemeG[5]) * pow(2., -5.);
  fraction += float(bytemeG[6]) * pow(2., -6.);
  fraction += float(bytemeG[7]) * pow(2., -7.);

  fraction += float(bytemeB[0]) * pow(2., -8.);
  fraction += float(bytemeB[1]) * pow(2., -9.);
  fraction += float(bytemeB[2]) * pow(2., -10.);
  fraction += float(bytemeB[3]) * pow(2., -11.);
  fraction += float(bytemeB[4]) * pow(2., -12.);
  fraction += float(bytemeB[5]) * pow(2., -13.);
  fraction += float(bytemeB[6]) * pow(2., -14.);
  fraction += float(bytemeB[7]) * pow(2., -15.);

  fraction += float(bytemeA[0]) * pow(2., -16.);
  fraction += float(bytemeA[1]) * pow(2., -17.);
  fraction += float(bytemeA[2]) * pow(2., -18.);
  fraction += float(bytemeA[3]) * pow(2., -19.);
  fraction += float(bytemeA[4]) * pow(2., -20.);
  fraction += float(bytemeA[5]) * pow(2., -21.);
  fraction += float(bytemeA[6]) * pow(2., -22.);
  fraction += float(bytemeA[7]) * pow(2., -23.);

  value = float(issigned) * pow( 2., float(exponent - 127)) * (1. + fraction);
}
    `;
  }

}

export default new Unpack();
<|endoftext|>


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

define([
	'./plugin',
	'webida-lib/plugins/workbench/plugin',
	'webida-lib/widgets/views/viewmanager',
	'dojo/topic',
	'external/lodash/lodash.min'
], function (
	editors,
	workbench,
	vm,
	topic,
	_
) {
    'use strict';

	function undo() {
        editors.execCommandForCurrentEditorViewer('undo');
	}

	function redo() {
        editors.execCommandForCurrentEditorViewer('redo');
	}

	function cursorLineToMiddle() {
        editors.execCommandForCurrentEditorViewer('cursorLineToMiddle');
	}

	function cursorLineToTop() {
        editors.execCommandForCurrentEditorViewer('cursorLineToTop');
	}

	function cursorLineToBottom() {
        editors.execCommandForCurrentEditorViewer('cursorLineToBottom');
	}

	function del() {
        editors.execCommandForCurrentEditorViewer('del');
	}

	function selectAll() {
        editors.execCommandForCurrentEditorViewer('selectAll');
	}

	function selectLine() {
        editors.execCommandForCurrentEditorViewer('selectLine');
	}

	function lineIndent() {
        editors.execCommandForCurrentEditorViewer('lineIndent');
	}

	function lineDedent() {
        editors.execCommandForCurrentEditorViewer('lineDedent');
	}

	function lineMoveUp() {
        editors.execCommandForCurrentEditorViewer('lineMoveUp');
	}

	function lineMoveDown() {
        editors.execCommandForCurrentEditorViewer('lineMoveDown');
	}

	function lineDelete() {
        editors.execCommandForCurrentEditorViewer('lineDelete');
	}

	function lineComment() {
        editors.execCommandForCurrentEditorViewer('lineComment');
	}

	function blockComment() {
        editors.execCommandForCurrentEditorViewer('blockComment');
	}

	function commentOutSelection() {
        editors.execCommandForCurrentEditorViewer('commentOutSelection');
	}

	function foldCode() {
        editors.execCommandForCurrentEditorViewer('foldCode');
	}

	function beautifyCode() {
        editors.execCommandForCurrentEditorViewer('beautifyCode');
	}

	function beautifyAllCode() {
        editors.execCommandForCurrentEditorViewer('beautifyAllCode');
	}

	function rename() {
        editors.execCommandForCurrentEditorViewer('rename');
	}

    function replace() {
        editors.execCommandForCurrentEditorViewer('replace');
    }

    function find() {
        editors.execCommandForCurrentEditorViewer('find');
    }

    function quickFind() {
        editors.execCommandForCurrentEditorViewer('quickFind');
    }

    function findNext() {
        editors.execCommandForCurrentEditorViewer('findNext');
    }

    function findPrev() {
        editors.execCommandForCurrentEditorViewer('findPrev');
    }

    function gotoDefinition() {
        editors.execCommandForCurrentEditorViewer('gotoDefinition');
    }

    function gotoLine() {
        editors.execCommandForCurrentEditorViewer('gotoLine');
    }

    function gotoMatchingBrace() {
        editors.execCommandForCurrentEditorViewer('gotoMatchingBrace');
    }

	function switchEditorTabToExSelected() {
		var exFile = editors.currentFiles[1];
		if (exFile) {
			var view = vm.getView(exFile.viewId);
			if (view) {
				view.select(true);
			} else {
				console.warn('unexpected');
			}
		}
	}

	function goPrevTab() {
		var focusedViewContainer = editors.splitViewContainer.getFocusedViewContainer();
		if (focusedViewContainer) {
			var view = focusedViewContainer.getSelectedView();
			var viewCount = focusedViewContainer.getNumOfViews();
			if (view && (viewCount > 1)) {
				var newIndex = focusedViewContainer.getViewIndex(view) - 1;
				if (newIndex < 0) {
					newIndex = viewCount - 1;
				}
				var targetView = focusedViewContainer.getViewByIndex(newIndex);
				if (targetView) {
					targetView.select(true);
				}
			}
		}
	}

	function goNextTab() {
		var focusedViewContainer = editors.splitViewContainer.getFocusedViewContainer();
		if (focusedViewContainer) {
			var view = focusedViewContainer.getSelectedView();
			var viewCount = focusedViewContainer.getNumOfViews();
			if (view && (viewCount > 1)) {
				var newIndex = focusedViewContainer.getViewIndex(view) + 1;
				if (newIndex >= viewCount) {
					newIndex = 0;
				}
				var targetView = focusedViewContainer.getViewByIndex(newIndex);
				if (targetView) {
					targetView.select(true);
				}
			}
		}
	}

	function switchEditorTab() {
		var fieldLayout = [{
			'name' : 'Name',
			'field' : 'title',
			'width' : '200'
		}, {
			'name' : 'Path',
			'field' : 'path',
			'width' : '500'
		}];
		editors.editorTabFocusController.showViewList(fieldLayout, 'Select Editor Tab from List');
	}

	function focusMoveToNextTabContainer() {
		var sp = editors.splitViewContainer;
		var focusedVc = sp.getFocusedViewContainer();
		var nextVc = null;
		//TODO FIXME
		if (focusedVc) {
			var showedVcList = sp.getShowedViewContainers();
			if (showedVcList.length > 1) {
				for (var i = 0; i < showedVcList.length; i++) {
					if (showedVcList[i] === focusedVc) {
						if (i >= showedVcList.length - 1) {
							nextVc = showedVcList[0];
						} else {
							nextVc = showedVcList[i + 1];
						}
						if (nextVc.getSelectedView()) {
							nextVc.getSelectedView().select(true);
						}
					}
				}

			}
		}
	}

	function moveToOtherTabContainer() {
		var spContainer = editors.splitViewContainer;
		var vc = spContainer.getFocusedViewContainer();
		var view = vc.getSelectedView();
		if (vc && view) {
			var viewContainers = spContainer.getViewContainers();
			var i = viewContainers.indexOf(vc);
			console.assert(i >= 0);
			var targetView = (i < viewContainers.length - 1 ? viewContainers[i + 1] : viewContainers[0]);
			var views = vc.getViewList();
			if (views.length === 1) {
				spContainer.moveView(targetView, view);
				view.select(true);
			} else {
				var j = views.indexOf(view);
				var nextSelectedView = (j > 0 ? views[j - 1] : views[1]);
				var nextSelectedFile = editors.getFileByViewId(nextSelectedView.getId());
				editors.ensureCreated(nextSelectedFile, false, function() {
					spContainer.moveView(targetView, view);
					view.select(true);
				});
			}
		}
	}

	function rotateToVertical() {
		var showedVc = editors.splitViewContainer.getShowedViewContainers();
		if (showedVc && (showedVc.length === 1)) {
			//editors.moveToNextTabContainer();
			moveToOtherTabContainer();
		}
		editors.splitViewContainer.set('verticalSplit', true);
	}

	function rotateToHorizontal() {
		var showedVc = editors.splitViewContainer.getShowedViewContainers();
		if (showedVc && (showedVc.length === 1)) {
			//editors.moveToNextTabContainer();
			moveToOtherTabContainer();
		}
		editors.splitViewContainer.set('verticalSplit', false);
	}

	function saveAllFiles() {
		// editors.files is currently opened file list
		var opened = _.values(editors.files);
		var currentFile = editors.currentFile;
		var part;

		_.each(opened, function (file) {
			part = editors.getPart(file);
			if (part.isDirty()) {
				editors.setCurrentFile(file);
				editors.saveFile();
			}
		});
		editors.setCurrentFile(currentFile);
	}

	function closeOtherFiles() {
		var curFilePath = editors.currentFile.path;

		// editors.files is currently opened file list
		var opened = _.values(editors.files);

		_.each(opened, function (file) {
			if (file.path !== curFilePath) {
				editors.closeFile({
					path : file.path
				});
			}
		});
	}

	function closeAllFiles() {
		// editors.files is currently opened file list
		var opened = _.values(editors.files);

		_.each(opened, function (file) {
			editors.closeFile({
				path : file.path
			});
		});
	}

	function openRecentFile(index) {
		var path = editors.recentFiles[index];
		topic.publish('#REQUEST.openFile', path);
	}

	return {
		undo : undo,
		redo : redo,
		del : del,
		selectAll : selectAll,
		selectLine : selectLine,
		cursorLineToMiddle : cursorLineToMiddle,
		cursorLineToTop : cursorLineToTop,
		cursorLineToBottom : cursorLineToBottom,
		lineIndent : lineIndent,
		lineDedent : lineDedent,
		lineMoveUp : lineMoveUp,
		lineMoveDown : lineMoveDown,
		lineDelete : lineDelete,
		lineComment : lineComment,
		blockComment : blockComment,
		commentOutSelection : commentOutSelection,
		foldCode : foldCode,
		beautifyCode : beautifyCode,
		beautifyAllCode : beautifyAllCode,
		rename : rename,
		switchEditorTabToExSelected : switchEditorTabToExSelected,
		goPrevTab : goPrevTab,
		goNextTab : goNextTab,
		switchEditorTab : switchEditorTab,
		focusMoveToNextTabContainer : focusMoveToNextTabContainer,
		moveToOtherTabContainer : moveToOtherTabContainer,
		rotateToVertical : rotateToVertical,
		rotateToHorizontal : rotateToHorizontal,
		saveAllFiles : saveAllFiles,
		closeOtherFiles : closeOtherFiles,
		closeAllFiles : closeAllFiles,
		replace : replace,
		find : find,
		quickFind : quickFind,
		findNext : findNext,
		findPrev : findPrev,
		gotoDefinition : gotoDefinition,
		gotoLine : gotoLine,
		gotoMatchingBrace : gotoMatchingBrace,
		openRecentFile : openRecentFile
	};
});
<commit_msg>[TASK] editors-commands.js : Logger added<commit_after>/*
 * Copyright (c) 2012-2015 S-Core Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

define([
	'./plugin',
	'webida-lib/plugins/workbench/plugin',
	'webida-lib/widgets/views/viewmanager',
	'webida-lib/util/logger/logger-client',
	'dojo/topic',
	'external/lodash/lodash.min'
], function (
	editors,
	workbench,
	vm,
	Logger,
	topic,
	_
) {
    'use strict';

    var logger = new Logger();
    //logger.setConfig('level', Logger.LEVELS.log);
    //logger.off();

	function undo() {
        editors.execCommandForCurrentEditorViewer('undo');
	}

	function redo() {
        editors.execCommandForCurrentEditorViewer('redo');
	}

	function cursorLineToMiddle() {
        editors.execCommandForCurrentEditorViewer('cursorLineToMiddle');
	}

	function cursorLineToTop() {
        editors.execCommandForCurrentEditorViewer('cursorLineToTop');
	}

	function cursorLineToBottom() {
        editors.execCommandForCurrentEditorViewer('cursorLineToBottom');
	}

	function del() {
        editors.execCommandForCurrentEditorViewer('del');
	}

	function selectAll() {
        editors.execCommandForCurrentEditorViewer('selectAll');
	}

	function selectLine() {
        editors.execCommandForCurrentEditorViewer('selectLine');
	}

	function lineIndent() {
        editors.execCommandForCurrentEditorViewer('lineIndent');
	}

	function lineDedent() {
        editors.execCommandForCurrentEditorViewer('lineDedent');
	}

	function lineMoveUp() {
        editors.execCommandForCurrentEditorViewer('lineMoveUp');
	}

	function lineMoveDown() {
        editors.execCommandForCurrentEditorViewer('lineMoveDown');
	}

	function lineDelete() {
        editors.execCommandForCurrentEditorViewer('lineDelete');
	}

	function lineComment() {
        editors.execCommandForCurrentEditorViewer('lineComment');
	}

	function blockComment() {
        editors.execCommandForCurrentEditorViewer('blockComment');
	}

	function commentOutSelection() {
        editors.execCommandForCurrentEditorViewer('commentOutSelection');
	}

	function foldCode() {
        editors.execCommandForCurrentEditorViewer('foldCode');
	}

	function beautifyCode() {
        editors.execCommandForCurrentEditorViewer('beautifyCode');
	}

	function beautifyAllCode() {
        editors.execCommandForCurrentEditorViewer('beautifyAllCode');
	}

	function rename() {
        editors.execCommandForCurrentEditorViewer('rename');
	}

    function replace() {
        editors.execCommandForCurrentEditorViewer('replace');
    }

    function find() {
        editors.execCommandForCurrentEditorViewer('find');
    }

    function quickFind() {
        editors.execCommandForCurrentEditorViewer('quickFind');
    }

    function findNext() {
        editors.execCommandForCurrentEditorViewer('findNext');
    }

    function findPrev() {
        editors.execCommandForCurrentEditorViewer('findPrev');
    }

    function gotoDefinition() {
        editors.execCommandForCurrentEditorViewer('gotoDefinition');
    }

    function gotoLine() {
        editors.execCommandForCurrentEditorViewer('gotoLine');
    }

    function gotoMatchingBrace() {
        editors.execCommandForCurrentEditorViewer('gotoMatchingBrace');
    }

	function switchEditorTabToExSelected() {
		var exFile = editors.currentFiles[1];
		if (exFile) {
			var view = vm.getView(exFile.viewId);
			if (view) {
				view.select(true);
			} else {
				console.warn('unexpected');
			}
		}
	}

	function goPrevTab() {
		var focusedViewContainer = editors.splitViewContainer.getFocusedViewContainer();
		if (focusedViewContainer) {
			var view = focusedViewContainer.getSelectedView();
			var viewCount = focusedViewContainer.getNumOfViews();
			if (view && (viewCount > 1)) {
				var newIndex = focusedViewContainer.getViewIndex(view) - 1;
				if (newIndex < 0) {
					newIndex = viewCount - 1;
				}
				var targetView = focusedViewContainer.getViewByIndex(newIndex);
				if (targetView) {
					targetView.select(true);
				}
			}
		}
	}

	function goNextTab() {
		var focusedViewContainer = editors.splitViewContainer.getFocusedViewContainer();
		if (focusedViewContainer) {
			var view = focusedViewContainer.getSelectedView();
			var viewCount = focusedViewContainer.getNumOfViews();
			if (view && (viewCount > 1)) {
				var newIndex = focusedViewContainer.getViewIndex(view) + 1;
				if (newIndex >= viewCount) {
					newIndex = 0;
				}
				var targetView = focusedViewContainer.getViewByIndex(newIndex);
				if (targetView) {
					targetView.select(true);
				}
			}
		}
	}

	function switchEditorTab() {
		var fieldLayout = [{
			'name' : 'Name',
			'field' : 'title',
			'width' : '200'
		}, {
			'name' : 'Path',
			'field' : 'path',
			'width' : '500'
		}];
		editors.editorTabFocusController.showViewList(fieldLayout, 'Select Editor Tab from List');
	}

	function focusMoveToNextTabContainer() {
		var sp = editors.splitViewContainer;
		var focusedVc = sp.getFocusedViewContainer();
		var nextVc = null;
		//TODO FIXME
		if (focusedVc) {
			var showedVcList = sp.getShowedViewContainers();
			if (showedVcList.length > 1) {
				for (var i = 0; i < showedVcList.length; i++) {
					if (showedVcList[i] === focusedVc) {
						if (i >= showedVcList.length - 1) {
							nextVc = showedVcList[0];
						} else {
							nextVc = showedVcList[i + 1];
						}
						if (nextVc.getSelectedView()) {
							nextVc.getSelectedView().select(true);
						}
					}
				}

			}
		}
	}

	function moveToOtherTabContainer() {
		var spContainer = editors.splitViewContainer;
		var vc = spContainer.getFocusedViewContainer();
		var view = vc.getSelectedView();
		if (vc && view) {
			var viewContainers = spContainer.getViewContainers();
			var i = viewContainers.indexOf(vc);
			console.assert(i >= 0);
			var targetView = (i < viewContainers.length - 1 ? viewContainers[i + 1] : viewContainers[0]);
			var views = vc.getViewList();
			if (views.length === 1) {
				spContainer.moveView(targetView, view);
				view.select(true);
			} else {
				var j = views.indexOf(view);
				var nextSelectedView = (j > 0 ? views[j - 1] : views[1]);
				var nextSelectedFile = editors.getFileByViewId(nextSelectedView.getId());
				editors.ensureCreated(nextSelectedFile, false, function() {
					spContainer.moveView(targetView, view);
					view.select(true);
				});
			}
		}
	}

	function rotateToVertical() {
		var showedVc = editors.splitViewContainer.getShowedViewContainers();
		if (showedVc && (showedVc.length === 1)) {
			//editors.moveToNextTabContainer();
			moveToOtherTabContainer();
		}
		editors.splitViewContainer.set('verticalSplit', true);
	}

	function rotateToHorizontal() {
		var showedVc = editors.splitViewContainer.getShowedViewContainers();
		if (showedVc && (showedVc.length === 1)) {
			//editors.moveToNextTabContainer();
			moveToOtherTabContainer();
		}
		editors.splitViewContainer.set('verticalSplit', false);
	}

	function saveAllFiles() {
		// editors.files is currently opened file list
		var opened = _.values(editors.files);
		var currentFile = editors.currentFile;
		var part;

		_.each(opened, function (file) {
			part = editors.getPart(file);
			if (part.isDirty()) {
				editors.setCurrentFile(file);
				editors.saveFile();
			}
		});
		editors.setCurrentFile(currentFile);
	}

	function closeOtherFiles() {
		var curFilePath = editors.currentFile.path;

		// editors.files is currently opened file list
		var opened = _.values(editors.files);

		_.each(opened, function (file) {
			if (file.path !== curFilePath) {
				editors.closeFile({
					path : file.path
				});
			}
		});
	}

	function closeAllFiles() {
		// editors.files is currently opened file list
		var opened = _.values(editors.files);

		_.each(opened, function (file) {
			editors.closeFile({
				path : file.path
			});
		});
	}

	function openRecentFile(index) {
		var path = editors.recentFiles[index];
		topic.publish('#REQUEST.openFile', path);
	}

	return {
		undo : undo,
		redo : redo,
		del : del,
		selectAll : selectAll,
		selectLine : selectLine,
		cursorLineToMiddle : cursorLineToMiddle,
		cursorLineToTop : cursorLineToTop,
		cursorLineToBottom : cursorLineToBottom,
		lineIndent : lineIndent,
		lineDedent : lineDedent,
		lineMoveUp : lineMoveUp,
		lineMoveDown : lineMoveDown,
		lineDelete : lineDelete,
		lineComment : lineComment,
		blockComment : blockComment,
		commentOutSelection : commentOutSelection,
		foldCode : foldCode,
		beautifyCode : beautifyCode,
		beautifyAllCode : beautifyAllCode,
		rename : rename,
		switchEditorTabToExSelected : switchEditorTabToExSelected,
		goPrevTab : goPrevTab,
		goNextTab : goNextTab,
		switchEditorTab : switchEditorTab,
		focusMoveToNextTabContainer : focusMoveToNextTabContainer,
		moveToOtherTabContainer : moveToOtherTabContainer,
		rotateToVertical : rotateToVertical,
		rotateToHorizontal : rotateToHorizontal,
		saveAllFiles : saveAllFiles,
		closeOtherFiles : closeOtherFiles,
		closeAllFiles : closeAllFiles,
		replace : replace,
		find : find,
		quickFind : quickFind,
		findNext : findNext,
		findPrev : findPrev,
		gotoDefinition : gotoDefinition,
		gotoLine : gotoLine,
		gotoMatchingBrace : gotoMatchingBrace,
		openRecentFile : openRecentFile
	};
});
<|endoftext|>


<commit_before>PANDA.views.DatasetSearch = Backbone.View.extend({
    events: {
        "submit #dataset-search-form":      "search_event",
        "click #toggle-advanced-search":    "toggle_advanced_search"
    },

    dataset: null,
    query: null,
    since: "all",
    search_filters: null,
    results: null,
    view: null,

    text: PANDA.text.DatasetSearch(),

    initialize: function(options) {
        _.bindAll(this, "reset", "render", "search_event", "search", "encode_query_string", "encode_human_readable", "decode_query_string", "make_solr_query");

        this.search_filters = new PANDA.views.DatasetSearchFilters();
        this.results = new PANDA.views.DatasetResults();
        this.view = new PANDA.views.DatasetView();
    },

    reset: function(dataset_slug, query_string, success_callback) {
        this.decode_query_string(query_string);
        this.since = "all";

        this.dataset = new PANDA.models.Dataset({ resource_uri: PANDA.API + "/dataset/" + dataset_slug + "/" });

        this.dataset.fetch({
            async: false,
            success: _.bind(function(model, response) {
                this.search_filters.reset(this);
                this.results.reset(this);
                this.view.reset(this.dataset);
                this.render();
            }, this),
            error: _.bind(function(model, response) {
                if (response.status == 404) {
                    Redd.goto_not_found();
                } else {
                    Redd.goto_server_error();
                }
            }, this)
        });
    },

    render: function() {
        var context = PANDA.utils.make_context({
            text: this.text,
            query: this.query,
            dataset: this.dataset.results()
        });

        this.$el.html(PANDA.templates.dataset_search(context));

        this.search_filters.setElement("#dataset-search-filters");
        this.search_filters.render();

        this.results.setElement("#dataset-search-results");
        this.view.setElement("#dataset-search-results");

        var task = this.dataset.current_task;

        if (task) {
            if (task.get("task_name").startsWith("panda.tasks.import")) {
                if (task.get("status") == "STARTED") {
                    var alert_body = interpolate(gettext("
This dataset is being made searchable. Search results may be incomplete.

Status: %(message)s. Refresh to see updated status »
", { message: task.get("message") }, true));
                    $("#dataset-search .alert").alert_block("alert-info", gettext("Import in progress!"), alert_body, false);
                } else if (task.get("status") == "PENDING") {
                    $("#dataset-search .alert").alert_block("alert-info", gettext("Import queued!"), gettext("
This dataset is waiting to be made searchable. Search results may be incomplete. Refresh to see updated status »</a
"), false);
                } else if (task.get("status") == "FAILURE") {
                    $("#dataset-search .alert").alert_block("alert-error", gettext("Import failed!"), gettext('
The process to make this dataset searchable failed. Search results may be incomplete. Show detailed error message
'), false);
                } else if (task.get("status") == "ABORTED") {
                    $("#dataset-search .alert").alert_block("alert-error", gettext("Import aborted!"), gettext('
The process to make data searchable was aborted by an administrator. Search results may be incomplete.
'), false);
                }
            }
            else if (task.get("task_name").startsWith("panda.tasks.reindex")) {
                if (task.get("status") == "STARTED") {
                    var alert_body = interpolate(gettext("
Search data for this dataset is being updated. Search results may be incomplete.

Status: %(message)s. Refresh to see updated status »
", { message: task.get("message") }, true));
                    $("#dataset-search .alert").alert_block("alert-info", gettext("Reindexing in progress!"), alert_body, false);
                } else if (task.get("status") == "PENDING") {
                    $("#dataset-search .alert").alert_block("alert-info", gettext("Reindexing queued!"), gettext("
This dataset is waiting to have its search data updated. Search results may be incomplete. Refresh to see updated status »</a
"), false);
                } else if (task.get("status") == "FAILURE") {
                    $("#dataset-search .alert").alert_block("alert-error", gettext("Reindexing failed!"), gettext('
The process to make update this dataset\'s search data failed. Search results may be incomplete. Show detailed error message
'), false);
                } else if (task.get("status") == "ABORTED") {
                    $("#dataset-search .alert").alert_block("alert-error", gettext("Reindexing aborted!"), gettext('
The process to udpate this dataset\'s search data was aborted by an administrator. Search results may be incomplete.
'), false);
                }
            }
        }

        if (!this.query) {
            this.view.render();
        }

        $('a[rel="popover"]').popover();
    },

    search_event: function() {
        // Clear any existing error text
        $("#dataset-search-filters .help-wrapper").hide();

        try {
            query_string = this.encode_query_string();
        } catch(e) {
            if (e instanceof PANDA.errors.FilterValidationError) {
                _.each(e.errors, function(message, i) {
                    var filter = $("#filter-" + i);

                    // Render error
                    filter.find(".help-wrapper").show();
                    filter.find(".help-inline").text(message);
                });
            } else {
                throw e;
            }

            return false;
        }

        Redd.goto_dataset_search(this.dataset.get("slug"), query_string);

        return false;
    },

    toggle_advanced_search: function() {
        $(".search-help").toggle();
        $("#dataset-search-filters").toggle();

        if ($("#dataset-search-filters").is(":visible")) {
            $("#toggle-advanced-search").text("Fewer search options");
        } else {
            $("#toggle-advanced-search").text("More search options");
        };

        return false;
    },

    slow_query_warning: function() {
        /*
         * Display a warning when a query is taking a very long time to return.
         */
        this.$("#dataset-search-results").html(gettext("Warning! This query seems to be taking a very long time. It may still finish or it may have failed."));
    },

    search_error: function(error) {
        /*
         * Display a server error resulting from search.
         */
        this.$("#dataset-search-results").html(interpolate(gettext("
Error executing query!

%(error)s
"), { error: error.error_message }, true));
    },

    search: function(query, since, limit, page) {
        /*
         * Execute a search.
         */
        this.decode_query_string(query);
        this.since = since || "all";

        this.render();

        var slow_query_timer = setTimeout(this.slow_query_warning, PANDA.settings.SLOW_QUERY_TIMEOUT);

        this.dataset.search(
            this.make_solr_query(),
            since,
            limit,
            page,
            _.bind(function(dataset) {
                clearTimeout(slow_query_timer);
                this.results.render();
            }, this),
            _.bind(function(dataset, error) {
                clearTimeout(slow_query_timer);
                this.search_error(error);

            }, this)
        );
    },

    encode_query_string: function() {
        /*
         * Convert arguments from the search fields into a URL.
         */
        var full_text = $(".dataset-search-query").val();
        var q = full_text;
        var filters = this.search_filters.encode();

        if (filters) {
            q += "|||" + filters;
        }

        return escape(q);
    },

    encode_human_readable: function() {
        var human = "";
        var full_text = null;
        var parts = [];

        _.each(this.query, function(v, k) {
            if (k == "__all__") {
                if (v) {
                    full_text = interpolate(gettext("Search for %(full_text_query)s"), { full_text_query: v }, true);
                }
            } else {
                var column = _.find(this.dataset.get("column_schema"), function(c) {
                    return c["name"] == k;
                });

                var operation_text = this.search_filters.operations[column["type"]][v["operator"]]["name"];
                var value = v["value"];
                var range_value = v["range_value"];

                if (column["type"] == "datetime") {
                    value = moment(value, "YYYY-MM-DD HH:mm:ss").format("YYYY-MM-DD HH:mm")
                } else if (column["type"] == "date") {
                    value = moment(value, "YYYY-MM-DD HH:mm:ss").format("YYYY-MM-DD")
                } else if (column["type"] == "time") {
                    value = moment(value, "YYYY-MM-DD HH:mm:ss").format("HH:mm")
                }

                var part = "" + k + " " + operation_text + " " + value + "";

                if (range_value) {
                    if (column["type"] == "datetime") {
                        range_value = moment(range_value, "YYYY-MM-DD HH:mm:ss").format("YYYY-MM-DD HH:mm")
                    } else if (column["type"] == "date") {
                        range_value = moment(range_value, "YYYY-MM-DD HH:mm:ss").format("YYYY-MM-DD")
                    } else if (column["type"] == "time") {
                        range_value = moment(range_value, "YYYY-MM-DD HH:mm:ss").format("HH:mm")
                    }

                    part += " to " + range_value + "";
                }

                parts.push(part);
            }
        }, this);

        if (full_text) {
            parts.unshift(full_text);
        }

        human = parts.join(" and ");

        return human;
    },

    decode_query_string: function(query_string) {
        /*
         * Parse a query from the URL into form values and a query object.
         */
        if (query_string) {
            this.query = {};

            var parts = unescape(query_string).split("\|\|\|");

            _.each(parts, _.bind(function(p, i) {
                if (i == 0) {
                    this.query["__all__"] = p;
                } else {
                    var parts = p.split(":::");
                    var column_name = parts[0];
                    var column_operator = parts[1];
                    var column_value = parts[2];
                    var column_range_value = parts[3];

                    this.query[column_name] = { "operator": column_operator, "value": column_value, "range_value": column_range_value };
                }
            }, this));
        } else {
            this.query = null;
        }
    },

    make_solr_query: function() {
        /*
         * Convert the internal query object into a Solr query string.
         */
        if (!this.query) {
            return "";
        }

        var q = this.query["__all__"];

        _.each(this.query, _.bind(function(v, k) {
            if (k == "__all__") {
                return;
            }

            var c = _.find(this.dataset.get("column_schema"), function(c) {
                return c["name"] == k;
            });

            // Convert datetimes to Solr format
            if (c["type"] == "datetime") {
                v["value"] = v["value"].replace(" ", "T") + ":00Z";

                if (v["range_value"]) {
                    v["range_value"] = v["range_value"].replace(" ", "T") + ":00Z";
                }
            } else if (c["type"] == "date") {
                v["value"] = v["value"] + "T00:00:00Z";

                if (v["range_value"]) {
                    v["range_value"] = v["range_value"] + "T00:00:00Z";
                }
            } else if (c["type"] == "time") {
                v["value"] = "9999-12-31T" + v["value"] + ":00Z";

                if (v["range_value"]) {
                    v["range_value"] = "9999-12-31T" + v["range_value"] + ":00Z";
                }
            }

            if (q) {
                q += " AND ";
            }

            if (v["operator"] == "is_like") {
                q += c["indexed_name"] + ':(' + v["value"] + ')';
            } else if (v["operator"] == "is") {
                q += c["indexed_name"] + ':"' + v["value"] + '"';
            } else if (v["operator"] == "is_greater") {
                q += c["indexed_name"] + ":[" + v["value"] + " TO *]";
            } else if (v["operator"] == "is_less") {
                q += c["indexed_name"] + ":[* TO " + v["value"] + "]";
            } else if (v["operator"] == "is_range") {
                q += c["indexed_name"] + ":[" + v["value"] + " TO " + v["range_value"] + "]";
            }
        }, this));

        return q;
    }
});

<commit_msg>Fix bugs in display of import progress.<commit_after>PANDA.views.DatasetSearch = Backbone.View.extend({
    events: {
        "submit #dataset-search-form":      "search_event",
        "click #toggle-advanced-search":    "toggle_advanced_search"
    },

    dataset: null,
    query: null,
    since: "all",
    search_filters: null,
    results: null,
    view: null,

    text: PANDA.text.DatasetSearch(),

    initialize: function(options) {
        _.bindAll(this, "reset", "render", "search_event", "search", "encode_query_string", "encode_human_readable", "decode_query_string", "make_solr_query");

        this.search_filters = new PANDA.views.DatasetSearchFilters();
        this.results = new PANDA.views.DatasetResults();
        this.view = new PANDA.views.DatasetView();
    },

    reset: function(dataset_slug, query_string, success_callback) {
        this.decode_query_string(query_string);
        this.since = "all";

        this.dataset = new PANDA.models.Dataset({ resource_uri: PANDA.API + "/dataset/" + dataset_slug + "/" });

        this.dataset.fetch({
            async: false,
            success: _.bind(function(model, response) {
                this.search_filters.reset(this);
                this.results.reset(this);
                this.view.reset(this.dataset);
                this.render();
            }, this),
            error: _.bind(function(model, response) {
                if (response.status == 404) {
                    Redd.goto_not_found();
                } else {
                    Redd.goto_server_error();
                }
            }, this)
        });
    },

    render: function() {
        var context = PANDA.utils.make_context({
            text: this.text,
            query: this.query,
            dataset: this.dataset.results()
        });

        this.$el.html(PANDA.templates.dataset_search(context));

        this.search_filters.setElement("#dataset-search-filters");
        this.search_filters.render();

        this.results.setElement("#dataset-search-results");
        this.view.setElement("#dataset-search-results");

        var task = this.dataset.current_task;

        if (task) {
            if (task.get("task_name").startsWith("panda.tasks.import")) {
                if (task.get("status") == "STARTED") {
                    var alert_body = interpolate(gettext("
This dataset is being made searchable. Search results may be incomplete.

Status: %(message)s. Refresh to see updated status »
"), { message: task.get("message") }, true);
                    $("#dataset-search .alert").alert_block("alert-info", gettext("Import in progress!"), alert_body, false);
                } else if (task.get("status") == "PENDING") {
                    $("#dataset-search .alert").alert_block("alert-info", gettext("Import queued!"), gettext("
This dataset is waiting to be made searchable. Search results may be incomplete. Refresh to see updated status »</a
"), false);
                } else if (task.get("status") == "FAILURE") {
                    $("#dataset-search .alert").alert_block("alert-error", gettext("Import failed!"), gettext('
The process to make this dataset searchable failed. Search results may be incomplete. Show detailed error message
'), false);
                } else if (task.get("status") == "ABORTED") {
                    $("#dataset-search .alert").alert_block("alert-error", gettext("Import aborted!"), gettext('
The process to make data searchable was aborted by an administrator. Search results may be incomplete.
'), false);
                }
            }
            else if (task.get("task_name").startsWith("panda.tasks.reindex")) {
                if (task.get("status") == "STARTED") {
                    var alert_body = interpolate(gettext("
Search data for this dataset is being updated. Search results may be incomplete.

Status: %(message)s. Refresh to see updated status »
"), { message: task.get("message") }, true);
                    $("#dataset-search .alert").alert_block("alert-info", gettext("Reindexing in progress!"), alert_body, false);
                } else if (task.get("status") == "PENDING") {
                    $("#dataset-search .alert").alert_block("alert-info", gettext("Reindexing queued!"), gettext("
This dataset is waiting to have its search data updated. Search results may be incomplete. Refresh to see updated status »</a
"), false);
                } else if (task.get("status") == "FAILURE") {
                    $("#dataset-search .alert").alert_block("alert-error", gettext("Reindexing failed!"), gettext('
The process to make update this dataset\'s search data failed. Search results may be incomplete. Show detailed error message
'), false);
                } else if (task.get("status") == "ABORTED") {
                    $("#dataset-search .alert").alert_block("alert-error", gettext("Reindexing aborted!"), gettext('
The process to udpate this dataset\'s search data was aborted by an administrator. Search results may be incomplete.
'), false);
                }
            }
        }

        if (!this.query) {
            this.view.render();
        }

        $('a[rel="popover"]').popover();
    },

    search_event: function() {
        // Clear any existing error text
        $("#dataset-search-filters .help-wrapper").hide();

        try {
            query_string = this.encode_query_string();
        } catch(e) {
            if (e instanceof PANDA.errors.FilterValidationError) {
                _.each(e.errors, function(message, i) {
                    var filter = $("#filter-" + i);

                    // Render error
                    filter.find(".help-wrapper").show();
                    filter.find(".help-inline").text(message);
                });
            } else {
                throw e;
            }

            return false;
        }

        Redd.goto_dataset_search(this.dataset.get("slug"), query_string);

        return false;
    },

    toggle_advanced_search: function() {
        $(".search-help").toggle();
        $("#dataset-search-filters").toggle();

        if ($("#dataset-search-filters").is(":visible")) {
            $("#toggle-advanced-search").text("Fewer search options");
        } else {
            $("#toggle-advanced-search").text("More search options");
        };

        return false;
    },

    slow_query_warning: function() {
        /*
         * Display a warning when a query is taking a very long time to return.
         */
        this.$("#dataset-search-results").html(gettext("Warning! This query seems to be taking a very long time. It may still finish or it may have failed."));
    },

    search_error: function(error) {
        /*
         * Display a server error resulting from search.
         */
        this.$("#dataset-search-results").html(interpolate(gettext("
Error executing query!

%(error)s
"), { error: error.error_message }, true));
    },

    search: function(query, since, limit, page) {
        /*
         * Execute a search.
         */
        this.decode_query_string(query);
        this.since = since || "all";

        this.render();

        var slow_query_timer = setTimeout(this.slow_query_warning, PANDA.settings.SLOW_QUERY_TIMEOUT);

        this.dataset.search(
            this.make_solr_query(),
            since,
            limit,
            page,
            _.bind(function(dataset) {
                clearTimeout(slow_query_timer);
                this.results.render();
            }, this),
            _.bind(function(dataset, error) {
                clearTimeout(slow_query_timer);
                this.search_error(error);

            }, this)
        );
    },

    encode_query_string: function() {
        /*
         * Convert arguments from the search fields into a URL.
         */
        var full_text = $(".dataset-search-query").val();
        var q = full_text;
        var filters = this.search_filters.encode();

        if (filters) {
            q += "|||" + filters;
        }

        return escape(q);
    },

    encode_human_readable: function() {
        var human = "";
        var full_text = null;
        var parts = [];

        _.each(this.query, function(v, k) {
            if (k == "__all__") {
                if (v) {
                    full_text = interpolate(gettext("Search for %(full_text_query)s"), { full_text_query: v }, true);
                }
            } else {
                var column = _.find(this.dataset.get("column_schema"), function(c) {
                    return c["name"] == k;
                });

                var operation_text = this.search_filters.operations[column["type"]][v["operator"]]["name"];
                var value = v["value"];
                var range_value = v["range_value"];

                if (column["type"] == "datetime") {
                    value = moment(value, "YYYY-MM-DD HH:mm:ss").format("YYYY-MM-DD HH:mm")
                } else if (column["type"] == "date") {
                    value = moment(value, "YYYY-MM-DD HH:mm:ss").format("YYYY-MM-DD")
                } else if (column["type"] == "time") {
                    value = moment(value, "YYYY-MM-DD HH:mm:ss").format("HH:mm")
                }

                var part = "" + k + " " + operation_text + " " + value + "";

                if (range_value) {
                    if (column["type"] == "datetime") {
                        range_value = moment(range_value, "YYYY-MM-DD HH:mm:ss").format("YYYY-MM-DD HH:mm")
                    } else if (column["type"] == "date") {
                        range_value = moment(range_value, "YYYY-MM-DD HH:mm:ss").format("YYYY-MM-DD")
                    } else if (column["type"] == "time") {
                        range_value = moment(range_value, "YYYY-MM-DD HH:mm:ss").format("HH:mm")
                    }

                    part += " to " + range_value + "";
                }

                parts.push(part);
            }
        }, this);

        if (full_text) {
            parts.unshift(full_text);
        }

        human = parts.join(" and ");

        return human;
    },

    decode_query_string: function(query_string) {
        /*
         * Parse a query from the URL into form values and a query object.
         */
        if (query_string) {
            this.query = {};

            var parts = unescape(query_string).split("\|\|\|");

            _.each(parts, _.bind(function(p, i) {
                if (i == 0) {
                    this.query["__all__"] = p;
                } else {
                    var parts = p.split(":::");
                    var column_name = parts[0];
                    var column_operator = parts[1];
                    var column_value = parts[2];
                    var column_range_value = parts[3];

                    this.query[column_name] = { "operator": column_operator, "value": column_value, "range_value": column_range_value };
                }
            }, this));
        } else {
            this.query = null;
        }
    },

    make_solr_query: function() {
        /*
         * Convert the internal query object into a Solr query string.
         */
        if (!this.query) {
            return "";
        }

        var q = this.query["__all__"];

        _.each(this.query, _.bind(function(v, k) {
            if (k == "__all__") {
                return;
            }

            var c = _.find(this.dataset.get("column_schema"), function(c) {
                return c["name"] == k;
            });

            // Convert datetimes to Solr format
            if (c["type"] == "datetime") {
                v["value"] = v["value"].replace(" ", "T") + ":00Z";

                if (v["range_value"]) {
                    v["range_value"] = v["range_value"].replace(" ", "T") + ":00Z";
                }
            } else if (c["type"] == "date") {
                v["value"] = v["value"] + "T00:00:00Z";

                if (v["range_value"]) {
                    v["range_value"] = v["range_value"] + "T00:00:00Z";
                }
            } else if (c["type"] == "time") {
                v["value"] = "9999-12-31T" + v["value"] + ":00Z";

                if (v["range_value"]) {
                    v["range_value"] = "9999-12-31T" + v["range_value"] + ":00Z";
                }
            }

            if (q) {
                q += " AND ";
            }

            if (v["operator"] == "is_like") {
                q += c["indexed_name"] + ':(' + v["value"] + ')';
            } else if (v["operator"] == "is") {
                q += c["indexed_name"] + ':"' + v["value"] + '"';
            } else if (v["operator"] == "is_greater") {
                q += c["indexed_name"] + ":[" + v["value"] + " TO *]";
            } else if (v["operator"] == "is_less") {
                q += c["indexed_name"] + ":[* TO " + v["value"] + "]";
            } else if (v["operator"] == "is_range") {
                q += c["indexed_name"] + ":[" + v["value"] + " TO " + v["range_value"] + "]";
            }
        }, this));

        return q;
    }
});

<|endoftext|>


<commit_before>var fs = require("fs"),
  _ = require("lodash"),
  dox = require("dox"),
  es = require("event-stream"),
  gutil = require("gulp-util"),
  PluginError = gutil.PluginError,
  PLUGIN_NAME = "gulp-doximator";

// ----------------------------------------------------------------------------
// Section
// ----------------------------------------------------------------------------
/**
 * A section / function of documentation.
 *
 * @param {Object} obj Objectified underlying data.
 */
var Section = function (data) {
  this.data = data;
};

Section.prototype.tmpl = {
  toc:     _.template("* [`<%= heading %>`](#<%= id %>)\n"),
  heading: _.template("<%= name %><%= params %>"),
  section: _.template(_.map([
    "### `<%= heading %>`\n",
    "<% _.each(tags, function (t) { %>",
    "  <% if (t.type === 'param') { %>",
    "    * **<%= t.name %>** (`<%= t.types.join('|') %>`) ",
    "    <%= t.description %>\n",
    "  <% } else if (t.type === 'returns') { %>",
    "    * **_<%= t.type %>_** <%= t.string %>\n",
    "  <% } %>",
    "<% }); %>\n",
    "<%= description.full %>\n",
    "<% _.each(tags, function (t) { %>",
    "  <% if (t.type === 'see') { %>",
    "    See: [<%= t.url %>](<%= t.url %>)\n\n",
    "  <% } %>",
    "<% }); %>"
  ], function (s) { return s.replace(/^\s+/, ""); }).join(""))
};

Section.prototype.isPublic = function () {
  var data = this.data;
  return !data.isPrivate && !data.ignore && _.any(data.tags, function (t) {
    return t.type === "api" && t.visibility === "public";
  });
};

Section.prototype.heading = function () {
  var params = _.chain(this.data.tags)
    .filter(function (t) { return t.type === "param"; })
    .map(function (t) {
      var isOpt = t.description.indexOf("_optional_") !== -1;
      return isOpt ? "[" + t.name + "]" : t.name;
    })
    .value()
    .join(", ");

  return this.tmpl.heading({
    name: this.data.ctx.name,
    params: params ? "(" + params + ")" : null
  });
};

// Memoize.
Section.prototype.heading = _.memoize(
  Section.prototype.heading, function () { return this.data.ctx.name; });

Section.prototype.headingId = function () {
  return this.heading().toLowerCase().replace(/[^\w]+/g, "-");
};

Section.prototype.renderToc = function () {
  return this.tmpl.toc({
    heading: this.heading(),
    id: this.headingId()
  });
};

Section.prototype.renderSection = function () {
  return this.tmpl.section(_.extend({
    heading: this.heading()
  }, this.data));
};

// ----------------------------------------------------------------------------
// Helpers
// ----------------------------------------------------------------------------
// Generate Markdown API snippets from dox object.
var _generateMdApi = function (obj) {
  var toc = [];

  // Finesse comment markdown data.
  // Also, statefully create TOC.
  var sections = _.chain(obj)
    .map(function (data) { return new Section(data); })
    .filter(function (s) { return s.isPublic(); })
    .map(function (s) {
      toc.push(s.renderToc());  // Add to TOC.
      return s.renderSection(); // Render section.
    })
    .value()
    .join("");

  return "\n" + toc.join("") + "\n" + sections;
};

// ----------------------------------------------------------------------------
// Stream
// ----------------------------------------------------------------------------
var gulpDoximator = function (opts) {
  // Set up options.
  opts = _.extend({
    startMarker: null,
    endMarker: null
  }, opts);

  // Validate.
  if (!opts.src || !opts.startMarker || !opts.endMarker) {
    throw new PluginError(PLUGIN_NAME, "Source and markers required");
  }

  // Variables.
  var buffer = [];

  // Buffer incoming `src` JS files.
  var bufferSources = function (file) {
    if (file.isBuffer()) {
      buffer.push(file.contents.toString("utf8"));
    } else if (file.isStream()) {
      return this.emit("error",
        new PluginError(PLUGIN_NAME, "Streams are not supported!"));
    }
  };

  // Join everything at end.
  var convertToDocs = function () {
    if (buffer.length === 0) {
      return this.emit("end");
    }

    var data = dox.parseComments(buffer.toString(), { raw: true });
    var mdApi = _generateMdApi(data);

    // TODO: Switch to a streams-friendly version.
    // For the life of me, I cannot figure out how to inject the README as
    // a separate stream into the mix here...
    var src = fs.readFileSync(opts.src).toString("utf8");
    var re = new RegExp(opts.startMarker + "(\n|.)*" + opts.endMarker, "m");
    var updated = src.replace(re, [
      opts.startMarker,
      "\n",
      mdApi,
      opts.endMarker
    ].join(""));

    this.emit("data", new gutil.File({
      path: opts.src,
      contents: new Buffer(updated)
    }));
    this.emit("end");
  };

  return es.through(bufferSources, convertToDocs);
};

module.exports = gulpDoximator;
<commit_msg>Save notes / WIP/POC pseudo code.<commit_after>var fs = require("fs"),
  _ = require("lodash"),
  dox = require("dox"),
  es = require("event-stream"),
  gutil = require("gulp-util"),
  PluginError = gutil.PluginError,
  PLUGIN_NAME = "gulp-doximator";

// ----------------------------------------------------------------------------
// Section
// ----------------------------------------------------------------------------
/**
 * A section / function of documentation.
 *
 * @param {Object} obj Objectified underlying data.
 */
var Section = function (data) {
  this.data = data;
};

Section.prototype.tmpl = {
  toc:     _.template("* [`<%= heading %>`](#<%= id %>)\n"),
  heading: _.template("<%= name %><%= params %>"),
  section: _.template(_.map([
    "### `<%= heading %>`\n",
    "<% _.each(tags, function (t) { %>",
    "  <% if (t.type === 'param') { %>",
    "    * **<%= t.name %>** (`<%= t.types.join('|') %>`) ",
    "    <%= t.description %>\n",
    "  <% } else if (t.type === 'returns') { %>",
    "    * **_<%= t.type %>_** <%= t.string %>\n",
    "  <% } %>",
    "<% }); %>\n",
    "<%= description.full %>\n",
    "<% _.each(tags, function (t) { %>",
    "  <% if (t.type === 'see') { %>",
    "    See: [<%= t.url %>](<%= t.url %>)\n\n",
    "  <% } %>",
    "<% }); %>"
  ], function (s) { return s.replace(/^\s+/, ""); }).join(""))
};

Section.prototype.isPublic = function () {
  var data = this.data;
  return !data.isPrivate && !data.ignore && _.any(data.tags, function (t) {
    return t.type === "api" && t.visibility === "public";
  });
};

Section.prototype.heading = function () {
  var params = _.chain(this.data.tags)
    .filter(function (t) { return t.type === "param"; })
    .map(function (t) {
      var isOpt = t.description.indexOf("_optional_") !== -1;
      return isOpt ? "[" + t.name + "]" : t.name;
    })
    .value()
    .join(", ");

  return this.tmpl.heading({
    name: this.data.ctx.name,
    params: params ? "(" + params + ")" : null
  });
};

// Memoize.
Section.prototype.heading = _.memoize(
  Section.prototype.heading, function () { return this.data.ctx.name; });

Section.prototype.headingId = function () {
  return this.heading().toLowerCase().replace(/[^\w]+/g, "-");
};

Section.prototype.renderToc = function () {
  return this.tmpl.toc({
    heading: this.heading(),
    id: this.headingId()
  });
};

Section.prototype.renderSection = function () {
  return this.tmpl.section(_.extend({
    heading: this.heading()
  }, this.data));
};

// ----------------------------------------------------------------------------
// Helpers
// ----------------------------------------------------------------------------
// Generate Markdown API snippets from dox object.
var _generateMdApi = function (obj) {
  var toc = [];

  // Finesse comment markdown data.
  // Also, statefully create TOC.
  var sections = _.chain(obj)
    .map(function (data) { return new Section(data); })
    .filter(function (s) { return s.isPublic(); })
    .map(function (s) {
      toc.push(s.renderToc());  // Add to TOC.
      return s.renderSection(); // Render section.
    })
    .value()
    .join("");

  return "\n" + toc.join("") + "\n" + sections;
};

// ----------------------------------------------------------------------------
// Stream
// ----------------------------------------------------------------------------
var gulpDoximator = function (opts) {
  // Set up options.
  opts = _.extend({
    startMarker: null,
    endMarker: null
  }, opts);

  var src = fs.readFileSync(opts.src).toString("utf8");

  // Validate.
  if (!opts.src || !opts.startMarker || !opts.endMarker) {
    throw new PluginError(PLUGIN_NAME, "Source and markers required");
  }

  // Variables.
  var buffer = [];

  // // Buffer incoming `src` JS files.
  // var bufferSources = function (file) {
  //   if (file.isBuffer()) {
  //     buffer.push(file.contents.toString("utf8"));
  //   } else if (file.isStream()) {
  //     return this.emit("error",
  //       new PluginError(PLUGIN_NAME, "Streams are not supported!"));
  //   }
  // };

  // // Join everything at end.
  // var convertToDocs = function () {
  //   if (buffer.length === 0) {
  //     return this.emit("end");
  //   }

  //   var data = dox.parseComments(buffer.toString(), { raw: true });
  //   var mdApi = _generateMdApi(data);

  //   // TODO: Switch to a streams-friendly version.
  //   // For the life of me, I cannot figure out how to inject the README as
  //   // a separate stream into the mix here...
  //   var src = fs.readFileSync(opts.src).toString("utf8");
  //   var re = new RegExp(opts.startMarker + "(\n|.)*" + opts.endMarker, "m");
  //   var updated = src.replace(re, [
  //     opts.startMarker,
  //     "\n",
  //     mdApi,
  //     opts.endMarker
  //   ].join(""));

  //   this.emit("data", new gutil.File({
  //     path: opts.src,
  //     contents: new Buffer(updated)
  //   }));
  //   this.emit("end");
  // };

  //var src = fs.createReadStream(opts.src).toString("utf8");

  var LookForIncludes = through2(function () {
    // is this the insert point?
    // IF YES. then push onto new stream.  this.push(MY_MD_DATA_TO_INSERT)
    // RYAN: Is that equivalent to this.emit("data", MY_MD_DATA_TO_INSERT).

  })

  fs.createReadStream(opts.src)
    .pipe(lines)
    .pipe(LookForIncludes())

  return es.through(function () {}, function () {
    this.emit("data", new gutil.File({
      path: opts.src + ".tmp",
      contents: fs.createReadStream(opts.src)
    }));
    this.emit("end");
  });
};

module.exports = gulpDoximator;
<|endoftext|>


<commit_before>Template.lesson.helpers({
    'activeLesson': function () {
        // Get the lesson ID from session
        // TODO: see if this can be done via reactive var
        var lessonID = Session.get('activeLesson');

        // Get the lesson from DB
        // selecting the zeroth array item
        var lesson = Lessons.findOne({_id: lessonID});

        return lesson;
    },
    'editingLessonText': function () {
        // return true if editing the lesson text
        // value is set on click event
        return editingLessonText.get();
    }
});

Template.lesson.events({
    'click .lesson-text': function () {
        // in edit mode,
        // add rich text editor
        // to lesson text
        if (Session.get('editMode')) {
            $('.lesson-text').summernote({
                // TODO: add more config parameters as needed
                height: 300
            });

            // editing lesson text, so set reactive variable
            editingLessonText.set(true);
        }
    }
});
<commit_msg>Using editing lesson mode reactive variable.<commit_after>Template.lesson.helpers({
    'activeLesson': function () {
        // Get the lesson ID from session
        var lessonID = activeLessonID.get();

        // Get the lesson from DB
        // selecting the zeroth array item
        var lesson = Lessons.findOne({_id: lessonID});

        return lesson;
    },
    'editingLessonText': function (template) {
        // return true if editing the lesson text
        // value is set on click event
        return editingLessonText.get();
    }
});

Template.lesson.events({
    'click .lesson-text': function () {
        // editing mode is true if text is clicked
        editingLessonText.set(true);

        // in edit mode,
        // add rich text editor
        // to lesson text
        if (editingLessonText.get()) {
            $('.lesson-text').summernote({
                // TODO: add more config parameters as needed
                height: 300
            });
        }
    }
});
<|endoftext|>


<commit_before>/*
 * grunt-zip
 * https://github.com/twolfson/grunt-zip
 *
 * Copyright (c) 2013 Todd Wolfson
 * Licensed under the MIT license.
 */

var fs = require('fs'),
    path = require('path'),
    Zip = require('node-zip'),
    gruntRetro = require('grunt-retro');
module.exports = function(grunt) {
  // Load and bind grunt-retro
  grunt = gruntRetro(grunt);

  // Please see the grunt documentation for more information regarding task and
  // helper creation: https://github.com/gruntjs/grunt/blob/master/docs/toc.md

  // ==========================================================================
  // TASKS
  // ==========================================================================

  // Localize underscore
  var _ = grunt.utils._;

  grunt.registerMultiTask('zip', 'Zip files together', function() {
    // Localize variables
    var file = this.file,
        data = this.data,
        src = file.src,
        dest = file.dest,
        router = data.router;

    // Fallback options (e.g. base64, compression)
    _.defaults(data, {
      base64: false
    });

    // Collect our file paths
    var globOptions = {dot: data.dot},
        srcFolders = grunt.file.expandDirs(globOptions, src),
        srcFiles = grunt.file.expandFiles(globOptions, src);

    // If there is no router
    if (!router) {
      // Grab the cwd and return the relative path as our router
      var cwd = data.cwd || process.cwd(),
          separator = new RegExp(path.sep.replace('\\', '\\\\'), 'g');
      router = function routerFn (filepath) {
        // Join path via /
        // DEV: Files zipped on Windows need to use /  to have the same layout on Linux
        return path.relative(cwd, filepath).replace(separator, '/');
      };
    } else if (data.cwd) {
    // Otherwise, if a `cwd` was specified, throw a fit and leave
      grunt.fail.warn('grunt-zip does not accept `cwd` and `router` in the same config due to potential ordering complications. Please choose one.');
    }

    // Generate our zipper
    var zip = new Zip();

    // For each of the srcFolders
    srcFolders.forEach(function (folderpath) {
      // Route the folder
      var routedPath = router(folderpath);

      // If there is a folder, add it to the zip (allows for skipping)
      if (routedPath) {
        zip.folder(routedPath);
      }
    });

    // For each of the srcFiles
    srcFiles.forEach(function (filepath) {
      // Read in the content and add it to the zip
      var input = fs.readFileSync(filepath, 'binary'),
          routedPath = router(filepath);

      // If it has a path, add it (allows for skipping)
      if (routedPath) {
        zip.file(routedPath, input, {binary: true});
      }
    });

    // Create the destination directory
    var destDir = path.dirname(dest);
    grunt.file.mkdir(destDir);

    // Write out the content
    var output = zip.generate({base64: data.base64, compression: data.compression});
    fs.writeFileSync(dest, output, 'binary');

    // Fail task if errors were logged.
    if (this.errorCount) { return false; }

    // Otherwise, print a success message.
    grunt.log.writeln('File "' + dest + '" created.');
  });

  function echo(a) {
    return a;
  }
  grunt.registerMultiTask('unzip', 'Unzip files into a folder', function() {
    // Collect the filepaths we need
    var file = this.file,
        data = this.data,
        src = file.src,
        srcFiles = grunt.file.expand(src),
        dest = file.dest,
        router = data.router || echo;

    // Fallback options (e.g. checkCRC32)
    _.defaults(data, {
      base64: false,
      checkCRC32: true
    });

    // Iterate over the srcFiles
    srcFiles.forEach(function (filepath) {
      // Read in the contents
      var input = fs.readFileSync(filepath, 'binary');

      // Unzip it
      var zip = new Zip(input, {base64: data.base64, checkCRC32: data.checkCRC32});

      // Pluck out the files
      var files = zip.files,
          filenames = Object.getOwnPropertyNames(files);

      // Filter out all non-leaf files
      filenames = filenames.filter(function filterNonLeafs (filename) {
        // Iterate over the other filenames
        var isLeaf = true,
            i = filenames.length,
            otherFile,
            pathToFile,
            isParentDir;
        while (i--) {
          // If the other file is the current file, skip it
          otherFile = filenames[i];
          if (otherFile === filename) {
            continue;
          }

          // Determine if this file contains the other
          pathToFile = path.relative(filename, otherFile);
          isParentDir = pathToFile.indexOf('..') === -1;

          // If it does, falsify isLeaf
          if (isParentDir) {
            isLeaf = false;
            break;
          }
        }

        // Return that the file was a leaf
        return isLeaf;
      });

      // Iterate over the files
      filenames.forEach(function (filename) {
        // Find the content
        var fileObj = files[filename],
            content = fileObj.data,
            routedName = router(filename);

        // If there is a file path (allows for skipping)
        if (routedName) {
          // Determine the filepath
          var filepath = path.join(dest, routedName);

          // Create the destination directory
          var fileDir = path.dirname(filepath);
          grunt.file.mkdir(fileDir);

          // Write out the content
          console.log('dir', fileDir);
          console.log('path', filepath);
          try {
            fs.writeFileSync(filepath, content, 'binary');
          } catch (e) {
            // If we misidentified a leaf as a directory (e.g. it's empty), create it
            console.log('error', e);
            console.log('error code', e.code);
            if (e.code === 'EISDIR') {
              grunt.file.mkdir(filepath);
            } else {
            // Otherwise, throw the error
              throw e;
            }
          }
        }
      });
    });

    // Fail task if errors were logged.
    if (this.errorCount) { return false; }

    // Otherwise, print a success message.
    grunt.log.writeln('File "' + this.file.dest + '" created.');
  });

};
<commit_msg>Attempting ENOENT as patch<commit_after>/*
 * grunt-zip
 * https://github.com/twolfson/grunt-zip
 *
 * Copyright (c) 2013 Todd Wolfson
 * Licensed under the MIT license.
 */

var fs = require('fs'),
    path = require('path'),
    Zip = require('node-zip'),
    gruntRetro = require('grunt-retro');
module.exports = function(grunt) {
  // Load and bind grunt-retro
  grunt = gruntRetro(grunt);

  // Please see the grunt documentation for more information regarding task and
  // helper creation: https://github.com/gruntjs/grunt/blob/master/docs/toc.md

  // ==========================================================================
  // TASKS
  // ==========================================================================

  // Localize underscore
  var _ = grunt.utils._;

  grunt.registerMultiTask('zip', 'Zip files together', function() {
    // Localize variables
    var file = this.file,
        data = this.data,
        src = file.src,
        dest = file.dest,
        router = data.router;

    // Fallback options (e.g. base64, compression)
    _.defaults(data, {
      base64: false
    });

    // Collect our file paths
    var globOptions = {dot: data.dot},
        srcFolders = grunt.file.expandDirs(globOptions, src),
        srcFiles = grunt.file.expandFiles(globOptions, src);

    // If there is no router
    if (!router) {
      // Grab the cwd and return the relative path as our router
      var cwd = data.cwd || process.cwd(),
          separator = new RegExp(path.sep.replace('\\', '\\\\'), 'g');
      router = function routerFn (filepath) {
        // Join path via /
        // DEV: Files zipped on Windows need to use /  to have the same layout on Linux
        return path.relative(cwd, filepath).replace(separator, '/');
      };
    } else if (data.cwd) {
    // Otherwise, if a `cwd` was specified, throw a fit and leave
      grunt.fail.warn('grunt-zip does not accept `cwd` and `router` in the same config due to potential ordering complications. Please choose one.');
    }

    // Generate our zipper
    var zip = new Zip();

    // For each of the srcFolders
    srcFolders.forEach(function (folderpath) {
      // Route the folder
      var routedPath = router(folderpath);

      // If there is a folder, add it to the zip (allows for skipping)
      if (routedPath) {
        zip.folder(routedPath);
      }
    });

    // For each of the srcFiles
    srcFiles.forEach(function (filepath) {
      // Read in the content and add it to the zip
      var input = fs.readFileSync(filepath, 'binary'),
          routedPath = router(filepath);

      // If it has a path, add it (allows for skipping)
      if (routedPath) {
        zip.file(routedPath, input, {binary: true});
      }
    });

    // Create the destination directory
    var destDir = path.dirname(dest);
    grunt.file.mkdir(destDir);

    // Write out the content
    var output = zip.generate({base64: data.base64, compression: data.compression});
    fs.writeFileSync(dest, output, 'binary');

    // Fail task if errors were logged.
    if (this.errorCount) { return false; }

    // Otherwise, print a success message.
    grunt.log.writeln('File "' + dest + '" created.');
  });

  function echo(a) {
    return a;
  }
  grunt.registerMultiTask('unzip', 'Unzip files into a folder', function() {
    // Collect the filepaths we need
    var file = this.file,
        data = this.data,
        src = file.src,
        srcFiles = grunt.file.expand(src),
        dest = file.dest,
        router = data.router || echo;

    // Fallback options (e.g. checkCRC32)
    _.defaults(data, {
      base64: false,
      checkCRC32: true
    });

    // Iterate over the srcFiles
    srcFiles.forEach(function (filepath) {
      // Read in the contents
      var input = fs.readFileSync(filepath, 'binary');

      // Unzip it
      var zip = new Zip(input, {base64: data.base64, checkCRC32: data.checkCRC32});

      // Pluck out the files
      var files = zip.files,
          filenames = Object.getOwnPropertyNames(files);

      // Filter out all non-leaf files
      filenames = filenames.filter(function filterNonLeafs (filename) {
        // Iterate over the other filenames
        var isLeaf = true,
            i = filenames.length,
            otherFile,
            pathToFile,
            isParentDir;
        while (i--) {
          // If the other file is the current file, skip it
          otherFile = filenames[i];
          if (otherFile === filename) {
            continue;
          }

          // Determine if this file contains the other
          pathToFile = path.relative(filename, otherFile);
          isParentDir = pathToFile.indexOf('..') === -1;

          // If it does, falsify isLeaf
          if (isParentDir) {
            isLeaf = false;
            break;
          }
        }

        // Return that the file was a leaf
        return isLeaf;
      });

      // Iterate over the files
      filenames.forEach(function (filename) {
        // Find the content
        var fileObj = files[filename],
            content = fileObj.data,
            routedName = router(filename);

        // If there is a file path (allows for skipping)
        if (routedName) {
          // Determine the filepath
          var filepath = path.join(dest, routedName);

          // Create the destination directory
          var fileDir = path.dirname(filepath);
          grunt.file.mkdir(fileDir);

          // Write out the content
          console.log('dir', fileDir);
          console.log('path', filepath);
          try {
            fs.writeFileSync(filepath, content, 'binary');
          } catch (e) {
            // If we misidentified a leaf as a directory (e.g. it's empty), create it
            console.log('error', e);
            console.log('error code', e.code);
            if (e.code === 'EISDIR' || e.code === 'ENOENT') {
              grunt.file.mkdir(filepath);
            } else {
            // Otherwise, throw the error
              throw e;
            }
          }
        }
      });
    });

    // Fail task if errors were logged.
    if (this.errorCount) { return false; }

    // Otherwise, print a success message.
    grunt.log.writeln('File "' + this.file.dest + '" created.');
  });

};
<|endoftext|>