<commit_before>frappe.provide('frappe.phone_call');

frappe.ui.form.ControlData = class ControlData extends frappe.ui.form.ControlInput {
	static html_element = "input";
	static input_type = "text";
	static trigger_change_on_input_event = true;
	make_input() {
		if(this.$input) return;

		let { html_element, input_type } = this.constructor;

		this.$input = $("<"+ html_element +">")
			.attr("type", input_type)
			.attr("autocomplete", "off")
			.addClass("input-with-feedback form-control")
			.prependTo(this.input_area);

		if (in_list(['Data', 'Link', 'Dynamic Link', 'Password', 'Select', 'Read Only', 'Attach', 'Attach Image'],
			this.df.fieldtype)) {
			this.$input.attr("maxlength", this.df.length || 140);
		}

		this.$input.on('paste', (e) => {
			let pasted_data = frappe.utils.get_clipboard_data(e);
			let maxlength = this.$input.attr('maxlength');
			if (maxlength && pasted_data.length > maxlength) {
				let warning_message = __('The value you pasted was {0} characters long. Max allowed characters is {1}.', [
					cstr(pasted_data.length).bold(),
					cstr(maxlength).bold()
				]);

				// Only show edit link to users who can update the doctype
				if (this.frm && frappe.model.can_write(this.frm.doctype)) {
					let doctype_edit_link = null;
					if (this.frm.meta.custom) {
						doctype_edit_link = frappe.utils.get_form_link(
							'DocType',
							this.frm.doctype, true,
							__('this form')
						);
					} else {
						doctype_edit_link = frappe.utils.get_form_link('Customize Form', 'Customize Form', true, null, {
							doc_type: this.frm.doctype
						});
					}
					let edit_note = __('{0}: You can increase the limit for the field if required via {1}', [
						__('Note').bold(),
						doctype_edit_link
					]);
					warning_message += `<br><br><span class="text-muted text-small">${edit_note}</span>`;
				}

				frappe.msgprint({
					message: warning_message,
					indicator: 'orange',
					title: __('Data Clipped')
				});
			}
		});

		this.set_input_attributes();
		this.input = this.$input.get(0);
		this.has_input = true;
		this.bind_change_event();
		this.setup_autoname_check();

		if (this.df.options == 'URL') {
			this.setup_url_field();
		}

		if (this.df.options == 'Barcode') {
			this.setup_barcode_field();
		}
	}

	setup_url_field() {
		this.$wrapper.find('.control-input').append(
			`

					${frappe.utils.icon('link-url', 'sm')}

			`
		);

		this.$link = this.$wrapper.find('.link-btn');
		this.$link_open = this.$link.find('.btn-open');

		this.$input.on("focus", () => {
			setTimeout(() => {
				let inputValue = this.get_input_value();

				if (inputValue && validate_url(inputValue)) {
					this.$link.toggle(true);
					this.$link_open.attr('href', this.get_input_value());
				}
			}, 500);
		});

		this.$input.bind("input", () => {
			let inputValue = this.get_input_value();

			if (inputValue && validate_url(inputValue)) {
				this.$link.toggle(true);
				this.$link_open.attr('href', this.get_input_value());
			} else {
				this.$link.toggle(false);
			}
		});

		this.$input.on("blur", () => {
			// if this disappears immediately, the user's click
			// does not register, hence timeout
			setTimeout(() => {
				this.$link.toggle(false);
			}, 500);
		});
	}

	setup_barcode_field() {
		this.$wrapper.find('.control-input').append(
			`

					${frappe.utils.icon('scan', 'sm')}

			`
		);

		this.$scan_btn = this.$wrapper.find('.link-btn');

		this.$input.on("focus", () => {
			setTimeout(() => {
				this.$scan_btn.toggle(true);
			}, 500);
		});

		const me = this;
		this.$scan_btn.on('click', 'a', () => {
			new frappe.ui.Scanner({
				dialog: true,
				multiple: false,
				on_scan(data) {
					if (data && data.result && data.result.text) {
						me.set_value(data.result.text);
					}
				}
			});
		});

		this.$input.on("blur", () => {
			setTimeout(() => {
				this.$scan_btn.toggle(false);
			}, 500);
		});
	}

	bind_change_event() {
		const change_handler = e => {
			if (this.change) this.change(e);
			else {
				let value = this.get_input_value();
				this.parse_validate_and_set_in_model(value, e);
			}
		};
		this.$input.on("change", change_handler);
		if (this.constructor.trigger_change_on_input_event) {
			// debounce to avoid repeated validations on value change
			this.$input.on("input", frappe.utils.debounce(change_handler, 500));
		}
	}
	setup_autoname_check() {
		if (!this.df.parent) return;
		this.meta = frappe.get_meta(this.df.parent);
		if (this.meta && ((this.meta.autoname
			&& this.meta.autoname.substr(0, 6)==='field:'
			&& this.meta.autoname.substr(6) === this.df.fieldname) || this.df.fieldname==='__newname') ) {
			this.$input.on('keyup', () => {
				this.set_description('');
				if (this.doc && this.doc.__islocal) {
					// check after 1 sec
					let timeout = setTimeout(() => {
						// clear any pending calls
						if (this.last_check) clearTimeout(this.last_check);

						// check if name exists
						frappe.db.get_value(this.doctype, this.$input.val(),
							'name', (val) => {
								if (val && val.name) {
									this.set_description(__('{0} already exists. Select another name', [val.name]));
								}
							},
							this.doc.parenttype
						);
						this.last_check = null;
					}, 1000);
					this.last_check = timeout;
				}
			});
		}
	}
	set_input_attributes() {
		this.$input
			.attr("data-fieldtype", this.df.fieldtype)
			.attr("data-fieldname", this.df.fieldname)
			.attr("placeholder", this.df.placeholder || "");
		if(this.doctype) {
			this.$input.attr("data-doctype", this.doctype);
		}
		if(this.df.input_css) {
			this.$input.css(this.df.input_css);
		}
		if(this.df.input_class) {
			this.$input.addClass(this.df.input_class);
		}
	}
	set_input(value) {
		this.last_value = this.value;
		this.value = value;
		this.set_formatted_input(value);
		this.set_disp_area(value);
		this.set_mandatory && this.set_mandatory(value);
	}
	set_formatted_input(value) {
		this.$input && this.$input.val(this.format_for_input(value));
	}
	get_input_value() {
		return this.$input ? this.$input.val() : undefined;
	}
	format_for_input(val) {
		return val==null ? "" : val;
	}
	validate(v) {
		if (!v) {
			return '';
		}
		if(this.df.is_filter) {
			return v;
		}
		if(this.df.options == 'Phone') {
			this.df.invalid = !validate_phone(v);
			return v;
		} else if (this.df.options == 'Name') {
			this.df.invalid = !validate_name(v);
			return v;
		} else if(this.df.options == 'Email') {
			var email_list = frappe.utils.split_emails(v);
			if (!email_list) {
				return '';
			} else {
				let email_invalid = false;
				email_list.forEach(function(email) {
					if (!validate_email(email)) {
						email_invalid = true;
					}
				});
				this.df.invalid = email_invalid;
				return v;
			}
		} else if (this.df.options == 'URL') {
			this.df.invalid = !validate_url(v);
			return v;
		} else {
			return v;
		}
	}
	toggle_container_scroll(el_class, scroll_class, add=false) {
		let el = this.$input.parents(el_class)[0];
		if (el) $(el).toggleClass(scroll_class, add);
	}
};
<commit_msg>fix: Avoid input events for controls in grid<commit_after>frappe.provide('frappe.phone_call');

frappe.ui.form.ControlData = class ControlData extends frappe.ui.form.ControlInput {
	static html_element = "input";
	static input_type = "text";
	static trigger_change_on_input_event = true;
	make_input() {
		if(this.$input) return;

		let { html_element, input_type } = this.constructor;

		this.$input = $("<"+ html_element +">")
			.attr("type", input_type)
			.attr("autocomplete", "off")
			.addClass("input-with-feedback form-control")
			.prependTo(this.input_area);

		if (in_list(['Data', 'Link', 'Dynamic Link', 'Password', 'Select', 'Read Only', 'Attach', 'Attach Image'],
			this.df.fieldtype)) {
			this.$input.attr("maxlength", this.df.length || 140);
		}

		this.$input.on('paste', (e) => {
			let pasted_data = frappe.utils.get_clipboard_data(e);
			let maxlength = this.$input.attr('maxlength');
			if (maxlength && pasted_data.length > maxlength) {
				let warning_message = __('The value you pasted was {0} characters long. Max allowed characters is {1}.', [
					cstr(pasted_data.length).bold(),
					cstr(maxlength).bold()
				]);

				// Only show edit link to users who can update the doctype
				if (this.frm && frappe.model.can_write(this.frm.doctype)) {
					let doctype_edit_link = null;
					if (this.frm.meta.custom) {
						doctype_edit_link = frappe.utils.get_form_link(
							'DocType',
							this.frm.doctype, true,
							__('this form')
						);
					} else {
						doctype_edit_link = frappe.utils.get_form_link('Customize Form', 'Customize Form', true, null, {
							doc_type: this.frm.doctype
						});
					}
					let edit_note = __('{0}: You can increase the limit for the field if required via {1}', [
						__('Note').bold(),
						doctype_edit_link
					]);
					warning_message += `<br><br><span class="text-muted text-small">${edit_note}</span>`;
				}

				frappe.msgprint({
					message: warning_message,
					indicator: 'orange',
					title: __('Data Clipped')
				});
			}
		});

		this.set_input_attributes();
		this.input = this.$input.get(0);
		this.has_input = true;
		this.bind_change_event();
		this.setup_autoname_check();

		if (this.df.options == 'URL') {
			this.setup_url_field();
		}

		if (this.df.options == 'Barcode') {
			this.setup_barcode_field();
		}
	}

	setup_url_field() {
		this.$wrapper.find('.control-input').append(
			`

					${frappe.utils.icon('link-url', 'sm')}

			`
		);

		this.$link = this.$wrapper.find('.link-btn');
		this.$link_open = this.$link.find('.btn-open');

		this.$input.on("focus", () => {
			setTimeout(() => {
				let inputValue = this.get_input_value();

				if (inputValue && validate_url(inputValue)) {
					this.$link.toggle(true);
					this.$link_open.attr('href', this.get_input_value());
				}
			}, 500);
		});

		this.$input.bind("input", () => {
			let inputValue = this.get_input_value();

			if (inputValue && validate_url(inputValue)) {
				this.$link.toggle(true);
				this.$link_open.attr('href', this.get_input_value());
			} else {
				this.$link.toggle(false);
			}
		});

		this.$input.on("blur", () => {
			// if this disappears immediately, the user's click
			// does not register, hence timeout
			setTimeout(() => {
				this.$link.toggle(false);
			}, 500);
		});
	}

	setup_barcode_field() {
		this.$wrapper.find('.control-input').append(
			`

					${frappe.utils.icon('scan', 'sm')}

			`
		);

		this.$scan_btn = this.$wrapper.find('.link-btn');

		this.$input.on("focus", () => {
			setTimeout(() => {
				this.$scan_btn.toggle(true);
			}, 500);
		});

		const me = this;
		this.$scan_btn.on('click', 'a', () => {
			new frappe.ui.Scanner({
				dialog: true,
				multiple: false,
				on_scan(data) {
					if (data && data.result && data.result.text) {
						me.set_value(data.result.text);
					}
				}
			});
		});

		this.$input.on("blur", () => {
			setTimeout(() => {
				this.$scan_btn.toggle(false);
			}, 500);
		});
	}

	bind_change_event() {
		const change_handler = e => {
			if (this.change) this.change(e);
			else {
				let value = this.get_input_value();
				this.parse_validate_and_set_in_model(value, e);
			}
		};
		this.$input.on("change", change_handler);
		if (this.constructor.trigger_change_on_input_event && !this.in_grid()) {
			// debounce to avoid repeated validations on value change
			this.$input.on("input", frappe.utils.debounce(change_handler, 500));
		}
	}
	setup_autoname_check() {
		if (!this.df.parent) return;
		this.meta = frappe.get_meta(this.df.parent);
		if (this.meta && ((this.meta.autoname
			&& this.meta.autoname.substr(0, 6)==='field:'
			&& this.meta.autoname.substr(6) === this.df.fieldname) || this.df.fieldname==='__newname') ) {
			this.$input.on('keyup', () => {
				this.set_description('');
				if (this.doc && this.doc.__islocal) {
					// check after 1 sec
					let timeout = setTimeout(() => {
						// clear any pending calls
						if (this.last_check) clearTimeout(this.last_check);

						// check if name exists
						frappe.db.get_value(this.doctype, this.$input.val(),
							'name', (val) => {
								if (val && val.name) {
									this.set_description(__('{0} already exists. Select another name', [val.name]));
								}
							},
							this.doc.parenttype
						);
						this.last_check = null;
					}, 1000);
					this.last_check = timeout;
				}
			});
		}
	}
	set_input_attributes() {
		this.$input
			.attr("data-fieldtype", this.df.fieldtype)
			.attr("data-fieldname", this.df.fieldname)
			.attr("placeholder", this.df.placeholder || "");
		if(this.doctype) {
			this.$input.attr("data-doctype", this.doctype);
		}
		if(this.df.input_css) {
			this.$input.css(this.df.input_css);
		}
		if(this.df.input_class) {
			this.$input.addClass(this.df.input_class);
		}
	}
	set_input(value) {
		this.last_value = this.value;
		this.value = value;
		this.set_formatted_input(value);
		this.set_disp_area(value);
		this.set_mandatory && this.set_mandatory(value);
	}
	set_formatted_input(value) {
		this.$input && this.$input.val(this.format_for_input(value));
	}
	get_input_value() {
		return this.$input ? this.$input.val() : undefined;
	}
	format_for_input(val) {
		return val==null ? "" : val;
	}
	validate(v) {
		if (!v) {
			return '';
		}
		if(this.df.is_filter) {
			return v;
		}
		if(this.df.options == 'Phone') {
			this.df.invalid = !validate_phone(v);
			return v;
		} else if (this.df.options == 'Name') {
			this.df.invalid = !validate_name(v);
			return v;
		} else if(this.df.options == 'Email') {
			var email_list = frappe.utils.split_emails(v);
			if (!email_list) {
				return '';
			} else {
				let email_invalid = false;
				email_list.forEach(function(email) {
					if (!validate_email(email)) {
						email_invalid = true;
					}
				});
				this.df.invalid = email_invalid;
				return v;
			}
		} else if (this.df.options == 'URL') {
			this.df.invalid = !validate_url(v);
			return v;
		} else {
			return v;
		}
	}
	toggle_container_scroll(el_class, scroll_class, add=false) {
		let el = this.$input.parents(el_class)[0];
		if (el) $(el).toggleClass(scroll_class, add);
	}
	in_grid() {
		return this.grid || this.layout && this.layout.grid;
	}
};
<|endoftext|>


<commit_before>
const got = require('got');
const azureService = 'https://attestations.azure.com';

module.exports = class Attestations {
  constructor (options = {}) {
    this.key = options.key;
  }

  instantiate (id) {
    return new Attestation(id, key);
  }

  create (options = {}) {
    return new Promise((resolve, reject) => {
      if (!options.ids && !options.chainpoint) {
        throw 'You must specify an attestation action to perform - your choices are: identity signing, chain anchoring, or both';
      }
      if (!options.data) {
        throw 'You provided no attestation data';
      }
      options.key = this.key;
      got.post(azureService + '/create', {
        json: true,
        body: options
      }).then(response => {
        resolve(response.record);
      }).catch(response => {
        reject(response)
      })
    });
  }

  retrieve (id) {
    return new Promise((resolve, reject) => {
      if (this.record) resolve(this.record);
      else got.get(azureService + '/attestation/' + id, {
        json: true,
        body: { key: this.key }
      }).then(response => {
        resolve(response.record);
      })
    });
  }

  status (id) {
    return got.get(azureService + '/status/' + id, {
      json: true,
      body: { key: this.key }
    })
  }

} <commit_msg>removed old class ref<commit_after>
const got = require('got');
const azureService = 'https://attestations.azure.com';

module.exports = class Attestations {
  constructor (options = {}) {
    this.key = options.key;
  }

  create (options = {}) {
    return new Promise((resolve, reject) => {
      if (!options.ids && !options.chainpoint) {
        throw 'You must specify an attestation action to perform - your choices are: identity signing, chain anchoring, or both';
      }
      if (!options.data) {
        throw 'You provided no attestation data';
      }
      options.key = this.key;
      got.post(azureService + '/create', {
        json: true,
        body: options
      }).then(response => {
        resolve(response.record);
      }).catch(response => {
        reject(response)
      })
    });
  }

  retrieve (id) {
    return new Promise((resolve, reject) => {
      if (this.record) resolve(this.record);
      else got.get(azureService + '/attestation/' + id, {
        json: true,
        body: { key: this.key }
      }).then(response => {
        resolve(response.record);
      })
    });
  }

  status (id) {
    return got.get(azureService + '/status/' + id, {
      json: true,
      body: { key: this.key }
    })
  }

} <|endoftext|>


<commit_before>/* global TD */
import { Timestamp } from './components/time';
import { BTDDebug } from './components/btdDebug';
import { RemoveRedirection } from './components/removeRedirection';

(async () => {
  const BTD_SETTINGS = $('[data-btd-settings]').data('btd-settings');
  const BTDTime = new Timestamp(BTD_SETTINGS, TD);

  new BTDDebug(BTD_SETTINGS, TD).attach();

  /*
 * If the user chose so, we override the timestamp function called by TweetDeck
 */
  if (BTD_SETTINGS.ts !== 'relative') {
    TD.util.prettyDate = d => BTDTime.prettyDate(d);
  }

  /*
 * If the user chose so, we override the link creation mechanism to remove the t.co redirection
 */
  if (BTD_SETTINGS.no_tco) {
    new RemoveRedirection(BTD_SETTINGS, TD).init();
  }

  $(document).one('dataColumnsLoaded', () => {
    console.log('ready!');
  });
})();
<commit_msg>:sparkles:<commit_after>/* global TD */
import { Timestamp } from './components/time';
import { BTDDebug } from './components/btdDebug';
import { RemoveRedirection } from './components/removeRedirection';
// import { msgToContent } from './util/messaging';

(async () => {
  const BTD_SETTINGS = $('[data-btd-settings]').data('btd-settings');
  const BTDTime = new Timestamp(BTD_SETTINGS, TD);

  new BTDDebug(BTD_SETTINGS, TD).attach();

  /*
 * If the user chose so, we override the timestamp function called by TweetDeck
 */
  if (BTD_SETTINGS.ts !== 'relative') {
    TD.util.prettyDate = d => BTDTime.prettyDate(d);
  }

  /*
 * If the user chose so, we override the link creation mechanism to remove the t.co redirection
 */
  if (BTD_SETTINGS.no_tco) {
    new RemoveRedirection(BTD_SETTINGS, TD).init();
  }

  $(document).one('dataColumnsLoaded', () => {
    console.log('ready!');
  });
})();
<|endoftext|>


<commit_before>import {View} from '../view';
import {Command} from '../command';
import {flatView as nodeFlatView} from '../node';
import {getFactory as valueFactory} from '../services/value';

export class GroupView extends View {
	constructor(model, commandManager) {
		super(model);

		this.valueFactory = valueFactory;
		this.toggleStatus = new Command({
			execute: node => {
				if (!node) {
					node = model.navigation().cell.row;
				}

				node.state.expand = !node.state.expand;
				const view = model.view;
				const nodes = view().nodes;
				view({rows: nodeFlatView(nodes)}, {behavior: 'core', source: 'group.view'});
			},
			canExecute: node => {
				if (!node) {
					const cell = model.navigation().cell;
					if (cell && cell.column.type === 'group') {
						node = cell.row;
					}
				}

				return node && node.type === 'group';
			},
			shortcut: model.group().shortcut.toggle
		});

		const shortcut = model.action().shortcut;
		shortcut.register(commandManager, [this.toggleStatus]);
	}

	count(node) {
		return node.children.length || node.rows.length;
	}

	status(node) {
		return node.state.expand ? 'expand' : 'collapse';
	}

	offset(node) {
		const groupColumn = (this.model.view().columns[0] || []).find(c => c.model.type === 'group');
		if (groupColumn) {
			return groupColumn.model.offset * node.level;
		}

		return 0;
	}

	value(node) {
		return node.key;
	}
}<commit_msg>Add toggle cmd<commit_after>import {View} from '../view';
import {Command} from '../command';
import {flatView as nodeFlatView} from '../node';
import {getFactory as valueFactory} from '../services/value';

export class GroupView extends View {
	constructor(model, commandManager) {
		super(model);

		this.valueFactory = valueFactory;
		this.toggleStatus = new Command({
			execute: node => {
				if (!node) {
					node = model.navigation().cell.row;
				}

				const toggle = model.group().toggle;
				if (toggle.execute(node) !== false) {
					node.state.expand = !node.state.expand;
					const view = model.view;
					const nodes = view().nodes;
					view({rows: nodeFlatView(nodes)}, {behavior: 'core', source: 'group.view'});
				}
			},
			canExecute: node => {
				if (!node) {
					const cell = model.navigation().cell;
					if (cell && cell.column.type === 'group') {
						node = cell.row;
					}
				}

				const toggle = model.group().toggle;
				return node && node.type === 'group' && toggle.canExecute(node);
			},
			shortcut: model.group().shortcut.toggle
		});

		const shortcut = model.action().shortcut;
		shortcut.register(commandManager, [this.toggleStatus]);
	}

	count(node) {
		return node.children.length || node.rows.length;
	}

	status(node) {
		return node.state.expand ? 'expand' : 'collapse';
	}

	offset(node) {
		const groupColumn = (this.model.view().columns[0] || []).find(c => c.model.type === 'group');
		if (groupColumn) {
			return groupColumn.model.offset * node.level;
		}

		return 0;
	}

	value(node) {
		return node.key;
	}
}<|endoftext|>


<commit_before>// Create the ConkerChrome object
var ConkerC = function(opts) {

    // Default options
    var defaults = {
	line: 40,        // Number of pixels to scroll up and down
	column: 20,      // Number of pixels to scroll left and right
	ctrl: "ctrl",    // Default key mappings
	meta: "meta",    // Users can change these
	shift: "shift"   // If they want
    };

    // Load the user provided options
    var options = jQuery.extend({}, defaults, opts);

    // Lots of pixels jump to the top or bottom of a page
    // The user shouldn't be able to set this
    var BIG = 10000000000;

    // HTML Selectors for ConkerChrome elements
    var selectors = {
	conker: "#conkerchrome",
	commandbar: "#commandbar",
	commandinput: "#conkerchrome input",
	number: ".conkerchrome_number"
    }

    // CSS Selectors for ConkerChrome elements
    var css = {
	highlight: "conkerchrome_highlight",
	selected: "conkerchrome_selected",
	number: "conkerchrome_number"
    }

    var baseMode = {
	enter: function(){},
	leave: function(){},
	update: function(e, bar){}
    }

    // Module to hold all the keybindings
    // I wrote this a while ago, not sure how it works
    var hotkeys = function() {
	var matched = false;
	var current = "";
	var combo = "";
	var partialKeyMap = {};
	var fullKeyMap = {};
	var keyMap = {};
	var unrecognized = function(){};

	var keyPress = function() {
	    if (partialKeyMap[combo]) {
		current = combo;
		matched = true;
	    } else if (fullKeyMap[combo]) {
		matched = true;
		current = "";
		fullKeyMap[combo]();
	    }
	};

	var keyFn = function(kk){
	    return function() {
		combo = current + kk;
		keyPress();
	    }
	};

	jQuery(document).keydown(function() {
	    matched = false;
	    command = false;
	});

	jQuery(document).keyup(function() {
	    if(!matched) {
		unrecognized();
		current = "";
	    }
	});

	// Return the hotkeys object
	return {
	    setUnrecognized: function(fn){ unrecognized = fn; },
	    add: function(k, fn){

		var keys = k.toLowerCase().split(" ");
		var seq = "";

		for ( var i = 0, l = keys.length; i < l; i++ ) {

		    //Create a partial mapping
		    seq += keys[i];
		    if (i < (l - 1)) {
			partialKeyMap[seq] = true;
		    } else {
			fullKeyMap[seq] = fn;
		    }

		    //Only maps keys we haven't seen before
		    if (!keyMap[ keys[i] ]) {
			keyMap[ keys[i] ] = true;
			$(document).bind('keydown', keys[i], keyFn(keys[i]));
		    }
		}
	    }
	}
    }();

    // Call this function when an unknown command is entered
    hotkeys.setUnrecognized(function(){});

    // Current mode
    var currentMode  = baseMode;

    // Create conkerbar
    var conkerBar = function(){

	jQuery(document.body).append("

<input type=\"text\">
");
	var bar = jQuery(selectors.conker);
	var title = jQuery(selectors.commandbar);
	var input = jQuery(selectors.commandinput);

	input.keyup(function(e) {
	    if(e.keyCode == 71 && e.ctrlKey){
		cancel();
	    }
	    currentMode.update(e, bar);
	});

	return {
	    hide: function(){ bar.hide(); input.val("").blur();},
	    show: function(text){
		title.text(text);
		bar.show();
		input.css({"left": title.width() + 10}).focus();
	    }
	};
    }();

    // Exit out of the current mode
    var cancel = function(){
	conkerBar.hide();
	currentMode.leave();
	currentMode = baseMode;
    };

    // Unfocus selected area (such as a textbox)
    hotkeys.add("esc", function(){
	$(":focus").blur();
    });

    // Cancel current command
    hotkeys.add("ctrl+g", cancel);

    // Move back one page in the history
    hotkeys.add("shift+b", function() {
	window.history.back();
    });

    // Move forward one page in the history
    hotkeys.add("shift+f", function() {
	window.history.forward();
    });

    // Reload the current page
    hotkeys.add("ctrl+r", function() {
	window.location.reload(true);
    });

    // Movement around the page

    // Scroll the page all the way to the right
    hotkeys.add("ctrl+a", function(){
	window.scrollBy(-BIG, 0);
    });

    // Scroll the page all the way to the left
    hotkeys.add("ctrl+e", function(){
	window.scrollBy(BIG, 0);
    });

    // Scroll the page forward a column
    hotkeys.add("ctrl+f", function(){
	window.scrollBy(options.column, 0);
    });

    // Scroll the page back a column
    hotkeys.add("ctrl+b", function(){
	window.scrollBy(-options.column, 0);
    });

    // Scroll the page down a line
    hotkeys.add("ctrl+n", function(){
	window.scrollBy(0, options.line);
    });

    // Scroll the page up a line
    hotkeys.add("ctrl+p", function(){
	window.scrollBy(0, -options.line);
    });

    // Jump down a page length
    hotkeys.add("ctrl+v", function(){
	window.scrollBy(0, window.innerHeight - options.line);
    });

    // Jump up a page length
    hotkeys.add("meta+v", function(){
	window.scrollBy(0, -(window.innerHeight - options.line));
    });

    // Jump to the end of the page
    hotkeys.add("meta+shift+.", function(){
	window.scrollBy(0, BIG);
    });

    // Jump to the top of the page
    hotkeys.add("meta+shift+,", function(){
	window.scrollBy(0, -BIG);
    });

    // Open a url
    // TODO: Make this work
    hotkeys.add('ctrl+x ctrl+f', function() {
	conkerBar.show();
    });

    // Close the current tab
    hotkeys.add('ctrl+x k', function() {
	chrome.extension.sendRequest({action: "close-tab"});
    });

    hotkeys.add('f', function (evt){
	followMode.enter();
	currentMode = followMode;
    });

    // Follow a link on the page
    var followMode = {
	enter: function(){
	    jQuery("a").each(function(i, elem){
		jQuery(this).append(jQuery("
", {
		    "class": css.number, "text": i}))
		    .addClass(css.highlight);
	    });
	    conkerBar.show("Enter Link ID");
	},
	update: function(e, bar) {
	    // Get the selected link or return
	    var v = bar.val();
	    if (!v) return;
	    link = jQuery("a:eq(" + v + ")");
	    // If the return was pressed,
	    if (e.keyCode == 13) {
		if (link && link.attr("href")) {
		    // If shift+return, open new tab
		    if (e.shiftKey) {
			chrome.extension.sendRequest({
			    action: "new-tab",
			    url: link.attr("href")
			});
		    } else {
			window.location.href = link.attr("href");
		    }
		}
	    } else {
		jQuery("a." + css.selected).removeClass(css.selected);
		if (link.hasClass(css.selected))
		    return;
		link.addClass(css.selected);
	    }
	},
	leave: function(){
	    jQuery("a").removeClass(css.highlight)
		.removeClass(css.selected);
	    jQuery(selectors.number).remove();
	}
    }
}({}); //This object will later be a user stored settings file<commit_msg>Fix regression where links were not followed<commit_after>// Create the ConkerChrome object
var ConkerC = function(opts) {

    // Default options
    var defaults = {
	line: 40,        // Number of pixels to scroll up and down
	column: 20,      // Number of pixels to scroll left and right
	ctrl: "ctrl",    // Default key mappings
	meta: "meta",    // Users can change these
	shift: "shift"   // If they want
    };

    // Load the user provided options
    var options = jQuery.extend({}, defaults, opts);

    // Lots of pixels jump to the top or bottom of a page
    // The user shouldn't be able to set this
    var BIG = 10000000000;

    // HTML Selectors for ConkerChrome elements
    var selectors = {
	conker: "#conkerchrome",
	commandbar: "#commandbar",
	commandinput: "#conkerchrome input",
	number: ".conkerchrome_number"
    }

    // CSS Selectors for ConkerChrome elements
    var css = {
	highlight: "conkerchrome_highlight",
	selected: "conkerchrome_selected",
	number: "conkerchrome_number"
    }

    var baseMode = {
	enter: function(){},
	leave: function(){},
	update: function(e, bar){}
    }

    // Module to hold all the keybindings
    // I wrote this a while ago, not sure how it works
    var hotkeys = function() {
	var matched = false;
	var current = "";
	var combo = "";
	var partialKeyMap = {};
	var fullKeyMap = {};
	var keyMap = {};
	var unrecognized = function(){};

	var keyPress = function() {
	    if (partialKeyMap[combo]) {
		current = combo;
		matched = true;
	    } else if (fullKeyMap[combo]) {
		matched = true;
		current = "";
		fullKeyMap[combo]();
	    }
	};

	var keyFn = function(kk){
	    return function() {
		combo = current + kk;
		keyPress();
	    }
	};

	jQuery(document).keydown(function() {
	    matched = false;
	    command = false;
	});

	jQuery(document).keyup(function() {
	    if(!matched) {
		unrecognized();
		current = "";
	    }
	});

	// Return the hotkeys object
	return {
	    setUnrecognized: function(fn){ unrecognized = fn; },
	    add: function(k, fn){

		var keys = k.toLowerCase().split(" ");
		var seq = "";

		for ( var i = 0, l = keys.length; i < l; i++ ) {

		    //Create a partial mapping
		    seq += keys[i];
		    if (i < (l - 1)) {
			partialKeyMap[seq] = true;
		    } else {
			fullKeyMap[seq] = fn;
		    }

		    //Only maps keys we haven't seen before
		    if (!keyMap[ keys[i] ]) {
			keyMap[ keys[i] ] = true;
			$(document).bind('keydown', keys[i], keyFn(keys[i]));
		    }
		}
	    }
	}
    }();

    // Call this function when an unknown command is entered
    hotkeys.setUnrecognized(function(){});

    // Create conkerbar
    var conkerBar = function(){

	var currentMode  = baseMode;

	jQuery(document.body).append("

<input type=\"text\">
");
	var bar = jQuery(selectors.conker);
	var title = jQuery(selectors.commandbar);
	var input = jQuery(selectors.commandinput);

	var change = function(mode) {
	    currentMode = mode;
	}

	input.keyup(function(e) {
	    if(e.keyCode == 71 && e.ctrlKey){
		hide();
	    }
	    currentMode.update(e, input);
	});

	return {
	    hide: function(){
		bar.hide();
		input.val("").blur();
		currentMode.leave();
		currentMode = baseMode;
	    },
	    show: function(mode){
		currentMode = mode
		title.text(mode.title);
		bar.show();
		input.css({"left": title.width() + 10}).focus();
		mode.enter();
	    }
	};
    }();

    // Unfocus selected area (such as a textbox)
    hotkeys.add("esc", function(){
	$(":focus").blur();
    });

    // Cancel current command
    hotkeys.add("ctrl+g", conkerBar.hide);

    // Move back one page in the history
    hotkeys.add("shift+b", function() {
	window.history.back();
    });

    // Move forward one page in the history
    hotkeys.add("shift+f", function() {
	window.history.forward();
    });

    // Reload the current page
    hotkeys.add("ctrl+r", function() {
	window.location.reload(true);
    });

    // Movement around the page

    // Scroll the page all the way to the right
    hotkeys.add("ctrl+a", function(){
	window.scrollBy(-BIG, 0);
    });

    // Scroll the page all the way to the left
    hotkeys.add("ctrl+e", function(){
	window.scrollBy(BIG, 0);
    });

    // Scroll the page forward a column
    hotkeys.add("ctrl+f", function(){
	window.scrollBy(options.column, 0);
    });

    // Scroll the page back a column
    hotkeys.add("ctrl+b", function(){
	window.scrollBy(-options.column, 0);
    });

    // Scroll the page down a line
    hotkeys.add("ctrl+n", function(){
	window.scrollBy(0, options.line);
    });

    // Scroll the page up a line
    hotkeys.add("ctrl+p", function(){
	window.scrollBy(0, -options.line);
    });

    // Jump down a page length
    hotkeys.add("ctrl+v", function(){
	window.scrollBy(0, window.innerHeight - options.line);
    });

    // Jump up a page length
    hotkeys.add("meta+v", function(){
	window.scrollBy(0, -(window.innerHeight - options.line));
    });

    // Jump to the end of the page
    hotkeys.add("meta+shift+.", function(){
	window.scrollBy(0, BIG);
    });

    // Jump to the top of the page
    hotkeys.add("meta+shift+,", function(){
	window.scrollBy(0, -BIG);
    });

    // Open a url
    // TODO: Make this work
    hotkeys.add('ctrl+x ctrl+f', function() {
	conkerBar.show();
    });

    // Close the current tab
    hotkeys.add('ctrl+x k', function() {
	chrome.extension.sendRequest({action: "close-tab"});
    });

    hotkeys.add('f', function (evt){
	conkerBar.show(followMode);
    });

    // Follow a link on the page
    var followMode = {
	title: "Enter Link ID",
	enter: function(){
	    jQuery("a").each(function(i, elem){
		jQuery(this).append(jQuery("
", {
		    "class": css.number, "text": i}))
		    .addClass(css.highlight);
	    });
	},
	update: function(e, bar) {
	    // Get the selected link or return
	    var v = bar.val();
	    if (!v) return;
	    link = jQuery("a:eq(" + v + ")");
	    // If the return was pressed,
	    if (e.keyCode == 13) {
		if (link && link.attr("href")) {
		    // If shift+return, open new tab
		    if (e.shiftKey) {
			chrome.extension.sendRequest({
			    action: "new-tab",
			    url: link.attr("href")
			});
		    } else {
			window.location.href = link.attr("href");
		    }
		}
	    } else {
		jQuery("a." + css.selected).removeClass(css.selected);
		if (link.hasClass(css.selected))
		    return;
		link.addClass(css.selected);
	    }
	},
	leave: function(){
	    jQuery("a").removeClass(css.highlight)
		.removeClass(css.selected);
	    jQuery(selectors.number).remove();
	}
    }
}({}); //This object will later be a user stored settings file<|endoftext|>


<commit_before>/**
 * Created by Ryan on 05 Mar 2015.
 */

//Define mpa layer variables
var map,BaseMap;
var BoC, NazBeth, BethEgypt, Temple, Nazareth, Bapt, Wedding, SoM, WoW, Geth, Calvary, Rez;

//Define the default map projection
var projection = ol.proj.get('EPSG:3857');

/**********************************************************/
/*             Begin location selection function          */
/**********************************************************/
function LocationSelector(location)
{
    switch (location)
    {
        case "BoC":

    }
}
/**********************************************************/
/*             End location selection function            */
/**********************************************************/

/**********************************************************/
/*             Begin layer definition function            */
/**********************************************************/
function CreateLayers() {
    BaseMap = new ol.layer.Tile({
        source: new ol.source.MapQuest({layer: 'osm'})
    });

    BoC = new ol.layer.Vector({
        source: new ol.source.KML({
            projection: projection,
            url: 'data/kml/birthofchrist.kml'
        })
    })

}
/**********************************************************/
/*             End layer definition function              */
/**********************************************************/

/**********************************************************/
/*                Begin map creation section              */
/**********************************************************/

function CreateMap() {

    //Build the layer objects for each KML file
    CreateLayers();

    //Declare the map object itself.
    map = new ol.Map({
        target: 'map',

        //Set up the layers that will be loaded in the map
        layers: [BaseMap, BoC],

        //Establish the view area. Note the reprojection from lat long (EPSG:4326) to Web Mercator (EPSG:3857)
        view: new ol.View({
            center: ol.proj.transform([35.2167, 31.7833], 'EPSG:4326', projection),
            zoom: 8
        })
    });

    //Add some useful map controls
    map.addControl(new ol.control.ScaleLine());

    //Add Popup system
    var element = document.getElementById('popup');

    var popup = new ol.Overlay({
        element: element,
        positioning: 'bottom-center',
        stopEvent: false
    });
    map.addOverlay(popup);

}

/**********************************************************/
/*                End map creation section                */
/**********************************************************/

/**********************************************************/
/*              Begin popup bubble scripting              */
/**********************************************************/

function PopUp_Bubble() {

    // display popup on click

    //try to destroy it before doing anything else
    $(element).popover('destroy');

    //Try to get a feature at the point of interest
    var feature = map.forEachFeatureAtPixel(evt.pixel,
        function (feature, layer) {
            return feature;
        });

    //if we found a feature then create and show the popup.
    if (feature) {
        var geometry = feature.getGeometry();
        var coord = geometry.getCoordinates();
        popup.setPosition(coord);
        var displaycontent = ('' + feature.get('name') + '' + '
'
        + '
' + feature.get('description')
        );
        $(element).popover({
            'placement': 'top',
            'html': true,
            'content': displaycontent
        });

        $(element).popover('show');

    } else {
        $(element).popover('destroy');
    }

}

/**********************************************************/
/*               End popup bubble scripting               */
/**********************************************************/<commit_msg>Modified JS<commit_after>/**
 * Created by Ryan on 05 Mar 2015.
 */

//Define mpa layer variables
var map,BaseMap;
var BoC, NazBeth, BethEgypt, Temple, Nazareth, Bapt, Wedding, SoM, WoW, Geth, Calvary, Rez;

//Define the default map projection
var projection = ol.proj.get('EPSG:3857');

/**********************************************************/
/*             Begin location selection function          */
/**********************************************************/
function LocationSelector(location)
{
    switch (location)
    {
        case "BoC":

    }
}
/**********************************************************/
/*             End location selection function            */
/**********************************************************/

/**********************************************************/
/*             Begin layer definition function            */
/**********************************************************/
function CreateLayers() {
    BaseMap = new ol.layer.Tile({
        source: new ol.source.MapQuest({layer: 'osm'})
    });

    BoC = new ol.layer.Vector({
        source: new ol.source.KML({
            projection: projection,
            url: 'data/kml/birthofchrist.kml'
        })
    })

}
/**********************************************************/
/*             End layer definition function              */
/**********************************************************/

/**********************************************************/
/*                Begin map creation section              */
/**********************************************************/

function CreateMap() {

    //Build the layer objects for each KML file
    CreateLayers();

    //Declare the map object itself.
    map = new ol.Map({
        target: 'map',

        //Set up the layers that will be loaded in the map
        layers: [BaseMap, BoC],

        //Establish the view area. Note the reprojection from lat long (EPSG:4326) to Web Mercator (EPSG:3857)
        view: new ol.View({
            center: ol.proj.transform([35.2167, 31.7833], 'EPSG:4326', projection),
            zoom: 8
        })
    });

    //Add some useful map controls
    map.addControl(new ol.control.ScaleLine());

    //Add Popup system
    var element = document.getElementById('popup');

    var popup = new ol.Overlay({
        element: element,
        positioning: 'bottom-center',
        stopEvent: false
    });
    map.addOverlay(popup);

    return map

}

/**********************************************************/
/*                End map creation section                */
/**********************************************************/

/**********************************************************/
/*              Begin popup bubble scripting              */
/**********************************************************/

function PopUp_Bubble() {

    // display popup on click

    //try to destroy it before doing anything else
    $(element).popover('destroy');

    //Try to get a feature at the point of interest
    var feature = map.forEachFeatureAtPixel(evt.pixel,
        function (feature, layer) {
            return feature;
        });

    //if we found a feature then create and show the popup.
    if (feature) {
        var geometry = feature.getGeometry();
        var coord = geometry.getCoordinates();
        popup.setPosition(coord);
        var displaycontent = ('' + feature.get('name') + '' + '
'
        + '
' + feature.get('description')
        );
        $(element).popover({
            'placement': 'top',
            'html': true,
            'content': displaycontent
        });

        $(element).popover('show');

    } else {
        $(element).popover('destroy');
    }

}

/**********************************************************/
/*               End popup bubble scripting               */
/**********************************************************/<|endoftext|>


<commit_before>const moment = require('moment');
const util = require('../../core/util.js');
const _ = require('lodash');
const log = require('../../core/log');

var config = util.getConfig();
var dirs = util.dirs();

var Fetcher = require(dirs.exchanges + 'binance');

util.makeEventEmitter(Fetcher);

var end = false;
var done = false;
var from = false;

var fetcher = new Fetcher(config.watch);

var fetch = () => {
  fetcher.import = true;
  fetcher.getTrades(from, handleFetch);
};

var handleFetch = (unk, trades) => {
  if (trades.length > 0) {
    var last = moment.unix(_.last(trades).date);

    if (last < from) {
      log.debug(
        'Skipping data, they are before from date (probably a programming error)',
        last.format()
      );
      return fetch();
    }
  }

  var next = from.add(1, 'd');
  if (next >= end) {
    fetcher.emit('done');

    var endUnix = end.unix();
    trades = _.filter(trades, t => t.date <= endUnix);
  }

  from = next.clone();
  fetcher.emit('trades', trades);
};

module.exports = function(daterange) {
  from = daterange.from.clone();
  end = daterange.to.clone();

  return {
    bus: fetcher,
    fetch: fetch,
  };
};
<commit_msg>Fix a few unlikely issues with empty trade iterations (Binance)<commit_after>const moment = require('moment');
const util = require('../../core/util.js');
const _ = require('lodash');
const log = require('../../core/log');

var config = util.getConfig();
var dirs = util.dirs();

var Fetcher = require(dirs.exchanges + 'binance');

util.makeEventEmitter(Fetcher);

var end = false;
var done = false;
var from = false;

var fetcher = new Fetcher(config.watch);

var fetch = () => {
  fetcher.import = true;
  fetcher.getTrades(from, handleFetch);
};

var handleFetch = (unk, trades) => {
  if (trades.length > 0) {
    var last = moment.unix(_.last(trades).date).utc();
    var next = last.clone();
  } else {
    var next = from.clone().add(1, 'd');
    log.debug('Import step returned no results, moving to the next 24h period');
  }

  if (from.add(1, 'd') >= end) {
    fetcher.emit('done');

    var endUnix = end.unix();
    trades = _.filter(trades, t => t.date <= endUnix);
  }

  from = next.clone();
  fetcher.emit('trades', trades);
};

module.exports = function(daterange) {
  from = daterange.from.clone().utc();
  end = daterange.to.clone().utc();

  return {
    bus: fetcher,
    fetch: fetch,
  };
};
<|endoftext|>


<commit_before>"use strict";

Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");

//derived from https://dxr.mozilla.org/comm-central/source/mozilla/accessible/tests/mochitest/autocomplete.js
var abAutoComplete = {

    tbSyncAutoCompleteSearch : null,

    /**
     * Register 'tbSyncAutoCompleteSearch' AutoCompleteSearch.
     */
    init : function () {
      abAutoComplete.tbSyncAutoCompleteSearch = new abAutoComplete.Search("tbSyncAutoCompleteSearch");
      abAutoComplete.register(abAutoComplete.tbSyncAutoCompleteSearch, "AutoCompleteSearch");
    },

    /**
     * Unregister 'tbSyncAutoCompleteSearch' AutoCompleteSearch.
     */
    shutdown : function () {
      abAutoComplete.unregister(abAutoComplete.tbSyncAutoCompleteSearch);
      abAutoComplete.tbSyncAutoCompleteSearch.cid = null;
      abAutoComplete.tbSyncAutoCompleteSearch = null;
    },

    /**
     * Register the given AutoCompleteSearch.
     *
     * @param aSearch       [in] AutoCompleteSearch object
     * @param aDescription  [in] description of the search object
     */
    register : function (aSearch, aDescription) {
      var name = "@mozilla.org/autocomplete/search;1?name=" + aSearch.name;

      var uuidGenerator = Components.classes["@mozilla.org/uuid-generator;1"].getService(Components.interfaces.nsIUUIDGenerator);
      var cid = uuidGenerator.generateUUID();

      var componentManager = Components.manager.QueryInterface(Components.interfaces.nsIComponentRegistrar);
      componentManager.registerFactory(cid, aDescription, name, aSearch);

      // Keep the id on the object so we can unregister later.
      aSearch.cid = cid;
    },

    /**
     * Unregister the given AutoCompleteSearch.
     */
    unregister : function (aSearch) {
      var componentManager = Components.manager.QueryInterface(Components.interfaces.nsIComponentRegistrar);
      componentManager.unregisterFactory(aSearch.cid, aSearch);
    },

    /**
     * nsIAutoCompleteSearch implementation.
     *
     * @param aName       [in] the name of autocomplete search
     */
    Search : function (aName) {
      this.name = aName;
    },

    /**
     * nsIAutoCompleteResult implementation.
     */
    Result : function (aValues, aComments) {
      this.values = aValues;
      this.comments = aComments;

      if (this.values.length > 0)
        this.searchResult = Components.interfaces.nsIAutoCompleteResult.RESULT_SUCCESS;
      else
        this.searchResult = Components.interfaces.nsIAutoCompleteResult.NOMATCH;
    },

}

abAutoComplete.Search.prototype = {
      constructor: abAutoComplete.Search,

      // nsIAutoCompleteSearch implementation
      startSearch : Task.async (function* (aSearchString, aSearchParam, aPreviousResult, aListener) {
        var result = yield this.getAutoCompleteResultFor(aSearchString);
        aListener.onSearchResult(this, result);
      }),

      stopSearch() {},

      // nsISupports implementation
      QueryInterface: XPCOMUtils.generateQI(["nsIFactory", "nsIAutoCompleteSearch"]), //ChromeUtils

      // nsIFactory implementation
      createInstance(outer, iid) {
        return this.QueryInterface(iid);
      },

      // Search name. Used by AutoCompleteController.
      name: null,

      /**
       * Return AutoCompleteResult for the given search string.
       */
      getAutoCompleteResultFor : Task.async (function* (aSearchString) {
        //check each account and init server request
        let accounts = tbSync.db.getAccounts();
        let requests = [];
        let values = [];
        let comments = [];

        if (aSearchString.length > 3) {
            for (let i=0; i<accounts.IDs.length; i++) {
                let account = accounts.IDs[i];
                let provider = accounts.data[account].provider;
                let status = accounts.data[account].status;

                if (status == "disabled") continue;

                //start all requests parallel (do not wait till done here, no yield, push the promise)
                if (tbSync[provider].abServerSearch) {
                    requests.push(tbSync[provider].abServerSearch (account, aSearchString));
                }
            }

            //wait for all requests to finish (only have to wait for the slowest, all others are done)
            for (let r=0; r < requests.length; r++) {
                let results = yield requests[r];
                for (let count=0; count < results.length; count++) {
                    if (results[count].autocomplete) {
                        values.push(results[count].autocomplete.value);
                        comments.push(results[count].autocomplete.account);
                    }
                }
            }
        }

        return new abAutoComplete.Result(values, comments);
      })
}

abAutoComplete.Result.prototype = {
      constructor: abAutoComplete.Result,

      searchString: "",
      searchResult: null,

      defaultIndex: 0,

      get matchCount() {
        return this.values.length;
      },

      getValueAt(aIndex) {
        return this.values[aIndex];
      },

    /**
     * This returns the string that is displayed in the dropdown
     */
      getLabelAt(aIndex) {
        return this.getValueAt(aIndex) + " (" + this.getCommentAt(aIndex) + ")";
      },

    /**
     * Get the comment of the result at the given index
     */
      getCommentAt(aIndex) {
        return this.comments[aIndex];
      },

    /**
     * Get the style hint for the result at the given index
     */
      getStyleAt(aIndex) {
        return null;
      },

    /**
     * Get the image of the result at the given index
     */
      getImageAt(aIndex) {
        return "chrome://tbsync/skin/contacts16.png";
      },

    /**
     * Get the final value that should be completed when the user confirms
     * the match at the given index.
     */
      getFinalCompleteValueAt(aIndex) {
        return this.getValueAt(aIndex);
      },

      removeValueAt(aRowIndex, aRemoveFromDb) {},

      // nsISupports implementation
      QueryInterface: XPCOMUtils.generateQI(["nsIAutoCompleteResult"]), //ChromeUtils

      // Data
      values: null,
      comments: null
}
<commit_msg>add space between icon and autocomplete result<commit_after>"use strict";

Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");

//derived from https://dxr.mozilla.org/comm-central/source/mozilla/accessible/tests/mochitest/autocomplete.js
var abAutoComplete = {

    tbSyncAutoCompleteSearch : null,

    /**
     * Register 'tbSyncAutoCompleteSearch' AutoCompleteSearch.
     */
    init : function () {
      abAutoComplete.tbSyncAutoCompleteSearch = new abAutoComplete.Search("tbSyncAutoCompleteSearch");
      abAutoComplete.register(abAutoComplete.tbSyncAutoCompleteSearch, "AutoCompleteSearch");
    },

    /**
     * Unregister 'tbSyncAutoCompleteSearch' AutoCompleteSearch.
     */
    shutdown : function () {
      abAutoComplete.unregister(abAutoComplete.tbSyncAutoCompleteSearch);
      abAutoComplete.tbSyncAutoCompleteSearch.cid = null;
      abAutoComplete.tbSyncAutoCompleteSearch = null;
    },

    /**
     * Register the given AutoCompleteSearch.
     *
     * @param aSearch       [in] AutoCompleteSearch object
     * @param aDescription  [in] description of the search object
     */
    register : function (aSearch, aDescription) {
      var name = "@mozilla.org/autocomplete/search;1?name=" + aSearch.name;

      var uuidGenerator = Components.classes["@mozilla.org/uuid-generator;1"].getService(Components.interfaces.nsIUUIDGenerator);
      var cid = uuidGenerator.generateUUID();

      var componentManager = Components.manager.QueryInterface(Components.interfaces.nsIComponentRegistrar);
      componentManager.registerFactory(cid, aDescription, name, aSearch);

      // Keep the id on the object so we can unregister later.
      aSearch.cid = cid;
    },

    /**
     * Unregister the given AutoCompleteSearch.
     */
    unregister : function (aSearch) {
      var componentManager = Components.manager.QueryInterface(Components.interfaces.nsIComponentRegistrar);
      componentManager.unregisterFactory(aSearch.cid, aSearch);
    },

    /**
     * nsIAutoCompleteSearch implementation.
     *
     * @param aName       [in] the name of autocomplete search
     */
    Search : function (aName) {
      this.name = aName;
    },

    /**
     * nsIAutoCompleteResult implementation.
     */
    Result : function (aValues, aComments) {
      this.values = aValues;
      this.comments = aComments;

      if (this.values.length > 0)
        this.searchResult = Components.interfaces.nsIAutoCompleteResult.RESULT_SUCCESS;
      else
        this.searchResult = Components.interfaces.nsIAutoCompleteResult.NOMATCH;
    },

}

abAutoComplete.Search.prototype = {
      constructor: abAutoComplete.Search,

      // nsIAutoCompleteSearch implementation
      startSearch : Task.async (function* (aSearchString, aSearchParam, aPreviousResult, aListener) {
        var result = yield this.getAutoCompleteResultFor(aSearchString);
        aListener.onSearchResult(this, result);
      }),

      stopSearch() {},

      // nsISupports implementation
      QueryInterface: XPCOMUtils.generateQI(["nsIFactory", "nsIAutoCompleteSearch"]), //ChromeUtils

      // nsIFactory implementation
      createInstance(outer, iid) {
        return this.QueryInterface(iid);
      },

      // Search name. Used by AutoCompleteController.
      name: null,

      /**
       * Return AutoCompleteResult for the given search string.
       */
      getAutoCompleteResultFor : Task.async (function* (aSearchString) {
        //check each account and init server request
        let accounts = tbSync.db.getAccounts();
        let requests = [];
        let values = [];
        let comments = [];

        if (aSearchString.length > 3) {
            for (let i=0; i<accounts.IDs.length; i++) {
                let account = accounts.IDs[i];
                let provider = accounts.data[account].provider;
                let status = accounts.data[account].status;

                if (status == "disabled") continue;

                //start all requests parallel (do not wait till done here, no yield, push the promise)
                if (tbSync[provider].abServerSearch) {
                    requests.push(tbSync[provider].abServerSearch (account, aSearchString));
                }
            }

            //wait for all requests to finish (only have to wait for the slowest, all others are done)
            for (let r=0; r < requests.length; r++) {
                let results = yield requests[r];
                for (let count=0; count < results.length; count++) {
                    if (results[count].autocomplete) {
                        values.push(results[count].autocomplete.value);
                        comments.push(results[count].autocomplete.account);
                    }
                }
            }
        }

        return new abAutoComplete.Result(values, comments);
      })
}

abAutoComplete.Result.prototype = {
      constructor: abAutoComplete.Result,

      searchString: "",
      searchResult: null,

      defaultIndex: 0,

      get matchCount() {
        return this.values.length;
      },

      getValueAt(aIndex) {
        return this.values[aIndex];
      },

    /**
     * This returns the string that is displayed in the dropdown
     */
      getLabelAt(aIndex) {
        return "  " + this.getValueAt(aIndex) + " (" + this.getCommentAt(aIndex) + ")";
      },

    /**
     * Get the comment of the result at the given index
     */
      getCommentAt(aIndex) {
        return this.comments[aIndex];
      },

    /**
     * Get the style hint for the result at the given index
     */
      getStyleAt(aIndex) {
        return null;
      },

    /**
     * Get the image of the result at the given index
     */
      getImageAt(aIndex) {
        return "chrome://tbsync/skin/contacts16.png";
      },

    /**
     * Get the final value that should be completed when the user confirms
     * the match at the given index.
     */
      getFinalCompleteValueAt(aIndex) {
        return this.getValueAt(aIndex);
      },

      removeValueAt(aRowIndex, aRemoveFromDb) {},

      // nsISupports implementation
      QueryInterface: XPCOMUtils.generateQI(["nsIAutoCompleteResult"]), //ChromeUtils

      // Data
      values: null,
      comments: null
}
<|endoftext|>


<commit_before>var SoundFont = require('soundfont-player');
var ctx = new AudioContext();

$( document ).keypress(function (e) {
  if(e.shiftKey){
    var key = e.which;
    switch( key ) {
      case 13: //Enter key
      e.preventDefault();
      play();
      break;
      default:
      break;
    }
  }
});

var play = function () {
  console.log("play!");

  var markup = $('.track').text();
  var trackCommands = parseMarkup(markup);

  playTrack(trackCommands);
};

var playTrack = function ( commands ) {
  var time = 0,
      soundfont = new SoundFont(ctx);

  for ( var x = 0; x < commands.length; x++ ) {

    var inst = soundfont.instrument('acoustic_grand_piano');

    (function(x) {
      var key        = commands[x].key,
          duration   = commands[x].duration;

      inst.onready(function() {
        inst.play(key, x + 1, 1);
      });
    })(x);
  }
};

var parseMarkup = function( markup ) {
  var output = [],
      notes = markup.toUpperCase().split(" ");

  for (var x in notes) {
    var key = noteToKey(notes[x]);
    if (key) {
      key["key"] = keyToNote(key["key"])
      output.push(key);
      console.log(key);
    }
  }
  return output; // i.e. { key: "Cb4", duration: 1 }
}

var noteToKey = function( token ) {
  var key = -1,
      duration = 1,
      instrument = 'acoustic_grand_piano';

  if (token.length > 3) {
    console.log(token);
    switch (token) {
      case "PIANO":
        instrument = 'acoustic_grand_piano';
        break;
      case "DRUMS":
        instrument = 'taiko_drum';
        break;
      case "GUITAR":
        instrument = 'acoustic_guitar_steel';
        break;
      case "SAXOPHONE":
        instrument = 'alto_sax';
        break;
      case "TRUMPET":
        instrument = 'trumpet';
        break;
      default:
        return;
    }
  }

  for (var x in token) {
    var cmd = token.charAt(x);
    switch( cmd ) {
      case 'A':
        key = 69;
        break;
      case 'B':
        key = 71;
        break;
      case 'C':
        key = 60;
        break;
      case 'D':
        key = 62;
        break;
      case 'E':
        key = 64;
        break;
      case 'F':
        key = 65;
        break;
      case 'G':
        key = 67;
        break;
      case '+':
        if (key === -1) return;
        key++;
        break;
      case '-':
        if (key === -1) return;
        key--;
        break;
      case '1':
      case '2':
      case '4':
      case '8':
        duration = parseInt(cmd);
        break;
      default:
        return;
    }
  }
  console.log(key + ": " + duration);
  return {
      key: key,
      duration: duration,
      instrument: instrument
    };
}

var keyToNote = function ( key ) {
  var octave = 4;
  var A0 = 0x15; // first note
  var C8 = 0x6C; // last note
  var number2key = ['C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'B'];
  return number2key[ key % 12] + octave;
}
<commit_msg>its lit yo :fire:<commit_after>var ctx, soundfont,
    Soundfont = require('soundfont-player');

$( document ).keypress(function (e) {
  if(e.shiftKey){
    var key = e.which;
    switch( key ) {
      case 13: //Enter key
      e.preventDefault();
      ctx = new AudioContext();
      soundfont = new Soundfont(ctx);
      play();
      break;
      default:
      break;
    }
  }
});

var play = function () {
  console.log("play!");

  var markup = $('.track').text();
  var trackCommands = parseMarkup(markup);

  playTrack(trackCommands);
};

var playTrack = function ( commands ) {
  var time = 0;

  for ( var x = 0; x < commands.length; x++ ) {

    (function(x) {
      var key        = commands[x].key,
          duration   = commands[x].duration,
          instrument = commands[x].instrument;

      var inst = soundfont.instrument(instrument);
      inst.onready(function() {
        inst.play(key, x + 1, 1);
      });
    })(x);
  }
};

var parseMarkup = function( markup ) {
  var output = [],
      notes = markup.toUpperCase().split(" ");

  for (var x in notes) {
    var key = noteToKey(notes[x]);
    if (key) {
      key["key"] = keyToNote(key["key"])
      output.push(key);
      console.log(key);
    }
  }
  return output; // i.e. { key: "Cb4", duration: 1 }
}

var instrumentSetting = 'acoustic_grand_piano';

var noteToKey = function( token ) {
  var key = -1,
      duration = 1;

  if (token.length > 3) {
    console.log(token);
    switch (token) {
      case "PIANO":
        instrumentSetting = 'acoustic_grand_piano';
        break;
      case "DRUMS":
        console.log("hererererererer");
        instrumentSetting = 'taiko_drum';
        break;
      case "GUITAR":
        instrumentSetting = 'acoustic_guitar_steel';
        break;
      case "SAXOPHONE":
        instrumentSetting = 'alto_sax';
        break;
      case "TRUMPET":
        instrumentSetting = 'trumpet';
        break;
      default:
        return;
    }
  }

  for (var x in token) {
    var cmd = token.charAt(x);
    switch( cmd ) {
      case 'A':
        key = 69;
        break;
      case 'B':
        key = 71;
        break;
      case 'C':
        key = 60;
        break;
      case 'D':
        key = 62;
        break;
      case 'E':
        key = 64;
        break;
      case 'F':
        key = 65;
        break;
      case 'G':
        key = 67;
        break;
      case '+':
        if (key === -1) return;
        key++;
        break;
      case '-':
        if (key === -1) return;
        key--;
        break;
      case '1':
      case '2':
      case '4':
      case '8':
        duration = parseInt(cmd);
        break;
      default:
        return;
    }
  }
  console.log(key + ": " + duration + ": " + instrumentSetting);
  return {
      key: key,
      duration: duration,
      instrument: instrumentSetting
    };
}

var keyToNote = function ( key ) {
  var octave = 4;
  var A0 = 0x15; // first note
  var C8 = 0x6C; // last note
  var number2key = ['C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'B'];
  return number2key[ key % 12] + octave;
}
<|endoftext|>


<commit_before>/*
==================================================================================================
  Jasy - JavaScript Tooling Framework
  Copyright 2010-2011 Sebastian Werner
==================================================================================================
*/

// Include ES5 support if not natively supported
if(!jasy.Env.isSet("es5"))
{
	// These classes don't really exist, so we need to protect the access.
	try{
		es5.Array;
		es5.Date;
		es5.String;
		es5.JSON;
	} catch(ex) {};
}

(function(global, undef) {
	var genericToString = function() {
		return "[class " + this.className + "]";
	};

	if (jasy.Env.isSet("debug"))
	{
		var checkMixinMemberConflicts = function(include, members, name)
		{
			// Simplifies routine
			if (!members) {
				members = {};
			}

			var allIncludeMembers = {};
			for (var i=0, l=include.length; i<l; i++)
			{
				var includedClass = include[i];
				var includedMembers = Object.keys(includedClass.prototype);

				for(var j=0, jl=includedMembers.length; j<jl; j++)
				{
					var key = includedMembers[j];

					if (members.hasOwnProperty(key))
					{
						// Private member conflict with including class (must fail, always)
						if (key.substring(0,2) == "__") {
							throw new Error("Included class " + includedClass.className + " overwrites private member of class " + name);
						}

						// members are allowed to override protected and public members of any included class
					}

					if (allIncludeMembers.hasOwnProperty(key))
					{
						// Private members conflict between included classes (must fail, always)
						if (key.substring(0,2) == "__") {
							throw new Error("Included class " + includedClass.className + " overwrites private member of other included class " + allIncludeMembers[key].className + " in class " + name);
						}

						// If both included classes define this key as a function check whether
						// the members section has a function as well (which might call both of them).
						if (key in members && members[key] instanceof Function && includedClass.prototype[key] instanceof Function && allIncludeMembers[key].prototype[key] instanceof Function) {
							// pass
						} else {
							throw new Error("Included class " + includedClass.className + " overwrites member " + key + " of other included class " + allIncludeMembers[key].className + " in class " + name);
						}
					}

					allIncludeMembers[key] = includedClass;
				}
			}
		};

		// Events between included classes must not collide
		// Including class can override any event
		var checkMixinEventConflicts = function(include, events, name)
		{
			var allIncludeEvents = {};
			for (var i=0, l=include.length; i<l; i++)
			{
				var includedClass = include[i];
				var includedEvents = includedClass.__events;

				for (var eventName in includedEvents) {
					if (eventName in allIncludeEvents) {
						throw new Error("Included class " + includedClass.className + " overwrites event of other included class " + allIncludeEvents[key].className + " in class " + name);
					}

					allIncludeEvents[eventName] = includedClass;
				}
			}
		};

		// Properties between included classes must not collide
		// Including class can override any property
		var checkMixinPropertyConflicts = function(include, properties, name)
		{
			var allIncludeProperties = {};
			for (var i=0, l=include.length; i<l; i++)
			{
				var includedClass = include[i];
				var includedProperties = includedClass.__properties;

				for (var propertyName in includedProperties) {
					if (propertyName in allIncludeProperties) {
						throw new Error("Included class " + includedClass.className + " overwrites event of other included class " + allIncludeEvents[key].className + " in class " + name);
					}

					allIncludeProperties[propertyName] = includedClass;
				}
			}
		};
	}

	var propertyJoinableNames = {};

	Module.declareName("Class", function(name, config)
	{
		if (jasy.Env.isSet("debug"))
		{
			jasy.Test.assertModuleName(name, "Invalid class name " + name + "!");
			jasy.Test.assertMap(config, "Invalid class configuration in " + name);
			jasy.Test.assertHasAllowedKeysOnly(config, ["construct","events","members","properties","include","implement"],
				"Invalid configuration in class " + name + "! Unallowed key(s) found!");

			if ("construct" in config) {
				jasy.Test.assertFunction(config.construct, "Invalid constructor in class " + name + "!");
			}

			if ("events" in config) {
				jasy.Test.assertMap(config.events, "Invalid event data in class " + name + "!");
			}

			if ("members" in config) {
				jasy.Test.assertMap(config.members, "Invalid member section in class " + name);
			}

			if ("properties" in config) {
				jasy.Test.assertMap(config.properties, "Invalid properties section in class " + name);
			}

			if ("include" in config) {
				jasy.Test.assertArray(config.include, "Invalid include list in class " + name);
			}

			if ("implement" in config) {
				jasy.Test.assertArray(config.implement, "Invalid implement list in class " + name);
			}
		}

		// ------------------------------------
		//   CONSTRUCTOR
		// ------------------------------------

		var construct = config.construct || function construct(){};

		// Store name / type
		construct.className = name;
		construct.displayName = name;
		construct.__isClass = true;

		// Add toString() / valueOf()
		construct.toString = genericToString;
		construct.valueOf = genericToString;

		// Attach events and properties data (use cryptic private fields for class storage)
		var events = construct.__events = config.events || {};
		var properties = construct.__properties = config.properties || {};

		// Prototype (stuff attached to all instances)
		var proto = construct.prototype;

		// ------------------------------------
		//   MIXINS
		// ------------------------------------

		// Insert other classes
		var include = config.include;
		if (include)
		{
			if (jasy.Env.isSet("debug"))
			{
				for (var i=0, l=include.length; i<l; i++) {
					jasy.Test.assertClass(include[i], "Class " + name + " includes invalid class " + include[i] + " at position: " + i + "!");
				}

				checkMixinMemberConflicts(include, config.members, name);
				checkMixinEventConflicts(include, config.events, name);
				checkMixinPropertyConflicts(include, config.properties, name);
			}

			for (var i=0, l=include.length; i<l; i++)
			{
				var includedClass = include[i];

				// Just remap members. Validation already happended in debug mode.
				// Function name keeps to be the same after inclusion. Still refering to original class.
				var includeMembers = includedClass.prototype;
				for (var key in includeMembers) {
					proto[key] = includeMembers[key];
				}

				// Just copy over the property data. Methods are already in member section.
				var includeProperties = includedClass.__properties;
				for (var key in includeProperties) {
					properties[key] = includeProperties[key];
				}

				// Events is just data to copy over.
				var includeEvents = includedClass.__events;
				for (var key in includeEvents) {
					events[key] = includeEvents[key];
				}
			}
		}

		// ------------------------------------
		//   LOCALS
		// ------------------------------------

		// Add properties
		for (var propertyName in properties)
		{
			var propertyConfig = properties[propertyName];

			// Inject property name into config
			propertyConfig.name = propertyName;

			// Create members via specific property implementation
			if (propertyConfig.group) {
				var propertyMembers = jasy.property.Group.create(propertyConfig);
			} else if (propertyConfig.themeable || propertyConfig.inheritable) {
				var propertyMembers = jasy.property.Multi.create(propertyConfig);
			} else {
				var propertyMembers = jasy.property.Simple.create(propertyConfig);
			}

			// Prepare function names
			var propertyMethodPostfix = propertyJoinableNames[propertyName];
			if (propertyMethodPostfix === undef)
			{
				propertyMethodPostfix = propertyName.charAt(0).toUpperCase() + propertyName.slice(1);
				propertyJoinableNames[propertyName] = propertyMethodPostfix;
			}

			// Attach property methods
			for (var propertyMemberKey in propertyMembers)
			{
				var propertyMemberName = propertyMemberKey + propertyMethodPostfix;
				var propertyMember = propertyMembers[propertyMemberKey];

				proto[propertyMemberName] = propertyMember;
				propertyMember.displayName = name + "." + propertyMemberName;
			}
		}

		// Attach members
		var members = config.members;
		if (members)
		{
			for (var key in members)
			{
				var entry = proto[key] = members[key];
				if (entry instanceof Function) {
					entry.displayName = name + "." + key;
				}
			}
		}

		// ------------------------------------
		//   INTERFACES
		// ------------------------------------

		if (jasy.Env.isSet("debug"))
		{
			var implement = config.implement;
			if (implement)
			{
				var iface;
				for (var i=0, l=implement.length; i<l; i++)
				{
					iface = implement[i];
					if (!iface) {
						throw new Error("Class " + name + " implements invalid interface " + iface + " at position: " + i);
					}

					try {
						Interface.assert(construct, iface);
					} catch(ex) {
						throw new Error("Class " + name + " fails to implement given interface: " + iface + ": " + ex);
					}
				}
			}

			var propertyFeatures = Class.getPropertyFeatures(construct);
			if (propertyFeatures)
			{
				if (propertyFeatures.fire) {
					Interface.assert(construct, jasy.property.IEvent);
				}

				if (propertyFeatures.themeable) {
					Interface.assert(construct, jasy.property.IThemeable);
				}

				if (propertyFeatures.inheritable) {
					Interface.assert(construct, jasy.property.IInheritable);
				}
			}
		}

		// ------------------------------------
		//   FINISH
		// ------------------------------------

		// Attach to namespace
		Module.declareName(name, construct, true);
	});

	/**
	 * Resolves a given Class name
	 *
	 * @param className {String} Name to resolve
	 * @return {Object} Returns the Class stored under the given name
	 */
	Class.getByName = function(className)
	{
		if (jasy.Env.isSet("debug")) {
			jasy.Test.assertString(className);
		}

		var obj = Module.resolveName(className);
		return isClass(obj) ? obj : null;
	};

	/**
	 * Returns the events supported by the given class
	 *
	 * @param cls {Class} Class to query
	 * @return {Map} Map of all events and their type
	 */
	Class.getEvents = function(cls)
	{
		if (jasy.Env.isSet("debug")) {
			jasy.Test.assertClass(cls);
		}

		return cls.__events;
	};

	/**
	 * Returns the properties supported by the given class
	 *
	 * @param cls {Class} Class to query
	 * @return {Map} Map of all properties and their configuration
	 */
	Class.getProperties = function(cls)
	{
		if (jasy.Env.isSet("debug")) {
			jasy.Test.assertClass(cls);
		}

		return cls.__properties;
	};

	/**
	 * Returns a list of all property features used in the given class.
	 *
	 * @return {Map} Map of all features (feature is used as a key for fast lookup)
	 */
	Class.getPropertyFeatures = function(cls)
	{
		var all = {};
		var properties = cls.__properties;
		for (var name in properties)
		{
			var config = properties[name];
			for (var key in config) {
				all[key] || (all[key] = true);
			}
		}

		return all;
	};

	/**
	 * Whether the given object is a Class
	 *
	 * @return {Boolean} Whether the given argument is an valid Class.
	 */
	var isClass = Class.isClass = function(cls) {
		return !!(cls && typeof cls == "function" && cls.__isClass);
	};

	/**
	 * Whether the given class includes the given class.
	 *
	 * @param cls {Class} Class to check for including other class.
	 * @param incCls {Class} Class for checking if being included into first one.
	 * @return {Boolean} Whether the second class is included in the first class.
	 */
	var includesClass = Class.includesClass = function(cls, incCls)
	{
		if (jasy.Env.isSet("debug")) {
			jasy.Test.assertClass(cls, "Class to check for including class is itself not a class!");
			jasy.Test.assertClass(incCls, "Class to check for being included is not a class!");
		}

		return cls.__includes.indexOf(incCls) != -1;
	};

	// Add assertions
	jasy.Test.add(isClass, "isClass", "Invalid class!");
	jasy.Test.add(includesClass, "includesClass", "Does not include class %1!");

})(this);
<commit_msg>Added currently unused extendClass for single include things (faster and more lightweight single inheritance)<commit_after>/*
==================================================================================================
	Jasy - JavaScript Tooling Framework
	Copyright 2010-2011 Sebastian Werner
==================================================================================================
*/

// Include ES5 support if not natively supported
if(!jasy.Env.isSet("es5"))
{
	// These classes don't really exist, so we need to protect the access.
	try{
		es5.Array;
		es5.Date;
		es5.String;
		es5.JSON;
	} catch(ex) {};
}

(function(global, undef) {
	var genericToString = function() {
		return "[class " + this.className + "]";
	};

	var extendClass = function(clazz, construct, superClass, name, basename)
	{
		var superproto = superClass.prototype;

		// Use helper function/class to save the unnecessary constructor call while
		// setting up inheritance.
		var helper = new Function;
		helper.prototype = superproto;
		var proto = new helper;

		// Apply prototype to new helper instance
		clazz.prototype = proto;

		// Store names in prototype
		proto.name = proto.classname = name;
		proto.basename = basename;

		// Store base constructor to constructor-
		// Store reference to extend class
		construct.base = clazz.superclass = superClass;

		// Store statics/constructor onto constructor/prototype
	 	// Store correct constructor
		// Store statics onto prototype
		construct.self = clazz.constructor = proto.constructor = clazz;
	};

	if (jasy.Env.isSet("debug"))
	{
		var checkMixinMemberConflicts = function(include, members, name)
		{
			// Simplifies routine
			if (!members) {
				members = {};
			}

			var allIncludeMembers = {};
			for (var i=0, l=include.length; i<l; i++)
			{
				var includedClass = include[i];
				var includedMembers = Object.keys(includedClass.prototype);

				for(var j=0, jl=includedMembers.length; j<jl; j++)
				{
					var key = includedMembers[j];

					if (members.hasOwnProperty(key))
					{
						// Private member conflict with including class (must fail, always)
						if (key.substring(0,2) == "__") {
							throw new Error("Included class " + includedClass.className + " overwrites private member of class " + name);
						}

						// members are allowed to override protected and public members of any included class
					}

					if (allIncludeMembers.hasOwnProperty(key))
					{
						// Private members conflict between included classes (must fail, always)
						if (key.substring(0,2) == "__") {
							throw new Error("Included class " + includedClass.className + " overwrites private member of other included class " + allIncludeMembers[key].className + " in class " + name);
						}

						// If both included classes define this key as a function check whether
						// the members section has a function as well (which might call both of them).
						if (key in members && members[key] instanceof Function && includedClass.prototype[key] instanceof Function && allIncludeMembers[key].prototype[key] instanceof Function) {
							// pass
						} else {
							throw new Error("Included class " + includedClass.className + " overwrites member " + key + " of other included class " + allIncludeMembers[key].className + " in class " + name);
						}
					}

					allIncludeMembers[key] = includedClass;
				}
			}
		};

		// Events between included classes must not collide
		// Including class can override any event
		var checkMixinEventConflicts = function(include, events, name)
		{
			var allIncludeEvents = {};
			for (var i=0, l=include.length; i<l; i++)
			{
				var includedClass = include[i];
				var includedEvents = includedClass.__events;

				for (var eventName in includedEvents) {
					if (eventName in allIncludeEvents) {
						throw new Error("Included class " + includedClass.className + " overwrites event of other included class " + allIncludeEvents[key].className + " in class " + name);
					}

					allIncludeEvents[eventName] = includedClass;
				}
			}
		};

		// Properties between included classes must not collide
		// Including class can override any property
		var checkMixinPropertyConflicts = function(include, properties, name)
		{
			var allIncludeProperties = {};
			for (var i=0, l=include.length; i<l; i++)
			{
				var includedClass = include[i];
				var includedProperties = includedClass.__properties;

				for (var propertyName in includedProperties) {
					if (propertyName in allIncludeProperties) {
						throw new Error("Included class " + includedClass.className + " overwrites event of other included class " + allIncludeEvents[key].className + " in class " + name);
					}

					allIncludeProperties[propertyName] = includedClass;
				}
			}
		};
	}

	var propertyJoinableNames = {};

	Module.declareName("Class", function(name, config)
	{
		if (jasy.Env.isSet("debug"))
		{
			jasy.Test.assertModuleName(name, "Invalid class name " + name + "!");
			jasy.Test.assertMap(config, "Invalid class configuration in " + name);
			jasy.Test.assertHasAllowedKeysOnly(config, ["construct","events","members","properties","include","implement"],
				"Invalid configuration in class " + name + "! Unallowed key(s) found!");

			if ("construct" in config) {
				jasy.Test.assertFunction(config.construct, "Invalid constructor in class " + name + "!");
			}

			if ("events" in config) {
				jasy.Test.assertMap(config.events, "Invalid event data in class " + name + "!");
			}

			if ("members" in config) {
				jasy.Test.assertMap(config.members, "Invalid member section in class " + name);
			}

			if ("properties" in config) {
				jasy.Test.assertMap(config.properties, "Invalid properties section in class " + name);
			}

			if ("include" in config) {
				jasy.Test.assertArray(config.include, "Invalid include list in class " + name);
			}

			if ("implement" in config) {
				jasy.Test.assertArray(config.implement, "Invalid implement list in class " + name);
			}
		}

		// ------------------------------------
		//	 CONSTRUCTOR
		// ------------------------------------

		var construct = config.construct || function construct(){};

		// Store name / type
		construct.className = name;
		construct.displayName = name;
		construct.__isClass = true;

		// Add toString() / valueOf()
		construct.toString = genericToString;
		construct.valueOf = genericToString;

		// Attach events and properties data (use cryptic private fields for class storage)
		var events = construct.__events = config.events || {};
		var properties = construct.__properties = config.properties || {};

		// Prototype (stuff attached to all instances)
		var proto = construct.prototype;

		// ------------------------------------
		//	 MIXINS
		// ------------------------------------

		// Insert other classes
		var include = config.include;
		if (include)
		{
			if (jasy.Env.isSet("debug"))
			{
				for (var i=0, l=include.length; i<l; i++) {
					jasy.Test.assertClass(include[i], "Class " + name + " includes invalid class " + include[i] + " at position: " + i + "!");
				}

				checkMixinMemberConflicts(include, config.members, name);
				checkMixinEventConflicts(include, config.events, name);
				checkMixinPropertyConflicts(include, config.properties, name);
			}

			for (var i=0, l=include.length; i<l; i++)
			{
				var includedClass = include[i];

				// Just remap members. Validation already happended in debug mode.
				// Function name keeps to be the same after inclusion. Still refering to original class.
				var includeMembers = includedClass.prototype;
				for (var key in includeMembers) {
					proto[key] = includeMembers[key];
				}

				// Just copy over the property data. Methods are already in member section.
				var includeProperties = includedClass.__properties;
				for (var key in includeProperties) {
					properties[key] = includeProperties[key];
				}

				// Events is just data to copy over.
				var includeEvents = includedClass.__events;
				for (var key in includeEvents) {
					events[key] = includeEvents[key];
				}
			}
		}

		// ------------------------------------
		//	 LOCALS
		// ------------------------------------

		// Add properties
		for (var propertyName in properties)
		{
			var propertyConfig = properties[propertyName];

			// Inject property name into config
			propertyConfig.name = propertyName;

			// Create members via specific property implementation
			if (propertyConfig.group) {
				var propertyMembers = jasy.property.Group.create(propertyConfig);
			} else if (propertyConfig.themeable || propertyConfig.inheritable) {
				var propertyMembers = jasy.property.Multi.create(propertyConfig);
			} else {
				var propertyMembers = jasy.property.Simple.create(propertyConfig);
			}

			// Prepare function names
			var propertyMethodPostfix = propertyJoinableNames[propertyName];
			if (propertyMethodPostfix === undef)
			{
				propertyMethodPostfix = propertyName.charAt(0).toUpperCase() + propertyName.slice(1);
				propertyJoinableNames[propertyName] = propertyMethodPostfix;
			}

			// Attach property methods
			for (var propertyMemberKey in propertyMembers)
			{
				var propertyMemberName = propertyMemberKey + propertyMethodPostfix;
				var propertyMember = propertyMembers[propertyMemberKey];

				proto[propertyMemberName] = propertyMember;
				propertyMember.displayName = name + "." + propertyMemberName;
			}
		}

		// Attach members
		var members = config.members;
		if (members)
		{
			for (var key in members)
			{
				var entry = proto[key] = members[key];
				if (entry instanceof Function) {
					entry.displayName = name + "." + key;
				}
			}
		}

		// ------------------------------------
		//	 INTERFACES
		// ------------------------------------

		if (jasy.Env.isSet("debug"))
		{
			var implement = config.implement;
			if (implement)
			{
				var iface;
				for (var i=0, l=implement.length; i<l; i++)
				{
					iface = implement[i];
					if (!iface) {
						throw new Error("Class " + name + " implements invalid interface " + iface + " at position: " + i);
					}

					try {
						Interface.assert(construct, iface);
					} catch(ex) {
						throw new Error("Class " + name + " fails to implement given interface: " + iface + ": " + ex);
					}
				}
			}

			var propertyFeatures = Class.getPropertyFeatures(construct);
			if (propertyFeatures)
			{
				if (propertyFeatures.fire) {
					Interface.assert(construct, jasy.property.IEvent);
				}

				if (propertyFeatures.themeable) {
					Interface.assert(construct, jasy.property.IThemeable);
				}

				if (propertyFeatures.inheritable) {
					Interface.assert(construct, jasy.property.IInheritable);
				}
			}
		}

		// ------------------------------------
		//	 FINISH
		// ------------------------------------

		// Attach to namespace
		Module.declareName(name, construct, true);
	});

	/**
	 * Resolves a given Class name
	 *
	 * @param className {String} Name to resolve
	 * @return {Object} Returns the Class stored under the given name
	 */
	Class.getByName = function(className)
	{
		if (jasy.Env.isSet("debug")) {
			jasy.Test.assertString(className);
		}

		var obj = Module.resolveName(className);
		return isClass(obj) ? obj : null;
	};

	/**
	 * Returns the events supported by the given class
	 *
	 * @param cls {Class} Class to query
	 * @return {Map} Map of all events and their type
	 */
	Class.getEvents = function(cls)
	{
		if (jasy.Env.isSet("debug")) {
			jasy.Test.assertClass(cls);
		}

		return cls.__events;
	};

	/**
	 * Returns the properties supported by the given class
	 *
	 * @param cls {Class} Class to query
	 * @return {Map} Map of all properties and their configuration
	 */
	Class.getProperties = function(cls)
	{
		if (jasy.Env.isSet("debug")) {
			jasy.Test.assertClass(cls);
		}

		return cls.__properties;
	};

	/**
	 * Returns a list of all property features used in the given class.
	 *
	 * @return {Map} Map of all features (feature is used as a key for fast lookup)
	 */
	Class.getPropertyFeatures = function(cls)
	{
		var all = {};
		var properties = cls.__properties;
		for (var name in properties)
		{
			var config = properties[name];
			for (var key in config) {
				all[key] || (all[key] = true);
			}
		}

		return all;
	};

	/**
	 * Whether the given object is a Class
	 *
	 * @return {Boolean} Whether the given argument is an valid Class.
	 */
	var isClass = Class.isClass = function(cls) {
		return !!(cls && typeof cls == "function" && cls.__isClass);
	};

	/**
	 * Whether the given class includes the given class.
	 *
	 * @param cls {Class} Class to check for including other class.
	 * @param incCls {Class} Class for checking if being included into first one.
	 * @return {Boolean} Whether the second class is included in the first class.
	 */
	var includesClass = Class.includesClass = function(cls, incCls)
	{
		if (jasy.Env.isSet("debug")) {
			jasy.Test.assertClass(cls, "Class to check for including class is itself not a class!");
			jasy.Test.assertClass(incCls, "Class to check for being included is not a class!");
		}

		return cls.__includes.indexOf(incCls) != -1;
	};

	// Add assertions
	jasy.Test.add(isClass, "isClass", "Invalid class!");
	jasy.Test.add(includesClass, "includesClass", "Does not include class %1!");

})(this);
<|endoftext|>


<commit_before>// Your code here.
<commit_msg>add not valid file<commit_after>// Your code here.
 var iiiii
<|endoftext|>