text:
/* ----------------------------------------------------------------------------------
 * Hint: This is a derived (generated) file. Changes should be done in the underlying
 * source files only (*.control, *.js) or they will be lost after the next generation.
 * ---------------------------------------------------------------------------------- */

// Provides control sap.m.InputBase.
jQuery.sap.declare("sap.m.InputBase");
jQuery.sap.require("sap.m.library");
jQuery.sap.require("sap.ui.core.Control");

/**
 * Constructor for a new InputBase.
 *
 * Accepts an object literal mSettings that defines initial
 * property values, aggregated and associated objects as well as event handlers.
 *
 * If the name of a setting is ambiguous (e.g. a property has the same name as an event),
 * then the framework assumes property, aggregation, association, event in that order.
 * To override this automatic resolution, one of the prefixes "aggregation:", "association:"
 * or "event:" can be added to the name of the setting (such a prefixed name must be
 * enclosed in single or double quotes).
 *
 * The supported settings are:
 *

 *
Properties
 *

 *
{@link #getValue value} : string

 *
{@link #getWidth width} : sap.ui.core.CSSSize

 *
{@link #getEnabled enabled} : boolean (default: true)

 *
{@link #getVisible visible} : boolean (default: true)

 *
{@link #getValueState valueState} : sap.ui.core.ValueState (default: sap.ui.core.ValueState.None)

 *
{@link #getName name} : string

 *
{@link #getPlaceholder placeholder} : string

 *
{@link #getEditable editable} : boolean (default: true)

 *

 *
Aggregations
 *

 *

 *
Associations
 *

 *

 *
Events
 *

 *
{@link sap.m.InputBase#event:change change} : fnListenerFunction or [fnListenerFunction, oListenerObject] or [oData, fnListenerFunction, oListenerObject]

 *

 *

 *
 * @param {string} [sId] id for the new control, generated automatically if no id is given
 * @param {object} [mSettings] initial settings for the new control
 *
 * @class
 * Base control for Input fields.
 * @extends sap.ui.core.Control
 *
 * @author SAP AG
 * @version 1.22.5
 *
 * @constructor
 * @public
 * @since 1.12.0
 * @name sap.m.InputBase
 */
sap.ui.core.Control.extend("sap.m.InputBase", { metadata : {

	// ---- object ----

	// ---- control specific ----
	library : "sap.m",
	properties : {
		"value" : {type : "string", group : "Data", defaultValue : null, bindable : "bindable"},
		"width" : {type : "sap.ui.core.CSSSize", group : "Dimension", defaultValue : null},
		"enabled" : {type : "boolean", group : "Behavior", defaultValue : true},
		"visible" : {type : "boolean", group : "Appearance", defaultValue : true},
		"valueState" : {type : "sap.ui.core.ValueState", group : "Appearance", defaultValue : sap.ui.core.ValueState.None},
		"name" : {type : "string", group : "Misc", defaultValue : null},
		"placeholder" : {type : "string", group : "Misc", defaultValue : null},
		"editable" : {type : "boolean", group : "Behavior", defaultValue : true}
	},
	events : {
		"change" : {}
	}
}});

/**
 * Creates a new subclass of class sap.m.InputBase with name sClassName
 * and enriches it with the information contained in oClassInfo.
 *
 * oClassInfo might contain the same kind of informations as described in {@link sap.ui.core.Element.extend Element.extend}.
 *
 * @param {string} sClassName name of the class to be created
 * @param {object} [oClassInfo] object literal with informations about the class
 * @param {function} [FNMetaImpl] constructor function for the metadata object. If not given, it defaults to sap.ui.core.ElementMetadata.
 * @return {function} the created class / constructor function
 * @public
 * @static
 * @name sap.m.InputBase.extend
 * @function
 */

sap.m.InputBase.M_EVENTS = {'change':'change'};

/**
 * Getter for property value.
 * Defines the value of the input.
 *
 * Default value is empty/undefined
 *
 * @return {string} the value of property value
 * @public
 * @name sap.m.InputBase#getValue
 * @function
 */

/**
 * Setter for property value.
 *
 * Default value is empty/undefined
 *
 * @param {string} sValue  new value for property value
 * @return {sap.m.InputBase} this to allow method chaining
 * @public
 * @name sap.m.InputBase#setValue
 * @function
 */

/**
 * Binder for property value.
 *
 * @param {string} sPath path to a property in the model
 * @param {function} [fnFormatter=null] the formatter function
 * @param {sap.ui.model.BindingMode} [sMode=Default] the binding mode to be used for this property binding (e.g. one way)
 * @return {sap.m.InputBase} this to allow method chaining
 * @public
 * @name sap.m.InputBase#bindValue
 * @function
 */

/**
 * Unbinder for property value.
 *
 * @return {sap.m.InputBase} this to allow method chaining
 * @public
 * @name sap.m.InputBase#unbindValue
 * @function
 */

/**
 * Getter for property width.
 * Defines the width of the input.
 *
 * Default value is empty/undefined
 *
 * @return {sap.ui.core.CSSSize} the value of property width
 * @public
 * @name sap.m.InputBase#getWidth
 * @function
 */

/**
 * Setter for property width.
 *
 * Default value is empty/undefined
 *
 * @param {sap.ui.core.CSSSize} sWidth  new value for property width
 * @return {sap.m.InputBase} this to allow method chaining
 * @public
 * @name sap.m.InputBase#setWidth
 * @function
 */

/**
 * Getter for property enabled.
 * Determines whether the user can change the input value (default is true).
 *
 * Default value is true
 *
 * @return {boolean} the value of property enabled
 * @public
 * @name sap.m.InputBase#getEnabled
 * @function
 */

/**
 * Setter for property enabled.
 *
 * Default value is true
 *
 * @param {boolean} bEnabled  new value for property enabled
 * @return {sap.m.InputBase} this to allow method chaining
 * @public
 * @name sap.m.InputBase#setEnabled
 * @function
 */

/**
 * Getter for property visible.
 * Determines whether the input is visible.
 *
 * Default value is true
 *
 * @return {boolean} the value of property visible
 * @public
 * @name sap.m.InputBase#getVisible
 * @function
 */

/**
 * Setter for property visible.
 *
 * Default value is true
 *
 * @param {boolean} bVisible  new value for property visible
 * @return {sap.m.InputBase} this to allow method chaining
 * @public
 * @name sap.m.InputBase#setVisible
 * @function
 */

/**
 * Getter for property valueState.
 * Visualizes warnings or errors related to the text field. Possible values: Warning, Error, Success.
 *
 * Default value is None
 *
 * @return {sap.ui.core.ValueState} the value of property valueState
 * @public
 * @name sap.m.InputBase#getValueState
 * @function
 */

/**
 * Setter for property valueState.
 *
 * Default value is None
 *
 * @param {sap.ui.core.ValueState} oValueState  new value for property valueState
 * @return {sap.m.InputBase} this to allow method chaining
 * @public
 * @name sap.m.InputBase#setValueState
 * @function
 */

/**
 * Getter for property name.
 * The "name" property to be used in the HTML code (e.g. for HTML forms that send data to the server via 'submit').
 *
 * Default value is empty/undefined
 *
 * @return {string} the value of property name
 * @public
 * @name sap.m.InputBase#getName
 * @function
 */

/**
 * Setter for property name.
 *
 * Default value is empty/undefined
 *
 * @param {string} sName  new value for property name
 * @return {sap.m.InputBase} this to allow method chaining
 * @public
 * @name sap.m.InputBase#setName
 * @function
 */

/**
 * Getter for property placeholder.
 * Text shown when no value available.
 *
 * Default value is empty/undefined
 *
 * @return {string} the value of property placeholder
 * @public
 * @name sap.m.InputBase#getPlaceholder
 * @function
 */

/**
 * Setter for property placeholder.
 *
 * Default value is empty/undefined
 *
 * @param {string} sPlaceholder  new value for property placeholder
 * @return {sap.m.InputBase} this to allow method chaining
 * @public
 * @name sap.m.InputBase#setPlaceholder
 * @function
 */

/**
 * Getter for property editable.
 * Controls if a user can change the value.
 *
 * Default value is true
 *
 * @return {boolean} the value of property editable
 * @public
 * @since 1.12.0
 * @name sap.m.InputBase#getEditable
 * @function
 */

/**
 * Setter for property editable.
 *
 * Default value is true
 *
 * @param {boolean} bEditable  new value for property editable
 * @return {sap.m.InputBase} this to allow method chaining
 * @public
 * @since 1.12.0
 * @name sap.m.InputBase#setEditable
 * @function
 */

/**
 * This event gets fired when the input operation has finished and the value has changed.
 *
 * @name sap.m.InputBase#change
 * @event
 * @param {sap.ui.base.Event} oControlEvent
 * @param {sap.ui.base.EventProvider} oControlEvent.getSource
 * @param {object} oControlEvent.getParameters

 * @param {string} oControlEvent.getParameters.value The new value of the input.
 * @public
 */

/**
 * Attach event handler fnFunction to the 'change' event of this sap.m.InputBase.
.
 * When called, the context of the event handler (its this) will be bound to oListener if specified
 * otherwise to this sap.m.InputBase.
 itself.
 *
 * This event gets fired when the input operation has finished and the value has changed.
 *
 * @param {object}
 *            [oData] An application specific payload object, that will be passed to the event handler along with the event object when firing the event.
 * @param {function}
 *            fnFunction The function to call, when the event occurs.
 * @param {object}
 *            [oListener] Context object to call the event handler with. Defaults to this sap.m.InputBase.
 itself.
 *
 * @return {sap.m.InputBase} this to allow method chaining
 * @public
 * @name sap.m.InputBase#attachChange
 * @function
 */

/**
 * Detach event handler fnFunction from the 'change' event of this sap.m.InputBase.

 *
 * The passed function and listener object must match the ones used for event registration.
 *
 * @param {function}
 *            fnFunction The function to call, when the event occurs.
 * @param {object}
 *            oListener Context object on which the given function had to be called.
 * @return {sap.m.InputBase} this to allow method chaining
 * @public
 * @name sap.m.InputBase#detachChange
 * @function
 */

/**
 * Fire event change to attached listeners.
 *
 * Expects following event parameters:
 *

 *
'value' of type string The new value of the input.

 *

 *
 * @param {Map} [mArguments] the arguments to pass along with the event.
 * @return {sap.m.InputBase} this to allow method chaining
 * @protected
 * @name sap.m.InputBase#fireChange
 * @function
 */

// Start of sap\m\InputBase.js
jQuery.sap.require("sap.ui.core.EnabledPropagator");
jQuery.sap.require("sap.ui.core.IconPool");
sap.ui.core.EnabledPropagator.call(sap.m.InputBase.prototype);
sap.ui.core.IconPool.insertFontFaceStyle();

/* Android browser does not scroll a focused input into the view correctly */
if (sap.ui.Device.os.android && sap.ui.Device.os.version >= 4){
	jQuery(window).on("resize", function(){
		var active = document.activeElement;
		if(active.tagName == "INPUT" && active.classList.contains("sapMInputBaseInner")){
			window.setTimeout(function(){
				active.scrollIntoViewIfNeeded();
			}, 0);
		}
	});
}

/* =========================================================== */
/* Private methods and properties                              */
/* =========================================================== */

/* ----------------------------------------------------------- */
/* Private properties                                          */
/* ----------------------------------------------------------- */

// use labels as placeholder configuration
sap.m.InputBase.prototype._bShowLabelAsPlaceholder = (function(oDevice) {

	// check native placeholder support first
	if (!oDevice.support.input.placeholder) {
		return true;
	}

	// according to HTML 5 placeholder specification,
	// http://www.w3.org/html/wg/drafts/html/master/single-page.html#the-placeholder-attribute
	// the placeholder attribute is only shown before the user enters a value
	// but IE removes placeholder when the user puts focus on the field
	// http://msdn.microsoft.com/en-us/library/ie/hh772942(v=vs.85).aspx
	if (oDevice.browser.msie) {
		return true;
	}

	// we exclude not right alignable placeholders
	// check test page : http://jsfiddle.net/89FhB/
	if (oDevice.os.android && oDevice.os.android.version < 4.4) {
		return true;
	}

}(sap.ui.Device));

/* ----------------------------------------------------------- */
/* Private methods                                             */
/* ----------------------------------------------------------- */

/**
 * To allow setting of default placeholder e.g. in DatePicker
 *
 * FIXME: Remove this workaround
 * What is the difference between _getPlaceholder and getPlaceholder
 */
sap.m.InputBase.prototype._getPlaceholder = function() {
	return this.getPlaceholder();
};

/**
 * Update the synthetic placeholder visibility.
 */
sap.m.InputBase.prototype._setLabelVisibility = function() {
	if (!this._bShowLabelAsPlaceholder || !this._$label || !this.isActive()) {
		return;
	}

	var sValue = this._getInputValue();
	this._$label.css("display", sValue ? "none" : "inline");
};

/**
 * Returns the DOM value respect to maxLength
 * When parameter is set chops the given parameter
 *
 * TODO: write two different functions for two different behaviour
 */
sap.m.InputBase.prototype._getInputValue = function(sValue) {
	sValue = (typeof sValue == "undefined") ? this._$input.val() : sValue.toString();

	if (this.getMaxLength && this.getMaxLength() > 0) {
		sValue = sValue.substring(0, this.getMaxLength());
	}

	return sValue;
};

/**
 * Triggers input event from the input field delayed
 * This event is marked as synthetic since it is not a native input event
 * Event properties can be specified with first parameter when necessary
 */
sap.m.InputBase.prototype._triggerInputEvent = function(mProperties) {
	mProperties = mProperties || {};
	var oEvent = new jQuery.Event("input", mProperties);
	oEvent.originalEvent = mProperties;
	oEvent.setMark("synthetic", true);

	// not to break real event order fire the event delayed
	jQuery.sap.delayedCall(0, this, function() {
		this.$("inner").trigger(oEvent);
	});
};

/* =========================================================== */
/* Lifecycle methods                                           */
/* =========================================================== */

/**
 * Initialization hook.
 *
 * TODO: respect hungarian notation for variables
 * @private
 */
sap.m.InputBase.prototype.init = function() {
	this._lastValue = "";	// last changed value
	this._changeProxy = jQuery.proxy(this.onChange, this);
};

/**
 * Required adaptations before rendering.
 *
 * @private
 */
sap.m.InputBase.prototype.onBeforeRendering = function() {

	// mark the rendering phase
	this._bRendering = true;

	// is DOM already available
	if (this._bCheckDomValue && this.isActive()) {

		// remember dom value in case of invalidation during keystrokes
		// so the following should only be used onAfterRendering
		this._sDomValue = this._getInputValue();
	}
};

/**
 * Required adaptations after rendering.
 *
 * @private
 */
sap.m.InputBase.prototype.onAfterRendering = function() {

	// cache input as jQuery
	this._$input = this.$("inner");

	// maybe control is invalidated on keystrokes and
	// even the value property did not change
	// dom value is still the old value
	// FIXME: This is very ugly to implement this because of the binding
	if (this._bCheckDomValue && this._sDomValue !== this._getInputValue()) {

		// so we should keep the dom up-to-date
		this._$input.val(this._sDomValue);
	}

	// now dom value is up-to-date
	this._bCheckDomValue = false;

	// handle synthetic placeholder visibility
	if (this._bShowLabelAsPlaceholder) {
		this._$label = this.$("placeholder");
		this._setLabelVisibility();
	}

	// rendering phase is finished
	this._bRendering = false;
};

/**
 * Cleans up before destruction.
 *
 * @private
 */
sap.m.InputBase.prototype.exit = function() {
	this._$input = null;
	this._$label = null;
};

/* =========================================================== */
/* Event handlers                                              */
/* =========================================================== */

/**
 * Handles the touch start event of the Input.
 *
 * @param {jQuery.Event} oEvent The event object.
 * @private
 */
sap.m.InputBase.prototype.ontouchstart = function(oEvent) {

	// mark the event for components that needs to know if the event was handled
	oEvent.setMarked();
};

/**
 * Handles the focusout event of the Input.
 *
 * @param {jQuery.Event} oEvent The event object.
 * @private
 */
sap.m.InputBase.prototype.onfocusout = function(oEvent) {

	// because dom is replaced during the rendering
	// onfocusout event is triggered probably focus goes to the document
	// so we ignore this event that comes during the rendering
	if (this._bRendering) {
		return;
	}

	// handle change event on blur
	this.onChange(oEvent);
};

/**
 * Handles the change event.
 *
 * @protected
 * @param {jQuery.Event} oEvent
 * @name sap.m.InputBase#onChange
 * @returns {true|undefined} true when change event is fired
 * @function
 */
sap.m.InputBase.prototype.onChange = function(oEvent) {

	// check the control is editable or not
	if (!this.getEditable() || !this.getEnabled()) {
		return;
	}

	// get the dom value respect to max length
	var sValue = this._getInputValue();

	// compare with the old known value
	if (sValue !== this._lastValue) {

		// save the value on change
		this.setValue(sValue);

		// remember the last value on change
		this._lastValue = sValue;

		// fire change event
		this.fireChangeEvent(sValue);

		// inform change detection
		return true;
	}
};

/**
 * Fires the change event for the listeners
 *
 * @protected
 * @name sap.m.InputBase#fireChangeEvent
 * @param {String} sValue value of the input.
 * @param {Object} [oParams] extra event parameters.
 * @since 1.22.1
 * @function
 */
sap.m.InputBase.prototype.fireChangeEvent = function(sValue, oParams) {
	// generate event parameters
	var oChangeEvent = jQuery.extend({
		value : sValue,

		// backwards compatibility
		newValue : sValue
	}, oParams);

	// fire change event
	this.fireChange(oChangeEvent);
};

/* ----------------------------------------------------------- */
/* Keyboard handling                                           */
/* ----------------------------------------------------------- */

/**
 * Handle when enter is pressed.
 *
 * @param {jQuery.Event} oEvent The event object.
 * @private
 */
sap.m.InputBase.prototype.onsapenter = function(oEvent) {

	// handle change event on enter
	this.onChange(oEvent);
};

/**
 * Handle when escape is pressed.
 *
 * @param {jQuery.Event} oEvent The event object.
 * @private
 */
sap.m.InputBase.prototype.onsapescape = function(oEvent) {

	// get the dom value that respect to max length
	var sValue = this._getInputValue();

	// compare last known value and dom value
	if (sValue !== this._lastValue) {

		// mark the event that it is handled
		oEvent.setMarked();
		oEvent.preventDefault();

		// revert to the old dom value
		this.updateDomValue(this._lastValue);

		// fire private live change event
		this.fireEvent("liveChange", {
			value: this._lastValue,

			// backwards compatibility
			newValue: this._lastValue
		});
	}
};

/**
 * Handle DOM input event.
 *
 * This event is fired synchronously when the value of an <input> or <textarea> element is changed.
 * IE9 does not fire an input event when the user removes characters via BACKSPACE / DEL / CUT
 * InputBase normalize this behaviour for IE9 and calls oninput for the subclasses
 *
 * @param {jQuery.Event} oEvent The event object.
 * @private
 */
sap.m.InputBase.prototype.oninput = function(oEvent) {

	// dom value updated other than value property
	this._bCheckDomValue = true;

	// update the synthetic placeholder visibility
	this._setLabelVisibility();
};

/**
 * Handle keydown event.
 *
 * @param {jQuery.Event} oEvent The event object.
 * @private
 */
sap.m.InputBase.prototype.onkeydown = function(oEvent) {

	// IE9 does not fire input event on BACKSPACE & DEL
	var mKC = jQuery.sap.KeyCodes;
	var mBrowser = sap.ui.Device.browser;
	if ((mBrowser.msie && mBrowser.version < 10) &&
		(oEvent.which === mKC.DELETE || oEvent.which === mKC.BACKSPACE)) {

		// trigger synthetic input event
		this._triggerInputEvent();
	}
};

/**
 * Handle cut event.
 *
 * @param {jQuery.Event} oEvent The event object.
 * @private
 */
sap.m.InputBase.prototype.oncut = function(oEvent) {

	// IE9 does not fire input event on cut
	var mBrowser = sap.ui.Device.browser;
	if (mBrowser.msie && mBrowser.version < 10) {

		// trigger synthetic input event
		this._triggerInputEvent();
	}
};

/* =========================================================== */
/* API methods                                                 */
/* =========================================================== */

/* ----------------------------------------------------------- */
/* protected methods                                           */
/* ----------------------------------------------------------- */

/**
 * Sets the start and end positions of the current text selection.
 *
 * @param {integer} iSelectionStart The index into the text at which the first selected character is located.
 * @param {integer} iSelectionEnd The index into the text at which the last selected character is located.
 * @returns {sap.m.InputBase} this to allow method chaining.
 * @protected
 * @since 1.22.1
 * @name sap.m.InputBase#selectText
 * @function
 */
sap.m.InputBase.prototype.selectText = function(iSelectionStart, iSelectionEnd) {
	jQuery(this.getFocusDomRef()).selectText(iSelectionStart, iSelectionEnd);
	return this;
};

/**
 * Overwrite setProperty function to know value property changes via API
 * @overwrite
 */
sap.m.InputBase.prototype.setProperty = function(sPropertyName, oValue, bSuppressInvalidate) {
	if (sPropertyName == "value") {

		// dom value will be updated with value property
		this._bCheckDomValue = false;
	}

	return sap.ui.core.Control.prototype.setProperty.apply(this, arguments);
};

/**
 * Registers an event listener to the browser input event.
 *
 * @param {function} fnCallback Function to be called when the value of the input element is changed.
 * @deprecated Since 1.22. Instead use event delegation(oninput) to listen input event.
 * @return {sap.m.InputBase} this to allow method chaining.
 * @name sap.m.InputBase#bindToInputEvent
 * @protected
 */
sap.m.InputBase.prototype.bindToInputEvent = function(fnCallback) {

	// remove the previous event delegate
	if (this._oInputEventDelegate) {
		this.removeEventDelegate(this._oInputEventDelegate);
	}

	// generate new input event delegate
	this._oInputEventDelegate = {
		oninput : fnCallback
	};

	// add the input event delegate
	return this.addEventDelegate(this._oInputEventDelegate);
};

/**
 * Sets the DOM value of the input field and handles placeholder visibility.
 *
 * @param {string} sValue value of the input field.
 * @return {sap.m.InputBase} this to allow method chaining.
 * @name sap.m.InputBase#updateDomValue
 * @since 1.22
 * @protected
 */
sap.m.InputBase.prototype.updateDomValue = function(sValue) {

	// dom value updated other than value property
	this._bCheckDomValue = true;

	// respect to max length
	sValue = this._getInputValue(sValue);

	// update the DOM value when necessary
	// otherwise cursor can goto end of text unnecessarily
	if (this.isActive() && (this._getInputValue() !== sValue)) {
		this._$input.val(sValue);
	}

	// update synthetic placeholder visibility
	this._setLabelVisibility();

	return this;
};

/* ----------------------------------------------------------- */
/* public methods                                              */
/* ----------------------------------------------------------- */

/**
 * Setter for property valueState.
 *
 * Default value is None.
 *
 * @param {sap.ui.core.ValueState} sValueState New value for property valueState.
 * @return {sap.m.InputBase} this to allow method chaining.
 * @public
 * @name sap.m.InputBase#setValueState
 * @function
 */
sap.m.InputBase.prototype.setValueState = function(sValueState) {
	var sOldValueState = this.getValueState();
	sValueState = this.validateProperty("valueState", sValueState);

	if (sValueState === sOldValueState) {
		return this;
	}

	if (!this.isActive()) {
		return this.setProperty("valueState", sValueState);
	}

	var $container = this.$();
	this.setProperty("valueState", sValueState, true);

	if (sOldValueState !== sap.ui.core.ValueState.None) {
		$container.removeClass("sapMInputBaseState sapMInputBase" + sOldValueState);
		this._$input.removeClass("sapMInputBaseStateInner sapMInputBase" + sOldValueState + "Inner");
	}

	if (sValueState  !== sap.ui.core.ValueState.None) {
		$container.addClass("sapMInputBaseState sapMInputBase" + sValueState);
		this._$input.addClass("sapMInputBaseStateInner sapMInputBase" + sValueState + "Inner");
	}

	// set tooltip based on state (will be undefined when state is None)
	var sTooltip = sap.ui.core.ValueStateSupport.enrichTooltip(this, this.getTooltip_AsString());
	this.$().attr("title", sTooltip || "");

	return this;
};

/**
 * Setter for property value.
 *
 * Default value is empty/undefined.
 *
 * @param {string} sValue New value for property value.
 * @return {sap.m.InputBase} this to allow method chaining.
 * @public
 * @name sap.m.InputBase#setValue
 * @function
 */
sap.m.InputBase.prototype.setValue = function(sValue) {

	// validate given value
	sValue = this.validateProperty("value", sValue);

	// get the value respect to the max length
	sValue = this._getInputValue(sValue);

	// update the dom value when necessary
	this.updateDomValue(sValue);

	// check if we need to update the last value because
	// when setProperty("value") called setValue is called again via binding
	if (sValue !== this.getProperty("value")) {
		this._lastValue = sValue;
	}

	// update value property
	this.setProperty("value", sValue, true);

	return this;
};

/**
 * Returns an object representing the serialized focus information.
 * To be overwritten by subclasses.
 *
 * @return {object} An object representing the serialized focus information.
 * @protected
 * @name sap.m.InputBase.prototype#getFocusInfo
 * @function
 */
sap.m.InputBase.prototype.getFocusInfo = function() {
	var oFocusInfo = sap.ui.core.Control.prototype.getFocusInfo.call(this),
		oFocusDomRef = this.getFocusDomRef();

	// extend the serialized focus information with the current text selection and the cursor position
	jQuery.extend(oFocusInfo, {
		cursorPos: 0,
		selectionStart: 0,
		selectionEnd: 0
	});

	if (oFocusDomRef) {
		oFocusInfo.cursorPos = jQuery(oFocusDomRef).cursorPos();

		try {
			oFocusInfo.selectionStart = oFocusDomRef.selectionStart;
			oFocusInfo.selectionEnd = oFocusDomRef.selectionEnd;
		} catch (e) {}	// note: chrome fail to read the "selectionStart" property from HTMLInputElement: The input element's type "number" does not support selection.
	}

	return oFocusInfo;
};

/**
 * Applies the focus info.
 * To be overwritten by subclasses.
 *
 * @param {object} oFocusInfo
 * @protected
 * @name sap.m.InputBase.prototype#applyFocusInfo
 * @function
 */
sap.m.InputBase.prototype.applyFocusInfo = function(oFocusInfo) {
	sap.ui.core.Control.prototype.applyFocusInfo.call(this, oFocusInfo);
	this.$("inner").cursorPos(oFocusInfo.cursorPos);
	this.selectText(oFocusInfo.selectionStart, oFocusInfo.selectionEnd);
	return this;
};

sap.m.InputBase.prototype.getFocusDomRef = function() {
	return this.getDomRef("inner");
};

sap.m.InputBase.prototype.getIdForLabel = function() {
	return this.getId() + "-inner";
};


text:
package com.intellij.xml.actions.validate;

import com.intellij.javaee.UriUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.xml.*;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.xml.util.XmlResourceResolver;
import org.apache.xerces.impl.Constants;
import org.apache.xerces.impl.XMLEntityManager;
import org.apache.xerces.impl.XercesAccessor;
import org.apache.xerces.jaxp.JAXPConstants;
import org.apache.xerces.jaxp.SAXParserFactoryImpl;
import org.apache.xerces.util.SecurityManager;
import org.apache.xerces.util.XMLGrammarPoolImpl;
import org.apache.xerces.xni.grammars.XMLGrammarPool;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.StringReader;
import java.util.Arrays;
import java.util.Map;

/**
 * @author Mike
 */
public class ValidateXmlActionHandler {
  private static final Logger LOG = Logger.getInstance("#com.intellij.xml.actions.validate.ValidateXmlAction");

  private static final String SCHEMA_FULL_CHECKING_FEATURE_ID = "http://apache.org/xml/features/validation/schema-full-checking";
  private static final String GRAMMAR_FEATURE_ID = Constants.XERCES_PROPERTY_PREFIX + Constants.XMLGRAMMAR_POOL_PROPERTY;
  private static final String ENTITY_MANAGER_PROPERTY_ID = Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_MANAGER_PROPERTY;
  private static final String SECURITY_MANAGER = Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY;

  private static final Key<XMLGrammarPool> GRAMMAR_POOL_KEY = Key.create("GrammarPoolKey");
  private static final Key<Long> GRAMMAR_POOL_TIME_STAMP_KEY = Key.create("GrammarPoolTimeStampKey");
  private static final Key<VirtualFile[]> DEPENDENT_FILES_KEY = Key.create("GrammarPoolFilesKey");
  private static final Key<String[]> KNOWN_NAMESPACES_KEY = Key.create("KnownNamespacesKey");
  private static final Key<Map<String, String>> ENTITIES_KEY = Key.create("EntityManagerKey");

  private Project myProject;
  private XmlFile myFile;
  private ErrorReporter myErrorReporter;
  private SAXParser myParser;
  private XmlResourceResolver myXmlResourceResolver;
  private final boolean myForceChecking;
  @NonNls
  private static final String ENTITY_RESOLVER_PROPERTY_NAME = "http://apache.org/xml/properties/internal/entity-resolver";

  public ValidateXmlActionHandler(boolean _forceChecking) {
    myForceChecking = _forceChecking;
  }

  public void setErrorReporter(ErrorReporter errorReporter) {
    myErrorReporter = errorReporter;
  }

  public VirtualFile getProblemFile(SAXParseException ex) {
    String publicId = ex.getPublicId();
    String systemId = ex.getSystemId();
    if (publicId == null) {
      if (systemId != null) {
        if (systemId.startsWith("file:/")) {
          VirtualFile file = VirtualFileManager.getInstance()
            .findFileByUrl(systemId.startsWith("file://") ? systemId : systemId.replace("file:/", "file://"));
          if (file != null) return file;
        }
        final String path = myXmlResourceResolver.getPathByPublicId(systemId);
        if (path != null) return UriUtil.findRelativeFile(path,null);
        final PsiFile file = myXmlResourceResolver.resolve(null, systemId);
        if (file != null) return file.getVirtualFile();
      }
      return myFile.getVirtualFile();
    }
    final String path = myXmlResourceResolver.getPathByPublicId(publicId);
    if (path != null) return UriUtil.findRelativeFile(path,null);
    return null;
  }

  public enum ProblemType { WARNING, ERROR, FATAL }

  public String buildMessageString(SAXParseException ex) {
    String msg = "(" + ex.getLineNumber() + ":" + ex.getColumnNumber() + ") " + ex.getMessage();
    final VirtualFile file = getProblemFile(ex);

    if ( file != null && !file.equals(myFile.getVirtualFile())) {
      msg = file.getName() + ":" + msg;
    }
    return msg;
  }

  public void doValidate(XmlFile file) {
    myProject = file.getProject();
    myFile = file;

    myXmlResourceResolver = new XmlResourceResolver(myFile, myProject, myErrorReporter);
    myXmlResourceResolver.setStopOnUnDeclaredResource( myErrorReporter.isStopOnUndeclaredResource() );

    try {
      try {
        myParser = createParser();
      }
      catch (Exception e) {
        filterAppException(e);
      }

      if (myParser == null) return;

      myErrorReporter.startProcessing();
    }
    catch (XmlResourceResolver.IgnoredResourceException ignore) {
    }
    catch (Exception exception) {
      filterAppException(exception);
    }
  }

  private void filterAppException(Exception exception) {
    if (!myErrorReporter.filterValidationException(exception)) {
      LOG.error(exception);
    }
  }

  public void doParse() {
    try {
      myParser.parse(new InputSource(new StringReader(myFile.getText())), new DefaultHandler() {
        @Override
        public void warning(SAXParseException e) throws SAXException {
          if (myErrorReporter.isUniqueProblem(e)) myErrorReporter.processError(e, ProblemType.WARNING);
        }

        @Override
        public void error(SAXParseException e) throws SAXException {
          if (myErrorReporter.isUniqueProblem(e)) myErrorReporter.processError(e, ProblemType.ERROR);
        }

        @Override
        public void fatalError(SAXParseException e) throws SAXException {
          if (myErrorReporter.isUniqueProblem(e)) myErrorReporter.processError(e, ProblemType.FATAL);
        }

        @Override
        public InputSource resolveEntity(String publicId, String systemId) {
          final PsiFile psiFile = myXmlResourceResolver.resolve(null, systemId);
          if (psiFile == null) return null;
          return new InputSource(new StringReader(psiFile.getText()));
        }

        @Override
        public void startDocument() throws SAXException {
          super.startDocument();
          myParser.setProperty(
            ENTITY_RESOLVER_PROPERTY_NAME,
            myXmlResourceResolver
          );
          configureEntityManager(myFile, myParser);
        }
      });

      final String[] resourcePaths = myXmlResourceResolver.getResourcePaths();
      if (resourcePaths.length > 0) { // if caches are used
        final VirtualFile[] files = new VirtualFile[resourcePaths.length];
        for (int i = 0; i < resourcePaths.length; ++i) {
          files[i] = UriUtil.findRelativeFile(resourcePaths[i], null);
        }

        myFile.putUserData(DEPENDENT_FILES_KEY, files);
        myFile.putUserData(GRAMMAR_POOL_TIME_STAMP_KEY, calculateTimeStamp(files, myProject));
      }
       myFile.putUserData(KNOWN_NAMESPACES_KEY, getNamespaces(myFile));
    }
    catch (SAXException e) {
      LOG.debug(e);
    }
    catch (Exception exception) {
      filterAppException(exception);
    }
    catch (StackOverflowError error) {
      // http://issues.apache.org/jira/browse/XERCESJ-589
    }
  }

  protected SAXParser createParser() throws SAXException, ParserConfigurationException {
      if (!needsDtdChecking() && !needsSchemaChecking() && !myForceChecking) {
        return null;
      }

      SAXParserFactory factory = new SAXParserFactoryImpl();
      boolean schemaChecking = false;

      if (hasDtdDeclaration()) {
        factory.setValidating(true);
      }

      if (needsSchemaChecking()) {
        factory.setValidating(true);
        factory.setNamespaceAware(true);
        //jdk 1.5 API
        try {
          factory.setXIncludeAware(true);
        } catch(NoSuchMethodError ignore) {}
        schemaChecking = true;
      }

      SAXParser parser = factory.newSAXParser();

      parser.setProperty(ENTITY_RESOLVER_PROPERTY_NAME, myXmlResourceResolver);

      SecurityManager securityManager = new SecurityManager();
      securityManager.setEntityExpansionLimit(10000);
      parser.setProperty(SECURITY_MANAGER, securityManager);

      if (schemaChecking) { // when dtd checking schema refs could not be validated @see http://marc.theaimsgroup.com/?l=xerces-j-user&m=112504202423704&w=2
        XMLGrammarPool grammarPool = getGrammarPool(myFile, myForceChecking);
        configureEntityManager(myFile, parser);
        parser.getXMLReader().setProperty(GRAMMAR_FEATURE_ID, grammarPool);
      }
      try {
        if (schemaChecking) {
          parser.setProperty(JAXPConstants.JAXP_SCHEMA_LANGUAGE,JAXPConstants.W3C_XML_SCHEMA);
          parser.getXMLReader().setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, true);

          if (Boolean.TRUE.equals(Boolean.getBoolean(XmlResourceResolver.HONOUR_ALL_SCHEMA_LOCATIONS_PROPERTY_KEY))) {
            parser.getXMLReader().setFeature("http://apache.org/xml/features/honour-all-schemaLocations", true);
          }

          parser.getXMLReader().setFeature("http://apache.org/xml/features/validation/warn-on-undeclared-elemdef",Boolean.TRUE);
          parser.getXMLReader().setFeature("http://apache.org/xml/features/validation/warn-on-duplicate-attdef",Boolean.TRUE);
        }

        parser.getXMLReader().setFeature("http://apache.org/xml/features/warn-on-duplicate-entitydef",Boolean.TRUE);
        parser.getXMLReader().setFeature("http://apache.org/xml/features/validation/unparsed-entity-checking",Boolean.FALSE);
      } catch(SAXNotRecognizedException ex) {
        // it is possible to continue work with configured parser
        LOG.info("Xml parser installation seems screwed", ex);
      }

      return parser;
  }

  public static XMLGrammarPool getGrammarPool(XmlFile file, boolean forceChecking) {
    final XMLGrammarPool previousGrammarPool = getGrammarPool(file);
    XMLGrammarPool grammarPool = null;

    // check if the pool is valid
    if (!forceChecking && !isValidationDependentFilesOutOfDate(file)) {
      grammarPool = previousGrammarPool;
    }

    if (grammarPool == null) {
      invalidateEntityManager(file);
      grammarPool = new XMLGrammarPoolImpl();
      file.putUserData(GRAMMAR_POOL_KEY, grammarPool);
    }
    return grammarPool;
  }

  @Nullable
  public static XMLGrammarPool getGrammarPool(XmlFile file) {
    return file.getUserData(GRAMMAR_POOL_KEY);
  }

  public static boolean isValidationDependentFilesOutOfDate(XmlFile myFile) {
    final VirtualFile[] files = myFile.getUserData(DEPENDENT_FILES_KEY);
    final Long grammarPoolTimeStamp = myFile.getUserData(GRAMMAR_POOL_TIME_STAMP_KEY);
    String[] ns = myFile.getUserData(KNOWN_NAMESPACES_KEY);

    if (!Arrays.equals(ns, getNamespaces(myFile))) {
      return true;
    }

    if (grammarPoolTimeStamp != null && files != null) {
      long dependentFilesTimestamp = calculateTimeStamp(files,myFile.getProject());

      if (dependentFilesTimestamp == grammarPoolTimeStamp.longValue()) {
        return false;
      }
    }

    return true;
  }

  private static void invalidateEntityManager(XmlFile file) {
    file.putUserData(ENTITIES_KEY, null);
  }

  private static void configureEntityManager(XmlFile file, SAXParser parser) throws SAXException {
    XMLEntityManager entityManager = (XMLEntityManager)parser.getXMLReader().getProperty(ENTITY_MANAGER_PROPERTY_ID);
    Map<String, String> entities = file.getUserData(ENTITIES_KEY);
    if (entities != null) {
      // passing of entityManager object would break validation, so we copy its entities
      XercesAccessor.getEntities(entityManager).putAll(entities);
    }
    else {
      file.putUserData(ENTITIES_KEY, XercesAccessor.getEntities(entityManager));
    }
  }

  private static String[] getNamespaces(XmlFile file) {
    XmlTag rootTag = file.getRootTag();
    if (rootTag == null) return ArrayUtil.EMPTY_STRING_ARRAY;
    return ContainerUtil.mapNotNull(rootTag.getAttributes(), attribute -> attribute.getValue(), ArrayUtil.EMPTY_STRING_ARRAY);
  }

  private static long calculateTimeStamp(final VirtualFile[] files, Project myProject) {
    long timestamp = 0;

    for(VirtualFile file:files) {
      if (file == null || !file.isValid()) break;
      final PsiFile psifile = PsiManager.getInstance(myProject).findFile(file);

      if (psifile != null && psifile.isValid()) {
        timestamp += psifile.getViewProvider().getModificationStamp();
      } else {
        break;
      }
    }
    return timestamp;
  }

  private boolean hasDtdDeclaration() {
    XmlDocument document = myFile.getDocument();
    if (document == null) return false;
    XmlProlog prolog = document.getProlog();
    if (prolog == null) return false;
    XmlDoctype doctype = prolog.getDoctype();
    if (doctype == null) return false;

    return true;
  }

  private boolean needsDtdChecking() {
    XmlDocument document = myFile.getDocument();
    if (document == null) return false;

    return (document.getProlog()!=null && document.getProlog().getDoctype()!=null);
  }

  private boolean needsSchemaChecking() {
    XmlDocument document = myFile.getDocument();
    if (document == null) return false;
    XmlTag rootTag = document.getRootTag();
    if (rootTag == null) return false;

    XmlAttribute[] attributes = rootTag.getAttributes();
    for (XmlAttribute attribute : attributes) {
      if (attribute.isNamespaceDeclaration()) return true;
    }

    return false;
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Mail;
use Session;
use Redirect;
use App\Models\Site\Widget;

class MailController extends Controller
{
    public function index()
    {
      $title = 'Anitoon - Contato';
      $titlepg = 'Contato';
      $widget = Widget::orderBy('id', 'DESC')->get();
      return view('site.contato', compact('title','titlepg', 'widget'));
    }

    public function store(Request $request)
    {
      $dataForm = $request->except(['_token']);
        Mail::send('site.contat',$request->all(), function($msg){
          $msg->subject('Correio de Contato');
          $msg->to('luucasroberto250@gmail.com');
        });
      Session::flash('message','Email enviado com sucesso');
      return Redirect::to('/contato');
    }
}


text:
require 'pathname'

module Pronto
  module Git
    class Repository
      def initialize(path)
        @repo = Rugged::Repository.new(path)
      end

      def diff(commit, options = nil)
        target, patches = case commit
                          when :unstaged, :index
                            [head_commit_sha, @repo.index.diff(options)]
                          when :staged
                            [head_commit_sha, head.diff(@repo.index, options)]
                          else
                            merge_base = merge_base(commit)
                            patches = @repo.diff(merge_base, head, options)
                            [merge_base, patches]
                          end

        patches.find_similar!(renames: true)
        Patches.new(self, target, patches)
      end

      def show_commit(sha)
        return empty_patches(sha) unless sha

        commit = @repo.lookup(sha)
        return empty_patches(sha) if commit.parents.count != 1

        # TODO: Rugged does not seem to support diffing against multiple parents
        diff = commit.diff(reverse: true)
        return empty_patches(sha) if diff.nil?

        Patches.new(self, sha, diff.patches)
      end

      def commits_until(sha)
        result = []
        @repo.walk(head_commit_sha, Rugged::SORT_TOPO).take_while do |commit|
          result << commit.oid
          !commit.oid.start_with?(sha)
        end
        result
      end

      def path
        Pathname.new(@repo.workdir).cleanpath
      end

      def blame(path, lineno)
        return if new_file?(path)

        Rugged::Blame.new(@repo, path, min_line: lineno, max_line: lineno,
                                       track_copies_same_file: true,
                                       track_copies_any_commit_copies: true)[0]
      end

      def branch
        @repo.head.name.sub('refs/heads/', '') if @repo.head.branch?
      end

      def remote_urls
        @repo.remotes.map(&:url)
      end

      def head_commit_sha
        head.oid
      end

      def head_detached?
        @repo.head_detached?
      end

      private

      def new_file?(path)
        @repo.status(path).include?(:index_new)
      end

      def empty_patches(sha)
        Patches.new(self, sha, [])
      end

      def merge_base(commit)
        @repo.merge_base(commit, head)
      end

      def head
        @repo.head.target
      end
    end
  end
end


text:
# justix
# (c) 2013 Justin Gottula
# The source code of this project is distributed under the terms of the
# simplified BSD license. See the LICENSE file for details.

AS:=nasm
ASFLAGS:=-fbin -MP -Ox -Wall

.PHONY: all clean mbr stage1 stage2

# default rule
all: mbr stage1 stage2

mbr:    out/bin/mbr    out/hex/mbr
stage1: out/bin/stage1 out/hex/stage1
stage2: out/bin/stage2 out/hex/stage2

clean:
	rm -rf $(wildcard out/*/*) $(wildcard src/*/*.dep)

out/hex/%: out/bin/% Makefile
	xxd -a out/bin/$* $@

out/bin/%: Makefile
	$(AS) $(ASFLAGS) -dMAPFILE=out/map/$* -o $@ -isrc/ -isrc/$*/ -lout/lst/$* -MD src/$*/$*.dep src/$*/$*.s
	grep $*_fill out/map/$*

# concatenate nasm's autogenerated dependencies
-include src/*/*.dep


text:
package com.lw.productunit.entity;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import com.lw.core.entity.BaseEntity;

/**
 * Product generated by hbm2java
 */
@Entity
@Table(name = "product", catalog = "mall")
public class Product extends BaseEntity {

	private static final long serialVersionUID = 7599772729394822540L;

	private Category category;
	private Brand brand;
	private String spu;
	private String title;
	private String subtitle;
	private String htmlDescription;
	private Set<Commodity> commodities = new HashSet<Commodity>(0);

	@ManyToOne(fetch = FetchType.EAGER)
	@JoinColumn(name = "categoryId")
	public Category getCategory() {
		return this.category;
	}

	public void setCategory(Category category) {
		this.category = category;
	}

	@ManyToOne(fetch = FetchType.EAGER)
	@JoinColumn(name = "brandId")
	public Brand getBrand() {
		return this.brand;
	}

	public void setBrand(Brand brand) {
		this.brand = brand;
	}

	@Column(name = "spu", nullable = false, length = 30)
	public String getSpu() {
		return this.spu;
	}

	public void setSpu(String spu) {
		this.spu = spu;
	}

	@Column(name = "title", nullable = false, length = 100)
	public String getTitle() {
		return this.title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	@Column(name = "subtitle", length = 100)
	public String getSubtitle() {
		return this.subtitle;
	}

	public void setSubtitle(String subtitle) {
		this.subtitle = subtitle;
	}

	@Column(name = "htmlDescription", length = 16777215)
	public String getHtmlDescription() {
		return this.htmlDescription;
	}

	public void setHtmlDescription(String htmlDescription) {
		this.htmlDescription = htmlDescription;
	}

	@OneToMany(fetch = FetchType.LAZY, mappedBy = "product", cascade=CascadeType.ALL)
	public Set<Commodity> getCommodities() {
		return this.commodities;
	}

	public void setCommodities(Set<Commodity> commodities) {
		this.commodities = commodities;
	}

	@Override
	public Map<String, String> validation() {
		// TODO Auto-generated method stub
		return null;
	}

}


text:
import PropTypes from 'prop-types';
import React from 'react';
import { ADMIN_URLS, STRINGS } from '../../config/wagtailConfig';

import Button from '../../components/Button/Button';
import Icon from '../../components/Icon/Icon';

/**
 * The bar at the top of the explorer, displaying the current level
 * and allowing access back to the parent level.
 */
const ExplorerHeader = ({ page, depth, onClick }) => {
  const isRoot = depth === 1;

  return (
    <Button
      href={page.id ? `${ADMIN_URLS.PAGES}${page.id}/` : ADMIN_URLS.PAGES}
      className="c-explorer__header"
      onClick={onClick}
    >

        <Icon name={isRoot ? 'home' : 'arrow-left'} />
        {page.admin_display_title || STRINGS.PAGES}

    </Button>
  );
};

ExplorerHeader.propTypes = {
  page: PropTypes.shape({
    id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    admin_display_title: PropTypes.string,
  }).isRequired,
  depth: PropTypes.number.isRequired,
  onClick: PropTypes.func.isRequired,
};

export default ExplorerHeader;


text:
using UnityEngine;
using UnityEngine.UI;
using Skahal.Threading;

#endregion

/// <summary>
/// Status bar controller.
/// </summary>
public class StatusBarController : MonoBehaviour {

	#region Fields
	private static StatusBarController s_instance;
	#endregion

	#region Editor properties
	public Text[] StatusLabels;
	#endregion

	#region Constructors
	public StatusBarController ()
	{
		s_instance = this;
	}
	#endregion

	#region Methods
	public static void SetStatusText (string text, float secondsTimeout = 0)
	{
		for (int i = 0; i < s_instance.StatusLabels.Length; i++) {

			var label = s_instance.StatusLabels[i];
			label.text = text;

			if (secondsTimeout > 0) {
				SHCoroutine.Start (secondsTimeout, () => {
					if (label.text.Equals (text, System.StringComparison.OrdinalIgnoreCase)) {
						label.text = string.Empty;
					}
				});
			}
		}
	}

	public static void ClearStatusText()
	{
		SetStatusText(string.Empty);
	}
	#endregion
}


text:
#ifndef Phonon_GSTREAMER_MEDIANODEEVENT_H
#define Phonon_GSTREAMER_MEDIANODEEVENT_H

#include "common.h"

#include <QtCore>

QT_BEGIN_NAMESPACE

namespace Phonon
{
namespace Gstreamer
{
class MediaNodeEvent
{
public:
    enum Type {
        VideoAvailable,
        AudioAvailable,
        SourceChanged,
        MediaObjectConnected,
        StateChanged,
        VideoSinkAdded,
        VideoSinkRemoved,
        AudioSinkAdded,
        AudioSinkRemoved,
        VideoHandleRequest,
        VideoSizeChanged
    };

    MediaNodeEvent(Type type, const void *data = 0);
    virtual ~MediaNodeEvent();

    inline Type type() const
    {
        return eventType;
    };
    inline const void* data() const
    {
        return eventData;
    };

private:
    Type eventType;
    const void *eventData;
};

}
} // namespace Phonon::Gstreamer

QT_END_NAMESPACE

#endif // Phonon_GSTREAMER_MEDIANODEEVENT_H


text:
#include "scanpopup.h"
#include "tapp.h"
#include "menubarcommandids.h"
#include "texception.h"
#include "mainwindow.h"
#include "tsystem.h"
#include "timagecache.h"
#include "tgl.h"
#include "tcurveutil.h"
#include "tpixelutils.h"
#include "trop.h"
#include "tiio.h"

#include "toonz/tscenehandle.h"
#include "toonz/tframehandle.h"
#include "toonz/txshlevelhandle.h"
#include "toonz/toonzscene.h"
#include "toonz/observer.h"
#include "toonz/sceneproperties.h"
#include "toonz/txshsimplelevel.h"
#include "toonz/stage2.h"
#include "toonz/glrasterpainter.h"
#include "tools/toolutils.h"
#include "toonz/preferences.h"
#include "toonz/cleanupparameters.h"
#include "toonz/tcleanupper.h"

#include "tools/toolhandle.h"
#include "tools/cursors.h"

#include "toonzqt/menubarcommand.h"
#include "toonzqt/doublefield.h"
#include "toonzqt/checkbox.h"
#include "toonzqt/gutil.h"

#include <QPushButton>
#include <QComboBox>
#include <QLabel>
#include <QSettings>
#include <QApplication>

using namespace DVGui;
using namespace CleanupTypes;

//-----------------------------------------------------------------------------
namespace
{

const double previewDPI = 64;
//-----------------------------------------------------------------------------

const QString
	BlackAndWhite = "Black & White",
	Graytones = "Graytones",
	Rgbcolors = "RGB Color";

bool ScannerHasBeenDefined = false;

void checkPaperFormat(TScannerParameters *parameters)
{
	if (parameters->getPaperOverflow()) {
		TScanner *scanner = TScanner::instance();
		QString scannerName = scanner ? scanner->getName() : "no scanner";
		DVGui::warning(QObject::tr("The selected paper format is not available for %1.").arg(scannerName));
	}
}

//-----------------------------------------------------------------------------

bool defineScanner(const QString &scannerType)
{
	bool ret = false;
	QApplication::setOverrideCursor(Qt::WaitCursor);

	TScanner::m_isTwain = (scannerType == "TWAIN");

	try {
		if (!TScanner::instance()->isDeviceAvailable()) {
			DVGui::warning(TScanner::m_isTwain ? QObject::tr("No TWAIN scanner is available") : QObject::tr("No scanner is available"));
			/* FIXME: try/catch からの goto って合法じゃないだろ……。とりあえず応急処置したところ"例外ってナニ?"って感じになったのが
		 indent も腐っておりつらいので後で直す */
			//goto end;
			QApplication::restoreOverrideCursor();
			return false;
		}
		TScanner::instance()->selectDevice();
	} catch (TException &e) {
		DVGui::warning(QString::fromStdWString(e.getMessage()));
		QApplication::restoreOverrideCursor();
		return false;
		//goto end;
	}

	TScannerParameters *scanParameters = TApp::instance()
											 ->getCurrentScene()
											 ->getScene()
											 ->getProperties()
											 ->getScanParameters();
	try {
		scanParameters->adaptToCurrentScanner();
	} catch (TException &e) {
		DVGui::warning(QString::fromStdWString(e.getMessage()));
		//goto end;
		QApplication::restoreOverrideCursor();
		return false;
	}
	scanParameters->updatePaperFormat();
	checkPaperFormat(scanParameters);
	//ScanSettingsPopup::instance()->updateUI();

	ret = true;

//end:
	QApplication::restoreOverrideCursor();
	return ret;
}

//-----------------------------------------------------------------------------

bool checkScannerDefinition()
{
	if (!ScannerHasBeenDefined) {
		QString scannerType = QSettings().value("CurrentScannerType").toString();
		if (scannerType == "") {
			QSettings().setValue("CurrentScannerType", "Internal");
			scannerType = "Internal";
		}
		ScannerHasBeenDefined = defineScanner(scannerType);
	}
	return ScannerHasBeenDefined;
}

//-----------------------------------------------------------------------------

void fillOutputType(QComboBox *t, TScannerParameters *params)
{
	while (t->count())
		t->removeItem(0);

	if (params->isSupported(TScannerParameters::BW))
		t->addItem(BlackAndWhite);
	if (params->isSupported(TScannerParameters::GR8))
		t->addItem(Graytones);
	if (params->isSupported(TScannerParameters::RGB24))
		t->addItem(Rgbcolors);
}

//-----------------------------------------------------------------------------

TPixelGR8 fromRGB(int r, int g, int b)
{
	return TPixelGR8((((UINT)(r)*19594 +
					   (UINT)(g)*38472 +
					   (UINT)(b)*7470 +
					   (UINT)(1 << 15)) >>
					  16));
}

//-----------------------------------------------------------------------------

void makeTransparent(const TRaster32P &ras)
{
	if (!ras)
		return;
	TRop::addBackground(ras, TPixel32::White);
	int x, y;
	for (x = 0; x < ras->getLx(); x++) {
		for (y = 0; y < ras->getLy(); y++) {
			TPixel32 *pix = &ras->pixels(y)[x];
			TPixelGR8 pixGR8 = fromRGB(pix->r, pix->g, pix->b);
			int value = pixGR8.value;
			pix->m = (UCHAR)tcrop<SHORT>(255 - value, 0, 255);
			premult(*pix);
		}
	}
}

//=============================================================================

} //namepsapce

//=============================================================================
/*! \class DefineScannerPopup
		\brief The DefineScannerPopup class provides a modal dialog to choose and define a scan for application.

		Inherits \b Dialog.
*/
//-----------------------------------------------------------------------------

DefineScannerPopup::DefineScannerPopup()
	: Dialog(TApp::instance()->getMainWindow(), true, Preferences::instance()->getCurrentLanguage() == "english", "DefineScanner")
{
#ifdef MACOSX
	setModal(false);
#endif
	setWindowTitle(tr("Define Scanner"));

	m_scanDriverOm = new QComboBox();
	m_scanDriverOm->setFixedSize(150, WidgetHeight);
	QStringList scan;
	scan << "TWAIN"
		 << "Internal";
	m_scanDriverOm->addItems(scan);
	addWidget(tr("Scanner Driver:"), m_scanDriverOm);

	if (QSettings().value("CurrentScannerType").toString() == "Internal")
		m_scanDriverOm->setCurrentIndex(1);

	QPushButton *okBtn = new QPushButton(tr("OK"), this);
	okBtn->setDefault(true);
	QPushButton *cancelBtn = new QPushButton(tr("Cancel"), this);
	connect(okBtn, SIGNAL(clicked()), this, SLOT(accept()));
	connect(cancelBtn, SIGNAL(clicked()), this, SLOT(reject()));

	addButtonBarWidget(okBtn, cancelBtn);
}

//-----------------------------------------------------------------------------

void DefineScannerPopup::accept()
{
	QString scannerType = m_scanDriverOm->currentText();

	if (QSettings().value("CurrentScannerType").toString() != scannerType || !ScannerHasBeenDefined) {
		QSettings().setValue("CurrentScannerType", scannerType);
		ScannerHasBeenDefined = defineScanner(scannerType);
		QAction *setCropAction = CommandManager::instance()->getAction("MI_SetScanCropbox");
		QAction *resetCropAction = CommandManager::instance()->getAction("MI_ResetScanCropbox");
		if (scannerType == "TWAIN")
			setCropAction->setDisabled(true);
		else
			setCropAction->setDisabled(false);
		resetCropAction->setDisabled(true);
	}
	QDialog::accept();
}

//-----------------------------------------------------------------------------

//=============================================================================
/*! \class ScanSettingsPopup
		\brief The ScanSettingsPopup class provides a dialog to change scan settings.

		Inherits \b Dialog.
*/
//-----------------------------------------------------------------------------

ScanSettingsPopup::ScanSettingsPopup()
	: Dialog(TApp::instance()->getMainWindow(), false, true, "ScanSettings")
{
	setWindowTitle(tr("Scan Settings"));
	m_scannerNameLbl = new QLabel(tr("[no scanner]"));

	addWidget(m_scannerNameLbl);

	beginVLayout();

	m_paperFormatOm = new QComboBox();
	m_paperFormatOm->setFixedSize(150, WidgetHeight);
	std::vector<std::string> formats;
	TPaperFormatManager::instance()->getFormats(formats);
	int i;
	for (i = 0; i < (int)formats.size(); i++)
		m_paperFormatOm->addItem(QString(formats[i].c_str()));
	addWidgets(m_formatLbl = new QLabel(tr("Paper Format:")), m_paperFormatOm);

	m_reverseOrderCB = new CheckBox(tr("Reverse Order"));
	m_reverseOrderCB->setFixedSize(150, WidgetHeight);
	addWidget(m_reverseOrderCB);

	m_paperFeederCB = new CheckBox(tr("Paper Feeder"));
	m_paperFeederCB->setFixedSize(150, WidgetHeight);
	addWidget(m_paperFeederCB);

	m_dpi = new DVGui::DoubleField();
	addWidgets(m_dpiLbl = new QLabel(tr("Dpi: ")), m_dpi);
	m_dpi->hide();
	m_dpiLbl->hide();

	m_modeOm = new QComboBox();
	m_modeOm->setMaximumHeight(WidgetHeight);
	addWidgets(m_modeLbl = new QLabel(tr("Mode:")), m_modeOm);

	m_threshold = new DVGui::IntField();
	addWidgets(m_thresholdLbl = new QLabel(tr("Threshold: ")), m_threshold);
	m_threshold->hide(), m_thresholdLbl->hide();

	m_brightness = new DVGui::IntField();
	addWidgets(m_brightnessLbl = new QLabel(tr("Brightness: ")), m_brightness);
	m_brightness->hide(), m_brightnessLbl->hide();

	endVLayout();

	connectAll();
}

//------------------------------------------------------------------------------

void ScanSettingsPopup::showEvent(QShowEvent *event)
{
	connectAll();
	updateUI();
}

//------------------------------------------------------------------------------

void ScanSettingsPopup::hideEvent(QHideEvent *event)
{
	disconnectAll();
	Dialog::hideEvent(event);
}

//------------------------------------------------------------------------------

void ScanSettingsPopup::connectAll()
{
	bool ret = true;
	ret = ret && connect(m_paperFormatOm, SIGNAL(currentIndexChanged(const QString &)), SLOT(onPaperChanged(const QString &)));
	ret = ret && connect(m_reverseOrderCB, SIGNAL(stateChanged(int)), SLOT(onToggle(int)));
	ret = ret && connect(m_paperFeederCB, SIGNAL(stateChanged(int)), SLOT(onToggle(int)));
	ret = ret && connect(m_dpi, SIGNAL(valueChanged(bool)), SLOT(onValueChanged(bool)));
	ret = ret && connect(m_brightness, SIGNAL(valueChanged(bool)), SLOT(onValueChanged(bool)));
	ret = ret && connect(m_threshold, SIGNAL(valueChanged(bool)), SLOT(onValueChanged(bool)));
	ret = ret && connect(m_modeOm, SIGNAL(currentIndexChanged(const QString &)), SLOT(onModeChanged(const QString &)));
	ret = ret && connect(TApp::instance()->getCurrentScene(), SIGNAL(sceneSwitched()), SLOT(updateUI()));
	assert(ret);
}

//------------------------------------------------------------------------------

void ScanSettingsPopup::disconnectAll()
{
	bool ret = true;
	ret = ret && m_paperFormatOm->disconnect();
	ret = ret && m_reverseOrderCB->disconnect();
	ret = ret && m_paperFeederCB->disconnect();
	ret = ret && m_dpi->disconnect();
	ret = ret && m_threshold->disconnect();
	ret = ret && m_brightness->disconnect();
	ret = ret && m_modeOm->disconnect();
	ret = ret && disconnect(TApp::instance()->getCurrentScene(), SIGNAL(sceneSwitched()), this, SLOT(updateUI()));
	assert(ret);
}

//------------------------------------------------------------------------------

void ScanSettingsPopup::onValueChanged(bool)
{
	TScannerParameters *params = TApp::instance()->getCurrentScene()->getScene()->getProperties()->getScanParameters();
	params->m_dpi.m_value = m_dpi->getValue();
	params->m_threshold.m_value = m_threshold->getValue();
	params->m_brightness.m_value = m_brightness->getValue();
}

//------------------------------------------------------------------------------

void ScanSettingsPopup::onToggle(int)
{
	TScannerParameters *sp = TApp::instance()->getCurrentScene()->getScene()->getProperties()->getScanParameters();

	sp->setReverseOrder(m_reverseOrderCB->isChecked());
	sp->enablePaperFeeder(m_paperFeederCB->isChecked());
}

//-----------------------------------------------------------------------------

void ScanSettingsPopup::onPaperChanged(const QString &format)
{
	if (!ScannerHasBeenDefined)
		return;

	TScannerParameters *sp = TApp::instance()->getCurrentScene()->getScene()->getProperties()->getScanParameters();
	sp->setPaperFormat(format.toStdString());
	sp->setCropBox(sp->getScanArea());
	checkPaperFormat(sp);
}

//------------------------------------------------------------------------------

void ScanSettingsPopup::onModeChanged(const QString &mode)
{
	if (!ScannerHasBeenDefined)
		return;

	TScannerParameters *sp = TApp::instance()->getCurrentScene()->getScene()->getProperties()->getScanParameters();
	m_threshold->setVisible(false);
	m_thresholdLbl->setVisible(false);

	if (mode == BlackAndWhite) {
		sp->setScanType(TScannerParameters::BW);
		m_threshold->setVisible(true);
		m_thresholdLbl->setVisible(true);
	} else if (mode == Graytones)
		sp->setScanType(TScannerParameters::GR8);
	else if (mode == Rgbcolors)
		sp->setScanType(TScannerParameters::RGB24);
	else {
		//assert(0);
		sp->setScanType(TScannerParameters::None);
	}
}

//------------------------------------------------------------------------------

void ScanSettingsPopup::updateUI()
{
	disconnectAll();
	checkScannerDefinition();
	TScannerParameters *params = TApp::instance()->getCurrentScene()->getScene()->getProperties()->getScanParameters();
	QApplication::setOverrideCursor(Qt::WaitCursor);
	params->adaptToCurrentScanner();
	QApplication::restoreOverrideCursor();

	TScanner *scanner = TScanner::instance();
	m_scannerNameLbl->setText(scanner && scanner->getName() != "" ? scanner->getName() : "[no scanner]");

	m_reverseOrderCB->setChecked(params->isReverseOrder());
	m_paperFeederCB->setChecked(params->m_paperFeeder.m_value == 1.0);

	if (params->m_dpi.m_supported) {
		if (params->m_dpi.m_max > params->m_dpi.m_min) {
			m_dpi->setRange(params->m_dpi.m_min, params->m_dpi.m_max);
			m_dpi->setValue(params->m_dpi.m_value);
		}
		m_dpi->show(), m_dpiLbl->show();
	} else
		m_dpi->hide(), m_dpiLbl->hide();

	if (TScanner::m_isTwain) {
		m_paperFeederCB->hide();
		m_modeOm->hide(), m_modeLbl->hide();
		m_paperFormatOm->hide(), m_formatLbl->hide();
		m_threshold->hide(), m_thresholdLbl->hide();
		m_brightness->hide(), m_brightnessLbl->hide();
		connectAll();
		return;
	}
	m_paperFeederCB->show();
	m_modeOm->show(), m_modeLbl->show();
	m_paperFormatOm->show(), m_formatLbl->show();

	disconnect(m_modeOm);
	fillOutputType(m_modeOm, params);
	connect(m_modeOm, SIGNAL(currentIndexChanged(const QString &)), SLOT(onModeChanged(const QString &)));

	m_modeOm->setEnabled(true);
	switch (params->getScanType()) {
	case TScannerParameters::BW:
		m_modeOm->setCurrentIndex(m_modeOm->findText(BlackAndWhite));
		break;
	case TScannerParameters::GR8:
		m_modeOm->setCurrentIndex(m_modeOm->findText(Graytones));
		break;
	case TScannerParameters::RGB24:
		m_modeOm->setCurrentIndex(m_modeOm->findText(Rgbcolors));
		break;
	default:
		m_modeOm->setEnabled(false);
		break;
	}

	m_paperFormatOm->setCurrentIndex(m_paperFormatOm->findText(QString::fromStdString(params->getPaperFormat())));

	if (params->m_threshold.m_supported) {
		m_threshold->setRange(params->m_threshold.m_min, params->m_threshold.m_max);
		m_threshold->setValue(params->m_threshold.m_value);
		if (params->getScanType() == TScannerParameters::BW) {
			m_threshold->show();
			m_thresholdLbl->show();
		} else {
			m_threshold->hide();
			m_thresholdLbl->hide();
		}
	}
	if (params->m_brightness.m_supported) {
		if (params->m_brightness.m_max > params->m_brightness.m_min) {
			m_brightness->setRange(params->m_brightness.m_min, params->m_brightness.m_max);
			m_brightness->setValue(params->m_brightness.m_value);
		}
		m_brightness->show(), m_brightnessLbl->show();
	} else
		m_brightness->hide(), m_brightnessLbl->hide();

	connectAll();
}
#ifdef LINETEST
//-----------------------------------------------------------------------------

AutocenterPopup::AutocenterPopup()
	: DVGui::Dialog(0, false, true)
{
	setWindowTitle(tr("Autocenter"));

	QGridLayout *settingsLayout = new QGridLayout(this);
	settingsLayout->setSizeConstraint(QLayout::SetFixedSize);
	settingsLayout->setSpacing(5);
	settingsLayout->setMargin(12);
	int row = 0;

	//AutoCenter
	QWidget *w = new QWidget();
	w->setFixedWidth(70);
	settingsLayout->addWidget(w, row, 0);
	m_autocenter = new CheckBox(tr("Autocenter"), this);
	m_autocenter->setFixedSize(150, WidgetHeight);
	settingsLayout->addWidget(m_autocenter, row, 1, Qt::AlignLeft);
	++row;

	//Pegbar Holse
	settingsLayout->addWidget(new QLabel(tr("Pegbar Holes:")), row, 0, Qt::AlignRight);
	m_pegbarHoles = new QComboBox(this);
	m_pegbarHoles->setFixedHeight(WidgetHeight);
	m_pegbarHoles->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Maximum);
	QStringList pegbarHoles;
	pegbarHoles << "Bottom"
				<< "Top"
				<< "Left"
				<< "Right";
	m_pegbarHoles->addItems(pegbarHoles);
	settingsLayout->addWidget(m_pegbarHoles, row, 1, Qt::AlignLeft);
	++row;

	//Feld Guide
	settingsLayout->addWidget(new QLabel(tr("Field Guide:")), row, 0, Qt::AlignRight);
	m_fieldGuide = new QComboBox(this);
	m_fieldGuide->setFixedHeight(WidgetHeight);
	m_fieldGuide->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Maximum);
	std::vector<std::string> fdgNames;
	CleanupParameters::getFdgNames(fdgNames);
	int i;
	for (i = 0; i < (int)fdgNames.size(); i++)
		m_fieldGuide->addItem(QString(fdgNames[i].c_str()));
	settingsLayout->addWidget(m_fieldGuide, row, 1, Qt::AlignLeft);
	++row;

	beginHLayout();
	addLayout(settingsLayout, false);
	endHLayout();

	bool ret = true;
	ret = ret && connect(m_autocenter, SIGNAL(toggled(bool)), this, SLOT(onAutocenterToggled(bool)));
	ret = ret && connect(m_pegbarHoles, SIGNAL(currentIndexChanged(const QString &)), this, SLOT(onPegbarHolesChanged(const QString &)));
	ret = ret && connect(m_fieldGuide, SIGNAL(currentIndexChanged(const QString &)), this, SLOT(onFieldGuideChanged(const QString &)));
	assert(ret);
}

//-----------------------------------------------------------------------------

void AutocenterPopup::showEvent(QShowEvent *e)
{
	CleanupParameters *cp = TApp::instance()->getCurrentScene()->getScene()->getProperties()->getCleanupParameters();
	m_autocenter->setChecked(cp->m_autocenterType == AUTOCENTER_FDG);

	CleanupTypes::PEGS_SIDE type = cp->m_pegSide;
	switch (cp->m_pegSide) {
	case PEGS_BOTTOM:
		m_pegbarHoles->setCurrentIndex(0);
		break;
	case PEGS_TOP:
		m_pegbarHoles->setCurrentIndex(1);
		break;
	case PEGS_LEFT:
		m_pegbarHoles->setCurrentIndex(2);
		break;
	case PEGS_RIGHT:
		m_pegbarHoles->setCurrentIndex(3);
		break;
	default:
		assert(false);
	}

	QString fieldName = QString::fromStdString(cp->getFdgName());
	int index = (fieldName == "") ? 0 : m_fieldGuide->findText(fieldName);
	assert(index != -1);
	m_fieldGuide->setCurrentIndex(index);
}

//-----------------------------------------------------------------------------

void AutocenterPopup::onAutocenterToggled(bool toggled)
{
	CleanupParameters *cp = TApp::instance()->getCurrentScene()->getScene()->getProperties()->getCleanupParameters();
	cp->m_autocenterType = toggled ? AUTOCENTER_FDG : AUTOCENTER_NONE;
}

//-----------------------------------------------------------------------------

void AutocenterPopup::onPegbarHolesChanged(const QString &pg)
{
	CleanupParameters *cp = TApp::instance()->getCurrentScene()->getScene()->getProperties()->getCleanupParameters();
	CleanupTypes::PEGS_SIDE type;
	if (pg == "Bottom")
		type = PEGS_BOTTOM;
	if (pg == "Top")
		type = PEGS_TOP;
	if (pg == "Left")
		type = PEGS_LEFT;
	if (pg == "Right")
		type = PEGS_RIGHT;
	if (cp->m_pegSide == type)
		return;
	cp->m_pegSide = type;
}

//-----------------------------------------------------------------------------

void AutocenterPopup::onFieldGuideChanged(const QString &fg)
{
	CleanupParameters *cp = TApp::instance()->getCurrentScene()->getScene()->getProperties()->getCleanupParameters();
	if (cp->getFdgName() == fg.toStdString())
		return;
	cp->setFdgByName(fg.toStdString());
}

//-----------------------------------------------------------------------------
#endif

MyScannerListener::MyScannerListener(const ScanList &scanList)
	: m_scanList(scanList), m_current(0), m_inc(+1), m_isCanceled(false), m_progressDialog(0)
{
	TScannerParameters *parameters = TApp::instance()
										 ->getCurrentScene()
										 ->getScene()
										 ->getProperties()
										 ->getScanParameters();

	m_isPreview = parameters->isPreview();
	if (m_isPreview)
		return;
	if (parameters->isPaperFeederEnabled()) {
		int frameCount = m_scanList.getFrameCount();
		ScanListFrame frame = m_scanList.getFrame(m_current);
		TXshSimpleLevel *newXl = frame.getLevel();
		TFilePath levelName(newXl->getName());
		QString imageName = toQString(levelName.withFrame(frame.getFrameId())) + QString(".tif");
		QString text = tr("Scanning in progress: ") + imageName + " 1/" + QString::number(frameCount);
		m_progressDialog = new DVGui::ProgressDialog(text, QObject::tr("Cancel"), 0, frameCount);
		connect(m_progressDialog, SIGNAL(canceled()), this, SLOT(cancelButtonPressed()));
		m_progressDialog->setWindowModality(Qt::WindowModal);
		m_progressDialog->show();
	}
	if (parameters->isReverseOrder()) {
		m_current = m_scanList.getFrameCount() - 1;
		m_inc = -1;
	}
}

//-----------------------------------------------------------------------------

void MyScannerListener::onImage(const TRasterImageP &rasImg)
{
	if (!rasImg || !rasImg->getRaster()) {
		DVGui::warning(tr("The pixel type is not supported."));
		m_current += m_inc;
		return;
	}
	if (!m_isPreview && (m_current < 0 || m_current >= m_scanList.getFrameCount())) {
		DVGui::warning(tr("The scanning process is completed."));
		return;
	}
	if (m_isPreview) {
		TImageCache::instance()->add((std::string) "setScanCropboxId", rasImg.getPointer());
	} else {
#ifdef LINETEST
		//Autocenter
		CleanupParameters *cp = TApp::instance()->getCurrentScene()->getScene()->getProperties()->getCleanupParameters();
		if (cp->m_autocenterType != AUTOCENTER_NONE) {
			bool autocentered;
			TCleanupper *cl = TCleanupper::instance();
			cl->setParameters(cp);
			TRasterImageP outImg = cl->autocenterOnly(rasImg, false, autocentered);
			if (!autocentered)
				DVGui::warning(QObject::tr("The autocentering failed on the current drawing."));
			else
				rasImg->setRaster(outImg->getRaster());
		}
		makeTransparent(rasImg->getRaster());
#endif
		TScannerParameters *params = TApp::instance()->getCurrentScene()->getScene()->getProperties()->getScanParameters();

		ScanListFrame frame = m_scanList.getFrame(m_current);
		bool isBW = false;
		if (params->getScanType() == TScannerParameters::BW) {
			isBW = true;
			rasImg->setScanBWFlag(true);
			Tiio::Writer::setBlackAndWhiteThreshold(params->m_threshold.m_value);
		}
		frame.setRasterImage(rasImg, isBW);

		TApp::instance()->getCurrentFrame()->setFid(frame.getFrameId());
		TApp::instance()->getCurrentScene()->notifyCastChange();
		TApp::instance()->getCurrentLevel()->notifyLevelChange();

		m_current += m_inc;
	}
}

//-----------------------------------------------------------------------------

void MyScannerListener::onError()
{
	if (m_progressDialog)
		m_progressDialog->hide();
	DVGui::warning(tr("There was an error during the scanning process."));
}

//-----------------------------------------------------------------------------

void MyScannerListener::onNextPaper()
{
	assert(!m_isPreview);
	if (TScanner::instance()->m_isTwain)
		DVGui::info(tr("Please, place the next paper drawing on the scanner flatbed, then select the relevant command in the TWAIN interface."));
	else {
		QString question(tr("Please, place the next paper drawing on the scanner flatbed, then click the Scan button."));
		int ret = DVGui::MsgBox(question, QObject::tr("Scan"), QObject::tr("Cancel"), 0);
		if (ret == 2 || ret == 0)
			m_isCanceled = true;
	}
}

//-----------------------------------------------------------------------------

void MyScannerListener::onAutomaticallyNextPaper()
{
	assert(!m_isPreview);
	assert(!!m_progressDialog);
	int frameCount = m_scanList.getFrameCount();
	int step = m_inc == -1 ? frameCount - m_current - 1 : m_current;
	if (step < frameCount) {
		ScanListFrame frame = m_scanList.getFrame(m_current);
		TXshSimpleLevel *newXl = frame.getLevel();
		TFilePath levelName(newXl->getName());
		QString imageName = toQString(levelName.withFrame(frame.getFrameId())) + QString(".tif");
		m_progressDialog->setLabelText(tr("Scanning in progress: ") + imageName + QString::number(m_current + 1) + " /" + QString::number(frameCount));
	}
	m_progressDialog->setValue(step);
	if (m_progressDialog && (step == frameCount))
		m_progressDialog->hide();
}

//-----------------------------------------------------------------------------

bool MyScannerListener::isCanceled()
{
	return m_isCanceled;
}

//-----------------------------------------------------------------------------

void MyScannerListener::cancelButtonPressed()
{
	assert(!!m_progressDialog);
	m_isCanceled = true;
}

//=============================================================================
//
void doScan()
{
	if (!checkScannerDefinition())
		return;
	ScanList scanList;
	if (scanList.areScannedFramesSelected()) {
		int ret = DVGui::MsgBox(QObject::tr("Some of the selected drawings were already scanned. Do you want to scan them again?"),
						 QObject::tr("Scan"), QObject::tr("Don't Scan"), QObject::tr("Cancel"));
		if (ret == 3)
			return;
		scanList.update(ret == 1);
	} else
		scanList.update(true);

	if (scanList.getFrameCount() == 0) {
		DVGui::warning(QObject::tr("There are no frames to scan."));
		return;
	}

	try {
		TScanner *scanner = TScanner::instance();

		int rc = scanner->isDeviceAvailable();
		if (!rc) {
			DVGui::warning(QObject::tr("TWAIN is not available."));
			return;
		}

		MyScannerListener lst(scanList);
		scanner->addListener(&lst);

		TScannerParameters *sp = TApp::instance()->getCurrentScene()->getScene()->getProperties()->getScanParameters();
		sp->adaptToCurrentScannerIfNeeded();
		scanner->acquire(*sp, scanList.getFrameCount());
		scanner->removeListener(&lst);

		SetScanCropboxCheck *cropboxCheck = SetScanCropboxCheck::instance();
		if (cropboxCheck->isEnabled())
			cropboxCheck->uncheck();
	} catch (TException &e) {
		DVGui::warning(QString::fromStdWString(e.getMessage()));
	}

	//If some levels were scanned successfully, their renumber table must be updated.

	//A level's renumber table is usually updated when it is either loaded or before saving -
	//this is a similar case, where a level is filled with frames.
	//An empty renumber table means that a renumbering operation was carried out with all frames
	//being eradicated - which may lead to the level being saved with missing frames.
	int i, frameCount = scanList.getFrameCount();
	TXshSimpleLevel *oldLevel = 0, *level;
	for (i = 0; i < frameCount; ++i) {
		level = scanList.getFrame(i).getLevel();
		if (level != oldLevel)
			level->setRenumberTable();
		oldLevel = level;
	}
}

//-----------------------------------------------------------------------------

OpenPopupCommandHandler<DefineScannerPopup> openDefineScannerPopup(MI_DefineScanner);

OpenPopupCommandHandler<ScanSettingsPopup> openScanSettingsPopup(MI_ScanSettings);

#ifdef LINETEST
OpenPopupCommandHandler<AutocenterPopup> openAutocenterPopup(MI_Autocenter);
#endif

class ScanCommand : public MenuItemHandler
{
public:
	ScanCommand() : MenuItemHandler("MI_Scan") {}
	void execute()
	{
		doScan();
	}
} ScanCommand;

//=========================================================================================
//
//SetCropboxCommand
//
//=========================================================================================

class SetCropboxCommand : public MenuItemHandler
{

	TTool *m_currentTool;

public:
	SetCropboxCommand()
		: MenuItemHandler("MI_SetScanCropbox"), m_currentTool(0)
	{
	}

	void execute()
	{
		TApp *app = TApp::instance();
		SetScanCropboxCheck *cropboxCheck = SetScanCropboxCheck::instance();
		cropboxCheck->setIsEnabled(!cropboxCheck->isEnabled());

		TScannerParameters *sp = TApp::instance()->getCurrentScene()->getScene()->getProperties()->getScanParameters();
		QAction *resetCropAction = CommandManager::instance()->getAction("MI_ResetScanCropbox");
		if (!cropboxCheck->isEnabled()) {
			if (m_currentTool)
				app->getCurrentTool()->setTool(QString::fromStdString(m_currentTool->getName()));
			return;
		}

		if (!checkScannerDefinition())
			return;
		ScanList scanList;
		scanList.update(true);
		try {
			TScanner *scanner = TScanner::instance();

			int rc = scanner->isDeviceAvailable();
			if (!rc) {
				DVGui::warning(QObject::tr("TWAIN is not available."));
				return;
			}

			double currentDPI = sp->m_dpi.m_value;
			sp->m_dpi.m_value = previewDPI;
			double reverse = sp->isReverseOrder();
			sp->setReverseOrder(false);
			sp->setIsPreview(true);

			MyScannerListener lst(scanList);
			scanner->addListener(&lst);

			sp->adaptToCurrentScannerIfNeeded();
			scanner->acquire(*sp, 1);
			scanner->removeListener(&lst);
			sp->m_dpi.m_value = currentDPI;
			sp->setReverseOrder(reverse);

			m_currentTool = app->getCurrentTool()->getTool();
			app->getCurrentTool()->setTool("T_SetScanCropbox");
			sp->setIsPreview(false);
			if (resetCropAction)
				resetCropAction->setDisabled(false);
		} catch (TException &e) {
			DVGui::warning(QString::fromStdWString(e.getMessage()));
		}
	}
} setCropboxCommand;

//=========================================================================================
//
//ResetCropboxCommand
//
//=========================================================================================

class ResetCropboxCommand : public MenuItemHandler
{
public:
	ResetCropboxCommand() : MenuItemHandler("MI_ResetScanCropbox") {}

	void execute()
	{
		TScannerParameters *sp = TApp::instance()->getCurrentScene()->getScene()->getProperties()->getScanParameters();
		sp->setCropBox(sp->getScanArea());
	}
} resetCropboxCommand;

//=========================================================================================
//
//SetScanCropboxTool
//
//=========================================================================================

class SetScanCropboxTool : public TTool
{
	const std::string m_imgId;
	TScannerParameters *m_parameters;
	int m_scaling;
	TPointD m_lastPos;
	enum { eNone,
		   eMove,
		   e00,
		   e01,
		   e10,
		   e11,
		   eM0,
		   e1M,
		   eM1,
		   e0M };

public:
	SetScanCropboxTool()
		: TTool("T_SetScanCropbox"), m_imgId("setScanCropboxId"), m_scaling(eNone), m_lastPos()
	{
		bind(TTool::AllTargets); // Deals with tool deactivation internally
	}

	//-----------------------------------------------------------------------------

	ToolType getToolType() const { return TTool::GenericTool; }

	//-----------------------------------------------------------------------------

	void draw()
	{
		TRasterImageP ri = TImageCache::instance()->get(m_imgId, false);
		if (ri) {
			TPointD center = ri->getRaster()->getCenterD();
			GLRasterPainter::drawRaster(TScale(Stage::inch / previewDPI, Stage::inch / previewDPI), ri, true);
		}

		TRectD cropBox = rect2pix(m_parameters->getCropBox());
		double pixelSize = getPixelSize();

		tglColor(TPixel::Red);
		glLineStipple(1, 0xFFFF);
		glEnable(GL_LINE_STIPPLE);

		tglDrawRect(cropBox);

		TPointD size(10, 10);
		tglColor(TPixel::Red);
		ToolUtils::drawSquare(cropBox.getP00(), pixelSize * 4, TPixel::Red);
		ToolUtils::drawSquare(cropBox.getP01(), pixelSize * 4, TPixel::Red);
		ToolUtils::drawSquare(cropBox.getP10(), pixelSize * 4, TPixel::Red);
		ToolUtils::drawSquare(cropBox.getP11(), pixelSize * 4, TPixel::Red);

		TPointD center = (cropBox.getP00() + cropBox.getP11()) * 0.5;

		ToolUtils::drawSquare(TPointD(center.x, cropBox.y0), pixelSize * 4, TPixel::Red); //draw M0 handle
		ToolUtils::drawSquare(TPointD(cropBox.x1, center.y), pixelSize * 4, TPixel::Red); //draw 1M handle
		ToolUtils::drawSquare(TPointD(center.x, cropBox.y1), pixelSize * 4, TPixel::Red); //draw M1 handle
		ToolUtils::drawSquare(TPointD(cropBox.x0, center.y), pixelSize * 4, TPixel::Red); //draw 0M handle

		glDisable(GL_LINE_STIPPLE);
	}

	//-----------------------------------------------------------------------------

	void mouseMove(const TPointD &p, const TMouseEvent &e)
	{
		double pixelSize = getPixelSize();
		TPointD size(10 * pixelSize, 10 * pixelSize);
		TRectD cropBox = rect2pix(m_parameters->getCropBox());

		double maxDist = 5 * pixelSize;

		if (TRectD(cropBox.getP00() - size, cropBox.getP00() + size).contains(p))
			m_scaling = e00;
		else if (TRectD(cropBox.getP01() - size, cropBox.getP01() + size).contains(p))
			m_scaling = e01;
		else if (TRectD(cropBox.getP11() - size, cropBox.getP11() + size).contains(p))
			m_scaling = e11;
		else if (TRectD(cropBox.getP10() - size, cropBox.getP10() + size).contains(p))
			m_scaling = e10;
		else if (isCloseToSegment(p, TSegment(cropBox.getP00(), cropBox.getP10()), maxDist))
			m_scaling = eM0;
		else if (isCloseToSegment(p, TSegment(cropBox.getP10(), cropBox.getP11()), maxDist))
			m_scaling = e1M;
		else if (isCloseToSegment(p, TSegment(cropBox.getP11(), cropBox.getP01()), maxDist))
			m_scaling = eM1;
		else if (isCloseToSegment(p, TSegment(cropBox.getP01(), cropBox.getP00()), maxDist))
			m_scaling = e0M;
		else if (cropBox.contains(p))
			m_scaling = eMove;
		else
			m_scaling = eNone;
	}

	//-----------------------------------------------------------------------------

	void leftButtonDown(const TPointD &pos, const TMouseEvent &e)
	{
		m_lastPos = pos;
	}

	//-----------------------------------------------------------------------------

	void leftButtonDrag(const TPointD &pos, const TMouseEvent &e)
	{
		TPointD dp = pos - m_lastPos;
		double scaleFactor = Stage::inch / previewDPI;
		dp.x = ((dp.x / scaleFactor) * 25.4) / previewDPI;
		dp.y = ((dp.y / scaleFactor) * 25.4) / previewDPI;

		TRectD scanArea = m_parameters->getScanArea();
		TRectD cropBox = m_parameters->getCropBox();
		if (m_scaling != eNone && m_scaling != eMove) {
			if ((m_scaling == eM1 || ((m_scaling == e11 || m_scaling == e01) && !e.isShiftPressed())) &&
				cropBox.x0 - dp.y < cropBox.x1)
				cropBox.x0 -= dp.y;
			if ((m_scaling == eM0 || ((m_scaling == e10 || m_scaling == e00) && !e.isShiftPressed())) &&
				cropBox.x1 - dp.y > cropBox.x0)
				cropBox.x1 -= dp.y;
			if ((m_scaling == e0M || ((m_scaling == e00 || m_scaling == e01) && !e.isShiftPressed())) &&
				cropBox.y1 - dp.x > cropBox.y0)
				cropBox.y1 -= dp.x;
			if ((m_scaling == e1M || ((m_scaling == e11 || m_scaling == e10) && !e.isShiftPressed())) &&
				cropBox.y0 - dp.x < cropBox.y1)
				cropBox.y0 -= dp.x;

			if (e.isShiftPressed()) {
				TPointD delta;
				delta.x = (fabs(dp.x) > fabs(dp.y)) ? dp.x : dp.y;
				delta.y = delta.x * scanArea.getLx() / scanArea.getLy();

				if (m_scaling == e11) {
					if (cropBox.y0 - delta.x < cropBox.y1)
						cropBox.y0 -= delta.x;
					if (cropBox.x0 - delta.y < cropBox.x1)
						cropBox.x0 -= delta.y;
				} else if (m_scaling == e00) {
					if (cropBox.y1 - delta.x > cropBox.y0)
						cropBox.y1 -= delta.x;
					if (cropBox.x1 - delta.y > cropBox.x0)
						cropBox.x1 -= delta.y;
				} else if (m_scaling == e01) {
					if (cropBox.y1 - delta.x > cropBox.y0)
						cropBox.y1 -= delta.x;
					if (cropBox.x0 - delta.y < cropBox.x1)
						cropBox.x0 -= delta.y;
				}
				if (m_scaling == e10) {
					if (cropBox.y0 - delta.x < cropBox.y1)
						cropBox.y0 -= delta.x;
					if (cropBox.x1 - delta.y > cropBox.x0)
						cropBox.x1 -= delta.y;
				}
			}
			cropBox *= scanArea;
			if (cropBox != m_parameters->getCropBox()) {
				m_parameters->setCropBox(cropBox);
				m_lastPos = pos;
			}
		} else if (m_scaling == eMove) {
			cropBox += TPointD(-dp.y, 0);
			if (scanArea.contains(cropBox))
				m_parameters->setCropBox(cropBox);
			cropBox += TPointD(0, -dp.x);
			if (scanArea.contains(cropBox))
				m_parameters->setCropBox(cropBox);
			m_lastPos = pos;
		}
		invalidate();
	}

	//-----------------------------------------------------------------------------

	int getCursorId() const
	{
		switch (m_scaling) {
		case eNone: return ToolCursor::StrokeSelectCursor;
		case eMove: return ToolCursor::MoveCursor;
		case e11: case e00: return ToolCursor::ScaleCursor;
		case e10: case e01: return ToolCursor::ScaleInvCursor;
		case e1M: case e0M: return ToolCursor::ScaleHCursor;
		case eM1: case eM0: return ToolCursor::ScaleVCursor;
		default:
			assert(false);
		}
		return 0;
	}

	//-----------------------------------------------------------------------------

	void onActivate()
	{
		m_parameters = TTool::getApplication()->getCurrentScene()->getScene()->getProperties()->getScanParameters();
	}

	void onEnter()
	{
		m_parameters = TTool::getApplication()->getCurrentScene()->getScene()->getProperties()->getScanParameters();
	}

	//-----------------------------------------------------------------------------

private:
	TRectD rect2pix(const TRectD &rect)
	{
		const double f = 25.4;
		TRectD scanArea = m_parameters->getScanArea();
		TPointD scanAreaCenter = (scanArea.getP00() + scanArea.getP11()) * 0.5;
		double scaleFactor = Stage::inch / previewDPI;

		double cbOffsetx = (((rect.x0 - scanAreaCenter.x) * previewDPI) / f) * scaleFactor;
		double cbOffsety = (((rect.y0 - scanAreaCenter.y) * previewDPI) / f) * scaleFactor;
		double cbSizelx = (((rect.x1 - rect.x0) * previewDPI) / f) * scaleFactor;
		double cbSizely = (((rect.y1 - rect.y0) * previewDPI) / f) * scaleFactor;

		TRectD rectPix(TPointD(cbOffsetx, cbOffsety), TDimensionD(cbSizelx, cbSizely));
		return TRectD(-rectPix.y1,
					  -rectPix.x1,
					  -rectPix.y0,
					  -rectPix.x0);
	}
} setScanCropboxTool;


text:
using System;
using System.Collections.Generic;

namespace SomeBasicNHApp.Core.Entities
{
    public class Order
    {
        public virtual Customer Customer { get; set; }

        public virtual DateTime OrderDate { get; set; }

        public virtual int Id { get; set; }

        public virtual IList<Product> Products { get; set; }

        public virtual int Version { get; set; }

    }
}