code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! FixedHeader 2.1.2 * ©2010-2014 SpryMedia Ltd - datatables.net/license */ /** * @summary FixedHeader * @description Fix a table's header or footer, so it is always visible while * Scrolling * @version 2.1.2 * @file dataTables.fixedHeader.js * @author SpryMedia Ltd (www.sprymedia.co.uk) * @contact www.sprymedia.co.uk/contact * @copyright Copyright 2009-2014 SpryMedia Ltd. * * This source file is free software, available under the following license: * MIT license - http://datatables.net/license/mit * * This source file is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details. * * For details please refer to: http://www.datatables.net */ /* Global scope for FixedColumns for backwards compatibility - will be removed * in future. Not documented in 1.1.x. */ /* Global scope for FixedColumns */ var FixedHeader; (function(window, document, undefined) { var factory = function( $, DataTable ) { "use strict"; /* * Function: FixedHeader * Purpose: Provide 'fixed' header, footer and columns for a DataTable * Returns: object:FixedHeader - must be called with 'new' * Inputs: mixed:mTable - target table * @param {object} dt DataTables instance or HTML table node. With DataTables * 1.10 this can also be a jQuery collection (with just a single table in its * result set), a jQuery selector, DataTables API instance or settings * object. * @param {object} [oInit] initialisation settings, with the following * properties (each optional) * * bool:top - fix the header (default true) * * bool:bottom - fix the footer (default false) * * int:left - fix the left column(s) (default 0) * * int:right - fix the right column(s) (default 0) * * int:zTop - fixed header zIndex * * int:zBottom - fixed footer zIndex * * int:zLeft - fixed left zIndex * * int:zRight - fixed right zIndex */ FixedHeader = function ( mTable, oInit ) { /* Sanity check - you just know it will happen */ if ( ! this instanceof FixedHeader ) { alert( "FixedHeader warning: FixedHeader must be initialised with the 'new' keyword." ); return; } var that = this; var oSettings = { "aoCache": [], "oSides": { "top": true, "bottom": false, "left": 0, "right": 0 }, "oZIndexes": { "top": 104, "bottom": 103, "left": 102, "right": 101 }, "oCloneOnDraw": { "top": false, "bottom": false, "left": true, "right": true }, "oMes": { "iTableWidth": 0, "iTableHeight": 0, "iTableLeft": 0, "iTableRight": 0, /* note this is left+width, not actually "right" */ "iTableTop": 0, "iTableBottom": 0 /* note this is top+height, not actually "bottom" */ }, "oOffset": { "top": 0 }, "nTable": null, "bFooter": false, "bInitComplete": false }; /* * Function: fnGetSettings * Purpose: Get the settings for this object * Returns: object: - settings object * Inputs: - */ this.fnGetSettings = function () { return oSettings; }; /* * Function: fnUpdate * Purpose: Update the positioning and copies of the fixed elements * Returns: - * Inputs: - */ this.fnUpdate = function () { this._fnUpdateClones(); this._fnUpdatePositions(); }; /* * Function: fnPosition * Purpose: Update the positioning of the fixed elements * Returns: - * Inputs: - */ this.fnPosition = function () { this._fnUpdatePositions(); }; var dt = $.fn.dataTable.Api ? new $.fn.dataTable.Api( mTable ).settings()[0] : mTable.fnSettings(); dt._oPluginFixedHeader = this; /* Let's do it */ this.fnInit( dt, oInit ); }; /* * Variable: FixedHeader * Purpose: Prototype for FixedHeader * Scope: global */ FixedHeader.prototype = { /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Initialisation */ /* * Function: fnInit * Purpose: The "constructor" * Returns: - * Inputs: {as FixedHeader function} */ fnInit: function ( oDtSettings, oInit ) { var s = this.fnGetSettings(); var that = this; /* Record the user definable settings */ this.fnInitSettings( s, oInit ); if ( oDtSettings.oScroll.sX !== "" || oDtSettings.oScroll.sY !== "" ) { alert( "FixedHeader 2 is not supported with DataTables' scrolling mode at this time" ); return; } s.nTable = oDtSettings.nTable; oDtSettings.aoDrawCallback.unshift( { "fn": function () { FixedHeader.fnMeasure(); that._fnUpdateClones.call(that); that._fnUpdatePositions.call(that); }, "sName": "FixedHeader" } ); s.bFooter = ($('>tfoot', s.nTable).length > 0) ? true : false; /* Add the 'sides' that are fixed */ if ( s.oSides.top ) { s.aoCache.push( that._fnCloneTable( "fixedHeader", "FixedHeader_Header", that._fnCloneThead ) ); } if ( s.oSides.bottom ) { s.aoCache.push( that._fnCloneTable( "fixedFooter", "FixedHeader_Footer", that._fnCloneTfoot ) ); } if ( s.oSides.left ) { s.aoCache.push( that._fnCloneTable( "fixedLeft", "FixedHeader_Left", that._fnCloneTLeft, s.oSides.left ) ); } if ( s.oSides.right ) { s.aoCache.push( that._fnCloneTable( "fixedRight", "FixedHeader_Right", that._fnCloneTRight, s.oSides.right ) ); } /* Event listeners for window movement */ FixedHeader.afnScroll.push( function () { that._fnUpdatePositions.call(that); } ); $(window).resize( function () { FixedHeader.fnMeasure(); that._fnUpdateClones.call(that); that._fnUpdatePositions.call(that); } ); $(s.nTable) .on('column-reorder.dt', function () { FixedHeader.fnMeasure(); that._fnUpdateClones( true ); that._fnUpdatePositions(); } ) .on('column-visibility.dt', function () { FixedHeader.fnMeasure(); that._fnUpdateClones( true ); that._fnUpdatePositions(); } ); /* Get things right to start with */ FixedHeader.fnMeasure(); that._fnUpdateClones(); that._fnUpdatePositions(); s.bInitComplete = true; }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Support functions */ /* * Function: fnInitSettings * Purpose: Take the user's settings and copy them to our local store * Returns: - * Inputs: object:s - the local settings object * object:oInit - the user's settings object */ fnInitSettings: function ( s, oInit ) { if ( oInit !== undefined ) { if ( oInit.top !== undefined ) { s.oSides.top = oInit.top; } if ( oInit.bottom !== undefined ) { s.oSides.bottom = oInit.bottom; } if ( typeof oInit.left == 'boolean' ) { s.oSides.left = oInit.left ? 1 : 0; } else if ( oInit.left !== undefined ) { s.oSides.left = oInit.left; } if ( typeof oInit.right == 'boolean' ) { s.oSides.right = oInit.right ? 1 : 0; } else if ( oInit.right !== undefined ) { s.oSides.right = oInit.right; } if ( oInit.zTop !== undefined ) { s.oZIndexes.top = oInit.zTop; } if ( oInit.zBottom !== undefined ) { s.oZIndexes.bottom = oInit.zBottom; } if ( oInit.zLeft !== undefined ) { s.oZIndexes.left = oInit.zLeft; } if ( oInit.zRight !== undefined ) { s.oZIndexes.right = oInit.zRight; } if ( oInit.offsetTop !== undefined ) { s.oOffset.top = oInit.offsetTop; } if ( oInit.alwaysCloneTop !== undefined ) { s.oCloneOnDraw.top = oInit.alwaysCloneTop; } if ( oInit.alwaysCloneBottom !== undefined ) { s.oCloneOnDraw.bottom = oInit.alwaysCloneBottom; } if ( oInit.alwaysCloneLeft !== undefined ) { s.oCloneOnDraw.left = oInit.alwaysCloneLeft; } if ( oInit.alwaysCloneRight !== undefined ) { s.oCloneOnDraw.right = oInit.alwaysCloneRight; } } }, /* * Function: _fnCloneTable * Purpose: Clone the table node and do basic initialisation * Returns: - * Inputs: - */ _fnCloneTable: function ( sType, sClass, fnClone, iCells ) { var s = this.fnGetSettings(); var nCTable; /* We know that the table _MUST_ has a DIV wrapped around it, because this is simply how * DataTables works. Therefore, we can set this to be relatively position (if it is not * alreadu absolute, and use this as the base point for the cloned header */ if ( $(s.nTable.parentNode).css('position') != "absolute" ) { s.nTable.parentNode.style.position = "relative"; } /* Just a shallow clone will do - we only want the table node */ nCTable = s.nTable.cloneNode( false ); nCTable.removeAttribute( 'id' ); var nDiv = document.createElement( 'div' ); nDiv.style.position = "absolute"; nDiv.style.top = "0px"; nDiv.style.left = "0px"; nDiv.className += " FixedHeader_Cloned "+sType+" "+sClass; /* Set the zIndexes */ if ( sType == "fixedHeader" ) { nDiv.style.zIndex = s.oZIndexes.top; } if ( sType == "fixedFooter" ) { nDiv.style.zIndex = s.oZIndexes.bottom; } if ( sType == "fixedLeft" ) { nDiv.style.zIndex = s.oZIndexes.left; } else if ( sType == "fixedRight" ) { nDiv.style.zIndex = s.oZIndexes.right; } /* remove margins since we are going to position it absolutely */ nCTable.style.margin = "0"; /* Insert the newly cloned table into the DOM, on top of the "real" header */ nDiv.appendChild( nCTable ); document.body.appendChild( nDiv ); return { "nNode": nCTable, "nWrapper": nDiv, "sType": sType, "sPosition": "", "sTop": "", "sLeft": "", "fnClone": fnClone, "iCells": iCells }; }, /* * Function: _fnMeasure * Purpose: Get the current positioning of the table in the DOM * Returns: - * Inputs: - */ _fnMeasure: function () { var s = this.fnGetSettings(), m = s.oMes, jqTable = $(s.nTable), oOffset = jqTable.offset(), iParentScrollTop = this._fnSumScroll( s.nTable.parentNode, 'scrollTop' ), iParentScrollLeft = this._fnSumScroll( s.nTable.parentNode, 'scrollLeft' ); m.iTableWidth = jqTable.outerWidth(); m.iTableHeight = jqTable.outerHeight(); m.iTableLeft = oOffset.left + s.nTable.parentNode.scrollLeft; m.iTableTop = oOffset.top + iParentScrollTop; m.iTableRight = m.iTableLeft + m.iTableWidth; m.iTableRight = FixedHeader.oDoc.iWidth - m.iTableLeft - m.iTableWidth; m.iTableBottom = FixedHeader.oDoc.iHeight - m.iTableTop - m.iTableHeight; }, /* * Function: _fnSumScroll * Purpose: Sum node parameters all the way to the top * Returns: int: sum * Inputs: node:n - node to consider * string:side - scrollTop or scrollLeft */ _fnSumScroll: function ( n, side ) { var i = n[side]; while ( n = n.parentNode ) { if ( n.nodeName == 'HTML' || n.nodeName == 'BODY' ) { break; } i = n[side]; } return i; }, /* * Function: _fnUpdatePositions * Purpose: Loop over the fixed elements for this table and update their positions * Returns: - * Inputs: - */ _fnUpdatePositions: function () { var s = this.fnGetSettings(); this._fnMeasure(); for ( var i=0, iLen=s.aoCache.length ; i<iLen ; i++ ) { if ( s.aoCache[i].sType == "fixedHeader" ) { this._fnScrollFixedHeader( s.aoCache[i] ); } else if ( s.aoCache[i].sType == "fixedFooter" ) { this._fnScrollFixedFooter( s.aoCache[i] ); } else if ( s.aoCache[i].sType == "fixedLeft" ) { this._fnScrollHorizontalLeft( s.aoCache[i] ); } else { this._fnScrollHorizontalRight( s.aoCache[i] ); } } }, /* * Function: _fnUpdateClones * Purpose: Loop over the fixed elements for this table and call their cloning functions * Returns: - * Inputs: - */ _fnUpdateClones: function ( full ) { var s = this.fnGetSettings(); if ( full ) { // This is a little bit of a hack to force a full clone draw. When // `full` is set to true, we want to reclone the source elements, // regardless of the clone-on-draw settings s.bInitComplete = false; } for ( var i=0, iLen=s.aoCache.length ; i<iLen ; i++ ) { s.aoCache[i].fnClone.call( this, s.aoCache[i] ); } if ( full ) { s.bInitComplete = true; } }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Scrolling functions */ /* * Function: _fnScrollHorizontalLeft * Purpose: Update the positioning of the scrolling elements * Returns: - * Inputs: object:oCache - the cached values for this fixed element */ _fnScrollHorizontalRight: function ( oCache ) { var s = this.fnGetSettings(), oMes = s.oMes, oWin = FixedHeader.oWin, oDoc = FixedHeader.oDoc, nTable = oCache.nWrapper, iFixedWidth = $(nTable).outerWidth(); if ( oWin.iScrollRight < oMes.iTableRight ) { /* Fully right aligned */ this._fnUpdateCache( oCache, 'sPosition', 'absolute', 'position', nTable.style ); this._fnUpdateCache( oCache, 'sTop', oMes.iTableTop+"px", 'top', nTable.style ); this._fnUpdateCache( oCache, 'sLeft', (oMes.iTableLeft+oMes.iTableWidth-iFixedWidth)+"px", 'left', nTable.style ); } else if ( oMes.iTableLeft < oDoc.iWidth-oWin.iScrollRight-iFixedWidth ) { /* Middle */ this._fnUpdateCache( oCache, 'sPosition', 'fixed', 'position', nTable.style ); this._fnUpdateCache( oCache, 'sTop', (oMes.iTableTop-oWin.iScrollTop)+"px", 'top', nTable.style ); this._fnUpdateCache( oCache, 'sLeft', (oWin.iWidth-iFixedWidth)+"px", 'left', nTable.style ); } else { /* Fully left aligned */ this._fnUpdateCache( oCache, 'sPosition', 'absolute', 'position', nTable.style ); this._fnUpdateCache( oCache, 'sTop', oMes.iTableTop+"px", 'top', nTable.style ); this._fnUpdateCache( oCache, 'sLeft', oMes.iTableLeft+"px", 'left', nTable.style ); } }, /* * Function: _fnScrollHorizontalLeft * Purpose: Update the positioning of the scrolling elements * Returns: - * Inputs: object:oCache - the cached values for this fixed element */ _fnScrollHorizontalLeft: function ( oCache ) { var s = this.fnGetSettings(), oMes = s.oMes, oWin = FixedHeader.oWin, oDoc = FixedHeader.oDoc, nTable = oCache.nWrapper, iCellWidth = $(nTable).outerWidth(); if ( oWin.iScrollLeft < oMes.iTableLeft ) { /* Fully left align */ this._fnUpdateCache( oCache, 'sPosition', 'absolute', 'position', nTable.style ); this._fnUpdateCache( oCache, 'sTop', oMes.iTableTop+"px", 'top', nTable.style ); this._fnUpdateCache( oCache, 'sLeft', oMes.iTableLeft+"px", 'left', nTable.style ); } else if ( oWin.iScrollLeft < oMes.iTableLeft+oMes.iTableWidth-iCellWidth ) { this._fnUpdateCache( oCache, 'sPosition', 'fixed', 'position', nTable.style ); this._fnUpdateCache( oCache, 'sTop', (oMes.iTableTop-oWin.iScrollTop)+"px", 'top', nTable.style ); this._fnUpdateCache( oCache, 'sLeft', "0px", 'left', nTable.style ); } else { /* Fully right align */ this._fnUpdateCache( oCache, 'sPosition', 'absolute', 'position', nTable.style ); this._fnUpdateCache( oCache, 'sTop', oMes.iTableTop+"px", 'top', nTable.style ); this._fnUpdateCache( oCache, 'sLeft', (oMes.iTableLeft+oMes.iTableWidth-iCellWidth)+"px", 'left', nTable.style ); } }, /* * Function: _fnScrollFixedFooter * Purpose: Update the positioning of the scrolling elements * Returns: - * Inputs: object:oCache - the cached values for this fixed element */ _fnScrollFixedFooter: function ( oCache ) { var s = this.fnGetSettings(), oMes = s.oMes, oWin = FixedHeader.oWin, oDoc = FixedHeader.oDoc, nTable = oCache.nWrapper, iTheadHeight = $("thead", s.nTable).outerHeight(), iCellHeight = $(nTable).outerHeight(); if ( oWin.iScrollBottom < oMes.iTableBottom ) { /* Below */ this._fnUpdateCache( oCache, 'sPosition', 'absolute', 'position', nTable.style ); this._fnUpdateCache( oCache, 'sTop', (oMes.iTableTop+oMes.iTableHeight-iCellHeight)+"px", 'top', nTable.style ); this._fnUpdateCache( oCache, 'sLeft', oMes.iTableLeft+"px", 'left', nTable.style ); } else if ( oWin.iScrollBottom < oMes.iTableBottom+oMes.iTableHeight-iCellHeight-iTheadHeight ) { this._fnUpdateCache( oCache, 'sPosition', 'fixed', 'position', nTable.style ); this._fnUpdateCache( oCache, 'sTop', (oWin.iHeight-iCellHeight)+"px", 'top', nTable.style ); this._fnUpdateCache( oCache, 'sLeft', (oMes.iTableLeft-oWin.iScrollLeft)+"px", 'left', nTable.style ); } else { /* Above */ this._fnUpdateCache( oCache, 'sPosition', 'absolute', 'position', nTable.style ); this._fnUpdateCache( oCache, 'sTop', (oMes.iTableTop+iCellHeight)+"px", 'top', nTable.style ); this._fnUpdateCache( oCache, 'sLeft', oMes.iTableLeft+"px", 'left', nTable.style ); } }, /* * Function: _fnScrollFixedHeader * Purpose: Update the positioning of the scrolling elements * Returns: - * Inputs: object:oCache - the cached values for this fixed element */ _fnScrollFixedHeader: function ( oCache ) { var s = this.fnGetSettings(), oMes = s.oMes, oWin = FixedHeader.oWin, oDoc = FixedHeader.oDoc, nTable = oCache.nWrapper, iTbodyHeight = 0, anTbodies = s.nTable.getElementsByTagName('tbody'); for (var i = 0; i < anTbodies.length; ++i) { iTbodyHeight += anTbodies[i].offsetHeight; } if ( oMes.iTableTop > oWin.iScrollTop + s.oOffset.top ) { /* Above the table */ this._fnUpdateCache( oCache, 'sPosition', "absolute", 'position', nTable.style ); this._fnUpdateCache( oCache, 'sTop', oMes.iTableTop+"px", 'top', nTable.style ); this._fnUpdateCache( oCache, 'sLeft', oMes.iTableLeft+"px", 'left', nTable.style ); } else if ( oWin.iScrollTop + s.oOffset.top > oMes.iTableTop+iTbodyHeight ) { /* At the bottom of the table */ this._fnUpdateCache( oCache, 'sPosition', "absolute", 'position', nTable.style ); this._fnUpdateCache( oCache, 'sTop', (oMes.iTableTop+iTbodyHeight)+"px", 'top', nTable.style ); this._fnUpdateCache( oCache, 'sLeft', oMes.iTableLeft+"px", 'left', nTable.style ); } else { /* In the middle of the table */ this._fnUpdateCache( oCache, 'sPosition', 'fixed', 'position', nTable.style ); this._fnUpdateCache( oCache, 'sTop', s.oOffset.top+"px", 'top', nTable.style ); this._fnUpdateCache( oCache, 'sLeft', (oMes.iTableLeft-oWin.iScrollLeft)+"px", 'left', nTable.style ); } }, /* * Function: _fnUpdateCache * Purpose: Check the cache and update cache and value if needed * Returns: - * Inputs: object:oCache - local cache object * string:sCache - cache property * string:sSet - value to set * string:sProperty - object property to set * object:oObj - object to update */ _fnUpdateCache: function ( oCache, sCache, sSet, sProperty, oObj ) { if ( oCache[sCache] != sSet ) { oObj[sProperty] = sSet; oCache[sCache] = sSet; } }, /** * Copy the classes of all child nodes from one element to another. This implies * that the two have identical structure - no error checking is performed to that * fact. * @param {element} source Node to copy classes from * @param {element} dest Node to copy classes too */ _fnClassUpdate: function ( source, dest ) { var that = this; if ( source.nodeName.toUpperCase() === "TR" || source.nodeName.toUpperCase() === "TH" || source.nodeName.toUpperCase() === "TD" || source.nodeName.toUpperCase() === "SPAN" ) { dest.className = source.className; } $(source).children().each( function (i) { that._fnClassUpdate( $(source).children()[i], $(dest).children()[i] ); } ); }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Cloning functions */ /* * Function: _fnCloneThead * Purpose: Clone the thead element * Returns: - * Inputs: object:oCache - the cached values for this fixed element */ _fnCloneThead: function ( oCache ) { var s = this.fnGetSettings(); var nTable = oCache.nNode; if ( s.bInitComplete && !s.oCloneOnDraw.top ) { this._fnClassUpdate( $('thead', s.nTable)[0], $('thead', nTable)[0] ); return; } /* Set the wrapper width to match that of the cloned table */ var iDtWidth = $(s.nTable).outerWidth(); oCache.nWrapper.style.width = iDtWidth+"px"; nTable.style.width = iDtWidth+"px"; /* Remove any children the cloned table has */ while ( nTable.childNodes.length > 0 ) { $('thead th', nTable).unbind( 'click' ); nTable.removeChild( nTable.childNodes[0] ); } /* Clone the DataTables header */ var nThead = $('thead', s.nTable).clone(true)[0]; nTable.appendChild( nThead ); /* Copy the widths across - apparently a clone isn't good enough for this */ var a = []; var b = []; $("thead>tr th", s.nTable).each( function (i) { a.push( $(this).width() ); } ); $("thead>tr td", s.nTable).each( function (i) { b.push( $(this).width() ); } ); $("thead>tr th", s.nTable).each( function (i) { $("thead>tr th:eq("+i+")", nTable).width( a[i] ); $(this).width( a[i] ); } ); $("thead>tr td", s.nTable).each( function (i) { $("thead>tr td:eq("+i+")", nTable).width( b[i] ); $(this).width( b[i] ); } ); // Stop DataTables 1.9 from putting a focus ring on the headers when // clicked to sort $('th.sorting, th.sorting_desc, th.sorting_asc', nTable).bind( 'click', function () { this.blur(); } ); }, /* * Function: _fnCloneTfoot * Purpose: Clone the tfoot element * Returns: - * Inputs: object:oCache - the cached values for this fixed element */ _fnCloneTfoot: function ( oCache ) { var s = this.fnGetSettings(); var nTable = oCache.nNode; /* Set the wrapper width to match that of the cloned table */ oCache.nWrapper.style.width = $(s.nTable).outerWidth()+"px"; /* Remove any children the cloned table has */ while ( nTable.childNodes.length > 0 ) { nTable.removeChild( nTable.childNodes[0] ); } /* Clone the DataTables footer */ var nTfoot = $('tfoot', s.nTable).clone(true)[0]; nTable.appendChild( nTfoot ); /* Copy the widths across - apparently a clone isn't good enough for this */ $("tfoot:eq(0)>tr th", s.nTable).each( function (i) { $("tfoot:eq(0)>tr th:eq("+i+")", nTable).width( $(this).width() ); } ); $("tfoot:eq(0)>tr td", s.nTable).each( function (i) { $("tfoot:eq(0)>tr td:eq("+i+")", nTable).width( $(this).width() ); } ); }, /* * Function: _fnCloneTLeft * Purpose: Clone the left column(s) * Returns: - * Inputs: object:oCache - the cached values for this fixed element */ _fnCloneTLeft: function ( oCache ) { var s = this.fnGetSettings(); var nTable = oCache.nNode; var nBody = $('tbody', s.nTable)[0]; /* Remove any children the cloned table has */ while ( nTable.childNodes.length > 0 ) { nTable.removeChild( nTable.childNodes[0] ); } /* Is this the most efficient way to do this - it looks horrible... */ nTable.appendChild( $("thead", s.nTable).clone(true)[0] ); nTable.appendChild( $("tbody", s.nTable).clone(true)[0] ); if ( s.bFooter ) { nTable.appendChild( $("tfoot", s.nTable).clone(true)[0] ); } /* Remove unneeded cells */ var sSelector = 'gt(' + (oCache.iCells - 1) + ')'; $('thead tr', nTable).each( function (k) { $('th:' + sSelector, this).remove(); } ); $('tfoot tr', nTable).each( function (k) { $('th:' + sSelector, this).remove(); } ); $('tbody tr', nTable).each( function (k) { $('td:' + sSelector, this).remove(); } ); this.fnEqualiseHeights( 'thead', nBody.parentNode, nTable ); this.fnEqualiseHeights( 'tbody', nBody.parentNode, nTable ); this.fnEqualiseHeights( 'tfoot', nBody.parentNode, nTable ); var iWidth = 0; for (var i = 0; i < oCache.iCells; i++) { iWidth += $('thead tr th:eq(' + i + ')', s.nTable).outerWidth(); } nTable.style.width = iWidth+"px"; oCache.nWrapper.style.width = iWidth+"px"; }, /* * Function: _fnCloneTRight * Purpose: Clone the right most column(s) * Returns: - * Inputs: object:oCache - the cached values for this fixed element */ _fnCloneTRight: function ( oCache ) { var s = this.fnGetSettings(); var nBody = $('tbody', s.nTable)[0]; var nTable = oCache.nNode; var iCols = $('tbody tr:eq(0) td', s.nTable).length; /* Remove any children the cloned table has */ while ( nTable.childNodes.length > 0 ) { nTable.removeChild( nTable.childNodes[0] ); } /* Is this the most efficient way to do this - it looks horrible... */ nTable.appendChild( $("thead", s.nTable).clone(true)[0] ); nTable.appendChild( $("tbody", s.nTable).clone(true)[0] ); if ( s.bFooter ) { nTable.appendChild( $("tfoot", s.nTable).clone(true)[0] ); } $('thead tr th:lt('+(iCols-oCache.iCells)+')', nTable).remove(); $('tfoot tr th:lt('+(iCols-oCache.iCells)+')', nTable).remove(); /* Remove unneeded cells */ $('tbody tr', nTable).each( function (k) { $('td:lt('+(iCols-oCache.iCells)+')', this).remove(); } ); this.fnEqualiseHeights( 'thead', nBody.parentNode, nTable ); this.fnEqualiseHeights( 'tbody', nBody.parentNode, nTable ); this.fnEqualiseHeights( 'tfoot', nBody.parentNode, nTable ); var iWidth = 0; for (var i = 0; i < oCache.iCells; i++) { iWidth += $('thead tr th:eq('+(iCols-1-i)+')', s.nTable).outerWidth(); } nTable.style.width = iWidth+"px"; oCache.nWrapper.style.width = iWidth+"px"; }, /** * Equalise the heights of the rows in a given table node in a cross browser way. Note that this * is more or less lifted as is from FixedColumns * @method fnEqualiseHeights * @returns void * @param {string} parent Node type - thead, tbody or tfoot * @param {element} original Original node to take the heights from * @param {element} clone Copy the heights to * @private */ "fnEqualiseHeights": function ( parent, original, clone ) { var that = this; var originals = $(parent +' tr', original); var height; $(parent+' tr', clone).each( function (k) { height = originals.eq( k ).css('height'); // This is nasty :-(. IE has a sub-pixel error even when setting // the height below (the Firefox fix) which causes the fixed column // to go out of alignment. Need to add a pixel before the assignment // Can this be feature detected? Not sure how... if ( navigator.appName == 'Microsoft Internet Explorer' ) { height = parseInt( height, 10 ) + 1; } $(this).css( 'height', height ); // For Firefox to work, we need to also set the height of the // original row, to the value that we read from it! Otherwise there // is a sub-pixel rounding error originals.eq( k ).css( 'height', height ); } ); } }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Static properties and methods * We use these for speed! This information is common to all instances of FixedHeader, so no * point if having them calculated and stored for each different instance. */ /* * Variable: oWin * Purpose: Store information about the window positioning * Scope: FixedHeader */ FixedHeader.oWin = { "iScrollTop": 0, "iScrollRight": 0, "iScrollBottom": 0, "iScrollLeft": 0, "iHeight": 0, "iWidth": 0 }; /* * Variable: oDoc * Purpose: Store information about the document size * Scope: FixedHeader */ FixedHeader.oDoc = { "iHeight": 0, "iWidth": 0 }; /* * Variable: afnScroll * Purpose: Array of functions that are to be used for the scrolling components * Scope: FixedHeader */ FixedHeader.afnScroll = []; /* * Function: fnMeasure * Purpose: Update the measurements for the window and document * Returns: - * Inputs: - */ FixedHeader.fnMeasure = function () { var jqWin = $(window), jqDoc = $(document), oWin = FixedHeader.oWin, oDoc = FixedHeader.oDoc; oDoc.iHeight = jqDoc.height(); oDoc.iWidth = jqDoc.width(); oWin.iHeight = jqWin.height(); oWin.iWidth = jqWin.width(); oWin.iScrollTop = jqWin.scrollTop(); oWin.iScrollLeft = jqWin.scrollLeft(); oWin.iScrollRight = oDoc.iWidth - oWin.iScrollLeft - oWin.iWidth; oWin.iScrollBottom = oDoc.iHeight - oWin.iScrollTop - oWin.iHeight; }; FixedHeader.version = "2.1.2"; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Global processing */ /* * Just one 'scroll' event handler in FixedHeader, which calls the required components. This is * done as an optimisation, to reduce calculation and proagation time */ $(window).scroll( function () { FixedHeader.fnMeasure(); for ( var i=0, iLen=FixedHeader.afnScroll.length ; i<iLen ; i++ ) { FixedHeader.afnScroll[i](); } } ); $.fn.dataTable.FixedHeader = FixedHeader; $.fn.DataTable.FixedHeader = FixedHeader; return FixedHeader; }; // /factory // Define as an AMD module if possible if ( typeof define === 'function' && define.amd ) { define( ['jquery', 'datatables'], factory ); } else if ( typeof exports === 'object' ) { // Node/CommonJS factory( require('jquery'), require('datatables') ); } else if ( jQuery && !jQuery.fn.dataTable.FixedHeader ) { // Otherwise simply initialise as normal, stopping multiple evaluation factory( jQuery, jQuery.fn.dataTable ); } })(window, document);
jagathsisira/app-cloud
modules/setup-scripts/conf/wso2das-3.0.1/repository/deployment/server/jaggeryapps/monitoring/themes/theme0/ui/thirdparty/datatables/extensions/FixedHeader/js/dataTables.fixedHeader.js
JavaScript
apache-2.0
29,978
/* * Copyright 2012 the original author or authors * @license MIT, see LICENSE.txt for details * * @author Scott Andrews */ (function (define) { 'use strict'; var undef; /** * Aggregate messages into batches as they are received. */ define(function (require) { var msgs = require('..'); /** * Aggregates messages into batches as they are received. Batches may * be chunked either by an absolute size and/or a timeout since the * first message was received for the chunk. Either a batch size or * timeout must be specified. * * @param {string} [name] the name to register the aggregator as * @param {number} [opts.batch=0] absolute size of a chunk. If <=0, * batch size is not a factor * @param {number} [opts.timeout=0] number of milliseconds since the * first message arrived to queue the chunk. If <=0, timeout is not a * factor * @param {string|Channel} [opts.output] the channel to post the * aggregated messages to * @param {string|Channel} [opts.input] the channel to receive message * from * @param {string|Channel} [opts.error] channel to receive errors * @returns the aggregator * @throws on invalid configuration, batch size or timeout is required */ msgs.prototype.batchingAggregator = msgs.utils.optionalName(function batchingAggregator(name, opts) { var timeout, batch; batch = []; opts = opts || {}; opts.batch = opts.batch || 0; opts.timeout = opts.timeout || 0; if (opts.batch <= 0 && opts.timeout <= 0) { throw new Error('Invalid configuration: batch size or timeout must be defined'); } function releaseHelper(release) { release(batch); batch = []; clearTimeout(timeout); timeout = undef; } return this.aggregator(name, function (message, release) { batch.push(message.payload); if (opts.batch > 0 && batch.length >= opts.batch) { releaseHelper(release); } else if (!timeout && opts.timeout > 0) { timeout = setTimeout(function () { releaseHelper(release); }, opts.timeout); } }, opts); }); return msgs; }); }( typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); } // Boilerplate for AMD and Node ));
timveil/iot-truck-streaming
storm-demo-webapp/src/main/webapp/assets/lib/msgs/aggregators/batching.js
JavaScript
apache-2.0
2,277
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.common.io.stream; import org.apache.lucene.util.BytesRef; import org.elasticsearch.common.CheckedBiConsumer; import org.elasticsearch.common.CheckedFunction; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.test.ESTestCase; import java.io.ByteArrayInputStream; import java.io.EOFException; import java.io.IOException; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.IntStream; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasToString; import static org.hamcrest.Matchers.iterableWithSize; public class StreamTests extends ESTestCase { public void testBooleanSerialization() throws IOException { final BytesStreamOutput output = new BytesStreamOutput(); output.writeBoolean(false); output.writeBoolean(true); final BytesReference bytesReference = output.bytes(); final BytesRef bytesRef = bytesReference.toBytesRef(); assertThat(bytesRef.length, equalTo(2)); final byte[] bytes = bytesRef.bytes; assertThat(bytes[0], equalTo((byte) 0)); assertThat(bytes[1], equalTo((byte) 1)); final StreamInput input = bytesReference.streamInput(); assertFalse(input.readBoolean()); assertTrue(input.readBoolean()); final Set<Byte> set = IntStream.range(Byte.MIN_VALUE, Byte.MAX_VALUE).mapToObj(v -> (byte) v).collect(Collectors.toSet()); set.remove((byte) 0); set.remove((byte) 1); final byte[] corruptBytes = new byte[]{randomFrom(set)}; final BytesReference corrupt = new BytesArray(corruptBytes); final IllegalStateException e = expectThrows(IllegalStateException.class, () -> corrupt.streamInput().readBoolean()); final String message = String.format(Locale.ROOT, "unexpected byte [0x%02x]", corruptBytes[0]); assertThat(e, hasToString(containsString(message))); } public void testOptionalBooleanSerialization() throws IOException { final BytesStreamOutput output = new BytesStreamOutput(); output.writeOptionalBoolean(false); output.writeOptionalBoolean(true); output.writeOptionalBoolean(null); final BytesReference bytesReference = output.bytes(); final BytesRef bytesRef = bytesReference.toBytesRef(); assertThat(bytesRef.length, equalTo(3)); final byte[] bytes = bytesRef.bytes; assertThat(bytes[0], equalTo((byte) 0)); assertThat(bytes[1], equalTo((byte) 1)); assertThat(bytes[2], equalTo((byte) 2)); final StreamInput input = bytesReference.streamInput(); final Boolean maybeFalse = input.readOptionalBoolean(); assertNotNull(maybeFalse); assertFalse(maybeFalse); final Boolean maybeTrue = input.readOptionalBoolean(); assertNotNull(maybeTrue); assertTrue(maybeTrue); assertNull(input.readOptionalBoolean()); final Set<Byte> set = IntStream.range(Byte.MIN_VALUE, Byte.MAX_VALUE).mapToObj(v -> (byte) v).collect(Collectors.toSet()); set.remove((byte) 0); set.remove((byte) 1); set.remove((byte) 2); final byte[] corruptBytes = new byte[]{randomFrom(set)}; final BytesReference corrupt = new BytesArray(corruptBytes); final IllegalStateException e = expectThrows(IllegalStateException.class, () -> corrupt.streamInput().readOptionalBoolean()); final String message = String.format(Locale.ROOT, "unexpected byte [0x%02x]", corruptBytes[0]); assertThat(e, hasToString(containsString(message))); } public void testRandomVLongSerialization() throws IOException { for (int i = 0; i < 1024; i++) { long write = randomLong(); BytesStreamOutput out = new BytesStreamOutput(); out.writeZLong(write); long read = out.bytes().streamInput().readZLong(); assertEquals(write, read); } } public void testSpecificVLongSerialization() throws IOException { List<Tuple<Long, byte[]>> values = Arrays.asList( new Tuple<>(0L, new byte[]{0}), new Tuple<>(-1L, new byte[]{1}), new Tuple<>(1L, new byte[]{2}), new Tuple<>(-2L, new byte[]{3}), new Tuple<>(2L, new byte[]{4}), new Tuple<>(Long.MIN_VALUE, new byte[]{-1, -1, -1, -1, -1, -1, -1, -1, -1, 1}), new Tuple<>(Long.MAX_VALUE, new byte[]{-2, -1, -1, -1, -1, -1, -1, -1, -1, 1}) ); for (Tuple<Long, byte[]> value : values) { BytesStreamOutput out = new BytesStreamOutput(); out.writeZLong(value.v1()); assertArrayEquals(Long.toString(value.v1()), value.v2(), BytesReference.toBytes(out.bytes())); BytesReference bytes = new BytesArray(value.v2()); assertEquals(Arrays.toString(value.v2()), (long) value.v1(), bytes.streamInput().readZLong()); } } public void testLinkedHashMap() throws IOException { int size = randomIntBetween(1, 1024); boolean accessOrder = randomBoolean(); List<Tuple<String, Integer>> list = new ArrayList<>(size); LinkedHashMap<String, Integer> write = new LinkedHashMap<>(size, 0.75f, accessOrder); for (int i = 0; i < size; i++) { int value = randomInt(); list.add(new Tuple<>(Integer.toString(i), value)); write.put(Integer.toString(i), value); } if (accessOrder) { // randomize access order Collections.shuffle(list, random()); for (Tuple<String, Integer> entry : list) { // touch the entries to set the access order write.get(entry.v1()); } } BytesStreamOutput out = new BytesStreamOutput(); out.writeGenericValue(write); LinkedHashMap<String, Integer> read = (LinkedHashMap<String, Integer>) out.bytes().streamInput().readGenericValue(); assertEquals(size, read.size()); int index = 0; for (Map.Entry<String, Integer> entry : read.entrySet()) { assertEquals(list.get(index).v1(), entry.getKey()); assertEquals(list.get(index).v2(), entry.getValue()); index++; } } public void testFilterStreamInputDelegatesAvailable() throws IOException { final int length = randomIntBetween(1, 1024); StreamInput delegate = StreamInput.wrap(new byte[length]); FilterStreamInput filterInputStream = new FilterStreamInput(delegate) { }; assertEquals(filterInputStream.available(), length); // read some bytes final int bytesToRead = randomIntBetween(1, length); filterInputStream.readBytes(new byte[bytesToRead], 0, bytesToRead); assertEquals(filterInputStream.available(), length - bytesToRead); } public void testInputStreamStreamInputDelegatesAvailable() throws IOException { final int length = randomIntBetween(1, 1024); ByteArrayInputStream is = new ByteArrayInputStream(new byte[length]); InputStreamStreamInput streamInput = new InputStreamStreamInput(is); assertEquals(streamInput.available(), length); // read some bytes final int bytesToRead = randomIntBetween(1, length); streamInput.readBytes(new byte[bytesToRead], 0, bytesToRead); assertEquals(streamInput.available(), length - bytesToRead); } public void testReadArraySize() throws IOException { BytesStreamOutput stream = new BytesStreamOutput(); byte[] array = new byte[randomIntBetween(1, 10)]; for (int i = 0; i < array.length; i++) { array[i] = randomByte(); } stream.writeByteArray(array); InputStreamStreamInput streamInput = new InputStreamStreamInput(StreamInput.wrap(BytesReference.toBytes(stream.bytes())), array .length - 1); expectThrows(EOFException.class, streamInput::readByteArray); streamInput = new InputStreamStreamInput(StreamInput.wrap(BytesReference.toBytes(stream.bytes())), BytesReference.toBytes(stream .bytes()).length); assertArrayEquals(array, streamInput.readByteArray()); } public void testWritableArrays() throws IOException { final String[] strings = generateRandomStringArray(10, 10, false, true); WriteableString[] sourceArray = Arrays.stream(strings).<WriteableString>map(WriteableString::new).toArray(WriteableString[]::new); WriteableString[] targetArray; BytesStreamOutput out = new BytesStreamOutput(); if (randomBoolean()) { if (randomBoolean()) { sourceArray = null; } out.writeOptionalArray(sourceArray); targetArray = out.bytes().streamInput().readOptionalArray(WriteableString::new, WriteableString[]::new); } else { out.writeArray(sourceArray); targetArray = out.bytes().streamInput().readArray(WriteableString::new, WriteableString[]::new); } assertThat(targetArray, equalTo(sourceArray)); } public void testArrays() throws IOException { final String[] strings; final String[] deserialized; Writeable.Writer<String> writer = StreamOutput::writeString; Writeable.Reader<String> reader = StreamInput::readString; BytesStreamOutput out = new BytesStreamOutput(); if (randomBoolean()) { if (randomBoolean()) { strings = null; } else { strings = generateRandomStringArray(10, 10, false, true); } out.writeOptionalArray(writer, strings); deserialized = out.bytes().streamInput().readOptionalArray(reader, String[]::new); } else { strings = generateRandomStringArray(10, 10, false, true); out.writeArray(writer, strings); deserialized = out.bytes().streamInput().readArray(reader, String[]::new); } assertThat(deserialized, equalTo(strings)); } public void testCollection() throws IOException { class FooBar implements Writeable { private final int foo; private final int bar; private FooBar(final int foo, final int bar) { this.foo = foo; this.bar = bar; } private FooBar(final StreamInput in) throws IOException { this.foo = in.readInt(); this.bar = in.readInt(); } @Override public void writeTo(final StreamOutput out) throws IOException { out.writeInt(foo); out.writeInt(bar); } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final FooBar that = (FooBar) o; return foo == that.foo && bar == that.bar; } @Override public int hashCode() { return Objects.hash(foo, bar); } } runWriteReadCollectionTest( () -> new FooBar(randomInt(), randomInt()), StreamOutput::writeCollection, in -> in.readList(FooBar::new)); } public void testStringCollection() throws IOException { runWriteReadCollectionTest(() -> randomUnicodeOfLength(16), StreamOutput::writeStringCollection, StreamInput::readStringList); } private <T> void runWriteReadCollectionTest( final Supplier<T> supplier, final CheckedBiConsumer<StreamOutput, Collection<T>, IOException> writer, final CheckedFunction<StreamInput, Collection<T>, IOException> reader) throws IOException { final int length = randomIntBetween(0, 10); final Collection<T> collection = new ArrayList<>(length); for (int i = 0; i < length; i++) { collection.add(supplier.get()); } try (BytesStreamOutput out = new BytesStreamOutput()) { writer.accept(out, collection); try (StreamInput in = out.bytes().streamInput()) { assertThat(collection, equalTo(reader.apply(in))); } } } public void testSetOfLongs() throws IOException { final int size = randomIntBetween(0, 6); final Set<Long> sourceSet = new HashSet<>(size); for (int i = 0; i < size; i++) { sourceSet.add(randomLongBetween(i * 1000, (i + 1) * 1000 - 1)); } assertThat(sourceSet, iterableWithSize(size)); final BytesStreamOutput out = new BytesStreamOutput(); out.writeCollection(sourceSet, StreamOutput::writeLong); final Set<Long> targetSet = out.bytes().streamInput().readSet(StreamInput::readLong); assertThat(targetSet, equalTo(sourceSet)); } public void testInstantSerialization() throws IOException { final Instant instant = Instant.now(); try (BytesStreamOutput out = new BytesStreamOutput()) { out.writeInstant(instant); try (StreamInput in = out.bytes().streamInput()) { final Instant serialized = in.readInstant(); assertEquals(instant, serialized); } } } public void testOptionalInstantSerialization() throws IOException { final Instant instant = Instant.now(); try (BytesStreamOutput out = new BytesStreamOutput()) { out.writeOptionalInstant(instant); try (StreamInput in = out.bytes().streamInput()) { final Instant serialized = in.readOptionalInstant(); assertEquals(instant, serialized); } } final Instant missing = null; try (BytesStreamOutput out = new BytesStreamOutput()) { out.writeOptionalInstant(missing); try (StreamInput in = out.bytes().streamInput()) { final Instant serialized = in.readOptionalInstant(); assertEquals(missing, serialized); } } } static final class WriteableString implements Writeable { final String string; WriteableString(String string) { this.string = string; } WriteableString(StreamInput in) throws IOException { this(in.readString()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } WriteableString that = (WriteableString) o; return string.equals(that.string); } @Override public int hashCode() { return string.hashCode(); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(string); } } }
strapdata/elassandra
server/src/test/java/org/elasticsearch/common/io/stream/StreamTests.java
Java
apache-2.0
16,395
/* * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.autoconfigure.session; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.session.SessionRepository; import org.springframework.session.data.redis.RedisOperationsSessionRepository; import org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration; /** * Redis backed session configuration. * * @author Andy Wilkinson * @author Tommy Ludwig * @author Eddú Meléndez * @author Stephane Nicoll * @author Vedran Pavic */ @Configuration @ConditionalOnClass({ RedisTemplate.class, RedisOperationsSessionRepository.class }) @ConditionalOnMissingBean(SessionRepository.class) @ConditionalOnBean(RedisConnectionFactory.class) @Conditional(SessionCondition.class) @EnableConfigurationProperties(RedisSessionProperties.class) class RedisSessionConfiguration { @Configuration public static class SpringBootRedisHttpSessionConfiguration extends RedisHttpSessionConfiguration { private SessionProperties sessionProperties; @Autowired public void customize(SessionProperties sessionProperties, RedisSessionProperties redisSessionProperties) { this.sessionProperties = sessionProperties; Integer timeout = this.sessionProperties.getTimeout(); if (timeout != null) { setMaxInactiveIntervalInSeconds(timeout); } setRedisNamespace(redisSessionProperties.getNamespace()); setRedisFlushMode(redisSessionProperties.getFlushMode()); } } }
bbrouwer/spring-boot
spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/session/RedisSessionConfiguration.java
Java
apache-2.0
2,669
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.samza.operators.spec; import java.util.Collection; /** * Spec for stateful operators. */ public interface StatefulOperatorSpec { /** * Get the store descriptors for stores required by this operator. * * @return store descriptors for this operator's stores */ Collection<StoreDescriptor> getStoreDescriptors(); }
fredji97/samza
samza-core/src/main/java/org/apache/samza/operators/spec/StatefulOperatorSpec.java
Java
apache-2.0
1,163
<widget-modal widget-modal-title="Administer Api Token"> <form name="cdf" class="form" ng-submit="ctrl.submit(cdf)" novalidate> <form-group input="apiUser" errors="{required: 'Api user name is required', minlength: 'Min length of 6 characters', maxlength: 'Max length of 50 characters', pattern : 'Special character(s) found. Please enter only letters, numbers or spaces.'}"> <label class="modal-label">Api User</label> <input type="text" name="apiUser" class="form-control" placeholder="Api User" ng-model="ctrl.apiUser" required disabled="true" maxlength="50" autocomplete="off" minlength="6" ng-pattern="/^[a-zA-Z0-9 ]*$/"/> <span class="text-danger"></span> </form-group> <form-group input="expDt" class="text-center" errors="{apiTokenError: 'Error updating api token.'}"> <br> <label class="modal-label" id="dtLabel">Expiration Date</label> <div class="row"> <div class="col-xs-offset-3 col-xs-6"> <date-picker disable-before-today="true" dp-Name="expDt" ng-model="ctrl.date"></date-picker> </div> </div> </form-group> <div class="button-row row text-center"> <button type="submit" class="btn btn-primary btn-wide">Save</button> </div> </form> </widget-modal>
pavan149679/Hygieia
UI/src/app/dashboard/views/editApiToken.html
HTML
apache-2.0
1,758
# frozen_string_literal: true # # Cookbook:: postgresql # Recipe:: contrib # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # db_name = node['postgresql']['database_name'] # Install the PostgreSQL contrib package(s) from the distribution, # as specified by the node attributes. package node['postgresql']['contrib']['packages'] include_recipe 'postgresql::server' # Install PostgreSQL contrib extentions into the database, as specified by the # node attribute node['postgresql']['database_name']. if node['postgresql']['contrib'].attribute?('extensions') node['postgresql']['contrib']['extensions'].each do |pg_ext| postgresql_extension "#{db_name}/#{pg_ext}" end end
Coveros/starcanada2016
www-db/cookbooks/postgresql/recipes/contrib.rb
Ruby
apache-2.0
1,177
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.accumulo.core.client.lexicoder; /** * An encoder represents a typed object that can be encoded/decoded to/from a byte array. * * @since 1.6.0 */ public interface Encoder<T> { byte[] encode(T object); T decode(byte[] bytes) throws IllegalArgumentException; }
milleruntime/accumulo
core/src/main/java/org/apache/accumulo/core/client/lexicoder/Encoder.java
Java
apache-2.0
1,095
package me.kafeitu.activiti.chapter15.leave; import me.kafeitu.activiti.chapter15.leave.ws.LeaveWebService; import org.apache.cxf.interceptor.LoggingInInterceptor; import org.apache.cxf.interceptor.LoggingOutInterceptor; import org.apache.cxf.jaxws.JaxWsProxyFactoryBean; import org.junit.After; import org.junit.Before; import org.junit.Test; import javax.xml.namespace.QName; import javax.xml.ws.Service; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * 测试请假流程的Webservice基础功能 * @author: Henry Yan */ public class LeaveWebServiceBusinessTest { /** * 发布并启动WebService */ @Before public void before() { LeaveWebserviceUtil.startServer(); } /** * 需要总经理审批 * @throws ParseException */ @Test public void testTrue() throws ParseException, MalformedURLException { /* // CXF方式 JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); factory.getInInterceptors().add(new LoggingInInterceptor()); factory.getOutInterceptors().add(new LoggingOutInterceptor()); factory.setServiceClass(LeaveWebService.class); factory.setAddress(LeaveWebserviceUtil.WEBSERVICE_URL); LeaveWebService leaveWebService = (LeaveWebService) factory.create();*/ // 标准方式 URL url = new URL(LeaveWebserviceUtil.WEBSERVICE_WSDL_URL); QName qname = new QName(LeaveWebserviceUtil.WEBSERVICE_URI, "LeaveWebService"); Service service = Service.create(url, qname); LeaveWebService leaveWebService = service.getPort(LeaveWebService.class); boolean audit = leaveWebService.generalManagerAudit("2013-01-01 09:00", "2013-01-05 17:30"); assertTrue(audit); } /** * 不需要总经理审批 * @throws ParseException */ @Test public void testFalse() throws ParseException { JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); factory.getInInterceptors().add(new LoggingInInterceptor()); factory.getOutInterceptors().add(new LoggingOutInterceptor()); factory.setServiceClass(LeaveWebService.class); factory.setAddress(LeaveWebserviceUtil.WEBSERVICE_URL); LeaveWebService leaveWebService = (LeaveWebService) factory.create(); boolean audit = leaveWebService.generalManagerAudit("2013-01-01 09:00", "2013-01-04 17:30"); assertFalse(audit); } @After public void after() { LeaveWebserviceUtil.stopServer(); } }
kutala/activiti-in-action-codes
bpmn20-example/src/test/java/me/kafeitu/activiti/chapter15/leave/LeaveWebServiceBusinessTest.java
Java
apache-2.0
2,672
# Yieldmo ## Example ```html <amp-ad width="300" height="168" type="yieldmo" data-ymid="1349317029731662884"> </amp-ad> ``` ## Configuration For semantics configuration, please [contact Yieldmo](https://yieldmo.com/#contact). Supported parameters: - `data-ymid` ## Multi-size Ad Yieldmo implicitly handles rendering different sized ads that are bid to the same placement. No additional configuration is required for the tag. --- Above the fold ads do not resize, so as not to not disrupt the user experience: ![](http://test.yieldmo.com.s3.amazonaws.com/amp-demo/big-notResized.gif) ![](http://test.yieldmo.com.s3.amazonaws.com/amp-demo/small-notResized.gif) --- Below the fold, ads resize: ![](http://test.yieldmo.com.s3.amazonaws.com/amp-demo/big-resized.gif) ![](http://test.yieldmo.com.s3.amazonaws.com/amp-demo/small-resized.gif) ---
alanorozco/amphtml
ads/vendors/yieldmo.md
Markdown
apache-2.0
856
<!DOCTYPE html> <html lang="en"> <head> <title>What is the Drop Box tool?</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta content="sakai.dropbox, main" name="description"> <meta content="student folders" name="search"> <link href="/library/skin/tool_base.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8"> <link href="/library/skin/morpheus-default/tool.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8"> <link href="/sakai-help-tool/css/help.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8"> <link href="/library/js/jquery/featherlight/0.4.0/featherlight.min.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8"> <script src="/library/webjars/jquery/1.11.3/jquery.min.js" type="text/javascript" charset="utf-8"></script><script src="/library/js/jquery/featherlight/0.4.0/featherlight.min.js" type="text/javascript" charset="utf-8"></script><script type="text/javascript" charset="utf-8"> $(document).ready(function(){ $("a[rel^='featherlight']").featherlight({ type: { image:true }, closeOnClick: 'anywhere' }); }); </script> </head> <body> <div id="wrapper"> <div id="article-content"> <div id="article-header"> <h1 class="article-title">What is the Drop Box tool?</h1> </div> <div id="article-description"> <p>The Drop Box tool creates a folder for each student in the course. &nbsp;Students are only able to access their own folder. Students and instructors can both place files in the Drop Box folders. &nbsp;</p> <p>The Drop Box mirrors the file management features and functionality of the Resources tool. See <a href="content.hlp?docId=whatistheResourcestool">What is the Resources tool?</a> for more information on how to add, upload, edit, and delete files and folders within Drop Box. (As with Resources, multiple files can also be uploaded using <a href="content.hlp?docId=howdoIdraganddropfilesfrommycomputertoaResourcesfolder">Drag and Drop</a>.)</p> </div> <div id="steps-container"> <div id="step-6360" class="step-container"> <h2 class="step-title">To access this tool, select Drop Box from the Tool Menu in your site.</h2> <div class="step-image-container"> <img src="/library/image/help/en/What-is-the-Drop-Box-tool-/To-access-this-tool--select-Drop-Box-from-the-Tool.png" width="146" height="126" class="step-image" alt="To access this tool, select Drop Box from the Tool Menu in your site."> </div> </div> <div class="clear"></div> <div id="step-6361" class="step-container"> <h2 class="step-title">Example: Folders for each student</h2> <div class="step-image-container step-image-fullsize"> <img src="/library/image/help/en/What-is-the-Drop-Box-tool-/Example--Folders-for-each-student-sm.png" width="640" height="285" class="step-image" alt="Example: Folders for each student"><div class="step-image-caption"> <a href="/library/image/help/en/What-is-the-Drop-Box-tool-/Example--Folders-for-each-student.png" rel="featherlight" target="_blank">Zoom</a> </div> </div> <div class="step-instructions"><p>Folders with the plus sign contain files.</p></div> </div> <div class="clear"></div> </div> </div> </div> </body> </html>
joserabal/sakai
help/help/src/sakai_screensteps_dropBoxInstructorGuide/What-is-the-Drop-Box-tool-.html
HTML
apache-2.0
3,465
/* * Copyright 2001-2013 Artima, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.scalatest.matchers import scala.reflect.ClassTag // T is the type of the object that has a property to verify with an instance of this trait, P is the type of that particular property // Since I should be able to pass /** * Trait extended by matcher objects, which may appear after the word <code>have</code>, that can match against a * property of the type specified by the <code>HavePropertyMatcher</code>'s second type parameter <code>P</code>. * <code>HavePropertyMatcher</code>'s first type parameter, <code>T</code>, specifies the type that declares the property. The match will succeed if and * only if the value of the property equals the specified value. * The object containing the property * is passed to the <code>HavePropertyMatcher</code>'s * <code>apply</code> method. The result is a <code>HavePropertyMatchResult[P]</code>. * A <code>HavePropertyMatcher</code> is, therefore, a function from the specified type, <code>T</code>, to * a <code>HavePropertyMatchResult[P]</code>. * * <p> * Although <code>HavePropertyMatcher</code> * and <code>Matcher</code> represent similar concepts, they have no inheritance relationship * because <code>Matcher</code> is intended for use right after <code>should</code> or <code>must</code> * whereas <code>HavePropertyMatcher</code> is intended for use right after <code>have</code>. * </p> * * <p> * A <code>HavePropertyMatcher</code> essentially allows you to write statically typed * property assertions similar to the dynamic ones that use symbols: * </p> * * <pre class="stHighlight"> * book should have ('title ("Moby Dick")) // dynamic: uses reflection * book should have (title ("Moby Dick")) // type safe: only works on Books; no reflection used * </pre> * * <p> * One good way to organize custom matchers is to place them inside one or more traits that * you can then mix into the suites or specs that need them. Here's an example that * includes two methods that produce <code>HavePropertyMatcher</code>s: * </p> * * <pre class="stHighlight"> * case class Book(val title: String, val author: String) * * trait CustomMatchers { * * def title(expectedValue: String) = * new HavePropertyMatcher[Book, String] { * def apply(book: Book) = * HavePropertyMatchResult( * book.title == expectedValue, * "title", * expectedValue, * book.title * ) * } * * def author(expectedValue: String) = * new HavePropertyMatcher[Book, String] { * def apply(book: Book) = * HavePropertyMatchResult( * book.author == expectedValue, * "author", * expectedValue, * book.author * ) * } * } * </pre> * * <p> * Each time the <code>title</code> method is called, it returns a new <code>HavePropertyMatcher[Book, String]</code> that * can be used to match against the <code>title</code> property of the <code>Book</code> passed to its <code>apply</code> * method. Because the type parameter of these two <code>HavePropertyMatcher</code>s is <code>Book</code>, they * can only be used with instances of that type. (The compiler will enforce this.) The match will succeed if the * <code>title</code> property equals the value passed as <code>expectedValue</code>. * If the match succeeds, the <code>matches</code> field of the returned <code>HavePropertyMatchResult</code> will be <code>true</code>. * The second field, <code>propertyName</code>, is simply the string name of the property. * The third and fourth fields, <code>expectedValue</code> and <code>actualValue</code> indicate the expected and actual * values, respectively, for the property. * Here's an example that uses these <code>HavePropertyMatchers</code>: * </p> * * <pre class="stHighlight"> * class ExampleSpec extends Spec with Matchers with CustomMatchers { * * describe("A book") { * * it("should have the correct title and author") { * * val book = Book("Moby Dick", "Melville") * * book should have ( * title ("Moby Dick"), * author ("Melville") * ) * } * } * } * </pre> * * <p> * These matches should succeed, but if for example the first property, <code>title ("Moby Dick")</code>, were to fail, you would get an error message like: * </p> * * <pre class="stExamples"> * The title property had value "A Tale of Two Cities", instead of its expected value "Moby Dick", * on object Book(A Tale of Two Cities,Dickens) * </pre> * * <p> * For more information on <code>HavePropertyMatchResult</code> and the meaning of its fields, please * see the documentation for <a href="HavePropertyMatchResult.html"><code>HavePropertyMatchResult</code></a>. To understand why <code>HavePropertyMatcher</code> * is contravariant in its type parameter, see the section entitled "Matcher's variance" in the * documentation for <a href="../Matcher.html"><code>Matcher</code></a>. * </p> * * @author Bill Venners */ trait HavePropertyMatcher[-T, P] extends Function1[T, HavePropertyMatchResult[P]] { thisHavePropertyMatcher => /** * Check to see if a property on the specified object, <code>objectWithProperty</code>, matches its * expected value, and report the result in * the returned <code>HavePropertyMatchResult</code>. The <code>objectWithProperty</code> is * usually the value to the left of a <code>should</code> or <code>must</code> invocation. For example, <code>book</code> * would be passed as the <code>objectWithProperty</code> in: * * <pre class="stHighlight"> * book should have (title ("Moby Dick")) * </pre> * * @param objectWithProperty the object with the property against which to match * @return the <code>HavePropertyMatchResult</code> that represents the result of the match */ def apply(objectWithProperty: T): HavePropertyMatchResult[P] /** * Compose this <code>HavePropertyMatcher</code> with the passed function, returning a new <code>HavePropertyMatcher</code>. * * <p> * This method overrides <code>compose</code> on <code>Function1</code> to * return a more specific function type of <code>HavePropertyMatcher</code>. * </p> */ override def compose[U](g: U => T): HavePropertyMatcher[U, P] = new HavePropertyMatcher[U, P] { def apply(u: U) = thisHavePropertyMatcher.apply(g(u)) } } /** * Companion object for trait <code>HavePropertyMatcher</code> that provides a * factory method that creates a <code>HavePropertyMatcher[T]</code> from a * passed function of type <code>(T =&gt; HavePropertyMatchResult)</code>. * * @author Bill Venners */ object HavePropertyMatcher { /** * Factory method that creates a <code>HavePropertyMatcher[T]</code> from a * passed function of type <code>(T =&gt; HavePropertyMatchResult)</code>. * * <p> * This allows you to create a <code>HavePropertyMatcher</code> in a slightly * more concise way, for example: * </p> * * <pre class="stHighlight"> * case class Person(name: String) * def name(expectedName: String) = { * HavePropertyMatcher { * (person: Person) =&gt; HavePropertyMatchResult( * person.name == expectedName, * "name", * expectedName, * person.name * ) * } * </pre> * * @author Bill Venners */ def apply[T, P](fun: T => HavePropertyMatchResult[P])(implicit evT: ClassTag[T], evP: ClassTag[P]): HavePropertyMatcher[T, P] = new HavePropertyMatcher[T, P] { def apply(left: T) = fun(left) override def toString: String = "HavePropertyMatcher[" + evT.runtimeClass.getName + ", " + evP.runtimeClass.getName + "](" + evT.runtimeClass.getName + " => HavePropertyMatchResult[" + evP.runtimeClass.getName + "])" } }
rahulkavale/scalatest
scalatest/src/main/scala/org/scalatest/matchers/HavePropertyMatcher.scala
Scala
apache-2.0
8,429
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.catalog.springboot; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.apache.camel.catalog.CamelCatalog; import org.apache.camel.catalog.CatalogHelper; import org.apache.camel.catalog.RuntimeProvider; /** * A Spring Boot based {@link RuntimeProvider} which only includes the supported Camel components, data formats, and languages * which can be installed in Spring Boot using the starter dependencies. */ public class SpringBootRuntimeProvider implements RuntimeProvider { private static final String COMPONENT_DIR = "org/apache/camel/catalog/springboot/components"; private static final String DATAFORMAT_DIR = "org/apache/camel/catalog/springboot/dataformats"; private static final String LANGUAGE_DIR = "org/apache/camel/catalog/springboot/languages"; private static final String OTHER_DIR = "org/apache/camel/catalog/springboot/others"; private static final String COMPONENTS_CATALOG = "org/apache/camel/catalog/springboot/components.properties"; private static final String DATA_FORMATS_CATALOG = "org/apache/camel/catalog/springboot/dataformats.properties"; private static final String LANGUAGE_CATALOG = "org/apache/camel/catalog/springboot/languages.properties"; private static final String OTHER_CATALOG = "org/apache/camel/catalog/springboot/others.properties"; private CamelCatalog camelCatalog; @Override public CamelCatalog getCamelCatalog() { return camelCatalog; } @Override public void setCamelCatalog(CamelCatalog camelCatalog) { this.camelCatalog = camelCatalog; } @Override public String getProviderName() { return "springboot"; } @Override public String getProviderGroupId() { return "org.apache.camel"; } @Override public String getProviderArtifactId() { return "camel-catalog-provider-springboot"; } @Override public String getComponentJSonSchemaDirectory() { return COMPONENT_DIR; } @Override public String getDataFormatJSonSchemaDirectory() { return DATAFORMAT_DIR; } @Override public String getLanguageJSonSchemaDirectory() { return LANGUAGE_DIR; } @Override public String getOtherJSonSchemaDirectory() { return OTHER_DIR; } @Override public List<String> findComponentNames() { List<String> names = new ArrayList<>(); InputStream is = camelCatalog.getVersionManager().getResourceAsStream(COMPONENTS_CATALOG); if (is != null) { try { CatalogHelper.loadLines(is, names); } catch (IOException e) { // ignore } } return names; } @Override public List<String> findDataFormatNames() { List<String> names = new ArrayList<>(); InputStream is = camelCatalog.getVersionManager().getResourceAsStream(DATA_FORMATS_CATALOG); if (is != null) { try { CatalogHelper.loadLines(is, names); } catch (IOException e) { // ignore } } return names; } @Override public List<String> findLanguageNames() { List<String> names = new ArrayList<>(); InputStream is = camelCatalog.getVersionManager().getResourceAsStream(LANGUAGE_CATALOG); if (is != null) { try { CatalogHelper.loadLines(is, names); } catch (IOException e) { // ignore } } return names; } @Override public List<String> findOtherNames() { List<String> names = new ArrayList<>(); InputStream is = camelCatalog.getVersionManager().getResourceAsStream(OTHER_CATALOG); if (is != null) { try { CatalogHelper.loadLines(is, names); } catch (IOException e) { // ignore } } return names; } }
onders86/camel
platforms/camel-catalog-provider-springboot/src/main/java/org/apache/camel/catalog/springboot/SpringBootRuntimeProvider.java
Java
apache-2.0
4,859
//>>built define("dojox/atom/widget/nls/hr/FeedEntryViewer",{displayOptions:"[opcije prikaza]",title:"Naslov",authors:"Autori",contributors:"Doprinositelji",id:"ID",close:"[zatvori]",updated:"A\u017eurirano",summary:"Sa\u017eetak",content:"Sadr\u017eaj"});
aconyteds/Esri-Ozone-Map-Widget
vendor/js/esri/arcgis_js_api/library/3.12/3.12compact/dojox/atom/widget/nls/hr/FeedEntryViewer.js
JavaScript
apache-2.0
256
<!DOCTYPE html> <html lang="en"> <head> <title>How do I delete an alias?</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta content="sakai.aliases" name="description"> <meta content="" name="search"> <link href="/library/skin/tool_base.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8"> <link href="/library/skin/morpheus-default/tool.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8"> <link href="/sakai-help-tool/css/help.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8"> <link href="/library/js/jquery/featherlight/0.4.0/featherlight.min.css" media="screen" rel="stylesheet" type="text/css" charset="utf-8"> <script src="/library/webjars/jquery/1.11.3/jquery.min.js" type="text/javascript" charset="utf-8"></script><script src="/library/js/jquery/featherlight/0.4.0/featherlight.min.js" type="text/javascript" charset="utf-8"></script><script type="text/javascript" charset="utf-8"> $(document).ready(function(){ $("a[rel^='featherlight']").featherlight({ type: { image:true }, closeOnClick: 'anywhere' }); }); </script> </head> <body> <div id="wrapper"> <div id="article-content"> <div id="article-header"> <h1 class="article-title">How do I delete an alias?</h1> </div> <div id="steps-container"> <div id="step-5445" class="step-container"> <h2 class="step-title">Go to the Aliases tool.</h2> <div class="step-instructions"><p>Select the <strong>Aliases</strong> tool from the Tool Menu in the Administration Workspace.</p></div> </div> <div class="clear"></div> <div id="step-5446" class="step-container"> <h3 class="step-title">Click on the alias you would like delete.</h3> <div class="step-image-container step-image-fullsize"> <img src="/library/image/help/en/How-do-I-delete-an-alias-/Click-on-the-alias-you-would-like-delete-sm.png" width="640" height="469" class="step-image" alt="Click on the alias you would like delete."><div class="step-image-caption"> <a href="/library/image/help/en/How-do-I-delete-an-alias-/Click-on-the-alias-you-would-like-delete.png" rel="featherlight" target="_blank">Zoom</a> </div> </div> </div> <div class="clear"></div> <div id="step-5447" class="step-container"> <h3 class="step-title">Click Remove Alias.</h3> <div class="step-image-container"> <img src="/library/image/help/en/How-do-I-delete-an-alias-/Click-Remove-Alias.png" width="578" height="319" class="step-image" alt="Click Remove Alias."> </div> </div> <div class="clear"></div> <div id="step-5448" class="step-container"> <h3 class="step-title">Confirm alias removal.</h3> <div class="step-image-container step-image-fullsize"> <img src="/library/image/help/en/How-do-I-delete-an-alias-/Confirm-alias-removal-sm.png" width="640" height="194" class="step-image" alt="Confirm alias removal."><div class="step-image-caption"> <a href="/library/image/help/en/How-do-I-delete-an-alias-/Confirm-alias-removal.png" rel="featherlight" target="_blank">Zoom</a> </div> </div> <div class="step-instructions"><p>Click <strong>Remove</strong> again when prompted to confirm the deletion of the alias.</p></div> </div> <div class="clear"></div> </div> </div> </div> </body> </html>
conder/sakai
help/help/src/sakai_screensteps_aliasesAdministratorGuide/How-do-I-delete-an-alias-.html
HTML
apache-2.0
3,616
/* Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package json import ( "bytes" "io/ioutil" "testing" "github.com/GoogleCloudPlatform/kubernetes/pkg/api" "github.com/GoogleCloudPlatform/kubernetes/pkg/api/testapi" "github.com/GoogleCloudPlatform/kubernetes/pkg/runtime" "github.com/GoogleCloudPlatform/kubernetes/pkg/watch" ) func TestEncodeDecodeRoundTrip(t *testing.T) { testCases := []struct { Type watch.EventType Object runtime.Object Codec runtime.Codec }{ { watch.Added, &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}, testapi.Codec(), }, { watch.Modified, &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}, testapi.Codec(), }, { watch.Deleted, &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}, testapi.Codec(), }, } for i, testCase := range testCases { buf := &bytes.Buffer{} encoder := NewEncoder(buf, testCase.Codec) if err := encoder.Encode(&watch.Event{Type: testCase.Type, Object: testCase.Object}); err != nil { t.Errorf("%d: unexpected error: %v", i, err) continue } decoder := NewDecoder(ioutil.NopCloser(buf), testCase.Codec) event, obj, err := decoder.Decode() if err != nil { t.Errorf("%d: unexpected error: %v", i, err) continue } if !api.Semantic.DeepDerivative(testCase.Object, obj) { t.Errorf("%d: expected %#v, got %#v", i, testCase.Object, obj) } if event != testCase.Type { t.Errorf("%d: unexpected type: %#v", i, event) } } }
wattsteve/kubernetes-1
pkg/watch/json/encoder_test.go
GO
apache-2.0
1,994
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.metastore.events; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.hive.metastore.IHMSHandler; import org.apache.hadoop.hive.metastore.api.Database; /** * Database read event */ @InterfaceAudience.Public @InterfaceStability.Stable public class PreReadDatabaseEvent extends PreEventContext { private final Database db; public PreReadDatabaseEvent(Database db, IHMSHandler handler) { super(PreEventType.READ_DATABASE, handler); this.db = db; } /** * @return the db */ public Database getDatabase() { return db; } }
alanfgates/hive
standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/events/PreReadDatabaseEvent.java
Java
apache-2.0
1,483
#!/usr/bin/env python # Line too long - pylint: disable=C0301 # Invalid name - pylint: disable=C0103 """ parseutils.py Routines to parse "flexible" configuration files for tools like gpaddmirrors, gprecoverseg, gpexpand, etc. Copyright (c) EMC/Greenplum Inc 2011. All Rights Reserved. """ import sys from gppylib.mainUtils import ExceptionNoStackTraceNeeded from gppylib.gplog import get_default_logger, logging_is_verbose logger = get_default_logger() def caller(): "Return name of calling function" if logging_is_verbose(): return sys._getframe(1).f_code.co_name + '()' return '' def canonicalize_address(addr): """ Encases addresses in [ ] per RFC 2732. Generally used to deal with ':' characters which are also often used as delimiters. Returns the addr string if it doesn't contain any ':' characters. If addr contains ':' and also contains a '[' then the addr string is simply returned under the assumption that it is already escaped as needed. Otherwise return a new string from addr by adding '[' prefix and ']' suffix. Examples -------- >>> canonicalize_address('myhost') 'myhost' >>> canonicalize_address('127.0.0.1') '127.0.0.1' >>> canonicalize_address('::1') '[::1]' >>> canonicalize_address('[::1]') '[::1]' >>> canonicalize_address('2620:0:170:610::13') '[2620:0:170:610::13]' >>> canonicalize_address('[2620:0:170:610::13]') '[2620:0:170:610::13]' @param addr: the address to possibly encase in [ ] @returns: the addresss, encased in [] if necessary """ if ':' not in addr: return addr if '[' in addr: return addr return '[' + addr + ']' # # line parsing # def consume_to(delimiter, rest): """ Consume characters from rest string until we encounter the delimiter. Returns (None, after, None) where after are the characters after delimiter or (None, rest, 'does not contain '+delimiter) when delimiter is not encountered. Examples -------- >>> consume_to('=', 'abc=def:ghi') (None, 'def:ghi', None) @param delimiter: the delimiter string @param rest: the string to read such as 'abc:def:ghi' @returns: (None, after, None) tuple such as (None, 'def:ghi', None) """ p = rest.find(delimiter) if p < 0: return None, rest, 'does not contain '+delimiter return None, rest[p+1:], None def read_to(delimiter, rest): """ Read characters from rest string until we encounter the delimiter. Separate the string into characters 'before' and 'after' the delimiter. If no delimiter is found, assign entire string to 'before' and None to 'after'. Examples -------- >>> read_to(':', 'abc:def:ghi') ('abc', 'def:ghi', None) >>> read_to(':', 'abc:def') ('abc', 'def', None) >>> read_to(':', 'abc') ('abc', None, None) >>> read_to(':', '') ('', None, None) Note this returns a 3-tuple for compatibility with other routines which use the third element as an error message @param delimiter: the delimiter string @param rest: the string to read such as 'abc:def:ghi' @returns: (before, after, None) tuple such as ('abc', 'def:ghi', None) """ p = rest.find(delimiter) if p < 0: return rest, None, None return rest[0:p], rest[p+1:], None def read_to_bracketed(delimiter, rest): """ Read characters from rest string which is expected to start with a '['. If rest does not start with '[', return a tuple (None, rest, 'does not begin with ['). If rest string starts with a '[', then read until we find ']'. If no ']' is found, return a tuple (None, rest, 'does not contain ending ]'). Otherwise separate the string into 'before' representing characters between '[' and ']' and 'after' representing characters after the ']' and then check that the first character found after the ']' is a :'. If there are no characters after the ']', return a tuple (before, None, None) where before contains the characters between '[' and ']'. If there are characters after ']' other than the delimiter, return a tuple (None, rest, 'characters not allowed after ending ]') Otherwise return a tuple (before, after, None) where before contains the characters between '[' and ']' and after contains the characters after the ']:'. This function avoids raising Exceptions for these particular cases of malformed input since they are easier to report in the calling function. Examples -------- >>> read_to_bracketed(':', '[abc:def]') ('abc:def', None, None) >>> read_to_bracketed(':', '[abc]:def:ghi') ('abc', 'def:ghi', None) >>> read_to_bracketed(':', '[abc:def]:ghi:jkl') ('abc:def', 'ghi:jkl', None) >>> read_to_bracketed(':', 'abc:def:ghi:jkl') (None, 'abc:def:ghi:jkl', 'does not begin with [') >>> read_to_bracketed(':', '[abc:def:ghi:jkl') (None, '[abc:def:ghi:jkl', 'does not contain ending ]') >>> read_to_bracketed(':', '[abc]extra:def:ghi:jkl') (None, '[abc]extra:def:ghi:jkl', 'characters not allowed after ending ]') @param delimiter: the delimiter string @param rest: the string to read such as '[abc:def]:ghi' @returns: (before, after, reason) tuple such as ('abc:def', 'ghi', None) """ if not rest.startswith('['): return None, rest, 'does not begin with [' p = rest.find(']') if p < 0: return None, rest, 'does not contain ending ]' if len(rest[p+1:]) < 1: return rest[1:p], None, None if rest[p+1] != delimiter: return None, rest, 'characters not allowed after ending ]' return rest[1:p], rest[p+2:], None def read_to_possibly_bracketed(delimiter, rest): """ Behave as read_bracketed above when rest starts with a '[', otherwise as read_to_colon. This is intended to support fields which may contain an IPv6 address, an IPv4 address or a hostname. Examples -------- >>> read_to_possibly_bracketed(':', 'abc:def:ghi') ('abc', 'def:ghi', None) >>> read_to_possibly_bracketed(':', '[abc]:def:ghi') ('abc', 'def:ghi', None) >>> read_to_possibly_bracketed(':', '[abc:def]:ghi') ('abc:def', 'ghi', None) >>> read_to_possibly_bracketed(':', '[]:ghi') ('', 'ghi', None) >>> read_to_possibly_bracketed(':', ':ghi') ('', 'ghi', None) >>> read_to_possibly_bracketed(':', '[ghi]') ('ghi', None, None) >>> read_to_possibly_bracketed(':', '[]') ('', None, None) >>> read_to_possibly_bracketed(':', '') ('', None, None) @param delimiter: the delimiter string @param rest: the string to read such as '[abc:def]:ghi' @returns: (before, after, reason) tuple such as ('abc:def', 'ghi', None) """ if rest.startswith('['): return read_to_bracketed(delimiter, rest) return read_to(delimiter, rest) class LineParser: """ Manage state to parse a single line, generally from a configuration file with fields delimited by colons. """ def __init__(self, caller, filename, lineno, line): "Initialize" (self.caller, self.filename, self.lineno, self.line, self.rest, self.error) = (caller, filename, lineno, line, line, None) self.logger = logger if logging_is_verbose(): self.logger.debug("%s:%s" % (filename, lineno)) def ensure_more_to_process(self, name): "Raise an exception if we've exhausted the input line" if self.rest is None: msg = "out of values (reading %s)" % name raise ExceptionNoStackTraceNeeded("%s:%s:%s LINE >>%s\n%s" % (self.filename, self.lineno, self.caller, self.line, msg)) def read_delimited_field(self, delimiter, name="next field", reader=read_to): """ Attempts to read the next field in the line up to the specified delimiter using the specified reading method, raising any error encountered as an exception. Returns the read field when successful. """ self.ensure_more_to_process(name) value, self.rest, error = reader(delimiter, self.rest) if error is not None: msg = "%s (reading %s) >>%s" % (error, name, self.rest) raise ExceptionNoStackTraceNeeded("%s:%s:%s LINE >>%s\n%s" % (self.filename, self.lineno, self.caller, self.line, msg)) if logging_is_verbose(): self.logger.debug(" name=%-30s delimiter='%s' value=%s" % (name, delimiter, value)) return value def does_starts_with(self, expected): "Returns true if line starts with expected value, or return false" return self.line.startswith(expected) def ensure_starts_with(self, expected): "Returns true if line starts with expected value, or raise an exception otherwise" if not self.does_starts_with(expected): msg = "does not start with %s" % expected raise ExceptionNoStackTraceNeeded("%s:%s:%s LINE >>%s\n%s" % (self.filename, self.lineno, self.caller, self.line, msg)) self.rest = self.rest[len(expected):] def handle_field(self, name, dst=None, delimiter=':', stripchars=None): """ Attempts to read the next field up to a given delimiter. Names starting with '[' indicate that the field should use the bracketed parsing logic. If dst is not none, also assigns the value to dst[name]. If stripchars is not none, value is first stripped of leading and trailing stripchars. """ if name[0] == '[': name = name.strip('[]') value = self.read_delimited_field(delimiter, name, read_to_possibly_bracketed) else: value = self.read_delimited_field(delimiter, name) if stripchars is not None: value = value.strip(stripchars) if dst is not None: dst[name] = value return value # # file parsing # def line_reader(f): """ Read the contents of the given input, generating the non-blank non-comment lines found within as a series of tuples of the form (line number, line). >>> [l for l in line_reader(['', '# test', 'abc:def'])] [(3, 'abc:def')] """ for offset, line in enumerate(f): line = line.strip() if len(line) < 1 or line[0] == '#': continue yield offset+1, line ################ # gpfilespace format # # First line in file is the filespace name, remaining lines are # specify hostname, dbid, and a path: # # filespace:name # hostname:dbid:path # ... ################ def parse_fspacename(filename, lineno, line): """ Parse the filespace: line which appears at the beginning of the gpfilespace configuration file. >>> parse_fspacename('file', 1, 'filespace:blah') 'blah' """ p = LineParser(caller(), filename, lineno, line) p.ensure_starts_with('filespace:') fspacename = p.read_delimited_field(':') if p.rest is not None: msg = "unexpected characters after filespace name >>%s" % p.rest raise ExceptionNoStackTraceNeeded("%s:%s:%s LINE >>%s\n%s" % (filename, lineno, caller(), line, msg)) return fspacename def parse_dfs_url(filename, lineno, line): """ Parse the filespace: line which appears at the beginning of the gpfilespace configuration file. >>> parse_dfs_url('file', 1, 'dfs_url::localhost:9000/gpsql') 'localhost:9000/gpsql' """ p = LineParser(caller(), filename, lineno, line) p.ensure_starts_with('dfs_url::') dfs_url = p.read_delimited_field('::') if p.rest is not None: msg = "unexpected characters after filespace name >>%s" % p.rest raise ExceptionNoStackTraceNeeded("%s:%s:%s LINE >>%s\n%s" % (filename, lineno, caller(), line, msg)) return dfs_url def parse_fspacesys(filename, lineno, line): """ Pasrse the filesystem name: the optional second line in the gpfilespace configuration file. >>> parse_fspacetype('file', 2, 'fsysname:local|filesystem_name') local|filesystem_name """ p = LineParser(caller(), filename, lineno, line) if not p.does_starts_with('fsysname:'): return None p.ensure_starts_with('fsysname:') fsysname = p.read_delimited_field(':') if p.rest is not None: msg = "unexpected characters after filespace type >>%s" % p.rest raise ExceptionNoStackTraceNeeded("%s:%s:%s LINE >>%s\n%s" % (filename, lineno, caller(), line, msg)) return fsysname def parse_fspacereplica(filename, lineno, line): """ Pasrse the filespace replica: the optional third line in the gpfilespace configuration file. >>> parse_fspacereplica('file', 3, 'fsreplica:repnum') repnum """ p = LineParser(caller(), filename, lineno, line) if not p.does_starts_with('fsreplica:'): return None p.ensure_starts_with('fsreplica:') fsreplica = p.read_delimited_field(':') if p.rest is not None: msg = "unexpected characters after filespace replica >>%s" % p.rest raise ExceptionNoStackTraceNeeded("%s:%s:%s LINE >>%s\n%s" % (filename, lineno, caller(), line, msg)) return fsreplica def parse_gpfilespace_line(filename, lineno, line): """ Parse a line of the gpfilespace configuration file other than the first. >>> parse_gpfilespace_line('file', 1, '[::1]:dbid:path') ('::1', 'dbid', 'path') >>> parse_gpfilespace_line('file', 1, 'host:dbid:path') ('host', 'dbid', 'path') """ p = LineParser(caller(), filename, lineno, line) host = p.handle_field('[host]') # [host] indicates possible IPv6 address dbid = p.handle_field('dbid') path = p.handle_field('[path]') # url contains the ':'. if p.rest is not None: msg = "unexpected characters after path name >>%s" % p.rest raise ExceptionNoStackTraceNeeded("%s:%s:%s LINE >>%s\n%s" % (filename, lineno, caller(), line, msg)) return host, dbid, path ################ # gpexpand segment file format: # # Form of file is hostname:address:port:dtadir:dbid:contentId:role[:replicationPort] ################ def parse_gpexpand_segment_line(filename, lineno, line): """ Parse a line of the gpexpand configuration file. >>> parse_gpexpand_segment_line('file', 1, "localhost:[::1]:40001:/Users/ctaylor/data/p2/gpseg1:4:1:p") ('localhost', '::1', '40001', '/Users/ctaylor/data/p2/gpseg1', '4', '1', 'p', None) >>> parse_gpexpand_segment_line('file', 1, "localhost:[::1]:40001:/Users/ctaylor/data/p2/gpseg1:4:1:p:41001") ('localhost', '::1', '40001', '/Users/ctaylor/data/p2/gpseg1', '4', '1', 'p', '41001') """ p = LineParser(caller(), filename, lineno, line) hostname = p.handle_field('[host]') # [host] indicates possible IPv6 address address = p.handle_field('[address]') # [address] indicates possible IPv6 address port = p.handle_field('port') datadir = p.handle_field('datadir') dbid = p.handle_field('dbid') contentId = p.handle_field('contentId') role = p.handle_field('role') replicationPort = None if p.rest is not None: replicationPort = p.handle_field('replicationPort') if p.rest is not None: msg = "unexpected characters after replicationPort >>%s" % p.rest raise ExceptionNoStackTraceNeeded("%s:%s:%s LINE >>%s\n%s" % (filename, lineno, caller(), line, msg)) return hostname, address, port, datadir, dbid, contentId, role, replicationPort ################ # gpaddmirrors format: # # filespaceOrder=[filespace1_fsname[:filespace2_fsname:...]] # mirror[content]=content:address:port:mir_replication_port:pri_replication_port:fselocation[:fselocation:...] # ################ def parse_filespace_order(filename, lineno, line): """ Parse the filespaceOrder= line appearing at the beginning of the gpaddmirrors, gpmovemirrors and gprecoverseg configuration files. >>> parse_filespace_order('file', 1, "filespaceOrder=fs1:fs2:fs3") ['fs1', 'fs2', 'fs3'] >>> parse_filespace_order('file', 1, "filespaceOrder=") [] """ p = LineParser(caller(), filename, lineno, line) p.ensure_starts_with('filespaceOrder=') fslist = [] while p.rest: fslist.append( p.read_delimited_field(':', 'next filespace') ) return fslist def parse_gpaddmirrors_line(filename, lineno, line, fslist): """ Parse a line in the gpaddmirrors configuration file other than the first. >>> line = "mirror0=0:[::1]:40001:50001:60001:/Users/ctaylor/data/p2/gpseg1" >>> fixed, flex = parse_gpaddmirrors_line('file', 1, line, []) >>> fixed["address"], fixed["contentId"], fixed["dataDirectory"] ('::1', '0', '/Users/ctaylor/data/p2/gpseg1') """ fixed = {} flexible = {} p = LineParser(caller(), filename, lineno, line) p.ensure_starts_with('mirror') p.read_delimited_field('=', 'content id', consume_to) # [address] indicates possible IPv6 address for field in [ 'contentId', '[address]', 'port', 'replicationPort', 'primarySegmentReplicationPort', 'dataDirectory' ]: p.handle_field(field, fixed) for fsname in fslist: p.handle_field('[' + fsname + ']', flexible) return fixed, flexible ################ # gpmovemirrors format: # # This is basically the same as the gprecoverseg format (since gpmovemirrors ultimately just # passes the input file after validating it) but the field names are slightly different. # # filespaceOrder=[filespace1_fsname[:filespace2_fsname:...] # old_address:port:datadir new_address:port:replication_port:datadir[:fselocation:...] # ^ # note space ################ def parse_gpmovemirrors_line(filename, lineno, line, fslist): """ Parse a line in the gpmovemirrors configuration file other than the first. >>> line = "[::1]:40001:/Users/ctaylor/data/m2/gpseg1 [::2]:40101:50101:/Users/ctaylor/data/m2/gpseg1:/fs1" >>> fixed, flex = parse_gpmovemirrors_line('file', 1, line, ['fs1']) >>> fixed["oldAddress"], fixed["newAddress"] ('::1', '::2') >>> flex {'fs1': '/fs1'} """ groups = len(line.split()) if groups != 2: msg = "need two groups of fields delimited by a space for old and new mirror, not %d" % groups raise ExceptionNoStackTraceNeeded("%s:%s:%s LINE >>%s\n%s" % (filename, lineno, caller(), line, msg)) fixed = {} flexible = {} p = LineParser(caller(), filename, lineno, line) p.handle_field('[oldAddress]', fixed) # [oldAddress] indicates possible IPv6 address p.handle_field('oldPort', fixed) p.handle_field('oldDataDirectory', fixed, delimiter=' ', stripchars=' \t') # MPP-15675 note stripchars here and next line p.handle_field('[newAddress]', fixed, stripchars=' \t') # [newAddress] indicates possible IPv6 address p.handle_field('newPort', fixed) p.handle_field('newReplicationPort', fixed) p.handle_field('newDataDirectory', fixed) for fsname in fslist: p.handle_field(fsname, flexible) if p.rest is not None: msg = "unexpected characters after mirror fields >>%s" % p.rest raise ExceptionNoStackTraceNeeded("%s:%s:%s LINE >>%s\n%s" % (filename, lineno, caller(), line, msg)) return fixed, flexible ################ # gprecoverseg format: # # filespaceOrder=[filespace1_fsname[:filespace2_fsname:...]] # failed_host_address:port:datadir [recovery_host_address:port:replication_port:datadir[:fselocation:...]] # ^ # note space # # filespace locations are only present at the end of the other fields when there # are two groups of fields separated by a space. If there is only one group of # fields then we assume the entire line is only three fields as below with no # filespace locations: # # failed_host_address:port:datadir ################ def parse_gprecoverseg_line(filename, lineno, line, fslist): """ Parse a line in the gprecoverseg configuration file other than the first. >>> line = "[::1]:40001:/Users/ctaylor/data/m2/gpseg1" >>> fixed, flex = parse_gprecoverseg_line('file', 1, line, []) >>> fixed["failedAddress"], fixed["failedPort"], fixed["failedDataDirectory"] ('::1', '40001', '/Users/ctaylor/data/m2/gpseg1') >>> line = "[::1]:40001:/Users/ctaylor/data/m2/gpseg1 [::2]:40101:50101:/Users/ctaylor/data/m2/gpseg1:/fs1" >>> fixed, flex = parse_gprecoverseg_line('file', 1, line, ['fs1']) >>> fixed["newAddress"], fixed["newPort"], fixed["newReplicationPort"], fixed["newDataDirectory"] ('::2', '40101', '50101', '/Users/ctaylor/data/m2/gpseg1') >>> flex {'fs1': '/fs1'} """ groups = len(line.split()) if groups not in [1, 2]: msg = "only one or two groups of fields delimited by a space, not %d" % groups raise ExceptionNoStackTraceNeeded("%s:%s:%s LINE >>%s\n%s" % (filename, lineno, caller(), line, msg)) fixed = {} flexible = {} p = LineParser(caller(), filename, lineno, line) p.handle_field('[failedAddress]', fixed) # [failedAddress] indicates possible IPv6 address p.handle_field('failedPort', fixed) if groups == 1: p.handle_field('failedDataDirectory', fixed) else: p.handle_field('failedDataDirectory', fixed, delimiter=' ', stripchars=' \t') # MPP-15675 note stripchars here and next line p.handle_field('[newAddress]', fixed, stripchars=' \t') # [newAddress] indicates possible IPv6 address p.handle_field('newPort', fixed) p.handle_field('newReplicationPort', fixed) p.handle_field('newDataDirectory', fixed) for fsname in fslist: p.handle_field('[' + fsname + ']', flexible) return fixed, flexible if __name__ == '__main__': import doctest doctest.testmod()
PGer/incubator-hawq
tools/bin/gppylib/parseutils.py
Python
apache-2.0
22,013
package org.keycloak.example.oauth; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.jboss.logging.Logger; import org.keycloak.KeycloakSecurityContext; import org.keycloak.adapters.AdapterUtils; import org.keycloak.servlet.ServletOAuthClient; import org.keycloak.util.JsonSerialization; import org.keycloak.util.UriUtils; import javax.enterprise.context.ApplicationScoped; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a> * @version $Revision: 1 $ */ @ApplicationScoped @Named("databaseClient") public class DatabaseClient { @Inject @ServletRequestQualifier private HttpServletRequest request; @Inject private HttpServletResponse response; @Inject private FacesContext facesContext; @Inject private ServletOAuthClient oauthClient; @Inject private UserData userData; private static final Logger logger = Logger.getLogger(DatabaseClient.class); public void retrieveAccessToken() { try { oauthClient.redirectRelative("client.jsf", request, response); } catch (IOException e) { throw new RuntimeException(e); } } static class TypedList extends ArrayList<String> {} public void sendCustomersRequest() { List<String> customers = sendRequestToDBApplication(getBaseUrl() + "/database/customers"); userData.setCustomers(customers); } public void sendProductsRequest() { List<String> products = sendRequestToDBApplication(getBaseUrl() + "/database/products"); userData.setProducts(products); } protected List<String> sendRequestToDBApplication(String dbUri) { HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(dbUri); try { if (userData.isHasAccessToken()) { get.addHeader("Authorization", "Bearer " + userData.getAccessToken()); } HttpResponse response = client.execute(get); switch (response.getStatusLine().getStatusCode()) { case 200: HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); try { return JsonSerialization.readValue(is, TypedList.class); } finally { is.close(); } case 401: facesContext.addMessage(null, new FacesMessage("Status: 401. Request not authenticated! You need to retrieve access token first.")); break; case 403: facesContext.addMessage(null, new FacesMessage("Status: 403. Access token has insufficient privileges")); break; default: facesContext.addMessage(null, new FacesMessage("Status: " + response.getStatusLine() + ". Not able to retrieve data. See log for details")); logger.warn("Error occured. Status: " + response.getStatusLine()); } return null; } catch (IOException e) { e.printStackTrace(); facesContext.addMessage(null, new FacesMessage("Unknown error. See log for details")); return null; } } public String getBaseUrl() { KeycloakSecurityContext session = (KeycloakSecurityContext)request.getAttribute(KeycloakSecurityContext.class.getName()); return AdapterUtils.getOriginForRestCalls(request.getRequestURL().toString(), session); } }
eugene-chow/keycloak
examples/demo-template/third-party-cdi/src/main/java/org/keycloak/example/oauth/DatabaseClient.java
Java
apache-2.0
4,047
# Oblivki ## Example ```html <amp-ad width="300" height="250" type="oblivki" data-use-a4a="true" data-block-key="XgSNxZnGpAmULblp9d23" src="https://oblivki.biz/amp_a4a?key=XgSNxZnGpAmULblp9d23" > </amp-ad> ``` ## Configuration For configuration details and to generate your tags, please contact support@oblivki.biz Supported parameters: - `data-block-key`
alanorozco/amphtml
ads/vendors/oblivki.md
Markdown
apache-2.0
376
<?php final class PhortuneLandingController extends PhortuneController { public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $accounts = PhortuneAccountQuery::loadAccountsForUser( $viewer, PhabricatorContentSource::newFromRequest($request)); if (count($accounts) == 1) { $account = head($accounts); $next_uri = $this->getApplicationURI($account->getID().'/'); } else { $next_uri = $this->getApplicationURI('account/'); } return id(new AphrontRedirectResponse())->setURI($next_uri); } }
gsinkovskiy/phabricator
src/applications/phortune/controller/PhortuneLandingController.php
PHP
apache-2.0
588
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.optimizer.stats.annotation; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.ql.lib.NodeProcessorCtx; import org.apache.hadoop.hive.ql.parse.ParseContext; import org.apache.hadoop.hive.ql.plan.Statistics; public class AnnotateStatsProcCtx implements NodeProcessorCtx { private ParseContext pctx; private HiveConf conf; private Statistics andExprStats = null; public AnnotateStatsProcCtx(ParseContext pctx) { this.setParseContext(pctx); if(pctx != null) { this.setConf(pctx.getConf()); } else { this.setConf(null); } } public HiveConf getConf() { return conf; } public void setConf(HiveConf conf) { this.conf = conf; } public ParseContext getParseContext() { return pctx; } public void setParseContext(ParseContext pctx) { this.pctx = pctx; } public Statistics getAndExprStats() { return andExprStats; } public void setAndExprStats(Statistics andExprStats) { this.andExprStats = andExprStats; } }
cschenyuan/hive-hack
ql/src/java/org/apache/hadoop/hive/ql/optimizer/stats/annotation/AnnotateStatsProcCtx.java
Java
apache-2.0
1,861
from collections import OrderedDict import copy import operator from functools import partial, reduce, update_wrapper import warnings from django import forms from django.conf import settings from django.contrib import messages from django.contrib.admin import widgets, helpers from django.contrib.admin import validation from django.contrib.admin.checks import (BaseModelAdminChecks, ModelAdminChecks, InlineModelAdminChecks) from django.contrib.admin.exceptions import DisallowedModelAdminToField from django.contrib.admin.utils import (quote, unquote, flatten_fieldsets, get_deleted_objects, model_format_dict, NestedObjects, lookup_needs_distinct) from django.contrib.admin.templatetags.admin_static import static from django.contrib.admin.templatetags.admin_urls import add_preserved_filters from django.contrib.auth import get_permission_codename from django.core import checks from django.core.exceptions import (PermissionDenied, ValidationError, FieldError, ImproperlyConfigured) from django.core.paginator import Paginator from django.core.urlresolvers import reverse from django.db import models, transaction, router from django.db.models.constants import LOOKUP_SEP from django.db.models.related import RelatedObject from django.db.models.fields import BLANK_CHOICE_DASH, FieldDoesNotExist from django.db.models.sql.constants import QUERY_TERMS from django.forms.formsets import all_valid, DELETION_FIELD_NAME from django.forms.models import (modelform_factory, modelformset_factory, inlineformset_factory, BaseInlineFormSet, modelform_defines_fields) from django.http import Http404, HttpResponseRedirect from django.http.response import HttpResponseBase from django.shortcuts import get_object_or_404 from django.template.response import SimpleTemplateResponse, TemplateResponse from django.utils import six from django.utils.decorators import method_decorator from django.utils.deprecation import (RenameMethodsBase, RemovedInDjango18Warning, RemovedInDjango19Warning) from django.utils.encoding import force_text, python_2_unicode_compatible from django.utils.html import escape, escapejs from django.utils.http import urlencode from django.utils.text import capfirst, get_text_list from django.utils.translation import ugettext as _ from django.utils.translation import ungettext from django.utils.safestring import mark_safe from django.views.decorators.csrf import csrf_protect IS_POPUP_VAR = '_popup' TO_FIELD_VAR = '_to_field' HORIZONTAL, VERTICAL = 1, 2 def get_content_type_for_model(obj): # Since this module gets imported in the application's root package, # it cannot import models from other applications at the module level. from django.contrib.contenttypes.models import ContentType return ContentType.objects.get_for_model(obj, for_concrete_model=False) def get_ul_class(radio_style): return 'radiolist' if radio_style == VERTICAL else 'radiolist inline' class IncorrectLookupParameters(Exception): pass # Defaults for formfield_overrides. ModelAdmin subclasses can change this # by adding to ModelAdmin.formfield_overrides. FORMFIELD_FOR_DBFIELD_DEFAULTS = { models.DateTimeField: { 'form_class': forms.SplitDateTimeField, 'widget': widgets.AdminSplitDateTime }, models.DateField: {'widget': widgets.AdminDateWidget}, models.TimeField: {'widget': widgets.AdminTimeWidget}, models.TextField: {'widget': widgets.AdminTextareaWidget}, models.URLField: {'widget': widgets.AdminURLFieldWidget}, models.IntegerField: {'widget': widgets.AdminIntegerFieldWidget}, models.BigIntegerField: {'widget': widgets.AdminBigIntegerFieldWidget}, models.CharField: {'widget': widgets.AdminTextInputWidget}, models.ImageField: {'widget': widgets.AdminFileWidget}, models.FileField: {'widget': widgets.AdminFileWidget}, models.EmailField: {'widget': widgets.AdminEmailInputWidget}, } csrf_protect_m = method_decorator(csrf_protect) class RenameBaseModelAdminMethods(forms.MediaDefiningClass, RenameMethodsBase): renamed_methods = ( ('queryset', 'get_queryset', RemovedInDjango18Warning), ) class BaseModelAdmin(six.with_metaclass(RenameBaseModelAdminMethods)): """Functionality common to both ModelAdmin and InlineAdmin.""" raw_id_fields = () fields = None exclude = None fieldsets = None form = forms.ModelForm filter_vertical = () filter_horizontal = () radio_fields = {} prepopulated_fields = {} formfield_overrides = {} readonly_fields = () ordering = None view_on_site = True # Validation of ModelAdmin definitions # Old, deprecated style: validator_class = None default_validator_class = validation.BaseValidator # New style: checks_class = BaseModelAdminChecks @classmethod def validate(cls, model): warnings.warn( 'ModelAdmin.validate() is deprecated. Use "check()" instead.', RemovedInDjango19Warning) if cls.validator_class: validator = cls.validator_class() else: validator = cls.default_validator_class() validator.validate(cls, model) @classmethod def check(cls, model, **kwargs): if cls.validator_class: warnings.warn( 'ModelAdmin.validator_class is deprecated. ' 'ModeAdmin validators must be converted to use ' 'the system check framework.', RemovedInDjango19Warning) validator = cls.validator_class() try: validator.validate(cls, model) except ImproperlyConfigured as e: return [checks.Error(e.args[0], hint=None, obj=cls)] else: return [] else: return cls.checks_class().check(cls, model, **kwargs) def __init__(self): overrides = FORMFIELD_FOR_DBFIELD_DEFAULTS.copy() overrides.update(self.formfield_overrides) self.formfield_overrides = overrides def formfield_for_dbfield(self, db_field, **kwargs): """ Hook for specifying the form Field instance for a given database Field instance. If kwargs are given, they're passed to the form Field's constructor. """ request = kwargs.pop("request", None) # If the field specifies choices, we don't need to look for special # admin widgets - we just need to use a select widget of some kind. if db_field.choices: return self.formfield_for_choice_field(db_field, request, **kwargs) # ForeignKey or ManyToManyFields if isinstance(db_field, (models.ForeignKey, models.ManyToManyField)): # Combine the field kwargs with any options for formfield_overrides. # Make sure the passed in **kwargs override anything in # formfield_overrides because **kwargs is more specific, and should # always win. if db_field.__class__ in self.formfield_overrides: kwargs = dict(self.formfield_overrides[db_field.__class__], **kwargs) # Get the correct formfield. if isinstance(db_field, models.ForeignKey): formfield = self.formfield_for_foreignkey(db_field, request, **kwargs) elif isinstance(db_field, models.ManyToManyField): formfield = self.formfield_for_manytomany(db_field, request, **kwargs) # For non-raw_id fields, wrap the widget with a wrapper that adds # extra HTML -- the "add other" interface -- to the end of the # rendered output. formfield can be None if it came from a # OneToOneField with parent_link=True or a M2M intermediary. if formfield and db_field.name not in self.raw_id_fields: related_modeladmin = self.admin_site._registry.get(db_field.rel.to) can_add_related = bool(related_modeladmin and related_modeladmin.has_add_permission(request)) formfield.widget = widgets.RelatedFieldWidgetWrapper( formfield.widget, db_field.rel, self.admin_site, can_add_related=can_add_related) return formfield # If we've got overrides for the formfield defined, use 'em. **kwargs # passed to formfield_for_dbfield override the defaults. for klass in db_field.__class__.mro(): if klass in self.formfield_overrides: kwargs = dict(copy.deepcopy(self.formfield_overrides[klass]), **kwargs) return db_field.formfield(**kwargs) # For any other type of field, just call its formfield() method. return db_field.formfield(**kwargs) def formfield_for_choice_field(self, db_field, request=None, **kwargs): """ Get a form Field for a database Field that has declared choices. """ # If the field is named as a radio_field, use a RadioSelect if db_field.name in self.radio_fields: # Avoid stomping on custom widget/choices arguments. if 'widget' not in kwargs: kwargs['widget'] = widgets.AdminRadioSelect(attrs={ 'class': get_ul_class(self.radio_fields[db_field.name]), }) if 'choices' not in kwargs: kwargs['choices'] = db_field.get_choices( include_blank=db_field.blank, blank_choice=[('', _('None'))] ) return db_field.formfield(**kwargs) def get_field_queryset(self, db, db_field, request): """ If the ModelAdmin specifies ordering, the queryset should respect that ordering. Otherwise don't specify the queryset, let the field decide (returns None in that case). """ related_admin = self.admin_site._registry.get(db_field.rel.to, None) if related_admin is not None: ordering = related_admin.get_ordering(request) if ordering is not None and ordering != (): return db_field.rel.to._default_manager.using(db).order_by(*ordering) return None def formfield_for_foreignkey(self, db_field, request=None, **kwargs): """ Get a form Field for a ForeignKey. """ db = kwargs.get('using') if db_field.name in self.raw_id_fields: kwargs['widget'] = widgets.ForeignKeyRawIdWidget(db_field.rel, self.admin_site, using=db) elif db_field.name in self.radio_fields: kwargs['widget'] = widgets.AdminRadioSelect(attrs={ 'class': get_ul_class(self.radio_fields[db_field.name]), }) kwargs['empty_label'] = _('None') if db_field.blank else None if 'queryset' not in kwargs: queryset = self.get_field_queryset(db, db_field, request) if queryset is not None: kwargs['queryset'] = queryset return db_field.formfield(**kwargs) def formfield_for_manytomany(self, db_field, request=None, **kwargs): """ Get a form Field for a ManyToManyField. """ # If it uses an intermediary model that isn't auto created, don't show # a field in admin. if not db_field.rel.through._meta.auto_created: return None db = kwargs.get('using') if db_field.name in self.raw_id_fields: kwargs['widget'] = widgets.ManyToManyRawIdWidget(db_field.rel, self.admin_site, using=db) kwargs['help_text'] = '' elif db_field.name in (list(self.filter_vertical) + list(self.filter_horizontal)): kwargs['widget'] = widgets.FilteredSelectMultiple(db_field.verbose_name, (db_field.name in self.filter_vertical)) if 'queryset' not in kwargs: queryset = self.get_field_queryset(db, db_field, request) if queryset is not None: kwargs['queryset'] = queryset return db_field.formfield(**kwargs) def get_view_on_site_url(self, obj=None): if obj is None or not self.view_on_site: return None if callable(self.view_on_site): return self.view_on_site(obj) elif self.view_on_site and hasattr(obj, 'get_absolute_url'): # use the ContentType lookup if view_on_site is True return reverse('admin:view_on_site', kwargs={ 'content_type_id': get_content_type_for_model(obj).pk, 'object_id': obj.pk }) @property def declared_fieldsets(self): warnings.warn( "ModelAdmin.declared_fieldsets is deprecated and " "will be removed in Django 1.9.", RemovedInDjango19Warning, stacklevel=2 ) if self.fieldsets: return self.fieldsets elif self.fields: return [(None, {'fields': self.fields})] return None def get_fields(self, request, obj=None): """ Hook for specifying fields. """ return self.fields def get_fieldsets(self, request, obj=None): """ Hook for specifying fieldsets. """ # We access the property and check if it triggers a warning. # If it does, then it's ours and we can safely ignore it, but if # it doesn't then it has been overridden so we must warn about the # deprecation. with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") declared_fieldsets = self.declared_fieldsets if len(w) != 1 or not issubclass(w[0].category, RemovedInDjango19Warning): warnings.warn( "ModelAdmin.declared_fieldsets is deprecated and " "will be removed in Django 1.9.", RemovedInDjango19Warning ) if declared_fieldsets: return declared_fieldsets if self.fieldsets: return self.fieldsets return [(None, {'fields': self.get_fields(request, obj)})] def get_ordering(self, request): """ Hook for specifying field ordering. """ return self.ordering or () # otherwise we might try to *None, which is bad ;) def get_readonly_fields(self, request, obj=None): """ Hook for specifying custom readonly fields. """ return self.readonly_fields def get_prepopulated_fields(self, request, obj=None): """ Hook for specifying custom prepopulated fields. """ return self.prepopulated_fields def get_queryset(self, request): """ Returns a QuerySet of all model instances that can be edited by the admin site. This is used by changelist_view. """ qs = self.model._default_manager.get_queryset() # TODO: this should be handled by some parameter to the ChangeList. ordering = self.get_ordering(request) if ordering: qs = qs.order_by(*ordering) return qs def lookup_allowed(self, lookup, value): from django.contrib.admin.filters import SimpleListFilter model = self.model # Check FKey lookups that are allowed, so that popups produced by # ForeignKeyRawIdWidget, on the basis of ForeignKey.limit_choices_to, # are allowed to work. for l in model._meta.related_fkey_lookups: # As ``limit_choices_to`` can be a callable, invoke it here. if callable(l): l = l() for k, v in widgets.url_params_from_lookup_dict(l).items(): if k == lookup and v == value: return True parts = lookup.split(LOOKUP_SEP) # Last term in lookup is a query term (__exact, __startswith etc) # This term can be ignored. if len(parts) > 1 and parts[-1] in QUERY_TERMS: parts.pop() # Special case -- foo__id__exact and foo__id queries are implied # if foo has been specifically included in the lookup list; so # drop __id if it is the last part. However, first we need to find # the pk attribute name. rel_name = None for part in parts[:-1]: try: field, _, _, _ = model._meta.get_field_by_name(part) except FieldDoesNotExist: # Lookups on non-existent fields are ok, since they're ignored # later. return True if hasattr(field, 'rel'): if field.rel is None: # This property or relation doesn't exist, but it's allowed # since it's ignored in ChangeList.get_filters(). return True model = field.rel.to if hasattr(field.rel, 'get_related_field'): rel_name = field.rel.get_related_field().name else: rel_name = None elif isinstance(field, RelatedObject): model = field.model rel_name = model._meta.pk.name else: rel_name = None if rel_name and len(parts) > 1 and parts[-1] == rel_name: parts.pop() if len(parts) == 1: return True clean_lookup = LOOKUP_SEP.join(parts) valid_lookups = [self.date_hierarchy] for filter_item in self.list_filter: if isinstance(filter_item, type) and issubclass(filter_item, SimpleListFilter): valid_lookups.append(filter_item.parameter_name) elif isinstance(filter_item, (list, tuple)): valid_lookups.append(filter_item[0]) else: valid_lookups.append(filter_item) return clean_lookup in valid_lookups def to_field_allowed(self, request, to_field): """ Returns True if the model associated with this admin should be allowed to be referenced by the specified field. """ opts = self.model._meta try: field = opts.get_field(to_field) except FieldDoesNotExist: return False # Check whether this model is the origin of a M2M relationship # in which case to_field has to be the pk on this model. if opts.many_to_many and field.primary_key: return True # Make sure at least one of the models registered for this site # references this field through a FK or a M2M relationship. registered_models = set() for model, admin in self.admin_site._registry.items(): registered_models.add(model) for inline in admin.inlines: registered_models.add(inline.model) for related_object in (opts.get_all_related_objects(include_hidden=True) + opts.get_all_related_many_to_many_objects()): related_model = related_object.model if (any(issubclass(model, related_model) for model in registered_models) and related_object.field.rel.get_related_field() == field): return True return False def has_add_permission(self, request): """ Returns True if the given request has permission to add an object. Can be overridden by the user in subclasses. """ opts = self.opts codename = get_permission_codename('add', opts) return request.user.has_perm("%s.%s" % (opts.app_label, codename)) def has_change_permission(self, request, obj=None): """ Returns True if the given request has permission to change the given Django model instance, the default implementation doesn't examine the `obj` parameter. Can be overridden by the user in subclasses. In such case it should return True if the given request has permission to change the `obj` model instance. If `obj` is None, this should return True if the given request has permission to change *any* object of the given type. """ opts = self.opts codename = get_permission_codename('change', opts) return request.user.has_perm("%s.%s" % (opts.app_label, codename)) def has_delete_permission(self, request, obj=None): """ Returns True if the given request has permission to change the given Django model instance, the default implementation doesn't examine the `obj` parameter. Can be overridden by the user in subclasses. In such case it should return True if the given request has permission to delete the `obj` model instance. If `obj` is None, this should return True if the given request has permission to delete *any* object of the given type. """ opts = self.opts codename = get_permission_codename('delete', opts) return request.user.has_perm("%s.%s" % (opts.app_label, codename)) @python_2_unicode_compatible class ModelAdmin(BaseModelAdmin): "Encapsulates all admin options and functionality for a given model." list_display = ('__str__',) list_display_links = () list_filter = () list_select_related = False list_per_page = 100 list_max_show_all = 200 list_editable = () search_fields = () date_hierarchy = None save_as = False save_on_top = False paginator = Paginator preserve_filters = True inlines = [] # Custom templates (designed to be over-ridden in subclasses) add_form_template = None change_form_template = None change_list_template = None delete_confirmation_template = None delete_selected_confirmation_template = None object_history_template = None # Actions actions = [] action_form = helpers.ActionForm actions_on_top = True actions_on_bottom = False actions_selection_counter = True # validation # Old, deprecated style: default_validator_class = validation.ModelAdminValidator # New style: checks_class = ModelAdminChecks def __init__(self, model, admin_site): self.model = model self.opts = model._meta self.admin_site = admin_site super(ModelAdmin, self).__init__() def __str__(self): return "%s.%s" % (self.model._meta.app_label, self.__class__.__name__) def get_inline_instances(self, request, obj=None): inline_instances = [] for inline_class in self.inlines: inline = inline_class(self.model, self.admin_site) if request: if not (inline.has_add_permission(request) or inline.has_change_permission(request, obj) or inline.has_delete_permission(request, obj)): continue if not inline.has_add_permission(request): inline.max_num = 0 inline_instances.append(inline) return inline_instances def get_urls(self): from django.conf.urls import patterns, url def wrap(view): def wrapper(*args, **kwargs): return self.admin_site.admin_view(view)(*args, **kwargs) return update_wrapper(wrapper, view) info = self.model._meta.app_label, self.model._meta.model_name urlpatterns = patterns('', url(r'^$', wrap(self.changelist_view), name='%s_%s_changelist' % info), url(r'^add/$', wrap(self.add_view), name='%s_%s_add' % info), url(r'^(.+)/history/$', wrap(self.history_view), name='%s_%s_history' % info), url(r'^(.+)/delete/$', wrap(self.delete_view), name='%s_%s_delete' % info), url(r'^(.+)/$', wrap(self.change_view), name='%s_%s_change' % info), ) return urlpatterns def urls(self): return self.get_urls() urls = property(urls) @property def media(self): extra = '' if settings.DEBUG else '.min' js = [ 'core.js', 'admin/RelatedObjectLookups.js', 'jquery%s.js' % extra, 'jquery.init.js' ] if self.actions is not None: js.append('actions%s.js' % extra) if self.prepopulated_fields: js.extend(['urlify.js', 'prepopulate%s.js' % extra]) return forms.Media(js=[static('admin/js/%s' % url) for url in js]) def get_model_perms(self, request): """ Returns a dict of all perms for this model. This dict has the keys ``add``, ``change``, and ``delete`` mapping to the True/False for each of those actions. """ return { 'add': self.has_add_permission(request), 'change': self.has_change_permission(request), 'delete': self.has_delete_permission(request), } def get_fields(self, request, obj=None): if self.fields: return self.fields form = self.get_form(request, obj, fields=None) return list(form.base_fields) + list(self.get_readonly_fields(request, obj)) def get_form(self, request, obj=None, **kwargs): """ Returns a Form class for use in the admin add view. This is used by add_view and change_view. """ if 'fields' in kwargs: fields = kwargs.pop('fields') else: fields = flatten_fieldsets(self.get_fieldsets(request, obj)) if self.exclude is None: exclude = [] else: exclude = list(self.exclude) exclude.extend(self.get_readonly_fields(request, obj)) if self.exclude is None and hasattr(self.form, '_meta') and self.form._meta.exclude: # Take the custom ModelForm's Meta.exclude into account only if the # ModelAdmin doesn't define its own. exclude.extend(self.form._meta.exclude) # if exclude is an empty list we pass None to be consistent with the # default on modelform_factory exclude = exclude or None defaults = { "form": self.form, "fields": fields, "exclude": exclude, "formfield_callback": partial(self.formfield_for_dbfield, request=request), } defaults.update(kwargs) if defaults['fields'] is None and not modelform_defines_fields(defaults['form']): defaults['fields'] = forms.ALL_FIELDS try: return modelform_factory(self.model, **defaults) except FieldError as e: raise FieldError('%s. Check fields/fieldsets/exclude attributes of class %s.' % (e, self.__class__.__name__)) def get_changelist(self, request, **kwargs): """ Returns the ChangeList class for use on the changelist page. """ from django.contrib.admin.views.main import ChangeList return ChangeList def get_object(self, request, object_id): """ Returns an instance matching the primary key provided. ``None`` is returned if no match is found (or the object_id failed validation against the primary key field). """ queryset = self.get_queryset(request) model = queryset.model try: object_id = model._meta.pk.to_python(object_id) return queryset.get(pk=object_id) except (model.DoesNotExist, ValidationError, ValueError): return None def get_changelist_form(self, request, **kwargs): """ Returns a Form class for use in the Formset on the changelist page. """ defaults = { "formfield_callback": partial(self.formfield_for_dbfield, request=request), } defaults.update(kwargs) if (defaults.get('fields') is None and not modelform_defines_fields(defaults.get('form'))): defaults['fields'] = forms.ALL_FIELDS return modelform_factory(self.model, **defaults) def get_changelist_formset(self, request, **kwargs): """ Returns a FormSet class for use on the changelist page if list_editable is used. """ defaults = { "formfield_callback": partial(self.formfield_for_dbfield, request=request), } defaults.update(kwargs) return modelformset_factory(self.model, self.get_changelist_form(request), extra=0, fields=self.list_editable, **defaults) def _get_formsets(self, request, obj): """ Helper function that exists to allow the deprecation warning to be executed while this function continues to return a generator. """ for inline in self.get_inline_instances(request, obj): yield inline.get_formset(request, obj) def get_formsets(self, request, obj=None): warnings.warn( "ModelAdmin.get_formsets() is deprecated and will be removed in " "Django 1.9. Use ModelAdmin.get_formsets_with_inlines() instead.", RemovedInDjango19Warning, stacklevel=2 ) return self._get_formsets(request, obj) def get_formsets_with_inlines(self, request, obj=None): """ Yields formsets and the corresponding inlines. """ # We call get_formsets() [deprecated] and check if it triggers a # warning. If it does, then it's ours and we can safely ignore it, but # if it doesn't then it has been overridden so we must warn about the # deprecation. with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") formsets = self.get_formsets(request, obj) if len(w) != 1 or not issubclass(w[0].category, RemovedInDjango19Warning): warnings.warn( "ModelAdmin.get_formsets() is deprecated and will be removed in " "Django 1.9. Use ModelAdmin.get_formsets_with_inlines() instead.", RemovedInDjango19Warning ) if formsets: zipped = zip(formsets, self.get_inline_instances(request, None)) for formset, inline in zipped: yield formset, inline else: for inline in self.get_inline_instances(request, obj): yield inline.get_formset(request, obj), inline def get_paginator(self, request, queryset, per_page, orphans=0, allow_empty_first_page=True): return self.paginator(queryset, per_page, orphans, allow_empty_first_page) def log_addition(self, request, object): """ Log that an object has been successfully added. The default implementation creates an admin LogEntry object. """ from django.contrib.admin.models import LogEntry, ADDITION LogEntry.objects.log_action( user_id=request.user.pk, content_type_id=get_content_type_for_model(object).pk, object_id=object.pk, object_repr=force_text(object), action_flag=ADDITION ) def log_change(self, request, object, message): """ Log that an object has been successfully changed. The default implementation creates an admin LogEntry object. """ from django.contrib.admin.models import LogEntry, CHANGE LogEntry.objects.log_action( user_id=request.user.pk, content_type_id=get_content_type_for_model(object).pk, object_id=object.pk, object_repr=force_text(object), action_flag=CHANGE, change_message=message ) def log_deletion(self, request, object, object_repr): """ Log that an object will be deleted. Note that this method must be called before the deletion. The default implementation creates an admin LogEntry object. """ from django.contrib.admin.models import LogEntry, DELETION LogEntry.objects.log_action( user_id=request.user.pk, content_type_id=get_content_type_for_model(object).pk, object_id=object.pk, object_repr=object_repr, action_flag=DELETION ) def action_checkbox(self, obj): """ A list_display column containing a checkbox widget. """ return helpers.checkbox.render(helpers.ACTION_CHECKBOX_NAME, force_text(obj.pk)) action_checkbox.short_description = mark_safe('<input type="checkbox" id="action-toggle" />') action_checkbox.allow_tags = True def get_actions(self, request): """ Return a dictionary mapping the names of all actions for this ModelAdmin to a tuple of (callable, name, description) for each action. """ # If self.actions is explicitly set to None that means that we don't # want *any* actions enabled on this page. from django.contrib.admin.views.main import _is_changelist_popup if self.actions is None or _is_changelist_popup(request): return OrderedDict() actions = [] # Gather actions from the admin site first for (name, func) in self.admin_site.actions: description = getattr(func, 'short_description', name.replace('_', ' ')) actions.append((func, name, description)) # Then gather them from the model admin and all parent classes, # starting with self and working back up. for klass in self.__class__.mro()[::-1]: class_actions = getattr(klass, 'actions', []) # Avoid trying to iterate over None if not class_actions: continue actions.extend(self.get_action(action) for action in class_actions) # get_action might have returned None, so filter any of those out. actions = filter(None, actions) # Convert the actions into an OrderedDict keyed by name. actions = OrderedDict( (name, (func, name, desc)) for func, name, desc in actions ) return actions def get_action_choices(self, request, default_choices=BLANK_CHOICE_DASH): """ Return a list of choices for use in a form object. Each choice is a tuple (name, description). """ choices = [] + default_choices for func, name, description in six.itervalues(self.get_actions(request)): choice = (name, description % model_format_dict(self.opts)) choices.append(choice) return choices def get_action(self, action): """ Return a given action from a parameter, which can either be a callable, or the name of a method on the ModelAdmin. Return is a tuple of (callable, name, description). """ # If the action is a callable, just use it. if callable(action): func = action action = action.__name__ # Next, look for a method. Grab it off self.__class__ to get an unbound # method instead of a bound one; this ensures that the calling # conventions are the same for functions and methods. elif hasattr(self.__class__, action): func = getattr(self.__class__, action) # Finally, look for a named method on the admin site else: try: func = self.admin_site.get_action(action) except KeyError: return None if hasattr(func, 'short_description'): description = func.short_description else: description = capfirst(action.replace('_', ' ')) return func, action, description def get_list_display(self, request): """ Return a sequence containing the fields to be displayed on the changelist. """ return self.list_display def get_list_display_links(self, request, list_display): """ Return a sequence containing the fields to be displayed as links on the changelist. The list_display parameter is the list of fields returned by get_list_display(). """ if self.list_display_links or self.list_display_links is None or not list_display: return self.list_display_links else: # Use only the first item in list_display as link return list(list_display)[:1] def get_list_filter(self, request): """ Returns a sequence containing the fields to be displayed as filters in the right sidebar of the changelist page. """ return self.list_filter def get_search_fields(self, request): """ Returns a sequence containing the fields to be searched whenever somebody submits a search query. """ return self.search_fields def get_search_results(self, request, queryset, search_term): """ Returns a tuple containing a queryset to implement the search, and a boolean indicating if the results may contain duplicates. """ # Apply keyword searches. def construct_search(field_name): if field_name.startswith('^'): return "%s__istartswith" % field_name[1:] elif field_name.startswith('='): return "%s__iexact" % field_name[1:] elif field_name.startswith('@'): return "%s__search" % field_name[1:] else: return "%s__icontains" % field_name use_distinct = False search_fields = self.get_search_fields(request) if search_fields and search_term: orm_lookups = [construct_search(str(search_field)) for search_field in search_fields] for bit in search_term.split(): or_queries = [models.Q(**{orm_lookup: bit}) for orm_lookup in orm_lookups] queryset = queryset.filter(reduce(operator.or_, or_queries)) if not use_distinct: for search_spec in orm_lookups: if lookup_needs_distinct(self.opts, search_spec): use_distinct = True break return queryset, use_distinct def get_preserved_filters(self, request): """ Returns the preserved filters querystring. """ match = request.resolver_match if self.preserve_filters and match: opts = self.model._meta current_url = '%s:%s' % (match.app_name, match.url_name) changelist_url = 'admin:%s_%s_changelist' % (opts.app_label, opts.model_name) if current_url == changelist_url: preserved_filters = request.GET.urlencode() else: preserved_filters = request.GET.get('_changelist_filters') if preserved_filters: return urlencode({'_changelist_filters': preserved_filters}) return '' def construct_change_message(self, request, form, formsets): """ Construct a change message from a changed object. """ change_message = [] if form.changed_data: change_message.append(_('Changed %s.') % get_text_list(form.changed_data, _('and'))) if formsets: for formset in formsets: for added_object in formset.new_objects: change_message.append(_('Added %(name)s "%(object)s".') % {'name': force_text(added_object._meta.verbose_name), 'object': force_text(added_object)}) for changed_object, changed_fields in formset.changed_objects: change_message.append(_('Changed %(list)s for %(name)s "%(object)s".') % {'list': get_text_list(changed_fields, _('and')), 'name': force_text(changed_object._meta.verbose_name), 'object': force_text(changed_object)}) for deleted_object in formset.deleted_objects: change_message.append(_('Deleted %(name)s "%(object)s".') % {'name': force_text(deleted_object._meta.verbose_name), 'object': force_text(deleted_object)}) change_message = ' '.join(change_message) return change_message or _('No fields changed.') def message_user(self, request, message, level=messages.INFO, extra_tags='', fail_silently=False): """ Send a message to the user. The default implementation posts a message using the django.contrib.messages backend. Exposes almost the same API as messages.add_message(), but accepts the positional arguments in a different order to maintain backwards compatibility. For convenience, it accepts the `level` argument as a string rather than the usual level number. """ if not isinstance(level, int): # attempt to get the level if passed a string try: level = getattr(messages.constants, level.upper()) except AttributeError: levels = messages.constants.DEFAULT_TAGS.values() levels_repr = ', '.join('`%s`' % l for l in levels) raise ValueError('Bad message level string: `%s`. ' 'Possible values are: %s' % (level, levels_repr)) messages.add_message(request, level, message, extra_tags=extra_tags, fail_silently=fail_silently) def save_form(self, request, form, change): """ Given a ModelForm return an unsaved instance. ``change`` is True if the object is being changed, and False if it's being added. """ return form.save(commit=False) def save_model(self, request, obj, form, change): """ Given a model instance save it to the database. """ obj.save() def delete_model(self, request, obj): """ Given a model instance delete it from the database. """ obj.delete() def save_formset(self, request, form, formset, change): """ Given an inline formset save it to the database. """ formset.save() def save_related(self, request, form, formsets, change): """ Given the ``HttpRequest``, the parent ``ModelForm`` instance, the list of inline formsets and a boolean value based on whether the parent is being added or changed, save the related objects to the database. Note that at this point save_form() and save_model() have already been called. """ form.save_m2m() for formset in formsets: self.save_formset(request, form, formset, change=change) def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None): opts = self.model._meta app_label = opts.app_label preserved_filters = self.get_preserved_filters(request) form_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, form_url) view_on_site_url = self.get_view_on_site_url(obj) context.update({ 'add': add, 'change': change, 'has_add_permission': self.has_add_permission(request), 'has_change_permission': self.has_change_permission(request, obj), 'has_delete_permission': self.has_delete_permission(request, obj), 'has_file_field': True, # FIXME - this should check if form or formsets have a FileField, 'has_absolute_url': view_on_site_url is not None, 'absolute_url': view_on_site_url, 'form_url': form_url, 'opts': opts, 'content_type_id': get_content_type_for_model(self.model).pk, 'save_as': self.save_as, 'save_on_top': self.save_on_top, 'to_field_var': TO_FIELD_VAR, 'is_popup_var': IS_POPUP_VAR, 'app_label': app_label, }) if add and self.add_form_template is not None: form_template = self.add_form_template else: form_template = self.change_form_template return TemplateResponse(request, form_template or [ "admin/%s/%s/change_form.html" % (app_label, opts.model_name), "admin/%s/change_form.html" % app_label, "admin/change_form.html" ], context, current_app=self.admin_site.name) def response_add(self, request, obj, post_url_continue=None): """ Determines the HttpResponse for the add_view stage. """ opts = obj._meta pk_value = obj._get_pk_val() preserved_filters = self.get_preserved_filters(request) msg_dict = {'name': force_text(opts.verbose_name), 'obj': force_text(obj)} # Here, we distinguish between different save types by checking for # the presence of keys in request.POST. if IS_POPUP_VAR in request.POST: to_field = request.POST.get(TO_FIELD_VAR) if to_field: attr = str(to_field) else: attr = obj._meta.pk.attname value = obj.serializable_value(attr) return SimpleTemplateResponse('admin/popup_response.html', { 'pk_value': escape(pk_value), # for possible backwards-compatibility 'value': escape(value), 'obj': escapejs(obj) }) elif "_continue" in request.POST: msg = _('The %(name)s "%(obj)s" was added successfully. You may edit it again below.') % msg_dict self.message_user(request, msg, messages.SUCCESS) if post_url_continue is None: post_url_continue = reverse('admin:%s_%s_change' % (opts.app_label, opts.model_name), args=(quote(pk_value),), current_app=self.admin_site.name) post_url_continue = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, post_url_continue) return HttpResponseRedirect(post_url_continue) elif "_addanother" in request.POST: msg = _('The %(name)s "%(obj)s" was added successfully. You may add another %(name)s below.') % msg_dict self.message_user(request, msg, messages.SUCCESS) redirect_url = request.path redirect_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, redirect_url) return HttpResponseRedirect(redirect_url) else: msg = _('The %(name)s "%(obj)s" was added successfully.') % msg_dict self.message_user(request, msg, messages.SUCCESS) return self.response_post_save_add(request, obj) def response_change(self, request, obj): """ Determines the HttpResponse for the change_view stage. """ opts = self.model._meta pk_value = obj._get_pk_val() preserved_filters = self.get_preserved_filters(request) msg_dict = {'name': force_text(opts.verbose_name), 'obj': force_text(obj)} if "_continue" in request.POST: msg = _('The %(name)s "%(obj)s" was changed successfully. You may edit it again below.') % msg_dict self.message_user(request, msg, messages.SUCCESS) redirect_url = request.path redirect_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, redirect_url) return HttpResponseRedirect(redirect_url) elif "_saveasnew" in request.POST: msg = _('The %(name)s "%(obj)s" was added successfully. You may edit it again below.') % msg_dict self.message_user(request, msg, messages.SUCCESS) redirect_url = reverse('admin:%s_%s_change' % (opts.app_label, opts.model_name), args=(pk_value,), current_app=self.admin_site.name) redirect_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, redirect_url) return HttpResponseRedirect(redirect_url) elif "_addanother" in request.POST: msg = _('The %(name)s "%(obj)s" was changed successfully. You may add another %(name)s below.') % msg_dict self.message_user(request, msg, messages.SUCCESS) redirect_url = reverse('admin:%s_%s_add' % (opts.app_label, opts.model_name), current_app=self.admin_site.name) redirect_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, redirect_url) return HttpResponseRedirect(redirect_url) else: msg = _('The %(name)s "%(obj)s" was changed successfully.') % msg_dict self.message_user(request, msg, messages.SUCCESS) return self.response_post_save_change(request, obj) def response_post_save_add(self, request, obj): """ Figure out where to redirect after the 'Save' button has been pressed when adding a new object. """ opts = self.model._meta if self.has_change_permission(request, None): post_url = reverse('admin:%s_%s_changelist' % (opts.app_label, opts.model_name), current_app=self.admin_site.name) preserved_filters = self.get_preserved_filters(request) post_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, post_url) else: post_url = reverse('admin:index', current_app=self.admin_site.name) return HttpResponseRedirect(post_url) def response_post_save_change(self, request, obj): """ Figure out where to redirect after the 'Save' button has been pressed when editing an existing object. """ opts = self.model._meta if self.has_change_permission(request, None): post_url = reverse('admin:%s_%s_changelist' % (opts.app_label, opts.model_name), current_app=self.admin_site.name) preserved_filters = self.get_preserved_filters(request) post_url = add_preserved_filters({'preserved_filters': preserved_filters, 'opts': opts}, post_url) else: post_url = reverse('admin:index', current_app=self.admin_site.name) return HttpResponseRedirect(post_url) def response_action(self, request, queryset): """ Handle an admin action. This is called if a request is POSTed to the changelist; it returns an HttpResponse if the action was handled, and None otherwise. """ # There can be multiple action forms on the page (at the top # and bottom of the change list, for example). Get the action # whose button was pushed. try: action_index = int(request.POST.get('index', 0)) except ValueError: action_index = 0 # Construct the action form. data = request.POST.copy() data.pop(helpers.ACTION_CHECKBOX_NAME, None) data.pop("index", None) # Use the action whose button was pushed try: data.update({'action': data.getlist('action')[action_index]}) except IndexError: # If we didn't get an action from the chosen form that's invalid # POST data, so by deleting action it'll fail the validation check # below. So no need to do anything here pass action_form = self.action_form(data, auto_id=None) action_form.fields['action'].choices = self.get_action_choices(request) # If the form's valid we can handle the action. if action_form.is_valid(): action = action_form.cleaned_data['action'] select_across = action_form.cleaned_data['select_across'] func = self.get_actions(request)[action][0] # Get the list of selected PKs. If nothing's selected, we can't # perform an action on it, so bail. Except we want to perform # the action explicitly on all objects. selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME) if not selected and not select_across: # Reminder that something needs to be selected or nothing will happen msg = _("Items must be selected in order to perform " "actions on them. No items have been changed.") self.message_user(request, msg, messages.WARNING) return None if not select_across: # Perform the action only on the selected objects queryset = queryset.filter(pk__in=selected) response = func(self, request, queryset) # Actions may return an HttpResponse-like object, which will be # used as the response from the POST. If not, we'll be a good # little HTTP citizen and redirect back to the changelist page. if isinstance(response, HttpResponseBase): return response else: return HttpResponseRedirect(request.get_full_path()) else: msg = _("No action selected.") self.message_user(request, msg, messages.WARNING) return None def response_delete(self, request, obj_display): """ Determines the HttpResponse for the delete_view stage. """ opts = self.model._meta self.message_user(request, _('The %(name)s "%(obj)s" was deleted successfully.') % { 'name': force_text(opts.verbose_name), 'obj': force_text(obj_display) }, messages.SUCCESS) if self.has_change_permission(request, None): post_url = reverse('admin:%s_%s_changelist' % (opts.app_label, opts.model_name), current_app=self.admin_site.name) preserved_filters = self.get_preserved_filters(request) post_url = add_preserved_filters( {'preserved_filters': preserved_filters, 'opts': opts}, post_url ) else: post_url = reverse('admin:index', current_app=self.admin_site.name) return HttpResponseRedirect(post_url) def render_delete_form(self, request, context): opts = self.model._meta app_label = opts.app_label return TemplateResponse(request, self.delete_confirmation_template or [ "admin/{}/{}/delete_confirmation.html".format(app_label, opts.model_name), "admin/{}/delete_confirmation.html".format(app_label), "admin/delete_confirmation.html" ], context, current_app=self.admin_site.name) def get_inline_formsets(self, request, formsets, inline_instances, obj=None): inline_admin_formsets = [] for inline, formset in zip(inline_instances, formsets): fieldsets = list(inline.get_fieldsets(request, obj)) readonly = list(inline.get_readonly_fields(request, obj)) prepopulated = dict(inline.get_prepopulated_fields(request, obj)) inline_admin_formset = helpers.InlineAdminFormSet(inline, formset, fieldsets, prepopulated, readonly, model_admin=self) inline_admin_formsets.append(inline_admin_formset) return inline_admin_formsets def get_changeform_initial_data(self, request): """ Get the initial form data. Unless overridden, this populates from the GET params. """ initial = dict(request.GET.items()) for k in initial: try: f = self.model._meta.get_field(k) except models.FieldDoesNotExist: continue # We have to special-case M2Ms as a list of comma-separated PKs. if isinstance(f, models.ManyToManyField): initial[k] = initial[k].split(",") return initial @csrf_protect_m @transaction.atomic def changeform_view(self, request, object_id=None, form_url='', extra_context=None): to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) if to_field and not self.to_field_allowed(request, to_field): raise DisallowedModelAdminToField("The field %s cannot be referenced." % to_field) model = self.model opts = model._meta add = object_id is None if add: if not self.has_add_permission(request): raise PermissionDenied obj = None else: obj = self.get_object(request, unquote(object_id)) if not self.has_change_permission(request, obj): raise PermissionDenied if obj is None: raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % { 'name': force_text(opts.verbose_name), 'key': escape(object_id)}) if request.method == 'POST' and "_saveasnew" in request.POST: return self.add_view(request, form_url=reverse('admin:%s_%s_add' % ( opts.app_label, opts.model_name), current_app=self.admin_site.name)) ModelForm = self.get_form(request, obj) if request.method == 'POST': form = ModelForm(request.POST, request.FILES, instance=obj) if form.is_valid(): form_validated = True new_object = self.save_form(request, form, change=not add) else: form_validated = False new_object = form.instance formsets, inline_instances = self._create_formsets(request, new_object) if all_valid(formsets) and form_validated: self.save_model(request, new_object, form, not add) self.save_related(request, form, formsets, not add) if add: self.log_addition(request, new_object) return self.response_add(request, new_object) else: change_message = self.construct_change_message(request, form, formsets) self.log_change(request, new_object, change_message) return self.response_change(request, new_object) else: if add: initial = self.get_changeform_initial_data(request) form = ModelForm(initial=initial) formsets, inline_instances = self._create_formsets(request, self.model()) else: form = ModelForm(instance=obj) formsets, inline_instances = self._create_formsets(request, obj) adminForm = helpers.AdminForm( form, list(self.get_fieldsets(request, obj)), self.get_prepopulated_fields(request, obj), self.get_readonly_fields(request, obj), model_admin=self) media = self.media + adminForm.media inline_formsets = self.get_inline_formsets(request, formsets, inline_instances, obj) for inline_formset in inline_formsets: media = media + inline_formset.media context = dict(self.admin_site.each_context(), title=(_('Add %s') if add else _('Change %s')) % force_text(opts.verbose_name), adminform=adminForm, object_id=object_id, original=obj, is_popup=(IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET), to_field=to_field, media=media, inline_admin_formsets=inline_formsets, errors=helpers.AdminErrorList(form, formsets), preserved_filters=self.get_preserved_filters(request), ) context.update(extra_context or {}) return self.render_change_form(request, context, add=add, change=not add, obj=obj, form_url=form_url) def add_view(self, request, form_url='', extra_context=None): return self.changeform_view(request, None, form_url, extra_context) def change_view(self, request, object_id, form_url='', extra_context=None): return self.changeform_view(request, object_id, form_url, extra_context) @csrf_protect_m def changelist_view(self, request, extra_context=None): """ The 'change list' admin view for this model. """ from django.contrib.admin.views.main import ERROR_FLAG opts = self.model._meta app_label = opts.app_label if not self.has_change_permission(request, None): raise PermissionDenied list_display = self.get_list_display(request) list_display_links = self.get_list_display_links(request, list_display) list_filter = self.get_list_filter(request) search_fields = self.get_search_fields(request) # Check actions to see if any are available on this changelist actions = self.get_actions(request) if actions: # Add the action checkboxes if there are any actions available. list_display = ['action_checkbox'] + list(list_display) ChangeList = self.get_changelist(request) try: cl = ChangeList(request, self.model, list_display, list_display_links, list_filter, self.date_hierarchy, search_fields, self.list_select_related, self.list_per_page, self.list_max_show_all, self.list_editable, self) except IncorrectLookupParameters: # Wacky lookup parameters were given, so redirect to the main # changelist page, without parameters, and pass an 'invalid=1' # parameter via the query string. If wacky parameters were given # and the 'invalid=1' parameter was already in the query string, # something is screwed up with the database, so display an error # page. if ERROR_FLAG in request.GET.keys(): return SimpleTemplateResponse('admin/invalid_setup.html', { 'title': _('Database error'), }) return HttpResponseRedirect(request.path + '?' + ERROR_FLAG + '=1') # If the request was POSTed, this might be a bulk action or a bulk # edit. Try to look up an action or confirmation first, but if this # isn't an action the POST will fall through to the bulk edit check, # below. action_failed = False selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME) # Actions with no confirmation if (actions and request.method == 'POST' and 'index' in request.POST and '_save' not in request.POST): if selected: response = self.response_action(request, queryset=cl.get_queryset(request)) if response: return response else: action_failed = True else: msg = _("Items must be selected in order to perform " "actions on them. No items have been changed.") self.message_user(request, msg, messages.WARNING) action_failed = True # Actions with confirmation if (actions and request.method == 'POST' and helpers.ACTION_CHECKBOX_NAME in request.POST and 'index' not in request.POST and '_save' not in request.POST): if selected: response = self.response_action(request, queryset=cl.get_queryset(request)) if response: return response else: action_failed = True # If we're allowing changelist editing, we need to construct a formset # for the changelist given all the fields to be edited. Then we'll # use the formset to validate/process POSTed data. formset = cl.formset = None # Handle POSTed bulk-edit data. if (request.method == "POST" and cl.list_editable and '_save' in request.POST and not action_failed): FormSet = self.get_changelist_formset(request) formset = cl.formset = FormSet(request.POST, request.FILES, queryset=cl.result_list) if formset.is_valid(): changecount = 0 for form in formset.forms: if form.has_changed(): obj = self.save_form(request, form, change=True) self.save_model(request, obj, form, change=True) self.save_related(request, form, formsets=[], change=True) change_msg = self.construct_change_message(request, form, None) self.log_change(request, obj, change_msg) changecount += 1 if changecount: if changecount == 1: name = force_text(opts.verbose_name) else: name = force_text(opts.verbose_name_plural) msg = ungettext("%(count)s %(name)s was changed successfully.", "%(count)s %(name)s were changed successfully.", changecount) % {'count': changecount, 'name': name, 'obj': force_text(obj)} self.message_user(request, msg, messages.SUCCESS) return HttpResponseRedirect(request.get_full_path()) # Handle GET -- construct a formset for display. elif cl.list_editable: FormSet = self.get_changelist_formset(request) formset = cl.formset = FormSet(queryset=cl.result_list) # Build the list of media to be used by the formset. if formset: media = self.media + formset.media else: media = self.media # Build the action form and populate it with available actions. if actions: action_form = self.action_form(auto_id=None) action_form.fields['action'].choices = self.get_action_choices(request) else: action_form = None selection_note_all = ungettext('%(total_count)s selected', 'All %(total_count)s selected', cl.result_count) context = dict( self.admin_site.each_context(), module_name=force_text(opts.verbose_name_plural), selection_note=_('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)}, selection_note_all=selection_note_all % {'total_count': cl.result_count}, title=cl.title, is_popup=cl.is_popup, to_field=cl.to_field, cl=cl, media=media, has_add_permission=self.has_add_permission(request), opts=cl.opts, action_form=action_form, actions_on_top=self.actions_on_top, actions_on_bottom=self.actions_on_bottom, actions_selection_counter=self.actions_selection_counter, preserved_filters=self.get_preserved_filters(request), ) context.update(extra_context or {}) return TemplateResponse(request, self.change_list_template or [ 'admin/%s/%s/change_list.html' % (app_label, opts.model_name), 'admin/%s/change_list.html' % app_label, 'admin/change_list.html' ], context, current_app=self.admin_site.name) @csrf_protect_m @transaction.atomic def delete_view(self, request, object_id, extra_context=None): "The 'delete' admin view for this model." opts = self.model._meta app_label = opts.app_label obj = self.get_object(request, unquote(object_id)) if not self.has_delete_permission(request, obj): raise PermissionDenied if obj is None: raise Http404( _('%(name)s object with primary key %(key)r does not exist.') % {'name': force_text(opts.verbose_name), 'key': escape(object_id)} ) using = router.db_for_write(self.model) # Populate deleted_objects, a data structure of all related objects that # will also be deleted. (deleted_objects, perms_needed, protected) = get_deleted_objects( [obj], opts, request.user, self.admin_site, using) if request.POST: # The user has already confirmed the deletion. if perms_needed: raise PermissionDenied obj_display = force_text(obj) self.log_deletion(request, obj, obj_display) self.delete_model(request, obj) return self.response_delete(request, obj_display) object_name = force_text(opts.verbose_name) if perms_needed or protected: title = _("Cannot delete %(name)s") % {"name": object_name} else: title = _("Are you sure?") context = dict( self.admin_site.each_context(), title=title, object_name=object_name, object=obj, deleted_objects=deleted_objects, perms_lacking=perms_needed, protected=protected, opts=opts, app_label=app_label, preserved_filters=self.get_preserved_filters(request), ) context.update(extra_context or {}) return self.render_delete_form(request, context) def history_view(self, request, object_id, extra_context=None): "The 'history' admin view for this model." from django.contrib.admin.models import LogEntry # First check if the user can see this history. model = self.model obj = get_object_or_404(self.get_queryset(request), pk=unquote(object_id)) if not self.has_change_permission(request, obj): raise PermissionDenied # Then get the history for this object. opts = model._meta app_label = opts.app_label action_list = LogEntry.objects.filter( object_id=unquote(object_id), content_type=get_content_type_for_model(model) ).select_related().order_by('action_time') context = dict(self.admin_site.each_context(), title=_('Change history: %s') % force_text(obj), action_list=action_list, module_name=capfirst(force_text(opts.verbose_name_plural)), object=obj, opts=opts, preserved_filters=self.get_preserved_filters(request), ) context.update(extra_context or {}) return TemplateResponse(request, self.object_history_template or [ "admin/%s/%s/object_history.html" % (app_label, opts.model_name), "admin/%s/object_history.html" % app_label, "admin/object_history.html" ], context, current_app=self.admin_site.name) def _create_formsets(self, request, obj): "Helper function to generate formsets for add/change_view." formsets = [] inline_instances = [] prefixes = {} get_formsets_args = [request] if obj.pk: get_formsets_args.append(obj) for FormSet, inline in self.get_formsets_with_inlines(*get_formsets_args): prefix = FormSet.get_default_prefix() prefixes[prefix] = prefixes.get(prefix, 0) + 1 if prefixes[prefix] != 1 or not prefix: prefix = "%s-%s" % (prefix, prefixes[prefix]) formset_params = { 'instance': obj, 'prefix': prefix, 'queryset': inline.get_queryset(request), } if request.method == 'POST': formset_params.update({ 'data': request.POST, 'files': request.FILES, 'save_as_new': '_saveasnew' in request.POST }) formsets.append(FormSet(**formset_params)) inline_instances.append(inline) return formsets, inline_instances class InlineModelAdmin(BaseModelAdmin): """ Options for inline editing of ``model`` instances. Provide ``fk_name`` to specify the attribute name of the ``ForeignKey`` from ``model`` to its parent. This is required if ``model`` has more than one ``ForeignKey`` to its parent. """ model = None fk_name = None formset = BaseInlineFormSet extra = 3 min_num = None max_num = None template = None verbose_name = None verbose_name_plural = None can_delete = True checks_class = InlineModelAdminChecks def __init__(self, parent_model, admin_site): self.admin_site = admin_site self.parent_model = parent_model self.opts = self.model._meta super(InlineModelAdmin, self).__init__() if self.verbose_name is None: self.verbose_name = self.model._meta.verbose_name if self.verbose_name_plural is None: self.verbose_name_plural = self.model._meta.verbose_name_plural @property def media(self): extra = '' if settings.DEBUG else '.min' js = ['jquery%s.js' % extra, 'jquery.init.js', 'inlines%s.js' % extra] if self.prepopulated_fields: js.extend(['urlify.js', 'prepopulate%s.js' % extra]) if self.filter_vertical or self.filter_horizontal: js.extend(['SelectBox.js', 'SelectFilter2.js']) return forms.Media(js=[static('admin/js/%s' % url) for url in js]) def get_extra(self, request, obj=None, **kwargs): """Hook for customizing the number of extra inline forms.""" return self.extra def get_min_num(self, request, obj=None, **kwargs): """Hook for customizing the min number of inline forms.""" return self.min_num def get_max_num(self, request, obj=None, **kwargs): """Hook for customizing the max number of extra inline forms.""" return self.max_num def get_formset(self, request, obj=None, **kwargs): """Returns a BaseInlineFormSet class for use in admin add/change views.""" if 'fields' in kwargs: fields = kwargs.pop('fields') else: fields = flatten_fieldsets(self.get_fieldsets(request, obj)) if self.exclude is None: exclude = [] else: exclude = list(self.exclude) exclude.extend(self.get_readonly_fields(request, obj)) if self.exclude is None and hasattr(self.form, '_meta') and self.form._meta.exclude: # Take the custom ModelForm's Meta.exclude into account only if the # InlineModelAdmin doesn't define its own. exclude.extend(self.form._meta.exclude) # If exclude is an empty list we use None, since that's the actual # default. exclude = exclude or None can_delete = self.can_delete and self.has_delete_permission(request, obj) defaults = { "form": self.form, "formset": self.formset, "fk_name": self.fk_name, "fields": fields, "exclude": exclude, "formfield_callback": partial(self.formfield_for_dbfield, request=request), "extra": self.get_extra(request, obj, **kwargs), "min_num": self.get_min_num(request, obj, **kwargs), "max_num": self.get_max_num(request, obj, **kwargs), "can_delete": can_delete, } defaults.update(kwargs) base_model_form = defaults['form'] class DeleteProtectedModelForm(base_model_form): def hand_clean_DELETE(self): """ We don't validate the 'DELETE' field itself because on templates it's not rendered using the field information, but just using a generic "deletion_field" of the InlineModelAdmin. """ if self.cleaned_data.get(DELETION_FIELD_NAME, False): using = router.db_for_write(self._meta.model) collector = NestedObjects(using=using) collector.collect([self.instance]) if collector.protected: objs = [] for p in collector.protected: objs.append( # Translators: Model verbose name and instance representation, suitable to be an item in a list _('%(class_name)s %(instance)s') % { 'class_name': p._meta.verbose_name, 'instance': p} ) params = {'class_name': self._meta.model._meta.verbose_name, 'instance': self.instance, 'related_objects': get_text_list(objs, _('and'))} msg = _("Deleting %(class_name)s %(instance)s would require " "deleting the following protected related objects: " "%(related_objects)s") raise ValidationError(msg, code='deleting_protected', params=params) def is_valid(self): result = super(DeleteProtectedModelForm, self).is_valid() self.hand_clean_DELETE() return result defaults['form'] = DeleteProtectedModelForm if defaults['fields'] is None and not modelform_defines_fields(defaults['form']): defaults['fields'] = forms.ALL_FIELDS return inlineformset_factory(self.parent_model, self.model, **defaults) def get_fields(self, request, obj=None): if self.fields: return self.fields form = self.get_formset(request, obj, fields=None).form return list(form.base_fields) + list(self.get_readonly_fields(request, obj)) def get_queryset(self, request): queryset = super(InlineModelAdmin, self).get_queryset(request) if not self.has_change_permission(request): queryset = queryset.none() return queryset def has_add_permission(self, request): if self.opts.auto_created: # We're checking the rights to an auto-created intermediate model, # which doesn't have its own individual permissions. The user needs # to have the change permission for the related model in order to # be able to do anything with the intermediate model. return self.has_change_permission(request) return super(InlineModelAdmin, self).has_add_permission(request) def has_change_permission(self, request, obj=None): opts = self.opts if opts.auto_created: # The model was auto-created as intermediary for a # ManyToMany-relationship, find the target model for field in opts.fields: if field.rel and field.rel.to != self.parent_model: opts = field.rel.to._meta break codename = get_permission_codename('change', opts) return request.user.has_perm("%s.%s" % (opts.app_label, codename)) def has_delete_permission(self, request, obj=None): if self.opts.auto_created: # We're checking the rights to an auto-created intermediate model, # which doesn't have its own individual permissions. The user needs # to have the change permission for the related model in order to # be able to do anything with the intermediate model. return self.has_change_permission(request, obj) return super(InlineModelAdmin, self).has_delete_permission(request, obj) class StackedInline(InlineModelAdmin): template = 'admin/edit_inline/stacked.html' class TabularInline(InlineModelAdmin): template = 'admin/edit_inline/tabular.html'
boooka/GeoPowerOff
venv/lib/python2.7/site-packages/django/contrib/admin/options.py
Python
apache-2.0
80,797
<?php /** * This file is part of the OpenPNE package. * (c) OpenPNE Project (http://www.openpne.jp/) * * For the full copyright and license information, please view the LICENSE * file and the NOTICE file that were distributed with this source code. */ /** * opSkinClassicPlugin actions. * * @package OpenPNE * @subpackage skin * @author Kousuke Ebihara <ebihara@tejimaya.com> */ class opSkinClassicPluginActions extends sfActions { public function executeCss(sfWebRequest $request) { opSkinClassicConfig::setCurrentTheme($request->getParameter('theme')); } public function executeLogin(sfWebRequest $request) { if ('@opSkinClassicPlugin_login' !== opConfig::get('external_pc_login_url')) { $this->redirect('member/login'); } $this->form = $this->getUser()->getAuthForm(); unset($this->form['next_uri']); } }
cripure/openpne3
plugins/opSkinClassicPlugin/apps/pc_frontend/modules/opSkinClassicPlugin/actions/actions.class.php
PHP
apache-2.0
873
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <stdint.h> #include <initializer_list> #include <string> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "tensorflow/lite/kernels/test_util.h" #include "tensorflow/lite/schema/schema_generated.h" #include "tensorflow/lite/string_type.h" namespace tflite { namespace { using ::testing::ElementsAreArray; using ::testing::IsEmpty; enum class TestType { kConst = 0, kDynamic = 1, }; template <typename dims_type, typename value_type> class FillOpModel : public SingleOpModel { public: explicit FillOpModel(TensorType dims_tensor_type, std::initializer_list<int> dims_shape, std::initializer_list<dims_type> dims_data, value_type value, TestType input_tensor_types) { if (input_tensor_types == TestType::kDynamic) { dims_ = AddInput(dims_tensor_type); } else { dims_ = AddConstInput(dims_tensor_type, dims_data, dims_shape); } value_ = AddInput(GetTensorType<value_type>()); output_ = AddOutput(GetTensorType<value_type>()); SetBuiltinOp(BuiltinOperator_FILL, BuiltinOptions_FillOptions, CreateFillOptions(builder_).Union()); BuildInterpreter({dims_shape, {}}); if (input_tensor_types == TestType::kDynamic) { if (dims_data.size() > 0) { PopulateTensor<dims_type>(dims_, dims_data); } } PopulateTensor<value_type>(value_, {value}); } std::vector<value_type> GetOutput() { return ExtractVector<value_type>(output_); } std::vector<int> GetOutputShape() { return GetTensorShape(output_); } protected: int dims_; int value_; int output_; }; template <typename dims_type, typename quant_type> class QuantizedFillOpModel : public SingleOpModel { public: explicit QuantizedFillOpModel(TensorType dims_tensor_type, std::initializer_list<int> dims_shape, std::initializer_list<dims_type> dims_data, const TensorData& tensor_data, float value) { dims_ = AddInput(dims_tensor_type); value_ = AddInput(tensor_data); output_ = AddOutput(tensor_data); SetBuiltinOp(BuiltinOperator_FILL, BuiltinOptions_FillOptions, CreateFillOptions(builder_).Union()); BuildInterpreter({dims_shape, {}}); if (dims_data.size() > 0) { PopulateTensor<dims_type>(dims_, dims_data); } QuantizeAndPopulate<quant_type>(value_, {value}); } std::vector<quant_type> GetOutput() { return ExtractVector<quant_type>(output_); } std::vector<float> GetDequantizedOutput() { TfLiteTensor* t = interpreter_->tensor(output_); return Dequantize(GetOutput(), t->params.scale, t->params.zero_point); } std::vector<int> GetOutputShape() { return GetTensorShape(output_); } protected: int dims_; int value_; int output_; }; class FillOpTest : public ::testing::TestWithParam<TestType> {}; TEST_P(FillOpTest, FillInt32) { FillOpModel<int32_t, int32_t> m(TensorType_INT32, {2}, {2, 3}, -11, GetParam()); m.Invoke(); EXPECT_THAT(m.GetOutput(), ElementsAreArray({-11, -11, -11, -11, -11, -11})); EXPECT_THAT(m.GetOutputShape(), ElementsAreArray({2, 3})); } TEST_P(FillOpTest, FillInt64) { FillOpModel<int64_t, int64_t> m(TensorType_INT64, {2}, {2, 4}, 1LL << 45, GetParam()); m.Invoke(); EXPECT_THAT(m.GetOutput(), ElementsAreArray({1LL << 45, 1LL << 45, 1LL << 45, 1LL << 45, 1LL << 45, 1LL << 45, 1LL << 45, 1LL << 45})); EXPECT_THAT(m.GetOutputShape(), ElementsAreArray({2, 4})); } TEST_P(FillOpTest, FillFloat) { FillOpModel<int64_t, float> m(TensorType_INT64, {3}, {2, 2, 2}, 4.0, GetParam()); m.Invoke(); EXPECT_THAT(m.GetOutput(), ElementsAreArray({4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0})); EXPECT_THAT(m.GetOutputShape(), ElementsAreArray({2, 2, 2})); } TEST_P(FillOpTest, FillFloatInt32Dims) { FillOpModel<int32_t, float> m(TensorType_INT32, {3}, {2, 2, 2}, 4.0, GetParam()); m.Invoke(); EXPECT_THAT(m.GetOutput(), ElementsAreArray({4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0})); EXPECT_THAT(m.GetOutputShape(), ElementsAreArray({2, 2, 2})); } TEST_P(FillOpTest, FillOutputScalar) { FillOpModel<int64_t, float> m(TensorType_INT64, {0}, {}, 4.0, GetParam()); m.Invoke(); EXPECT_THAT(m.GetOutput(), ElementsAreArray({4.0})); EXPECT_THAT(m.GetOutputShape(), IsEmpty()); } TEST_P(FillOpTest, FillBool) { FillOpModel<int64_t, bool> m(TensorType_INT64, {3}, {2, 2, 2}, true, GetParam()); m.Invoke(); EXPECT_THAT(m.GetOutput(), ElementsAreArray({true, true, true, true, true, true, true, true})); EXPECT_THAT(m.GetOutputShape(), ElementsAreArray({2, 2, 2})); } TEST(FillOpTest, FillString) { FillOpModel<int64_t, std::string> m(TensorType_INT64, {3}, {2, 2, 2}, "AB", TestType::kDynamic); m.Invoke(); EXPECT_THAT(m.GetOutput(), ElementsAreArray({"AB", "AB", "AB", "AB", "AB", "AB", "AB", "AB"})); EXPECT_THAT(m.GetOutputShape(), ElementsAreArray({2, 2, 2})); } TEST_P(FillOpTest, FillInt8) { FillOpModel<int64_t, int8_t> m(TensorType_INT64, {3}, {2, 2, 2}, 5, GetParam()); m.Invoke(); EXPECT_THAT(m.GetOutput(), ElementsAreArray({5, 5, 5, 5, 5, 5, 5, 5})); EXPECT_THAT(m.GetOutputShape(), ElementsAreArray({2, 2, 2})); } template <typename quant_type> void QuantizedFill(float value) { // Prepare TensorData for quantization of value const float kMin = -1; // Workaround to get a zero-point of 0 const float kMax = std::numeric_limits<quant_type>::max() / static_cast<float>(std::numeric_limits<quant_type>::max() + 1); const TensorData tensor_data(GetTensorType<quant_type>(), {}, std::abs(value) * kMin, std::abs(value) * kMax); QuantizedFillOpModel<int32_t, quant_type> m(TensorType_INT32, {2}, {2, 3}, tensor_data, value); m.Invoke(); constexpr float epsilon = 0.01f; const float min_value = tensor_data.min - epsilon; const float max_value = tensor_data.max + epsilon; const float kQuantizedTolerance = (max_value - min_value) / (std::numeric_limits<quant_type>::max() - std::numeric_limits<quant_type>::min()); EXPECT_THAT( m.GetDequantizedOutput(), ElementsAreArray(ArrayFloatNear( {value, value, value, value, value, value}, kQuantizedTolerance))); EXPECT_THAT(m.GetOutputShape(), ElementsAreArray({2, 3})); } TEST(FillOpTest, QuantizedFillInt8) { QuantizedFill<int8_t>(3.14f); } TEST(FillOpTest, QuantizedFillInt16) { QuantizedFill<int16_t>(3.14f); } INSTANTIATE_TEST_SUITE_P(FillOpTest, FillOpTest, ::testing::Values(TestType::kConst, TestType::kDynamic)); } // namespace } // namespace tflite
tensorflow/tensorflow
tensorflow/lite/kernels/fill_test.cc
C++
apache-2.0
7,859
/** * Copyright 2017 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {isLayoutSizeDefined} from '../../../src/layout'; import {tryParseJson} from '../../../src/json'; import {user} from '../../../src/log'; import {removeElement} from '../../../src/dom'; import { installVideoManagerForDoc, } from '../../../src/service/video-manager-impl'; import {isObject} from '../../../src/types'; import {listen} from '../../../src/event-helper'; import {VideoEvents} from '../../../src/video-interface'; import {videoManagerForDoc} from '../../../src/services'; /** * @implements {../../../src/video-interface.VideoInterface} */ class Amp3QPlayer extends AMP.BaseElement { /** @param {!AmpElement} element */ constructor(element) { super(element); /** @private {?Element} */ this.iframe_ = null; /** @private {?Function} */ this.unlistenMessage_ = null; /** @private {?Promise} */ this.playerReadyPromise_ = null; /** @private {?Function} */ this.playerReadyResolver_ = null; this.dataId = null; } /** * @param {boolean=} opt_onLayout * @override */ preconnectCallback(opt_onLayout) { this.preconnect.url('https://playout.3qsdn.com', opt_onLayout); } /** @override */ buildCallback() { this.dataId = user().assert( this.element.getAttribute('data-id'), 'The data-id attribute is required for <amp-3q-player> %s', this.element); this.playerReadyPromise_ = new Promise(resolve => { this.playerReadyResolver_ = resolve; }); installVideoManagerForDoc(this.element); videoManagerForDoc(this.element).register(this); } /** @override */ layoutCallback() { const iframe = this.element.ownerDocument.createElement('iframe'); iframe.setAttribute('frameborder', '0'); iframe.setAttribute('allowfullscreen', 'true'); this.iframe_ = iframe; this.unlistenMessage_ = listen( this.win, 'message', this.sdnBridge_.bind(this) ); this.applyFillContent(iframe, true); iframe.src = 'https://playout.3qsdn.com/' + encodeURIComponent(this.dataId) + '?autoplay=false&amp=true'; this.element.appendChild(iframe); return this.loadPromise(this.iframe_).then(() => this.playerReadyPromise_); } /** @override */ unlayoutCallback() { if (this.iframe_) { removeElement(this.iframe_); this.iframe_ = null; } if (this.unlistenMessage_) { this.unlistenMessage_(); } this.playerReadyPromise_ = new Promise(resolve => { this.playerReadyResolver_ = resolve; }); return true; } /** @override */ isLayoutSupported(layout) { return isLayoutSizeDefined(layout); } /** @override */ viewportCallback(visible) { this.element.dispatchCustomEvent(VideoEvents.VISIBILITY, {visible}); } /** @override */ pauseCallback() { if (this.iframe_) { this.pause(); } } sdnBridge_(event) { if (event.source) { if (event.source != this.iframe_.contentWindow) { return; } } const data = isObject(event.data) ? event.data : tryParseJson(event.data); if (data === undefined) { return; } switch (data.data) { case 'ready': this.element.dispatchCustomEvent(VideoEvents.LOAD); this.playerReadyResolver_(); break; case 'playing': this.element.dispatchCustomEvent(VideoEvents.PLAY); break; case 'paused': this.element.dispatchCustomEvent(VideoEvents.PAUSE); break; case 'muted': this.element.dispatchCustomEvent(VideoEvents.MUTED); break; case 'unmuted': this.element.dispatchCustomEvent(VideoEvents.UNMUTED); break; } } sdnPostMessage_(message) { this.playerReadyPromise_.then(() => { if (this.iframe_ && this.iframe_.contentWindow) { this.iframe_.contentWindow./*OK*/postMessage(message, '*'); } }); } // VideoInterface Implementation. See ../src/video-interface.VideoInterface /** @override */ play() { this.sdnPostMessage_('play2'); } /** @override */ pause() { this.sdnPostMessage_('pause'); } /** @override */ mute() { this.sdnPostMessage_('mute'); } /** @override */ unmute() { this.sdnPostMessage_('unmute'); } /** @override */ supportsPlatform() { return true; } /** @override */ isInteractive() { return true; } /** @override */ showControls() { this.sdnPostMessage_('showControlbar'); } /** @override */ hideControls() { this.sdnPostMessage_('hideControlbar'); } }; AMP.registerElement('amp-3q-player', Amp3QPlayer);
ecoron/amphtml
extensions/amp-3q-player/0.1/amp-3q-player.js
JavaScript
apache-2.0
5,238
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.flex.forks.batik.svggen; import java.awt.Composite; import java.awt.Paint; import java.awt.Rectangle; import java.awt.image.BufferedImageOp; /** * The ExtensionHandler interface allows the user to handle * Java 2D API extensions that map to SVG concepts (such as custom * Paints, Composites or BufferedImageOp filters). * * @author <a href="mailto:vincent.hardy@eng.sun.com">Vincent Hardy</a> * @version $Id: ExtensionHandler.java 478176 2006-11-22 14:50:50Z dvholten $ */ public interface ExtensionHandler { /** * @param paint Custom Paint to be converted to SVG * @param generatorContext allows the handler to build DOM objects as needed. * @return an SVGPaintDescriptor */ SVGPaintDescriptor handlePaint(Paint paint, SVGGeneratorContext generatorContext); /** * @param composite Custom Composite to be converted to SVG. * @param generatorContext allows the handler to build DOM objects as needed. * @return an SVGCompositeDescriptor which contains a valid SVG filter, * or null if the composite cannot be handled * */ SVGCompositeDescriptor handleComposite(Composite composite, SVGGeneratorContext generatorContext); /** * @param filter Custom filter to be converted to SVG. * @param filterRect Rectangle, in device space, that defines the area * to which filtering applies. May be null, meaning that the * area is undefined. * @param generatorContext allows the handler to build DOM objects as needed. * @return an SVGFilterDescriptor which contains a valid SVG filter, * or null if the composite cannot be handled */ SVGFilterDescriptor handleFilter(BufferedImageOp filter, Rectangle filterRect, SVGGeneratorContext generatorContext); }
adufilie/flex-sdk
modules/thirdparty/batik/sources/org/apache/flex/forks/batik/svggen/ExtensionHandler.java
Java
apache-2.0
2,772
/** * Coder for Raspberry Pi * A simple platform for experimenting with web stuff. * http://goo.gl/coder * * Copyright 2013 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ exports.settings={}; //These are dynamically updated by the runtime //settings.appname - the app id (folder) where your app is installed //settings.viewpath - prefix to where your view html files are located //settings.staticurl - base url path to static assets /static/apps/appname //settings.appurl - base url path to this app /app/appname exports.get_routes = [ { path:'/', handler:'index_handler' }, ]; exports.post_routes = [ ]; exports.index_handler = function( req, res ) { var tmplvars = {}; tmplvars['static_url'] = exports.settings.staticurl; tmplvars['app_name'] = exports.settings.appname; tmplvars['app_url'] = exports.settings.appurl; tmplvars['device_name'] = exports.settings.device_name; res.render( exports.settings.viewpath + '/index', tmplvars ); }; exports.on_destroy = function() { };
jmp407/coderJmp
coder-base/apps/game2d/app.js
JavaScript
apache-2.0
1,564
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Threading; using XenAdmin.Network; using XenAPI; namespace XenAdmin.Actions { /// <summary> /// ParallelAction takes a list of any number of actions and runs a certain number of them simultaneously. /// Once one simultaneous action is finished the next one in the queue is started until all are complete /// </summary> public class ParallelAction : MultipleAction { //Change parameter to increase the number of concurrent actions running private const int DEFAULT_MAX_NUMBER_OF_PARALLEL_ACTIONS = 25; private Dictionary<IXenConnection, List<AsyncAction>> actionsByConnection = new Dictionary<IXenConnection, List<AsyncAction>>(); private Dictionary<IXenConnection, ProduceConsumerQueue> queuesByConnection = new Dictionary<IXenConnection, ProduceConsumerQueue>(); private List<AsyncAction> actionsWithNoConnection = new List<AsyncAction>(); private ProduceConsumerQueue queueWithNoConnection; private readonly int maxNumberOfParallelActions; private int actionsCount; public ParallelAction(IXenConnection connection, string title, string startDescription, string endDescription, List<AsyncAction> subActions, bool suppressHistory, bool showSubActionsDetails, int maxNumberOfParallelActions = DEFAULT_MAX_NUMBER_OF_PARALLEL_ACTIONS) : base(connection, title, startDescription, endDescription, subActions, suppressHistory, showSubActionsDetails) { if (Connection != null) { actionsByConnection.Add(Connection, subActions); actionsCount = subActions.Count; } else GroupActionsByConnection(); this.maxNumberOfParallelActions = maxNumberOfParallelActions; } public ParallelAction(IXenConnection connection, string title, string startDescription, string endDescription, List<AsyncAction> subActions, int maxNumberOfParallelActions = DEFAULT_MAX_NUMBER_OF_PARALLEL_ACTIONS) : this(connection, title, startDescription, endDescription, subActions, false, false, maxNumberOfParallelActions) { } /// <summary> /// Use this constructor to create a cross connection ParallelAction. /// It takes a list of any number of actions, separates them by connections /// and runs a certain number of them simultaneously on each connection, all connections in parallel. /// Once one simultaneous action is finished the next one in the queue is started until all are complete. /// </summary> public ParallelAction(string title, string startDescription, string endDescription, List<AsyncAction> subActions, bool suppressHistory, bool showSubActionsDetails, int maxNumberOfParallelActions = DEFAULT_MAX_NUMBER_OF_PARALLEL_ACTIONS) : base(null, title, startDescription, endDescription, subActions, suppressHistory, showSubActionsDetails) { GroupActionsByConnection(); this.maxNumberOfParallelActions = maxNumberOfParallelActions; } public ParallelAction(string title, string startDescription, string endDescription, List<AsyncAction> subActions, int maxNumberOfParallelActions = DEFAULT_MAX_NUMBER_OF_PARALLEL_ACTIONS) : this(title, startDescription, endDescription, subActions, false, false, maxNumberOfParallelActions) { } private void GroupActionsByConnection() { actionsCount = 0; foreach (AsyncAction action in subActions) { if (action.Connection != null) { if (action.Connection.IsConnected) { if (!actionsByConnection.ContainsKey(action.Connection)) { actionsByConnection.Add(action.Connection, new List<AsyncAction>()); } actionsByConnection[action.Connection].Add(action); actionsCount++; } } else { actionsWithNoConnection.Add(action); actionsCount++; } } } protected override void RunSubActions(List<Exception> exceptions) { if (actionsCount == 0) return; foreach (IXenConnection connection in actionsByConnection.Keys) { queuesByConnection[connection] = new ProduceConsumerQueue(Math.Min(maxNumberOfParallelActions, actionsByConnection[connection].Count)); foreach (AsyncAction subAction in actionsByConnection[connection]) { EnqueueAction(subAction, queuesByConnection[connection], exceptions); } } if (actionsWithNoConnection.Count > 0) queueWithNoConnection = new ProduceConsumerQueue(Math.Min(maxNumberOfParallelActions, actionsWithNoConnection.Count)); foreach (AsyncAction subAction in actionsWithNoConnection) { EnqueueAction(subAction, queueWithNoConnection, exceptions); } lock (_lock) { Monitor.Wait(_lock); } } void EnqueueAction(AsyncAction action, ProduceConsumerQueue queue, List<Exception> exceptions) { action.Completed += action_Completed; queue.EnqueueItem( () => { if (Cancelling) // don't start any more actions return; try { action.RunExternal(action.Session); } catch (Exception e) { Failure f = e as Failure; if (f != null && Connection != null && f.ErrorDescription[0] == Failure.RBAC_PERMISSION_DENIED) { Failure.ParseRBACFailure(f, action.Connection, action.Session ?? action.Connection.Session); } exceptions.Add(e); // Record the first exception we come to. Though later if there are more than one we will replace this with non specific one. if (Exception == null) Exception = e; } }); } protected override void RecalculatePercentComplete() { int total = 0; foreach (IXenConnection connection in actionsByConnection.Keys) { foreach (var action in actionsByConnection[connection]) total += action.PercentComplete; } foreach (var action in actionsWithNoConnection) total += action.PercentComplete; PercentComplete = (int)(total / actionsCount); } private readonly object _lock = new object(); private volatile int i = 0; void action_Completed(ActionBase sender) { sender.Completed -= action_Completed; lock (_lock) { i++; if (i == actionsCount) { Monitor.Pulse(_lock); PercentComplete = 100; } } } protected override void MultipleAction_Completed(ActionBase sender) { base.MultipleAction_Completed(sender); foreach (IXenConnection connection in queuesByConnection.Keys) { queuesByConnection[connection].StopWorkers(false); } if (queueWithNoConnection != null) queueWithNoConnection.StopWorkers(false); } } }
geosharath/xenadmin
XenModel/Actions/ParallelAction.cs
C#
bsd-2-clause
9,686
cask 'malwarebytes' do version '3.0.3.433' sha256 'ab592edc1aec714d009455fe7b53a759dd2f0cc21e3b74697a028979ef5d50f7' # data-cdn.mbamupdates.com/web was verified as official when first introduced to the cask url "https://data-cdn.mbamupdates.com/web/mb#{version.major}_mac/Malwarebytes-#{version}.dmg" name 'Malwarebytes for Mac' homepage 'https://www.malwarebytes.com/mac/' auto_updates true depends_on macos: '>= :yosemite' pkg "Install Malwarebytes #{version.major}.pkg" uninstall delete: '/Library/Application Support/Malwarebytes/MBAM', kext: 'com.malwarebytes.mbam.rtprotection', launchctl: [ 'com.malwarebytes.mbam.frontend.agent', 'com.malwarebytes.mbam.rtprotection.daemon', 'com.malwarebytes.mbam.settings.daemon', ], pkgutil: 'com.malwarebytes.mbam', quit: 'com.malwarebytes.mbam.frontend.agent', rmdir: '/Library/Application Support/Malwarebytes' end
shonjir/homebrew-cask
Casks/malwarebytes.rb
Ruby
bsd-2-clause
1,063
/*------------------------------------------------------------------------- * * planner.h * prototypes for planner.c. * * * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * src/include/optimizer/planner.h * *------------------------------------------------------------------------- */ #ifndef PLANNER_H #define PLANNER_H #include "nodes/plannodes.h" #include "nodes/relation.h" /* Hook for plugins to get control in planner() */ typedef PlannedStmt *(*planner_hook_type) (Query *parse, int cursorOptions, ParamListInfo boundParams); extern PGDLLIMPORT planner_hook_type planner_hook; extern PlannedStmt *planner(Query *parse, int cursorOptions, ParamListInfo boundParams); extern PlannedStmt *standard_planner(Query *parse, int cursorOptions, ParamListInfo boundParams); extern Plan *subquery_planner(PlannerGlobal *glob, Query *parse, PlannerInfo *parent_root, bool hasRecursion, double tuple_fraction, PlannerInfo **subroot); extern Expr *expression_planner(Expr *expr); extern bool plan_cluster_use_sort(Oid tableOid, Oid indexOid); #endif /* PLANNER_H */
LomoX-Offical/nginx-openresty-windows
src/ngx_postgres-1.0/include/server/optimizer/planner.h
C
bsd-2-clause
1,232
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * Asserts that device property values match properties in |expectedProperties|. * The method will *not* assert that the device contains *only* properties * specified in expected properties. * @param {Object} expectedProperties Expected device properties. * @param {Object} device Device object to test. */ function assertDeviceMatches(expectedProperties, device) { Object.keys(expectedProperties).forEach(function(key) { chrome.test.assertEq(expectedProperties[key], device[key], 'Property ' + key + ' of device ' + device.id); }); } /** * Verifies that list of devices contains all and only devices from set of * expected devices. If will fail the test if an unexpected device is found. * * @param {Object.<string, Object>} expectedDevices Expected set of test * devices. Maps device ID to device properties. * @param {Array.<Object>} devices List of input devices. */ function assertDevicesMatch(expectedDevices, devices) { var deviceIds = {}; devices.forEach(function(device) { chrome.test.assertFalse(!!deviceIds[device.id], 'Duplicated device id: \'' + device.id + '\'.'); deviceIds[device.id] = true; }); function sortedKeys(obj) { return Object.keys(obj).sort(); } chrome.test.assertEq(sortedKeys(expectedDevices), sortedKeys(deviceIds)); devices.forEach(function(device) { assertDeviceMatches(expectedDevices[device.id], device); }); } /** * * @param {Array.<Object>} devices List of devices returned by * chrome.audio.getInfo or chrome.audio.getDevices. * @return {Object.<string, Object>} List of devices formatted as map of * expected devices used to assert devices match expectation. */ function deviceListToExpectedDevicesMap(devices) { var expectedDevicesMap = {}; devices.forEach(function(device) { expectedDevicesMap[device.id] = device; }); return expectedDevicesMap; } /** * @param {Array.<Object>} devices List of devices returned by * chrome.audio.getInfo or chrome.audio.getDevices. * @return {Array.<string>} Sorted list devices IDs for devices in |devices|. */ function getDeviceIds(devices) { return devices.map(function(device) {return device.id;}).sort(); } function EventListener(targetEvent) { this.targetEvent = targetEvent; this.listener = this.handleEvent.bind(this); this.targetEvent.addListener(this.listener); this.eventCount = 0; } EventListener.prototype.handleEvent = function() { ++this.eventCount; } EventListener.prototype.reset = function() { this.targetEvent.removeListener(this.listener); } var deviceChangedListener = null; chrome.test.runTests([ // Sets up a listener for audio.onDeviceChanged event - // |verifyNoDeviceChangedEvents| test will later verify that no // onDeviceChanged events have been observed. function startDeviceChangedListener() { deviceChangedListener = new EventListener(chrome.audio.onDeviceChanged); chrome.test.succeed(); }, function getDevicesTest() { // Test output devices. Maps device ID -> tested device properties. var kTestDevices = { '30001': { id: '30001', stableDeviceId: '0', displayName: 'Jabra Speaker 1', deviceName: 'Jabra Speaker', streamType: 'OUTPUT' }, '30002': { id: '30002', stableDeviceId: '1', displayName: 'Jabra Speaker 2', deviceName: 'Jabra Speaker', streamType: 'OUTPUT' }, '30003': { id: '30003', stableDeviceId: '2', displayName: 'HDA Intel MID', deviceName: 'HDMI output', streamType: 'OUTPUT' }, '40001': { id: '40001', stableDeviceId: '3', displayName: 'Jabra Mic 1', deviceName: 'Jabra Mic', streamType: 'INPUT' }, '40002': { id: '40002', stableDeviceId: '4', displayName: 'Jabra Mic 2', deviceName: 'Jabra Mic', streamType: 'INPUT' }, '40003': { id: '40003', stableDeviceId: '5', displayName: 'Logitech Webcam', deviceName: 'Webcam Mic', streamType: 'INPUT' } }; chrome.audio.getDevices(chrome.test.callbackPass(function(devices) { assertDevicesMatch(kTestDevices, devices); })); }, function getDevicesWithEmptyFilterTest() { // Test output devices. Maps device ID -> tested device properties. var kTestDevices = { '30001': { id: '30001', stableDeviceId: '0', displayName: 'Jabra Speaker 1', deviceName: 'Jabra Speaker', streamType: 'OUTPUT' }, '30002': { id: '30002', stableDeviceId: '1', displayName: 'Jabra Speaker 2', deviceName: 'Jabra Speaker', streamType: 'OUTPUT' }, '30003': { id: '30003', stableDeviceId: '2', displayName: 'HDA Intel MID', deviceName: 'HDMI output', streamType: 'OUTPUT' }, '40001': { id: '40001', stableDeviceId: '3', displayName: 'Jabra Mic 1', deviceName: 'Jabra Mic', streamType: 'INPUT' }, '40002': { id: '40002', stableDeviceId: '4', displayName: 'Jabra Mic 2', deviceName: 'Jabra Mic', streamType: 'INPUT' }, '40003': { id: '40003', stableDeviceId: '5', displayName: 'Logitech Webcam', deviceName: 'Webcam Mic', streamType: 'INPUT' } }; chrome.audio.getDevices({}, chrome.test.callbackPass(function(devices) { assertDevicesMatch(kTestDevices, devices); })); }, function getInputDevicesTest() { var kTestDevices = { '40001': { id: '40001', streamType: 'INPUT' }, '40002': { id: '40002', streamType: 'INPUT' }, '40003': { id: '40003', streamType: 'INPUT' } }; chrome.audio.getDevices({ streamTypes: ['INPUT'] }, chrome.test.callbackPass(function(devices) { assertDevicesMatch(kTestDevices, devices); })); }, function getOutputDevicesTest() { var kTestDevices = { '30001': { id: '30001', streamType: 'OUTPUT' }, '30002': { id: '30002', streamType: 'OUTPUT' }, '30003': { id: '30003', streamType: 'OUTPUT' }, }; chrome.audio.getDevices({ streamTypes: ['OUTPUT'] }, chrome.test.callbackPass(function(devices) { assertDevicesMatch(kTestDevices, devices); })); }, function getActiveDevicesTest() { chrome.audio.getDevices(chrome.test.callbackPass(function(initial) { var initialActiveDevices = initial.filter(function(device) { return device.isActive; }); chrome.test.assertTrue(initialActiveDevices.length > 0); chrome.audio.getDevices({ isActive: true }, chrome.test.callbackPass(function(devices) { assertDevicesMatch( deviceListToExpectedDevicesMap(initialActiveDevices), devices); })); var initialActiveInputs = initialActiveDevices.filter(function(device) { return device.streamType === 'INPUT'; }); chrome.test.assertTrue(initialActiveInputs.length > 0); chrome.audio.getDevices({ isActive: true, streamTypes: ['INPUT'] }, chrome.test.callbackPass(function(devices) { assertDevicesMatch( deviceListToExpectedDevicesMap(initialActiveInputs), devices); })); var initialActiveOutputs = initialActiveDevices.filter(function(device) { return device.streamType === 'OUTPUT'; }); chrome.test.assertTrue(initialActiveOutputs.length > 0); chrome.audio.getDevices({ isActive: true, streamTypes: ['OUTPUT'] }, chrome.test.callbackPass(function(devices) { assertDevicesMatch( deviceListToExpectedDevicesMap(initialActiveOutputs), devices); })); })); }, function getInactiveDevicesTest() { chrome.audio.getDevices(chrome.test.callbackPass(function(initial) { var initialInactiveDevices = initial.filter(function(device) { return !device.isActive; }); chrome.test.assertTrue(initialInactiveDevices.length > 0); chrome.audio.getDevices({ isActive: false }, chrome.test.callbackPass(function(devices) { assertDevicesMatch( deviceListToExpectedDevicesMap(initialInactiveDevices), devices); })); })); }, function setPropertiesTest() { chrome.audio.getDevices(chrome.test.callbackPass(function(initial) { var expectedDevices = deviceListToExpectedDevicesMap(initial); // Update expected input devices with values that should be changed in // test. var updatedInput = expectedDevices['40002']; chrome.test.assertFalse(updatedInput.gain === 65); updatedInput.level = 65; // Update expected output devices with values that should be changed in // test. var updatedOutput = expectedDevices['30001']; chrome.test.assertFalse(updatedOutput.volume === 45); updatedOutput.level = 45; chrome.audio.setProperties('30001', { level: 45 }, chrome.test.callbackPass(function() { chrome.audio.setProperties('40002', { level: 65 }, chrome.test.callbackPass(function() { chrome.audio.getDevices(chrome.test.callbackPass(function(devices) { assertDevicesMatch(expectedDevices, devices); })); })); })); })); }, function inputMuteTest() { var getMute = function(callback) { chrome.audio.getMute('INPUT', chrome.test.callbackPass(callback)); }; getMute(function(originalValue) { chrome.audio.setMute( 'INPUT', !originalValue, chrome.test.callbackPass(function() { getMute(function(value) { chrome.test.assertEq(!originalValue, value); }); })); }); }, function outputMuteTest() { var getMute = function(callback) { chrome.audio.getMute('OUTPUT', chrome.test.callbackPass(callback)); }; getMute(function(originalValue) { chrome.audio.setMute( 'OUTPUT', !originalValue, chrome.test.callbackPass(function() { getMute(function(value) { chrome.test.assertEq(!originalValue, value); }); })); }); }, function setActiveDevicesTest() { chrome.audio.setActiveDevices({ input: ['40002', '40003'], output: ['30001'] }, chrome.test.callbackPass(function() { chrome.audio.getDevices({ isActive: true }, chrome.test.callbackPass(function(activeDevices) { chrome.test.assertEq(['30001', '40002', '40003'], getDeviceIds(activeDevices)); })); })); }, function setActiveDevicesOutputOnlyTest() { chrome.audio.getDevices({ streamTypes: ['INPUT'], isActive: true }, chrome.test.callbackPass(function(initial) { var initialActiveInputs = getDeviceIds(initial); chrome.test.assertTrue(initialActiveInputs.length > 0); chrome.audio.setActiveDevices({ output: ['30003'] }, chrome.test.callbackPass(function() { chrome.audio.getDevices({ isActive: true }, chrome.test.callbackPass(function(devices) { var expected = ['30003'].concat(initialActiveInputs).sort(); chrome.test.assertEq(expected, getDeviceIds(devices)); })); })); })); }, function setActiveDevicesFailInputTest() { chrome.audio.getDevices({ isActive: true }, chrome.test.callbackPass(function(initial) { var initialActiveIds = getDeviceIds(initial); chrome.test.assertTrue(initialActiveIds.length > 0); chrome.audio.setActiveDevices({ input: ['0000000'], /* does not exist */ output: [] }, chrome.test.callbackFail('Failed to set active devices.', function() { chrome.audio.getDevices({ isActive: true }, chrome.test.callbackPass(function(devices) { chrome.test.assertEq(initialActiveIds, getDeviceIds(devices)); })); })); })); }, function setActiveDevicesFailOutputTest() { chrome.audio.getDevices({ isActive: true }, chrome.test.callbackPass(function(initial) { var initialActiveIds = getDeviceIds(initial); chrome.test.assertTrue(initialActiveIds.length > 0); chrome.audio.setActiveDevices({ input: [], output: ['40001'] /* id is input node ID */ }, chrome.test.callbackFail('Failed to set active devices.', function() { chrome.audio.getDevices({ isActive: true }, chrome.test.callbackPass(function(devices) { chrome.test.assertEq(initialActiveIds, getDeviceIds(devices)); })); })); })); }, function clearActiveDevicesTest() { chrome.audio.getDevices({ isActive: true }, chrome.test.callbackPass(function(initial) { chrome.test.assertTrue(getDeviceIds(initial).length > 0); chrome.audio.setActiveDevices({ input: [], output: [] }, chrome.test.callbackPass(function() { chrome.audio.getDevices({ isActive: true }, chrome.test.callbackPass(function(devices) { chrome.test.assertEq([], devices); })); })); })); }, function verifyNoDeviceChangedEvents() { chrome.test.assertTrue(!!deviceChangedListener); chrome.test.assertEq(0, deviceChangedListener.eventCount); deviceChangedListener.reset(); deviceChangedListener = null; chrome.test.succeed(); }, // Tests verifying the app doesn't have access to deprecated part of the API: function deprecated_GetInfoTest() { chrome.audio.getInfo(chrome.test.callbackFail( 'audio.getInfo is deprecated, use audio.getDevices instead.')); }, function deprecated_setProperties_isMuted() { chrome.audio.getDevices(chrome.test.callbackPass(function(initial) { var expectedDevices = deviceListToExpectedDevicesMap(initial); var expectedError = '|isMuted| property is deprecated, use |audio.setMute|.'; chrome.audio.setProperties('30001', { isMuted: true, // Output device - should have volume set. level: 55 }, chrome.test.callbackFail(expectedError, function() { // Assert that device properties haven't changed. chrome.audio.getDevices(chrome.test.callbackPass(function(devices) { assertDevicesMatch(expectedDevices, devices); })); })); })); }, function deprecated_setProperties_volume() { chrome.audio.getDevices(chrome.test.callbackPass(function(initial) { var expectedDevices = deviceListToExpectedDevicesMap(initial); var expectedError = '|volume| property is deprecated, use |level|.'; chrome.audio.setProperties('30001', { volume: 2, // Output device - should have volume set. level: 55 }, chrome.test.callbackFail(expectedError, function() { // Assert that device properties haven't changed. chrome.audio.getDevices(chrome.test.callbackPass(function(devices) { assertDevicesMatch(expectedDevices, devices); })); })); })); }, function deprecated_setProperties_gain() { chrome.audio.getDevices(chrome.test.callbackPass(function(initial) { var expectedDevices = deviceListToExpectedDevicesMap(initial); var expectedError = '|gain| property is deprecated, use |level|.'; chrome.audio.setProperties('40001', { gain: 2, // Output device - should have volume set. level: 55 }, chrome.test.callbackFail(expectedError, function() { // Assert that device properties haven't changed. chrome.audio.getDevices(chrome.test.callbackPass(function(devices) { assertDevicesMatch(expectedDevices, devices); })); })); })); }, function deprecated_SetActiveDevicesTest() { var kExpectedError = 'String list |ids| is deprecated, use DeviceIdLists type.'; chrome.audio.setActiveDevices([ '30003', '40002' ], chrome.test.callbackFail(kExpectedError)); }, ]);
scheib/chromium
extensions/test/data/api_test/audio/test.js
JavaScript
bsd-3-clause
16,571
// // This macro reads the Hits Tree // void AliPMDHitsRead(Int_t nevt = 1) { TStopwatch timer; timer.Start(); TH2F *h2 = new TH2F("h2"," Y vs. X",200,-100.,100.,200,-100.,100.); // FILE *fpw = fopen("alipmdhits.dat","w"); AliRunLoader *fRunLoader = AliRunLoader::Open("galice.root"); if (!fRunLoader) { printf("Can not open session for file "); } if (!fRunLoader->GetAliRun()) fRunLoader->LoadgAlice(); if (!fRunLoader->TreeE()) fRunLoader->LoadHeader(); if (!fRunLoader->TreeK()) fRunLoader->LoadKinematics(); gAlice = fRunLoader->GetAliRun(); if (gAlice) { printf("Alirun object found\n"); } else { printf("Could not found Alirun object\n"); } fPMD = (AliPMD*)gAlice->GetDetector("PMD"); fPMDLoader = fRunLoader->GetLoader("PMDLoader"); if (fPMDLoader == 0x0) { printf("Can not find PMDLoader\n"); } fPMDLoader->LoadHits("READ"); // This reads the PMD Hits tree and assigns the right track number // to a cell and stores in the summable digits tree // const Int_t kPi0 = 111; const Int_t kGamma = 22; Int_t npmd; Int_t trackno; Int_t smnumber; Int_t trackpid; Int_t mtrackno; Int_t mtrackpid; Int_t xpad = -1, ypad = -1; Float_t edep; Float_t vx = -999.0, vy = -999.0, vz = -999.0; Float_t xPos, yPos, zPos; Float_t xx, yy; AliPMDUtility cc; for (Int_t ievt = 0; ievt < nevt; ievt++) { printf("Event Number = %d\n",ievt); Int_t nparticles = fRunLoader->GetHeader()->GetNtrack(); printf("Number of Particles = %d\n",nparticles); fRunLoader->GetEvent(ievt); // ------------------------------------------------------- // // Pointer to specific detector hits. // Get pointers to Alice detectors and Hits containers TTree* treeH = fPMDLoader->TreeH(); Int_t ntracks = (Int_t) treeH->GetEntries(); printf("Number of Tracks in the TreeH = %d\n", ntracks); TClonesArray* hits = 0; if (fPMD) hits = fPMD->Hits(); // Start loop on tracks in the hits containers for (Int_t track=0; track<ntracks;track++) { gAlice->GetMCApp()->ResetHits(); treeH->GetEvent(track); if (fPMD) { npmd = hits->GetEntriesFast(); for (int ipmd = 0; ipmd < npmd; ipmd++) { fPMDHit = (AliPMDhit*) hits->UncheckedAt(ipmd); trackno = fPMDHit->GetTrack(); //fprintf(fpw,"trackno = %d\n",trackno); // get kinematics of the particles TParticle* mparticle = gAlice->GetMCApp()->Particle(trackno); trackpid = mparticle->GetPdgCode(); Int_t igatr = -999; Int_t ichtr = -999; Int_t igapid = -999; Int_t imo; Int_t igen = 0; Int_t idmo = -999; Int_t tracknoOld=0, trackpidOld=0, statusOld = 0; if (mparticle->GetFirstMother() == -1) { tracknoOld = trackno; trackpidOld = trackpid; statusOld = -1; vx = mparticle->Vx(); vy = mparticle->Vy(); vz = mparticle->Vz(); //fprintf(fpw,"==> Mother ID %5d %5d %5d Vertex: %13.3f %13.3f %13.3f\n", igen, -1, trackpid, vx, vy, vz); } Int_t igstatus = 0; while((imo = mparticle->GetFirstMother()) >= 0) { igen++; mparticle = gAlice->GetMCApp()->Particle(imo); idmo = mparticle->GetPdgCode(); vx = mparticle->Vx(); vy = mparticle->Vy(); vz = mparticle->Vz(); //printf("==> Mother ID %5d %5d %5d Vertex: %13.3f %13.3f %13.3f\n", igen, imo, idmo, vx, vy, vz); //fprintf(fpw,"==> Mother ID %5d %5d %5d Vertex: %13.3f %13.3f %13.3f\n", igen, imo, idmo, vx, vy, vz); if ((idmo == kGamma || idmo == -11 || idmo == 11) && vx == 0. && vy == 0. && vz == 0.) { igatr = imo; igapid = idmo; igstatus = 1; } if(igstatus == 0) { if (idmo == kPi0 && vx == 0. && vy == 0. && vz == 0.) { igatr = imo; igapid = idmo; } } ichtr = imo; } // end of while loop if (idmo == kPi0 && vx == 0. && vy == 0. && vz == 0.) { mtrackno = igatr; mtrackpid = igapid; } else { mtrackno = ichtr; mtrackpid = idmo; } if (statusOld == -1) { mtrackno = tracknoOld; mtrackpid = trackpidOld; } //printf("mtrackno = %d mtrackpid = %d\n",mtrackno,mtrackpid); xPos = fPMDHit->X(); yPos = fPMDHit->Y(); zPos = fPMDHit->Z(); Float_t time = fPMDHit->GetTime(); printf("++++++++++ time = %f\n",time); edep = fPMDHit->GetEnergy(); Int_t vol1 = fPMDHit->GetVolume(1); // Column Int_t vol2 = fPMDHit->GetVolume(2); // Row Int_t vol3 = fPMDHit->GetVolume(4); // UnitModule // -----------------------------------------// // For Super Module 1 & 2 // // nrow = 96, ncol = 48 // // For Super Module 3 & 4 // // nrow = 48, ncol = 96 // // -----------------------------------------// if (vol3 < 24) { smnumber = vol3; } else { smnumber = vol3 - 24; } xpad = vol1; ypad = vol2; if(zPos > 361.5) { cc.RectGeomCellPos(smnumber,xpad,ypad,xx,yy); h2->Fill(xx,yy); } } } } // Track Loop ended } h2->Draw(); fRunLoader->UnloadgAlice(); fRunLoader->UnloadHeader(); fRunLoader->UnloadKinematics(); fPMDLoader->UnloadHits(); timer.Stop(); timer.Print(); }
ecalvovi/AliRoot
PMD/macro/AliPMDHitsRead.C
C++
bsd-3-clause
5,688
#!/usr/bin/env python # Copyright (c) 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Valid certificate chain where the target certificate contains a public key with a 512-bit modulus (weak).""" import sys sys.path += ['../..'] import gencerts # Self-signed root certificate. root = gencerts.create_self_signed_root_certificate('Root') # Intermediate intermediate = gencerts.create_intermediate_certificate('Intermediate', root) # Target certificate. target = gencerts.create_end_entity_certificate('Target', intermediate) target.set_key(gencerts.get_or_generate_rsa_key( 512, gencerts.create_key_path(target.name))) chain = [target, intermediate, root] gencerts.write_chain(__doc__, chain, 'chain.pem')
nwjs/chromium.src
net/data/verify_certificate_chain_unittest/target-has-512bit-rsa-key/generate-chains.py
Python
bsd-3-clause
820
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/public/browser/render_process_host_creation_observer.h" #include "content/browser/renderer_host/render_process_host_impl.h" namespace content { RenderProcessHostCreationObserver::RenderProcessHostCreationObserver() { RenderProcessHostImpl::RegisterCreationObserver(this); } RenderProcessHostCreationObserver::~RenderProcessHostCreationObserver() { RenderProcessHostImpl::UnregisterCreationObserver(this); } } // namespace content
endlessm/chromium-browser
content/browser/renderer_host/render_process_host_creation_observer.cc
C++
bsd-3-clause
624
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/widget/desktop_aura/x11_topmost_window_finder.h" #include <algorithm> #include <vector> #include <X11/extensions/shape.h> #include <X11/Xlib.h> #include <X11/Xregion.h> // Get rid of X11 macros which conflict with gtest. #undef Bool #undef None #include "base/memory/scoped_ptr.h" #include "base/path_service.h" #include "third_party/skia/include/core/SkRect.h" #include "third_party/skia/include/core/SkRegion.h" #include "ui/aura/window.h" #include "ui/aura/window_tree_host.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/ui_base_paths.h" #include "ui/events/platform/x11/x11_event_source.h" #include "ui/gfx/path.h" #include "ui/gfx/path_x11.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gl/test/gl_surface_test_support.h" #include "ui/views/test/views_test_base.h" #include "ui/views/test/x11_property_change_waiter.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #include "ui/views/widget/desktop_aura/x11_desktop_handler.h" #include "ui/views/widget/widget.h" namespace views { namespace { // Waits till |window| is minimized. class MinimizeWaiter : public X11PropertyChangeWaiter { public: explicit MinimizeWaiter(XID window) : X11PropertyChangeWaiter(window, "_NET_WM_STATE") { const char* kAtomsToCache[] = { "_NET_WM_STATE_HIDDEN", NULL }; atom_cache_.reset(new ui::X11AtomCache(gfx::GetXDisplay(), kAtomsToCache)); } ~MinimizeWaiter() override {} private: // X11PropertyChangeWaiter: bool ShouldKeepOnWaiting(const ui::PlatformEvent& event) override { std::vector<Atom> wm_states; if (ui::GetAtomArrayProperty(xwindow(), "_NET_WM_STATE", &wm_states)) { std::vector<Atom>::iterator it = std::find( wm_states.begin(), wm_states.end(), atom_cache_->GetAtom("_NET_WM_STATE_HIDDEN")); return it == wm_states.end(); } return true; } scoped_ptr<ui::X11AtomCache> atom_cache_; DISALLOW_COPY_AND_ASSIGN(MinimizeWaiter); }; // Waits till |_NET_CLIENT_LIST_STACKING| is updated to include // |expected_windows|. class StackingClientListWaiter : public X11PropertyChangeWaiter { public: StackingClientListWaiter(XID* expected_windows, size_t count) : X11PropertyChangeWaiter(ui::GetX11RootWindow(), "_NET_CLIENT_LIST_STACKING"), expected_windows_(expected_windows, expected_windows + count) { } ~StackingClientListWaiter() override {} // X11PropertyChangeWaiter: void Wait() override { // StackingClientListWaiter may be created after // _NET_CLIENT_LIST_STACKING already contains |expected_windows|. if (!ShouldKeepOnWaiting(NULL)) return; X11PropertyChangeWaiter::Wait(); } private: // X11PropertyChangeWaiter: bool ShouldKeepOnWaiting(const ui::PlatformEvent& event) override { std::vector<XID> stack; ui::GetXWindowStack(ui::GetX11RootWindow(), &stack); for (size_t i = 0; i < expected_windows_.size(); ++i) { std::vector<XID>::iterator it = std::find( stack.begin(), stack.end(), expected_windows_[i]); if (it == stack.end()) return true; } return false; } std::vector<XID> expected_windows_; DISALLOW_COPY_AND_ASSIGN(StackingClientListWaiter); }; } // namespace class X11TopmostWindowFinderTest : public ViewsTestBase { public: X11TopmostWindowFinderTest() { } ~X11TopmostWindowFinderTest() override {} // Creates and shows a Widget with |bounds|. The caller takes ownership of // the returned widget. scoped_ptr<Widget> CreateAndShowWidget(const gfx::Rect& bounds) { scoped_ptr<Widget> toplevel(new Widget); Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.native_widget = new DesktopNativeWidgetAura(toplevel.get()); params.bounds = bounds; params.remove_standard_frame = true; toplevel->Init(params); toplevel->Show(); return toplevel.Pass(); } // Creates and shows an X window with |bounds|. XID CreateAndShowXWindow(const gfx::Rect& bounds) { XID root = DefaultRootWindow(xdisplay()); XID xid = XCreateSimpleWindow(xdisplay(), root, 0, 0, 1, 1, 0, // border_width 0, // border 0); // background ui::SetUseOSWindowFrame(xid, false); ShowAndSetXWindowBounds(xid, bounds); return xid; } // Shows |xid| and sets its bounds. void ShowAndSetXWindowBounds(XID xid, const gfx::Rect& bounds) { XMapWindow(xdisplay(), xid); XWindowChanges changes = {0}; changes.x = bounds.x(); changes.y = bounds.y(); changes.width = bounds.width(); changes.height = bounds.height(); XConfigureWindow(xdisplay(), xid, CWX | CWY | CWWidth | CWHeight, &changes); } Display* xdisplay() { return gfx::GetXDisplay(); } // Returns the topmost X window at the passed in screen position. XID FindTopmostXWindowAt(int screen_x, int screen_y) { X11TopmostWindowFinder finder; return finder.FindWindowAt(gfx::Point(screen_x, screen_y)); } // Returns the topmost aura::Window at the passed in screen position. Returns // NULL if the topmost window does not have an associated aura::Window. aura::Window* FindTopmostLocalProcessWindowAt(int screen_x, int screen_y) { X11TopmostWindowFinder finder; return finder.FindLocalProcessWindowAt(gfx::Point(screen_x, screen_y), std::set<aura::Window*>()); } // Returns the topmost aura::Window at the passed in screen position ignoring // |ignore_window|. Returns NULL if the topmost window does not have an // associated aura::Window. aura::Window* FindTopmostLocalProcessWindowWithIgnore( int screen_x, int screen_y, aura::Window* ignore_window) { std::set<aura::Window*> ignore; ignore.insert(ignore_window); X11TopmostWindowFinder finder; return finder.FindLocalProcessWindowAt(gfx::Point(screen_x, screen_y), ignore); } static void SetUpTestCase() { gfx::GLSurfaceTestSupport::InitializeOneOff(); ui::RegisterPathProvider(); base::FilePath ui_test_pak_path; ASSERT_TRUE(PathService::Get(ui::UI_TEST_PAK, &ui_test_pak_path)); ui::ResourceBundle::InitSharedInstanceWithPakPath(ui_test_pak_path); } // ViewsTestBase: void SetUp() override { ViewsTestBase::SetUp(); // Make X11 synchronous for our display connection. This does not force the // window manager to behave synchronously. XSynchronize(xdisplay(), True); // Ensure that the X11DesktopHandler exists. The X11DesktopHandler is // necessary to properly track menu windows. X11DesktopHandler::get(); } void TearDown() override { XSynchronize(xdisplay(), False); ViewsTestBase::TearDown(); } private: DISALLOW_COPY_AND_ASSIGN(X11TopmostWindowFinderTest); }; TEST_F(X11TopmostWindowFinderTest, Basic) { // Avoid positioning test windows at 0x0 because window managers often have a // panel/launcher along one of the screen edges and do not allow windows to // position themselves to overlap the panel/launcher. scoped_ptr<Widget> widget1( CreateAndShowWidget(gfx::Rect(100, 100, 200, 100))); aura::Window* window1 = widget1->GetNativeWindow(); XID xid1 = window1->GetHost()->GetAcceleratedWidget(); XID xid2 = CreateAndShowXWindow(gfx::Rect(200, 100, 100, 200)); scoped_ptr<Widget> widget3( CreateAndShowWidget(gfx::Rect(100, 190, 200, 110))); aura::Window* window3 = widget3->GetNativeWindow(); XID xid3 = window3->GetHost()->GetAcceleratedWidget(); XID xids[] = { xid1, xid2, xid3 }; StackingClientListWaiter waiter(xids, arraysize(xids)); waiter.Wait(); ui::X11EventSource::GetInstance()->DispatchXEvents(); EXPECT_EQ(xid1, FindTopmostXWindowAt(150, 150)); EXPECT_EQ(window1, FindTopmostLocalProcessWindowAt(150, 150)); EXPECT_EQ(xid2, FindTopmostXWindowAt(250, 150)); EXPECT_EQ(NULL, FindTopmostLocalProcessWindowAt(250, 150)); EXPECT_EQ(xid3, FindTopmostXWindowAt(250, 250)); EXPECT_EQ(window3, FindTopmostLocalProcessWindowAt(250, 250)); EXPECT_EQ(xid3, FindTopmostXWindowAt(150, 250)); EXPECT_EQ(window3, FindTopmostLocalProcessWindowAt(150, 250)); EXPECT_EQ(xid3, FindTopmostXWindowAt(150, 195)); EXPECT_EQ(window3, FindTopmostLocalProcessWindowAt(150, 195)); EXPECT_NE(xid1, FindTopmostXWindowAt(1000, 1000)); EXPECT_NE(xid2, FindTopmostXWindowAt(1000, 1000)); EXPECT_NE(xid3, FindTopmostXWindowAt(1000, 1000)); EXPECT_EQ(NULL, FindTopmostLocalProcessWindowAt(1000, 1000)); EXPECT_EQ(window1, FindTopmostLocalProcessWindowWithIgnore(150, 150, window3)); EXPECT_EQ(NULL, FindTopmostLocalProcessWindowWithIgnore(250, 250, window3)); EXPECT_EQ(NULL, FindTopmostLocalProcessWindowWithIgnore(150, 250, window3)); EXPECT_EQ(window1, FindTopmostLocalProcessWindowWithIgnore(150, 195, window3)); XDestroyWindow(xdisplay(), xid2); } // Test that the minimized state is properly handled. TEST_F(X11TopmostWindowFinderTest, Minimized) { scoped_ptr<Widget> widget1( CreateAndShowWidget(gfx::Rect(100, 100, 100, 100))); aura::Window* window1 = widget1->GetNativeWindow(); XID xid1 = window1->GetHost()->GetAcceleratedWidget(); XID xid2 = CreateAndShowXWindow(gfx::Rect(300, 100, 100, 100)); XID xids[] = { xid1, xid2 }; StackingClientListWaiter stack_waiter(xids, arraysize(xids)); stack_waiter.Wait(); ui::X11EventSource::GetInstance()->DispatchXEvents(); EXPECT_EQ(xid1, FindTopmostXWindowAt(150, 150)); { MinimizeWaiter minimize_waiter(xid1); XIconifyWindow(xdisplay(), xid1, 0); minimize_waiter.Wait(); } EXPECT_NE(xid1, FindTopmostXWindowAt(150, 150)); EXPECT_NE(xid2, FindTopmostXWindowAt(150, 150)); // Repeat test for an X window which does not belong to a views::Widget // because the code path is different. EXPECT_EQ(xid2, FindTopmostXWindowAt(350, 150)); { MinimizeWaiter minimize_waiter(xid2); XIconifyWindow(xdisplay(), xid2, 0); minimize_waiter.Wait(); } EXPECT_NE(xid1, FindTopmostXWindowAt(350, 150)); EXPECT_NE(xid2, FindTopmostXWindowAt(350, 150)); XDestroyWindow(xdisplay(), xid2); } // Test that non-rectangular windows are properly handled. TEST_F(X11TopmostWindowFinderTest, NonRectangular) { if (!ui::IsShapeExtensionAvailable()) return; scoped_ptr<Widget> widget1( CreateAndShowWidget(gfx::Rect(100, 100, 100, 100))); XID xid1 = widget1->GetNativeWindow()->GetHost()->GetAcceleratedWidget(); SkRegion* skregion1 = new SkRegion; skregion1->op(SkIRect::MakeXYWH(0, 10, 10, 90), SkRegion::kUnion_Op); skregion1->op(SkIRect::MakeXYWH(10, 0, 90, 100), SkRegion::kUnion_Op); // Widget takes ownership of |skregion1|. widget1->SetShape(skregion1); SkRegion skregion2; skregion2.op(SkIRect::MakeXYWH(0, 10, 10, 90), SkRegion::kUnion_Op); skregion2.op(SkIRect::MakeXYWH(10, 0, 90, 100), SkRegion::kUnion_Op); XID xid2 = CreateAndShowXWindow(gfx::Rect(300, 100, 100, 100)); gfx::XScopedPtr<REGION, gfx::XObjectDeleter<REGION, int, XDestroyRegion>> region2(gfx::CreateRegionFromSkRegion(skregion2)); XShapeCombineRegion(xdisplay(), xid2, ShapeBounding, 0, 0, region2.get(), false); XID xids[] = { xid1, xid2 }; StackingClientListWaiter stack_waiter(xids, arraysize(xids)); stack_waiter.Wait(); ui::X11EventSource::GetInstance()->DispatchXEvents(); EXPECT_EQ(xid1, FindTopmostXWindowAt(105, 120)); EXPECT_NE(xid1, FindTopmostXWindowAt(105, 105)); EXPECT_NE(xid2, FindTopmostXWindowAt(105, 105)); // Repeat test for an X window which does not belong to a views::Widget // because the code path is different. EXPECT_EQ(xid2, FindTopmostXWindowAt(305, 120)); EXPECT_NE(xid1, FindTopmostXWindowAt(305, 105)); EXPECT_NE(xid2, FindTopmostXWindowAt(305, 105)); XDestroyWindow(xdisplay(), xid2); } // Test that a window with an empty shape are properly handled. TEST_F(X11TopmostWindowFinderTest, NonRectangularEmptyShape) { if (!ui::IsShapeExtensionAvailable()) return; scoped_ptr<Widget> widget1( CreateAndShowWidget(gfx::Rect(100, 100, 100, 100))); XID xid1 = widget1->GetNativeWindow()->GetHost()->GetAcceleratedWidget(); SkRegion* skregion1 = new SkRegion; skregion1->op(SkIRect::MakeXYWH(0, 0, 0, 0), SkRegion::kUnion_Op); // Widget takes ownership of |skregion1|. widget1->SetShape(skregion1); XID xids[] = { xid1 }; StackingClientListWaiter stack_waiter(xids, arraysize(xids)); stack_waiter.Wait(); ui::X11EventSource::GetInstance()->DispatchXEvents(); EXPECT_NE(xid1, FindTopmostXWindowAt(105, 105)); } // Test that setting a Null shape removes the shape. TEST_F(X11TopmostWindowFinderTest, NonRectangularNullShape) { if (!ui::IsShapeExtensionAvailable()) return; scoped_ptr<Widget> widget1( CreateAndShowWidget(gfx::Rect(100, 100, 100, 100))); XID xid1 = widget1->GetNativeWindow()->GetHost()->GetAcceleratedWidget(); SkRegion* skregion1 = new SkRegion; skregion1->op(SkIRect::MakeXYWH(0, 0, 0, 0), SkRegion::kUnion_Op); // Widget takes ownership of |skregion1|. widget1->SetShape(skregion1); // Remove the shape - this is now just a normal window. widget1->SetShape(NULL); XID xids[] = { xid1 }; StackingClientListWaiter stack_waiter(xids, arraysize(xids)); stack_waiter.Wait(); ui::X11EventSource::GetInstance()->DispatchXEvents(); EXPECT_EQ(xid1, FindTopmostXWindowAt(105, 105)); } // Test that the TopmostWindowFinder finds windows which belong to menus // (which may or may not belong to Chrome). TEST_F(X11TopmostWindowFinderTest, Menu) { XID xid = CreateAndShowXWindow(gfx::Rect(100, 100, 100, 100)); XID root = DefaultRootWindow(xdisplay()); XSetWindowAttributes swa; swa.override_redirect = True; XID menu_xid = XCreateWindow(xdisplay(), root, 0, 0, 1, 1, 0, // border width CopyFromParent, // depth InputOutput, CopyFromParent, // visual CWOverrideRedirect, &swa); { const char* kAtomsToCache[] = { "_NET_WM_WINDOW_TYPE_MENU", NULL }; ui::X11AtomCache atom_cache(gfx::GetXDisplay(), kAtomsToCache); ui::SetAtomProperty(menu_xid, "_NET_WM_WINDOW_TYPE", "ATOM", atom_cache.GetAtom("_NET_WM_WINDOW_TYPE_MENU")); } ui::SetUseOSWindowFrame(menu_xid, false); ShowAndSetXWindowBounds(menu_xid, gfx::Rect(140, 110, 100, 100)); ui::X11EventSource::GetInstance()->DispatchXEvents(); // |menu_xid| is never added to _NET_CLIENT_LIST_STACKING. XID xids[] = { xid }; StackingClientListWaiter stack_waiter(xids, arraysize(xids)); stack_waiter.Wait(); EXPECT_EQ(xid, FindTopmostXWindowAt(110, 110)); EXPECT_EQ(menu_xid, FindTopmostXWindowAt(150, 120)); EXPECT_EQ(menu_xid, FindTopmostXWindowAt(210, 120)); XDestroyWindow(xdisplay(), xid); XDestroyWindow(xdisplay(), menu_xid); } } // namespace views
CapOM/ChromiumGStreamerBackend
ui/views/widget/desktop_aura/x11_topmost_window_finder_interactive_uitest.cc
C++
bsd-3-clause
15,664
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>This tests that the querySelector and querySelectorAll fast path for IDs is not overzelous.</title> <script src="../../../resources/testharness.js"></script> <script src="../../../resources/testharnessreport.js"></script> </head> <body> <script src="resources/id-fastpath-strict.js"></script> </body> </html>
scheib/chromium
third_party/blink/web_tests/fast/dom/SelectorAPI/id-fastpath-strict.html
HTML
bsd-3-clause
424
li a { color: green; } body { background: white url("images/background.gif") no-repeat right bottom; }
zhljen/django-tutorial
templates/polls/static/polls/style.css
CSS
bsd-3-clause
113
<!DOCTYPE html> <!-- Copyright (c) 2013 Samsung Electronics Co., Ltd. Licensed under the Apache License, Version 2.0 (the License); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Authors: Roman Frolow <r.frolow@samsung.com> --> <html> <head> <title>SystemInfo_addPropertyValueChangeListener</title> <meta charset="utf-8"/> <script type="text/javascript" src="support/unitcommon.js"></script> <script type="text/javascript" src="support/systeminfo_common.js"></script> </head> <body> <div id="log"></div> <script type="text/javascript"> //==== TEST: SystemInfo_addPropertyValueChangeListener //==== LABEL Check method addPropertyValueChangeListener of SystemInfo //==== SPEC Tizen Web API:Tizen Specification:SystemInfo:SystemInfo:addPropertyValueChangeListener M //==== SPEC_URL https://developer.tizen.org/help/topic/org.tizen.web.device.apireference/tizen/systeminfo.html //==== TEST_CRITERIA MMINA MAST MR //==== ONLOAD_DELAY 90 var t = async_test(document.title, {timeout: 90000}), addPropertyValueChangeListenerSuccess, addPropertyValueChangeListenerError, retValue = null; setup({timeout: 90000}); t.step(function () { addPropertyValueChangeListenerError = t.step_func(function (error) { assert_unreached("addPropertyValueChangeListener() error callback invoked: name:" + error.name + ", msg:" + error.message); }); addPropertyValueChangeListenerSuccess = t.step_func(function (property) { assert_own_property(property, "load", "CPU does not own load property."); assert_type(retValue, "unsigned long", "addPropertyValueChangeListener returns wrong value"); t.done(); }); retValue = tizen.systeminfo.addPropertyValueChangeListener("CPU", addPropertyValueChangeListenerSuccess); }); </script> </body> </html>
qiuzhong/crosswalk-test-suite
webapi/tct-systeminfo-tizen-tests/systeminfo/SystemInfo_addPropertyValueChangeListener.html
HTML
bsd-3-clause
2,199
/*********************************************************************/ /* Copyright 2009, 2010 The University of Texas at Austin. */ /* All rights reserved. */ /* */ /* Redistribution and use in source and binary forms, with or */ /* without modification, are permitted provided that the following */ /* conditions are met: */ /* */ /* 1. Redistributions of source code must retain the above */ /* copyright notice, this list of conditions and the following */ /* disclaimer. */ /* */ /* 2. Redistributions in binary form must reproduce the above */ /* copyright notice, this list of conditions and the following */ /* disclaimer in the documentation and/or other materials */ /* provided with the distribution. */ /* */ /* THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF TEXAS AT */ /* AUSTIN ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, */ /* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF */ /* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */ /* DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OF TEXAS AT */ /* AUSTIN OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, */ /* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */ /* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE */ /* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR */ /* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF */ /* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */ /* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT */ /* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */ /* POSSIBILITY OF SUCH DAMAGE. */ /* */ /* The views and conclusions contained in the software and */ /* documentation are those of the authors and should not be */ /* interpreted as representing official policies, either expressed */ /* or implied, of The University of Texas at Austin. */ /*********************************************************************/ #ifndef COMMON_ALPHA #define COMMON_ALPHA #ifndef ASSEMBLER #define MB asm("mb") #define WMB asm("wmb") static void __inline blas_lock(unsigned long *address){ #ifndef __DECC unsigned long tmp1, tmp2; asm volatile( "1: ldq %1, %0\n" " bne %1, 2f\n" " ldq_l %1, %0\n" " bne %1, 2f\n" " or %1, 1, %2\n" " stq_c %2, %0\n" " beq %2, 2f\n" " mb\n " " br $31, 3f\n" "2: br $31, 1b\n" "3:\n" : "=m"(*address), "=&r"(tmp1), "=&r"(tmp2) : : "memory"); #else asm ( "10:" " ldq %t0, 0(%a0); " " bne %t0, 20f; " " ldq_l %t0, 0(%a0); " " bne %t0, 20f; " " or %t0, 1, %t1;" " stq_c %t1, 0(%a0); " " beq %t1, 20f; " " mb; " " br %r31,30f; " "20: " " br %r31,10b; " "30:", address); #endif } static __inline unsigned int rpcc(void){ unsigned int r0; #ifndef __DECC asm __volatile__("rpcc %0" : "=r"(r0) : : "memory"); #else r0 = asm("rpcc %v0"); #endif return r0; } #define HALT ldq $0, 0($0) #ifndef __DECC #define GET_IMAGE(res) asm __volatile__("fmov $f1, %0" : "=f"(res) : : "memory") #else #define GET_IMAGE(res) res = dasm("fmov $f1, %f0") #endif #ifdef SMP #ifdef USE64BITINT static __inline long blas_quickdivide(long x, long y){ return x/y; } #else extern unsigned int blas_quick_divide_table[]; static __inline int blas_quickdivide(unsigned int x, unsigned int y){ if (y <= 1) return x; return (int)((x * (unsigned long)blas_quick_divide_table[y]) >> 32); } #endif #endif #define BASE_ADDRESS ((0x1b0UL << 33) | (0x1c0UL << 23) | (0x000UL << 13)) #ifndef PAGESIZE #define PAGESIZE ( 8UL << 10) #define HUGE_PAGESIZE ( 4 << 20) #endif #define BUFFER_SIZE (32UL << 20) #else #ifndef F_INTERFACE #define REALNAME ASMNAME #else #define REALNAME ASMFNAME #endif #define PROLOGUE \ .arch ev6; \ .set noat; \ .set noreorder; \ .text; \ .align 5; \ .globl REALNAME; \ .ent REALNAME; \ REALNAME: #ifdef PROFILE #define PROFCODE \ ldgp $gp, 0($27); \ lda $28, _mcount; \ jsr $28, ($28), _mcount; \ .prologue 1 #else #define PROFCODE .prologue 0 #endif #if defined(__linux__) && defined(__ELF__) #define GNUSTACK .section .note.GNU-stack,"",@progbits #else #define GNUSTACK #endif #define EPILOGUE \ .end REALNAME; \ .ident VERSION; \ GNUSTACK #endif #ifdef DOUBLE #define SXADDQ s8addq #define SXSUBL s8subl #define LD ldt #define ST stt #define STQ stq #define ADD addt/su #define SUB subt/su #define MUL mult/su #define DIV divt/su #else #define SXADDQ s4addq #define SXSUBL s4subl #define LD lds #define ST sts #define STQ stl #define ADD adds/su #define SUB subs/su #define MUL muls/su #define DIV divs/su #endif #endif
zhmz90/OpenBLAS
common_alpha.h
C
bsd-3-clause
5,440
/* eslint strict:0 */ var modules = Object.create(null); var inGuard = false; function define(id, factory) { modules[id] = { factory, module: {exports: {}}, isInitialized: false, hasError: false, }; if (__DEV__) { // HMR Object.assign(modules[id].module, { hot: { acceptCallback: null, accept: function(callback) { modules[id].module.hot.acceptCallback = callback; } } }); } } function require(id) { var mod = modules[id]; if (mod && mod.isInitialized) { return mod.module.exports; } return requireImpl(id); } function requireImpl(id) { if (global.ErrorUtils && !inGuard) { inGuard = true; var returnValue; try { returnValue = requireImpl.apply(this, arguments); } catch (e) { global.ErrorUtils.reportFatalError(e); } inGuard = false; return returnValue; } var mod = modules[id]; if (!mod) { var msg = 'Requiring unknown module "' + id + '"'; if (__DEV__) { msg += '. If you are sure the module is there, try restarting the packager.'; } throw new Error(msg); } if (mod.hasError) { throw new Error( 'Requiring module "' + id + '" which threw an exception' ); } try { // We must optimistically mark mod as initialized before running the factory to keep any // require cycles inside the factory from causing an infinite require loop. mod.isInitialized = true; __DEV__ && Systrace().beginEvent('JS_require_' + id); // keep args in sync with with defineModuleCode in // packager/react-packager/src/Resolver/index.js mod.factory.call(global, global, require, mod.module, mod.module.exports); __DEV__ && Systrace().endEvent(); } catch (e) { mod.hasError = true; mod.isInitialized = false; throw e; } return mod.module.exports; } const Systrace = __DEV__ && (() => { var _Systrace; try { _Systrace = require('Systrace'); } catch (e) {} return _Systrace && _Systrace.beginEvent ? _Systrace : { beginEvent: () => {}, endEvent: () => {} }; }); global.__d = define; global.require = require; if (__DEV__) { // HMR function accept(id, factory) { var mod = modules[id]; if (!mod) { define(id, factory); return; // new modules don't need to be accepted } if (!mod.module.hot) { console.warn( 'Cannot accept module because Hot Module Replacement ' + 'API was not installed.' ); return; } if (mod.module.hot.acceptCallback) { mod.factory = factory; mod.isInitialized = false; require(id); mod.module.hot.acceptCallback(); } else { console.warn( '[HMR] Module `' + id + '` can\'t be hot reloaded because it ' + 'doesn\'t provide accept callback hook. Reload the app to get the updates.' ); } } global.__accept = accept; }
shinate/react-native
packager/react-packager/src/Resolver/polyfills/require.js
JavaScript
bsd-3-clause
2,910
/*! * \copy * Copyright (c) 2009-2013, Cisco Systems * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * * \file expand_pic.h * * \brief Interface for expanding reconstructed picture to be used for reference * * \date 06/08/2009 ************************************************************************************* */ #ifndef EXPAND_PICTURE_H #define EXPAND_PICTURE_H #include "typedefs.h" #if defined(__cplusplus) extern "C" { #endif//__cplusplus #define PADDING_LENGTH 32 // reference extension #define CHROMA_PADDING_LENGTH 16 // chroma reference extension #if defined(X86_ASM) void ExpandPictureLuma_sse2 (uint8_t* pDst, const int32_t kiStride, const int32_t kiPicW, const int32_t kiPicH); void ExpandPictureChromaAlign_sse2 (uint8_t* pDst, const int32_t kiStride, const int32_t kiPicW, const int32_t kiPicH); void ExpandPictureChromaUnalign_sse2 (uint8_t* pDst, const int32_t kiStride, const int32_t kiPicW, const int32_t kiPicH); #endif//X86_ASM #if defined(HAVE_NEON) void ExpandPictureLuma_neon (uint8_t* pDst, const int32_t kiStride, const int32_t kiPicW, const int32_t kiPicH); void ExpandPictureChroma_neon (uint8_t* pDst, const int32_t kiStride, const int32_t kiPicW, const int32_t kiPicH); #endif #if defined(HAVE_NEON_AARCH64) void ExpandPictureLuma_AArch64_neon (uint8_t* pDst, const int32_t kiStride, const int32_t kiPicW, const int32_t kiPicH); void ExpandPictureChroma_AArch64_neon (uint8_t* pDst, const int32_t kiStride, const int32_t kiPicW, const int32_t kiPicH); #endif #if defined(HAVE_MMI) void ExpandPictureLuma_mmi (uint8_t* pDst, const int32_t kiStride, const int32_t kiPicW, const int32_t kiPicH); void ExpandPictureChromaAlign_mmi (uint8_t* pDst, const int32_t kiStride, const int32_t kiPicW, const int32_t kiPicH); void ExpandPictureChromaUnalign_mmi (uint8_t* pDst, const int32_t kiStride, const int32_t kiPicW, const int32_t kiPicH); #endif//HAVE_MMI typedef void (*PExpandPictureFunc) (uint8_t* pDst, const int32_t kiStride, const int32_t kiPicW, const int32_t kiPicH); typedef struct TagExpandPicFunc { PExpandPictureFunc pfExpandLumaPicture; PExpandPictureFunc pfExpandChromaPicture[2]; } SExpandPicFunc; void PadMBLuma_c (uint8_t*& pDst, const int32_t& kiStride, const int32_t& kiPicW, const int32_t& kiPicH, const int32_t& kiMbX, const int32_t& kiMbY, const int32_t& kiMBWidth, const int32_t& kiMBHeight); void PadMBChroma_c (uint8_t*& pDst, const int32_t& kiStride, const int32_t& kiPicW, const int32_t& kiPicH, const int32_t& kiMbX, const int32_t& kiMbY, const int32_t& kiMBWidth, const int32_t& kiMBHeight); void ExpandReferencingPicture (uint8_t* pData[3], int32_t iWidth, int32_t iHeight, int32_t iStride[3], PExpandPictureFunc pExpLuma, PExpandPictureFunc pExpChrom[2]); void InitExpandPictureFunc (SExpandPicFunc* pExpandPicFunc, const uint32_t kuiCPUFlags); #if defined(__cplusplus) } #endif//__cplusplus #endif
endlessm/chromium-browser
third_party/openh264/src/codec/common/inc/expand_pic.h
C
bsd-3-clause
4,812
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview * * It2MeHelpeeChannel relays messages between the Hangouts web page (Hangouts) * and the It2Me Native Messaging Host (It2MeHost) for the helpee (the Hangouts * participant who is receiving remoting assistance). * * It runs in the background page. It contains a chrome.runtime.Port object, * representing a connection to Hangouts, and a remoting.It2MeHostFacade object, * representing a connection to the IT2Me Native Messaging Host. * * Hangouts It2MeHelpeeChannel It2MeHost * |---------runtime.connect()-------->| | * |-----------hello message---------->| | * |<-----helloResponse message------->| | * |----------connect message--------->| | * | |-----showConfirmDialog()----->| * | |----------connect()---------->| * | |<-------hostStateChanged------| * | | (RECEIVED_ACCESS_CODE) | * |<---connect response (access code)-| | * | | | * * Hangouts will send the access code to the web app on the helper side. * The helper will then connect to the It2MeHost using the access code. * * Hangouts It2MeHelpeeChannel It2MeHost * | |<-------hostStateChanged------| * | | (CONNECTED) | * |<-- hostStateChanged(CONNECTED)----| | * |-------disconnect message--------->| | * |<--hostStateChanged(DISCONNECTED)--| | * * * It also handles host downloads and install status queries: * * Hangouts It2MeHelpeeChannel * |------isHostInstalled message----->| * |<-isHostInstalled response(false)--| * | | * |--------downloadHost message------>| * | | * |------isHostInstalled message----->| * |<-isHostInstalled response(false)--| * | | * |------isHostInstalled message----->| * |<-isHostInstalled response(true)---| */ 'use strict'; /** @suppress {duplicate} */ var remoting = remoting || {}; /** * @param {chrome.runtime.Port} hangoutPort * @param {remoting.It2MeHostFacade} host * @param {remoting.HostInstaller} hostInstaller * @param {function()} onDisposedCallback Callback to notify the client when * the connection is torn down. * * @constructor * @implements {base.Disposable} */ remoting.It2MeHelpeeChannel = function(hangoutPort, host, hostInstaller, onDisposedCallback) { /** * @type {chrome.runtime.Port} * @private */ this.hangoutPort_ = hangoutPort; /** * @type {remoting.It2MeHostFacade} * @private */ this.host_ = host; /** * @type {?remoting.HostInstaller} * @private */ this.hostInstaller_ = hostInstaller; /** * @type {remoting.HostSession.State} * @private */ this.hostState_ = remoting.HostSession.State.UNKNOWN; /** * @type {?function()} * @private */ this.onDisposedCallback_ = onDisposedCallback; this.onHangoutMessageRef_ = this.onHangoutMessage_.bind(this); this.onHangoutDisconnectRef_ = this.onHangoutDisconnect_.bind(this); }; /** @enum {string} */ remoting.It2MeHelpeeChannel.HangoutMessageTypes = { CONNECT: 'connect', CONNECT_RESPONSE: 'connectResponse', DISCONNECT: 'disconnect', DOWNLOAD_HOST: 'downloadHost', ERROR: 'error', HELLO: 'hello', HELLO_RESPONSE: 'helloResponse', HOST_STATE_CHANGED: 'hostStateChanged', IS_HOST_INSTALLED: 'isHostInstalled', IS_HOST_INSTALLED_RESPONSE: 'isHostInstalledResponse' }; /** @enum {string} */ remoting.It2MeHelpeeChannel.Features = { REMOTE_ASSISTANCE: 'remoteAssistance' }; remoting.It2MeHelpeeChannel.prototype.init = function() { this.hangoutPort_.onMessage.addListener(this.onHangoutMessageRef_); this.hangoutPort_.onDisconnect.addListener(this.onHangoutDisconnectRef_); }; remoting.It2MeHelpeeChannel.prototype.dispose = function() { if (this.host_ !== null) { this.host_.unhookCallbacks(); this.host_.disconnect(); this.host_ = null; } if (this.hangoutPort_ !== null) { this.hangoutPort_.onMessage.removeListener(this.onHangoutMessageRef_); this.hangoutPort_.onDisconnect.removeListener(this.onHangoutDisconnectRef_); this.hostState_ = remoting.HostSession.State.DISCONNECTED; try { var MessageTypes = remoting.It2MeHelpeeChannel.HangoutMessageTypes; this.hangoutPort_.postMessage({ method: MessageTypes.HOST_STATE_CHANGED, state: this.hostState_ }); } catch (e) { // |postMessage| throws if |this.hangoutPort_| is disconnected // It is safe to ignore the exception. } this.hangoutPort_.disconnect(); this.hangoutPort_ = null; } if (this.onDisposedCallback_ !== null) { this.onDisposedCallback_(); this.onDisposedCallback_ = null; } }; /** * Message Handler for incoming runtime messages from Hangouts. * * @param {{method:string, data:Object.<string,*>}} message * @private */ remoting.It2MeHelpeeChannel.prototype.onHangoutMessage_ = function(message) { try { var MessageTypes = remoting.It2MeHelpeeChannel.HangoutMessageTypes; switch (message.method) { case MessageTypes.HELLO: this.hangoutPort_.postMessage({ method: MessageTypes.HELLO_RESPONSE, supportedFeatures: base.values(remoting.It2MeHelpeeChannel.Features) }); return true; case MessageTypes.IS_HOST_INSTALLED: this.handleIsHostInstalled_(message); return true; case MessageTypes.DOWNLOAD_HOST: this.handleDownloadHost_(message); return true; case MessageTypes.CONNECT: this.handleConnect_(message); return true; case MessageTypes.DISCONNECT: this.dispose(); return true; } throw new Error('Unsupported message method=' + message.method); } catch(e) { var error = /** @type {Error} */ e; this.sendErrorResponse_(message, error.message); } return false; }; /** * Queries the |hostInstaller| for the installation status. * * @param {{method:string, data:Object.<string,*>}} message * @private */ remoting.It2MeHelpeeChannel.prototype.handleIsHostInstalled_ = function(message) { /** @type {remoting.It2MeHelpeeChannel} */ var that = this; /** @param {boolean} installed */ function sendResponse(installed) { var MessageTypes = remoting.It2MeHelpeeChannel.HangoutMessageTypes; that.hangoutPort_.postMessage({ method: MessageTypes.IS_HOST_INSTALLED_RESPONSE, result: installed }); } this.hostInstaller_.isInstalled().then( sendResponse, this.sendErrorResponse_.bind(this, message) ); }; /** * @param {{method:string, data:Object.<string,*>}} message * @private */ remoting.It2MeHelpeeChannel.prototype.handleDownloadHost_ = function(message) { try { this.hostInstaller_.download(); } catch (e) { var error = /** @type {Error} */ e; this.sendErrorResponse_(message, error.message); } }; /** * Disconnect the session if the |hangoutPort| gets disconnected. * @private */ remoting.It2MeHelpeeChannel.prototype.onHangoutDisconnect_ = function() { this.dispose(); }; /** * Connects to the It2Me Native messaging Host and retrieves the access code. * * @param {{method:string, data:Object.<string,*>}} message * @private */ remoting.It2MeHelpeeChannel.prototype.handleConnect_ = function(message) { var email = getStringAttr(message, 'email'); if (!email) { throw new Error('Missing required parameter: email'); } if (this.hostState_ !== remoting.HostSession.State.UNKNOWN) { throw new Error('An existing connection is in progress.'); } this.showConfirmDialog_().then( this.initializeHost_.bind(this) ).then( this.fetchOAuthToken_.bind(this) ).then( this.connectToHost_.bind(this, email), this.sendErrorResponse_.bind(this, message) ); }; /** * Prompts the user before starting the It2Me Native Messaging Host. This * ensures that even if Hangouts is compromised, an attacker cannot start the * host without explicit user confirmation. * * @return {Promise} A promise that resolves to a boolean value, indicating * whether the user accepts the remote assistance or not. * @private */ remoting.It2MeHelpeeChannel.prototype.showConfirmDialog_ = function() { if (base.isAppsV2()) { return this.showConfirmDialogV2_(); } else { return this.showConfirmDialogV1_(); } }; /** * @return {Promise} A promise that resolves to a boolean value, indicating * whether the user accepts the remote assistance or not. * @private */ remoting.It2MeHelpeeChannel.prototype.showConfirmDialogV1_ = function() { var messageHeader = l10n.getTranslationOrError( /*i18n-content*/'HANGOUTS_CONFIRM_DIALOG_MESSAGE_1'); var message1 = l10n.getTranslationOrError( /*i18n-content*/'HANGOUTS_CONFIRM_DIALOG_MESSAGE_2'); var message2 = l10n.getTranslationOrError( /*i18n-content*/'HANGOUTS_CONFIRM_DIALOG_MESSAGE_3'); var message = base.escapeHTML(messageHeader) + '\n' + '- ' + base.escapeHTML(message1) + '\n' + '- ' + base.escapeHTML(message2) + '\n'; if(window.confirm(message)) { return Promise.resolve(); } else { return Promise.reject(new Error(remoting.Error.CANCELLED)); } }; /** * @return {Promise} A promise that resolves to a boolean value, indicating * whether the user accepts the remote assistance or not. * @private */ remoting.It2MeHelpeeChannel.prototype.showConfirmDialogV2_ = function() { var messageHeader = l10n.getTranslationOrError( /*i18n-content*/'HANGOUTS_CONFIRM_DIALOG_MESSAGE_1'); var message1 = l10n.getTranslationOrError( /*i18n-content*/'HANGOUTS_CONFIRM_DIALOG_MESSAGE_2'); var message2 = l10n.getTranslationOrError( /*i18n-content*/'HANGOUTS_CONFIRM_DIALOG_MESSAGE_3'); var message = '<div>' + base.escapeHTML(messageHeader) + '</div>' + '<ul class="insetList">' + '<li>' + base.escapeHTML(message1) + '</li>' + '<li>' + base.escapeHTML(message2) + '</li>' + '</ul>'; /** * @param {function(*=):void} resolve * @param {function(*=):void} reject */ return new Promise(function(resolve, reject) { /** @param {number} result */ function confirmDialogCallback(result) { if (result === 1) { resolve(); } else { reject(new Error(remoting.Error.CANCELLED)); } } remoting.MessageWindow.showConfirmWindow( '', // Empty string to use the package name as the dialog title. message, l10n.getTranslationOrError( /*i18n-content*/'HANGOUTS_CONFIRM_DIALOG_ACCEPT'), l10n.getTranslationOrError( /*i18n-content*/'HANGOUTS_CONFIRM_DIALOG_DECLINE'), confirmDialogCallback ); }); }; /** * @return {Promise} A promise that resolves when the host is initialized. * @private */ remoting.It2MeHelpeeChannel.prototype.initializeHost_ = function() { /** @type {remoting.It2MeHostFacade} */ var host = this.host_; /** * @param {function(*=):void} resolve * @param {function(*=):void} reject */ return new Promise(function(resolve, reject) { if (host.initialized()) { resolve(); } else { host.initialize(resolve, reject); } }); }; /** * @return {Promise} Promise that resolves with the OAuth token as the value. */ remoting.It2MeHelpeeChannel.prototype.fetchOAuthToken_ = function() { if (base.isAppsV2()) { /** * @param {function(*=):void} resolve */ return new Promise(function(resolve){ // TODO(jamiewalch): Make this work with {interactive: true} as well. chrome.identity.getAuthToken({ 'interactive': false }, resolve); }); } else { /** * @param {function(*=):void} resolve */ return new Promise(function(resolve) { /** @type {remoting.OAuth2} */ var oauth2 = new remoting.OAuth2(); var onAuthenticated = function() { oauth2.callWithToken( resolve, function() { throw new Error('Authentication failed.'); }); }; /** @param {remoting.Error} error */ var onError = function(error) { if (error != remoting.Error.NOT_AUTHENTICATED) { throw new Error('Unexpected error fetch auth token: ' + error); } oauth2.doAuthRedirect(onAuthenticated); }; oauth2.callWithToken(resolve, onError); }); } }; /** * Connects to the It2Me Native Messaging Host and retrieves the access code * in the |onHostStateChanged_| callback. * * @param {string} email * @param {string} accessToken * @private */ remoting.It2MeHelpeeChannel.prototype.connectToHost_ = function(email, accessToken) { base.debug.assert(this.host_.initialized()); this.host_.connect( email, 'oauth2:' + accessToken, this.onHostStateChanged_.bind(this), base.doNothing, // Ignore |onNatPolicyChanged|. console.log.bind(console), // Forward logDebugInfo to console.log. remoting.settings.XMPP_SERVER_FOR_IT2ME_HOST, remoting.settings.XMPP_SERVER_USE_TLS, remoting.settings.DIRECTORY_BOT_JID, this.onHostConnectError_); }; /** * @param {remoting.Error} error * @private */ remoting.It2MeHelpeeChannel.prototype.onHostConnectError_ = function(error) { this.sendErrorResponse_(null, error); }; /** * @param {remoting.HostSession.State} state * @private */ remoting.It2MeHelpeeChannel.prototype.onHostStateChanged_ = function(state) { this.hostState_ = state; var MessageTypes = remoting.It2MeHelpeeChannel.HangoutMessageTypes; var HostState = remoting.HostSession.State; switch (state) { case HostState.RECEIVED_ACCESS_CODE: var accessCode = this.host_.getAccessCode(); this.hangoutPort_.postMessage({ method: MessageTypes.CONNECT_RESPONSE, accessCode: accessCode }); break; case HostState.CONNECTED: case HostState.DISCONNECTED: this.hangoutPort_.postMessage({ method: MessageTypes.HOST_STATE_CHANGED, state: state }); break; case HostState.ERROR: this.sendErrorResponse_(null, remoting.Error.UNEXPECTED); break; case HostState.INVALID_DOMAIN_ERROR: this.sendErrorResponse_(null, remoting.Error.INVALID_HOST_DOMAIN); break; default: // It is safe to ignore other state changes. } }; /** * @param {?{method:string, data:Object.<string,*>}} incomingMessage * @param {string|Error} error * @private */ remoting.It2MeHelpeeChannel.prototype.sendErrorResponse_ = function(incomingMessage, error) { if (error instanceof Error) { error = error.message; } console.error('Error responding to message method:' + (incomingMessage ? incomingMessage.method : 'null') + ' error:' + error); this.hangoutPort_.postMessage({ method: remoting.It2MeHelpeeChannel.HangoutMessageTypes.ERROR, message: error, request: incomingMessage }); };
mohamed--abdel-maksoud/chromium.src
remoting/webapp/crd/js/it2me_helpee_channel.js
JavaScript
bsd-3-clause
15,736
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "skia/ext/skia_trace_memory_dump_impl.h" #include "base/trace_event/memory_allocator_dump.h" #include "base/trace_event/memory_dump_manager.h" #include "base/trace_event/process_memory_dump.h" #include "skia/ext/SkDiscardableMemory_chrome.h" namespace skia { namespace { const char kMallocBackingType[] = "malloc"; } SkiaTraceMemoryDumpImpl::SkiaTraceMemoryDumpImpl( base::trace_event::MemoryDumpLevelOfDetail level_of_detail, base::trace_event::ProcessMemoryDump* process_memory_dump) : SkiaTraceMemoryDumpImpl("", level_of_detail, process_memory_dump) {} SkiaTraceMemoryDumpImpl::SkiaTraceMemoryDumpImpl( const std::string& dump_name_prefix, base::trace_event::MemoryDumpLevelOfDetail level_of_detail, base::trace_event::ProcessMemoryDump* process_memory_dump) : dump_name_prefix_(dump_name_prefix), process_memory_dump_(process_memory_dump), request_level_( level_of_detail == base::trace_event::MemoryDumpLevelOfDetail::LIGHT ? SkTraceMemoryDump::kLight_LevelOfDetail : SkTraceMemoryDump::kObjectsBreakdowns_LevelOfDetail) {} SkiaTraceMemoryDumpImpl::~SkiaTraceMemoryDumpImpl() = default; void SkiaTraceMemoryDumpImpl::dumpNumericValue(const char* dumpName, const char* valueName, const char* units, uint64_t value) { auto* dump = process_memory_dump_->GetOrCreateAllocatorDump(dumpName); dump->AddScalar(valueName, units, value); } void SkiaTraceMemoryDumpImpl::dumpStringValue(const char* dump_name, const char* value_name, const char* value) { auto* dump = process_memory_dump_->GetOrCreateAllocatorDump(dump_name); dump->AddString(value_name, "", value); } void SkiaTraceMemoryDumpImpl::setMemoryBacking(const char* dumpName, const char* backingType, const char* backingObjectId) { if (strcmp(backingType, kMallocBackingType) == 0) { auto* dump = process_memory_dump_->GetOrCreateAllocatorDump(dumpName); const char* system_allocator_name = base::trace_event::MemoryDumpManager::GetInstance() ->system_allocator_pool_name(); if (system_allocator_name) { process_memory_dump_->AddSuballocation(dump->guid(), system_allocator_name); } } else { NOTREACHED(); } } void SkiaTraceMemoryDumpImpl::setDiscardableMemoryBacking( const char* dumpName, const SkDiscardableMemory& discardableMemoryObject) { std::string name = dump_name_prefix_ + dumpName; DCHECK(!process_memory_dump_->GetAllocatorDump(name)); const SkDiscardableMemoryChrome& discardable_memory_obj = static_cast<const SkDiscardableMemoryChrome&>(discardableMemoryObject); auto* dump = discardable_memory_obj.CreateMemoryAllocatorDump( name.c_str(), process_memory_dump_); DCHECK(dump); } SkTraceMemoryDump::LevelOfDetail SkiaTraceMemoryDumpImpl::getRequestedDetails() const { return request_level_; } bool SkiaTraceMemoryDumpImpl::shouldDumpWrappedObjects() const { // Chrome already dumps objects it imports into Skia. Avoid duplicate dumps // by asking Skia not to dump them. return false; } } // namespace skia
scheib/chromium
skia/ext/skia_trace_memory_dump_impl.cc
C++
bsd-3-clause
3,620
/* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "MissFailoverRoute.h" #include <folly/dynamic.h> #include "mcrouter/lib/config/RouteHandleFactory.h" #include "mcrouter/routes/McRouteHandleBuilder.h" #include "mcrouter/routes/McrouterRouteHandle.h" namespace facebook { namespace memcache { namespace mcrouter { McrouterRouteHandlePtr makeNullRoute(); McrouterRouteHandlePtr makeMissFailoverRoute( std::vector<McrouterRouteHandlePtr> targets) { if (targets.empty()) { return makeNullRoute(); } if (targets.size() == 1) { return std::move(targets[0]); } return makeMcrouterRouteHandle<MissFailoverRoute>(std::move(targets)); } McrouterRouteHandlePtr makeMissFailoverRoute( RouteHandleFactory<McrouterRouteHandleIf>& factory, const folly::dynamic& json) { std::vector<McrouterRouteHandlePtr> children; if (json.isObject()) { if (auto jchildren = json.get_ptr("children")) { children = factory.createList(*jchildren); } } else { children = factory.createList(json); } return makeMissFailoverRoute(std::move(children)); } }}} // facebook::memcache::mcrouter
is00hcw/mcrouter
mcrouter/routes/MissFailoverRoute.cpp
C++
bsd-3-clause
1,389
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_WM_TOPLEVEL_WINDOW_EVENT_HANDLER_H_ #define ASH_WM_TOPLEVEL_WINDOW_EVENT_HANDLER_H_ #include <set> #include "ash/ash_export.h" #include "ash/display/window_tree_host_manager.h" #include "ash/wm/wm_types.h" #include "base/callback.h" #include "base/compiler_specific.h" #include "base/macros.h" #include "base/memory/scoped_ptr.h" #include "ui/events/event_handler.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/rect.h" #include "ui/wm/public/window_move_client.h" namespace aura { class Window; } namespace ui { class LocatedEvent; } namespace ash { class WindowResizer; class ASH_EXPORT ToplevelWindowEventHandler : public ui::EventHandler, public aura::client::WindowMoveClient, public WindowTreeHostManager::Observer { public: ToplevelWindowEventHandler(); ~ToplevelWindowEventHandler() override; // Overridden from ui::EventHandler: void OnKeyEvent(ui::KeyEvent* event) override; void OnMouseEvent(ui::MouseEvent* event) override; void OnGestureEvent(ui::GestureEvent* event) override; // Overridden form aura::client::WindowMoveClient: aura::client::WindowMoveResult RunMoveLoop( aura::Window* source, const gfx::Vector2d& drag_offset, aura::client::WindowMoveSource move_source) override; void EndMoveLoop() override; // Overridden form ash::WindowTreeHostManager::Observer: void OnDisplayConfigurationChanging() override; private: class ScopedWindowResizer; enum DragCompletionStatus { DRAG_COMPLETE, DRAG_REVERT, // To be used when WindowResizer::GetTarget() is destroyed. Neither // completes nor reverts the drag because both access the WindowResizer's // window. DRAG_RESIZER_WINDOW_DESTROYED }; // Attempts to start a drag if one is not already in progress. Returns true if // successful. bool AttemptToStartDrag(aura::Window* window, const gfx::Point& point_in_parent, int window_component, aura::client::WindowMoveSource source); // Completes or reverts the drag if one is in progress. Returns true if a // drag was completed or reverted. bool CompleteDrag(DragCompletionStatus status); void HandleMousePressed(aura::Window* target, ui::MouseEvent* event); void HandleMouseReleased(aura::Window* target, ui::MouseEvent* event); // Called during a drag to resize/position the window. void HandleDrag(aura::Window* target, ui::LocatedEvent* event); // Called during mouse moves to update window resize shadows. void HandleMouseMoved(aura::Window* target, ui::LocatedEvent* event); // Called for mouse exits to hide window resize shadows. void HandleMouseExited(aura::Window* target, ui::LocatedEvent* event); // Called when mouse capture is lost. void HandleCaptureLost(ui::LocatedEvent* event); // Sets |window|'s state type to |new_state_type|. Called after the drag has // been completed for fling gestures. void SetWindowStateTypeFromGesture(aura::Window* window, wm::WindowStateType new_state_type); // Invoked from ScopedWindowResizer if the window is destroyed. void ResizerWindowDestroyed(); // The hittest result for the first finger at the time that it initially // touched the screen. |first_finger_hittest_| is one of ui/base/hit_test.h int first_finger_hittest_; // The window bounds when the drag was started. When a window is minimized, // maximized or snapped via a swipe/fling gesture, the restore bounds should // be set to the bounds of the window when the drag was started. gfx::Rect pre_drag_window_bounds_; // Are we running a nested message loop from RunMoveLoop(). bool in_move_loop_; // Is a window move/resize in progress because of gesture events? bool in_gesture_drag_; // Whether the drag was reverted. Set by CompleteDrag(). bool drag_reverted_; scoped_ptr<ScopedWindowResizer> window_resizer_; base::Closure quit_closure_; // Used to track if this object is deleted while running a nested message // loop. If non-null the destructor sets this to true. bool* destroyed_; DISALLOW_COPY_AND_ASSIGN(ToplevelWindowEventHandler); }; } // namespace aura #endif // ASH_WM_TOPLEVEL_WINDOW_EVENT_HANDLER_H_
js0701/chromium-crosswalk
ash/wm/toplevel_window_event_handler.h
C
bsd-3-clause
4,456
#/bin/sh #set -x # Script for processing DETdigits.C (or digitITSDET.C) macros # and generating files with histograms. # Generated histograms can be then plot with plotDigits2.C. # Currently the macro has to be run in the directory # with the aliroot output, and one has to specify the # number of events and the number of files in the chain # to be prcessed. # # By E.Sicking, CERN; I. Hrivnacova, IPN Orsay scriptdir=$ALICE_ROOT/test/vmctest/scripts export NEVENTS=10 export NFILES=4 for DET in SDD SSD SPD TPC TRD TOF EMCAL HMPID PHOS; do echo Processing $DET digits aliroot -b -q $scriptdir/digits${DET}.C\($NEVENTS,$NFILES\) done
jgrosseo/AliRoot
test/vmctest/scripts/digits.sh
Shell
bsd-3-clause
647
.window { font-size:12px; position:absolute; overflow:hidden; background:transparent url('images/panel_title.png'); background1:#878787; padding:5px; border:1px solid #99BBE8; -moz-border-radius:5px; -webkit-border-radius: 5px; } .window-shadow{ position:absolute; background:#ddd; -moz-border-radius:5px; -webkit-border-radius: 5px; -moz-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2); -webkit-box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.2); filter: progid:DXImageTransform.Microsoft.Blur(pixelRadius=2,MakeShadow=false,ShadowOpacity=0.2); } .window .window-header{ background:transparent; padding:2px 0px 4px 0px; } .window .window-body{ background:#fff; border:1px solid #99BBE8; border-top-width:0px; } .window .window-header .panel-icon{ left:1px; top:1px; } .window .window-header .panel-with-icon{ padding-left:18px; } .window .window-header .panel-tool{ top:0px; right:1px; } .window-proxy{ position:absolute; overflow:hidden; border:1px dashed #15428b; } .window-mask{ position:absolute; left:0; top:0; width:100%; height:100%; filter:alpha(opacity=40); opacity:0.40; background:#ccc; display1:none; font-size:1px; *zoom:1; overflow:hidden; }
Y2MD/blog
web/weixin/js/themes/default/window.css
CSS
bsd-3-clause
1,244
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/security_interstitials/core/ssl_error_options_mask.h" #include "net/base/net_errors.h" #include "testing/gtest/include/gtest/gtest.h" namespace security_interstitials { TEST(SSLErrorOptionsMask, CalculateSSLErrorOptionsMask) { int mask; // Non-overridable cert error. mask = CalculateSSLErrorOptionsMask( net::ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN, /* cert_error */ false, /* hard_override_disabled */ false /* should_ssl_errors_be_fatal */ ); EXPECT_EQ(0, mask); mask = CalculateSSLErrorOptionsMask( net::ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN, /* cert_error */ true, /* hard_override_disabled */ false /* should_ssl_errors_be_fatal */ ); EXPECT_EQ(SSLErrorOptionsMask::HARD_OVERRIDE_DISABLED, mask); mask = CalculateSSLErrorOptionsMask( net::ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN, /* cert_error */ false, /* hard_override_disabled */ true /* should_ssl_errors_be_fatal */ ); EXPECT_EQ(SSLErrorOptionsMask::STRICT_ENFORCEMENT, mask); // Overridable cert error. mask = CalculateSSLErrorOptionsMask(net::ERR_CERT_DATE_INVALID, /* cert_error */ false, /* hard_override_disabled */ false /* should_ssl_errors_be_fatal */ ); EXPECT_EQ(SSLErrorOptionsMask::SOFT_OVERRIDE_ENABLED, mask); mask = CalculateSSLErrorOptionsMask(net::ERR_CERT_DATE_INVALID, /* cert_error */ true, /* hard_override_disabled */ false /* should_ssl_errors_be_fatal */ ); EXPECT_EQ(SSLErrorOptionsMask::HARD_OVERRIDE_DISABLED, mask); mask = CalculateSSLErrorOptionsMask(net::ERR_CERT_DATE_INVALID, /* cert_error */ false, /* hard_override_disabled */ true /* should_ssl_errors_be_fatal */ ); EXPECT_EQ(SSLErrorOptionsMask::STRICT_ENFORCEMENT, mask); } } // namespace security_interstitials
scheib/chromium
components/security_interstitials/core/ssl_error_options_mask_unittest.cc
C++
bsd-3-clause
2,296
<html> <head> <title>Weak Showers</title> <link rel="stylesheet" type="text/css" href="pythia.css"/> <link rel="shortcut icon" href="pythia32.gif"/> </head> <body> <h2>Weak Showers</h2> The emission of <i>W^+-</i> and <i>Z^0</i> gauge bosons off fermions is intended to be an integrated part of the initial- and final-state radiation frameworks, and is fully interleaved with QCD and QED emissions. It is a new and still not fully explored feature, however, and therefore it is off by default. The weak-emission machinery is described in detail in [<a href="Bibliography.html" target="page">Chr14</a>]; here we only bring up some of the most relevant points for using this machinery. <p/> In QCD and QED showers the real and virtual corrections are directly related with each other, which means that the appropriate Sudakov factors can be directly obtained as a by-product of the real-emission evolution. This does not hold for <i>W^+-</i>, owing to the flavour-changing character of emissions, so-called Bloch-Nordsieck violations. These effects are not expected to be large, but they are not properly included, since our evolution framework makes no distinction in this respect between QCD, QED or weak emissions. Another restriction is that there is no simulation of the full <i>gamma^*/Z^0</i> interference: at low masses the QED shower involves a pure <i>gamma^*</i> component, whereas the weak shower generates a pure <i>Z^0</i>. <p/> The non-negligible <i>W/Z</i> masses have a considerable impact both on the matrix elements and on the phase space for their emission. The shower on its own is not set up to handle those aspects with a particularly good accuracy. Therefore the weak shower emissions are always matched to the matrix element for emission off a <i>f fbar</i> weak dipole, or some other <i>2 &rarr; 3</i> matrix element that resembles the topology at hand. Even if the match may not be perfect, at least the main features should be caught that way. Notably, the correction procedure is used throughout the shower, not only for the emission closest to the hard <i>2 &rarr; 2</i> process. In such extended applications, emission rates are normalized to the invariant mass of the dipole at the time of the weak emission, i.e. discounting the energy change by previous QCD/QED emissions. <p/> Also the angular distribution in the subsequent <i>V = W^+-/Z^0</i> decay is matched to the matrix element expression for <i>f fbar &rarr; f fbar V &rarr; f fbar f' fbar'</i> (FSR) and <i>f fbar &rarr; g^* V &rarr; g^* f' fbar'</i> (ISR). Afterwards the <i>f' fbar'</i> system undergoes showers and hadronization just like any <i>W^+-/Z^0</i> decay products would. <p/> Special for the weak showers is that couplings are different for left- and righthanded fermions. With incoming unpolarized beams this should average out, at least so long as only one weak emission occurs. In the case of several weak emissions off the same fermion the correlation between them will carry a memory of the fermion helicity. Such a memory is retained for the affected dipole end, and is reflected in the <code>Particle::pol()</code> property, it being <i>+1</i> (<i>-1</i>) for fermions considered righthanded (lefthanded), and 0 for the bulk where no choice has been made. <p/> Most events will not contain a <i>W^+-/Z^0</i> emission at all, which means that dedicated generator studies of weak emissions can become quite inefficient. In a shower framework it is not straightforward to force such emissions to happen without biasing the event sample in some respect. An option is available to enhance the emission rate artificially, but it is then the responsibility of the user to correct the cross section accordingly, and not to pick an enhancement so big that the probability for more than one emission is non-negligible. (It is not enough to assign an event weight <i>1/e^n</i> where <i>e</i> is the enhancement factor and <i>n</i> is the number of emitted gauge bosons. This still misses to account for the change in phase space for late emissions by the effect of earlier ones, or equivalently for the unwanted change in the Sudakov form factor. See [<a href="Bibliography.html" target="page">Lon12a</a>] for a detailed discussion and possible solutions.) <p/> Another enhancement probability is to only allow some specific <i>W^+-/Z^0</i> decay modes. By default the shower is inclusive, since it should describe all that can happen with unit probability. This also holds even if the <i>W^+-</i> and <i>Z^0</i> produced in the hard process have been restricted to specific decay channels. The trick that allows this is that two new "aliases" have been produced, a <code>Zcopy</code> with identity code 93 and a <code>Wcopy</code> with code 94. These copies are used specifically to bookkeep decay channels open for <i>W^+-/Z^0</i> bosons produced in the shower. For the rest they are invisible, i.e. you will not find these codes in event listings, but only the regular 23 and 24 ones. The identity code duplication allows the selection of specific decay modes for 93 and 94, i.e. for only the gauge bosons produced in the shower. As above it is here up to the user to reweight the event to compensate for the bias introduced, and to watch out for possible complications. In this case there is no kinematics bias, but one would miss out on topologies where a not-selected decay channel could be part of the background to the selected one, notably when more than one gauge boson is produced. <p/> Note that the common theme is that a bias leads to an event-specific weight, since each event is unique. It also means that the cross-section information obtained e.g. by <code>Pythia::stat()</code> is misleading, since it has not been corrected for such weights. This is different from biases in a predetermined hard process, where the net reduction in cross section can be calculated once and for all at initialization, and events generated with unit weight thereafter. <p/> The weak shower introduces a possible doublecounting problem. Namely that it is now possible to produce weak bosons in association with jets from two different channels, Drell-Yan weak production with QCD emissions and QCD hard process with a weak emission. A method, built on a classification of each event with the <i>kT</i> jet algorithm, is used to remove the doublecounting. Specifically, consider a tentative final state consisting of a <i>W/Z</i> and two jets. Based on the principle that the shower emission ought to be softer than the hard emission, the emission of a hard <i>W/Z</i> should be vetoed in a QCD event, and that of two hard jets in a Drell-Yan event. The dividing criterion is this whether the first clustering step involves the <i>W/Z</i> or not. It is suggested to turn this method on only if you simulate both Drell-Yan weak production and QCD hard production with a weak shower. Do not turn on the veto algorithm if you only intend to generate one of the two processes. <h3>variables</h3> Below are listed the variables related to the weak shower and common to both the initial- and final-state radiation. For variables only related to the initial-state radiation (e.g. to turn the weak shower on for ISR) see <a href="SpacelikeShowers.html" target="page">Spacelike Showers</a> and for final-state radiation see <a href="TimelikeShowers.html" target="page">Timelike Showers</a>. <p/><code>parm&nbsp; </code><strong> WeakShower:enhancement &nbsp;</strong> (<code>default = <strong>1.</strong></code>; <code>minimum = 1.</code>; <code>maximum = 1000.</code>)<br/> Enhancement factor for the weak shower. This is used to increase the statistics of weak shower emissions. Remember afterwards to correct for the additional weak emissions (i.e. divide the rate of weak emissions by the same factor). <p/><code>flag&nbsp; </code><strong> WeakShower:singleEmission &nbsp;</strong> (<code>default = <strong>off</strong></code>)<br/> This parameter allows to stop the weak shower after a single emission. <br/>If on, only a single weak emission is allowed. <br/>If off, an unlimited number of weak emissions possible. <p/><code>flag&nbsp; </code><strong> WeakShower:vetoWeakJets &nbsp;</strong> (<code>default = <strong>off</strong></code>)<br/> There are two ways to produce weak bosons in association with jets, namely Drell-Yan weak production with QCD radiation and QCD hard process with weak radiation. In order to avoid double counting between the two production channels, a veto procedure built on the <i>kT</i> jet algorithm is implemented in the evolution starting from a <i>2 &rarr; 2</i> QCD process, process codes in the range 111 - 129. The veto algorithm finds the first cluster step, and if it does not involve a weak boson the radiation of the weak boson is vetoed when <code>WeakShower:vetoWeakJets</code> is on. Note that this flag does not affect other internal or external processes, only the 111 - 129 ones. For the Drell-Yan process the same veto algorithm is used, but this time the event should be vetoed if the first clustering does contain a weak boson, see <code>WeakShower:vetoQCDjets</code> below. <p/><code>flag&nbsp; </code><strong> WeakShower:vetoQCDjets &nbsp;</strong> (<code>default = <strong>off</strong></code>)<br/> This flag vetoes some QCD emission for Drell-Yan weak production to avoid doublecounting with weak emission in QCD hard processes. For more information see <code>WeakShower:vetoWeakJets</code> above. Note that this flag only affects the process codes 221 and 222, i.e. the main built-in processes for <i>gamma^*/Z^0/W^+-</i> production, and not other internal or external processes. <p/><code>parm&nbsp; </code><strong> WeakShower:vetoWeakDeltaR &nbsp;</strong> (<code>default = <strong>0.6</strong></code>; <code>minimum = 0.1</code>; <code>maximum = 2.</code>)<br/> The <i>delta R</i> parameter used in the <i>kT</i> clustering for the veto algorithm used to avoid double counting. Relates to the relative importance given to ISR and FSR emissionbs. </body> </html> <!-- Copyright (C) 2015 Torbjorn Sjostrand -->
miranov25/AliRoot
PYTHIA8/pythia8205/share/Pythia8/htmldoc/WeakShowers.html
HTML
bsd-3-clause
10,275
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/gfx/render_text.h" #include <algorithm> #include <climits> #include "base/command_line.h" #include "base/i18n/break_iterator.h" #include "base/logging.h" #include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "third_party/icu/source/common/unicode/rbbi.h" #include "third_party/icu/source/common/unicode/utf16.h" #include "third_party/skia/include/core/SkTypeface.h" #include "third_party/skia/include/effects/SkGradientShader.h" #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/safe_integer_conversions.h" #include "ui/gfx/render_text_harfbuzz.h" #include "ui/gfx/scoped_canvas.h" #include "ui/gfx/skia_util.h" #include "ui/gfx/switches.h" #include "ui/gfx/text_elider.h" #include "ui/gfx/text_utils.h" #include "ui/gfx/utf16_indexing.h" namespace gfx { namespace { // All chars are replaced by this char when the password style is set. // TODO(benrg): GTK uses the first of U+25CF, U+2022, U+2731, U+273A, '*' // that's available in the font (find_invisible_char() in gtkentry.c). const base::char16 kPasswordReplacementChar = '*'; // Default color used for the text and cursor. const SkColor kDefaultColor = SK_ColorBLACK; // Default color used for drawing selection background. const SkColor kDefaultSelectionBackgroundColor = SK_ColorGRAY; // Fraction of the text size to lower a strike through below the baseline. const SkScalar kStrikeThroughOffset = (-SK_Scalar1 * 6 / 21); // Fraction of the text size to lower an underline below the baseline. const SkScalar kUnderlineOffset = (SK_Scalar1 / 9); // Fraction of the text size to use for a strike through or under-line. const SkScalar kLineThickness = (SK_Scalar1 / 18); // Fraction of the text size to use for a top margin of a diagonal strike. const SkScalar kDiagonalStrikeMarginOffset = (SK_Scalar1 / 4); // Invalid value of baseline. Assigning this value to |baseline_| causes // re-calculation of baseline. const int kInvalidBaseline = INT_MAX; // Returns the baseline, with which the text best appears vertically centered. int DetermineBaselineCenteringText(const Rect& display_rect, const FontList& font_list) { const int display_height = display_rect.height(); const int font_height = font_list.GetHeight(); // Lower and upper bound of baseline shift as we try to show as much area of // text as possible. In particular case of |display_height| == |font_height|, // we do not want to shift the baseline. const int min_shift = std::min(0, display_height - font_height); const int max_shift = std::abs(display_height - font_height); const int baseline = font_list.GetBaseline(); const int cap_height = font_list.GetCapHeight(); const int internal_leading = baseline - cap_height; // Some platforms don't support getting the cap height, and simply return // the entire font ascent from GetCapHeight(). Centering the ascent makes // the font look too low, so if GetCapHeight() returns the ascent, center // the entire font height instead. const int space = display_height - ((internal_leading != 0) ? cap_height : font_height); const int baseline_shift = space / 2 - internal_leading; return baseline + std::max(min_shift, std::min(max_shift, baseline_shift)); } // Converts |Font::FontStyle| flags to |SkTypeface::Style| flags. SkTypeface::Style ConvertFontStyleToSkiaTypefaceStyle(int font_style) { int skia_style = SkTypeface::kNormal; skia_style |= (font_style & Font::BOLD) ? SkTypeface::kBold : 0; skia_style |= (font_style & Font::ITALIC) ? SkTypeface::kItalic : 0; return static_cast<SkTypeface::Style>(skia_style); } // Given |font| and |display_width|, returns the width of the fade gradient. int CalculateFadeGradientWidth(const FontList& font_list, int display_width) { // Fade in/out about 2.5 characters of the beginning/end of the string. // The .5 here is helpful if one of the characters is a space. // Use a quarter of the display width if the display width is very short. const int average_character_width = font_list.GetExpectedTextWidth(1); const double gradient_width = std::min(average_character_width * 2.5, display_width / 4.0); DCHECK_GE(gradient_width, 0.0); return static_cast<int>(floor(gradient_width + 0.5)); } // Appends to |positions| and |colors| values corresponding to the fade over // |fade_rect| from color |c0| to color |c1|. void AddFadeEffect(const Rect& text_rect, const Rect& fade_rect, SkColor c0, SkColor c1, std::vector<SkScalar>* positions, std::vector<SkColor>* colors) { const SkScalar left = static_cast<SkScalar>(fade_rect.x() - text_rect.x()); const SkScalar width = static_cast<SkScalar>(fade_rect.width()); const SkScalar p0 = left / text_rect.width(); const SkScalar p1 = (left + width) / text_rect.width(); // Prepend 0.0 to |positions|, as required by Skia. if (positions->empty() && p0 != 0.0) { positions->push_back(0.0); colors->push_back(c0); } positions->push_back(p0); colors->push_back(c0); positions->push_back(p1); colors->push_back(c1); } // Creates a SkShader to fade the text, with |left_part| specifying the left // fade effect, if any, and |right_part| specifying the right fade effect. skia::RefPtr<SkShader> CreateFadeShader(const Rect& text_rect, const Rect& left_part, const Rect& right_part, SkColor color) { // Fade alpha of 51/255 corresponds to a fade of 0.2 of the original color. const SkColor fade_color = SkColorSetA(color, 51); std::vector<SkScalar> positions; std::vector<SkColor> colors; if (!left_part.IsEmpty()) AddFadeEffect(text_rect, left_part, fade_color, color, &positions, &colors); if (!right_part.IsEmpty()) AddFadeEffect(text_rect, right_part, color, fade_color, &positions, &colors); DCHECK(!positions.empty()); // Terminate |positions| with 1.0, as required by Skia. if (positions.back() != 1.0) { positions.push_back(1.0); colors.push_back(colors.back()); } SkPoint points[2]; points[0].iset(text_rect.x(), text_rect.y()); points[1].iset(text_rect.right(), text_rect.y()); return skia::AdoptRef( SkGradientShader::CreateLinear(&points[0], &colors[0], &positions[0], colors.size(), SkShader::kClamp_TileMode)); } // Converts a FontRenderParams::Hinting value to the corresponding // SkPaint::Hinting value. SkPaint::Hinting FontRenderParamsHintingToSkPaintHinting( FontRenderParams::Hinting params_hinting) { switch (params_hinting) { case FontRenderParams::HINTING_NONE: return SkPaint::kNo_Hinting; case FontRenderParams::HINTING_SLIGHT: return SkPaint::kSlight_Hinting; case FontRenderParams::HINTING_MEDIUM: return SkPaint::kNormal_Hinting; case FontRenderParams::HINTING_FULL: return SkPaint::kFull_Hinting; } return SkPaint::kNo_Hinting; } } // namespace namespace internal { // Value of |underline_thickness_| that indicates that underline metrics have // not been set explicitly. const SkScalar kUnderlineMetricsNotSet = -1.0f; SkiaTextRenderer::SkiaTextRenderer(Canvas* canvas) : canvas_(canvas), canvas_skia_(canvas->sk_canvas()), underline_thickness_(kUnderlineMetricsNotSet), underline_position_(0.0f) { DCHECK(canvas_skia_); paint_.setTextEncoding(SkPaint::kGlyphID_TextEncoding); paint_.setStyle(SkPaint::kFill_Style); paint_.setAntiAlias(true); paint_.setSubpixelText(true); paint_.setLCDRenderText(true); paint_.setHinting(SkPaint::kNormal_Hinting); } SkiaTextRenderer::~SkiaTextRenderer() { } void SkiaTextRenderer::SetDrawLooper(SkDrawLooper* draw_looper) { paint_.setLooper(draw_looper); } void SkiaTextRenderer::SetFontRenderParams(const FontRenderParams& params, bool background_is_transparent) { ApplyRenderParams(params, background_is_transparent, &paint_); } void SkiaTextRenderer::SetTypeface(SkTypeface* typeface) { paint_.setTypeface(typeface); } void SkiaTextRenderer::SetTextSize(SkScalar size) { paint_.setTextSize(size); } void SkiaTextRenderer::SetFontFamilyWithStyle(const std::string& family, int style) { DCHECK(!family.empty()); skia::RefPtr<SkTypeface> typeface = CreateSkiaTypeface(family.c_str(), style); if (typeface) { // |paint_| adds its own ref. So don't |release()| it from the ref ptr here. SetTypeface(typeface.get()); // Enable fake bold text if bold style is needed but new typeface does not // have it. paint_.setFakeBoldText((style & Font::BOLD) && !typeface->isBold()); } } void SkiaTextRenderer::SetForegroundColor(SkColor foreground) { paint_.setColor(foreground); } void SkiaTextRenderer::SetShader(SkShader* shader) { paint_.setShader(shader); } void SkiaTextRenderer::SetUnderlineMetrics(SkScalar thickness, SkScalar position) { underline_thickness_ = thickness; underline_position_ = position; } void SkiaTextRenderer::DrawPosText(const SkPoint* pos, const uint16* glyphs, size_t glyph_count) { const size_t byte_length = glyph_count * sizeof(glyphs[0]); canvas_skia_->drawPosText(&glyphs[0], byte_length, &pos[0], paint_); } void SkiaTextRenderer::DrawDecorations(int x, int y, int width, bool underline, bool strike, bool diagonal_strike) { if (underline) DrawUnderline(x, y, width); if (strike) DrawStrike(x, y, width); if (diagonal_strike) { if (!diagonal_) diagonal_.reset(new DiagonalStrike(canvas_, Point(x, y), paint_)); diagonal_->AddPiece(width, paint_.getColor()); } else if (diagonal_) { EndDiagonalStrike(); } } void SkiaTextRenderer::EndDiagonalStrike() { if (diagonal_) { diagonal_->Draw(); diagonal_.reset(); } } void SkiaTextRenderer::DrawUnderline(int x, int y, int width) { SkScalar x_scalar = SkIntToScalar(x); SkRect r = SkRect::MakeLTRB( x_scalar, y + underline_position_, x_scalar + width, y + underline_position_ + underline_thickness_); if (underline_thickness_ == kUnderlineMetricsNotSet) { const SkScalar text_size = paint_.getTextSize(); r.fTop = SkScalarMulAdd(text_size, kUnderlineOffset, y); r.fBottom = r.fTop + SkScalarMul(text_size, kLineThickness); } canvas_skia_->drawRect(r, paint_); } void SkiaTextRenderer::DrawStrike(int x, int y, int width) const { const SkScalar text_size = paint_.getTextSize(); const SkScalar height = SkScalarMul(text_size, kLineThickness); const SkScalar offset = SkScalarMulAdd(text_size, kStrikeThroughOffset, y); SkScalar x_scalar = SkIntToScalar(x); const SkRect r = SkRect::MakeLTRB(x_scalar, offset, x_scalar + width, offset + height); canvas_skia_->drawRect(r, paint_); } SkiaTextRenderer::DiagonalStrike::DiagonalStrike(Canvas* canvas, Point start, const SkPaint& paint) : canvas_(canvas), start_(start), paint_(paint), total_length_(0) { } SkiaTextRenderer::DiagonalStrike::~DiagonalStrike() { } void SkiaTextRenderer::DiagonalStrike::AddPiece(int length, SkColor color) { pieces_.push_back(Piece(length, color)); total_length_ += length; } void SkiaTextRenderer::DiagonalStrike::Draw() { const SkScalar text_size = paint_.getTextSize(); const SkScalar offset = SkScalarMul(text_size, kDiagonalStrikeMarginOffset); const int thickness = SkScalarCeilToInt(SkScalarMul(text_size, kLineThickness) * 2); const int height = SkScalarCeilToInt(text_size - offset); const Point end = start_ + Vector2d(total_length_, -height); const int clip_height = height + 2 * thickness; paint_.setAntiAlias(true); paint_.setStrokeWidth(SkIntToScalar(thickness)); const bool clipped = pieces_.size() > 1; SkCanvas* sk_canvas = canvas_->sk_canvas(); int x = start_.x(); for (size_t i = 0; i < pieces_.size(); ++i) { paint_.setColor(pieces_[i].second); if (clipped) { canvas_->Save(); sk_canvas->clipRect(RectToSkRect( Rect(x, end.y() - thickness, pieces_[i].first, clip_height))); } canvas_->DrawLine(start_, end, paint_); if (clipped) canvas_->Restore(); x += pieces_[i].first; } } StyleIterator::StyleIterator(const BreakList<SkColor>& colors, const std::vector<BreakList<bool> >& styles) : colors_(colors), styles_(styles) { color_ = colors_.breaks().begin(); for (size_t i = 0; i < styles_.size(); ++i) style_.push_back(styles_[i].breaks().begin()); } StyleIterator::~StyleIterator() {} Range StyleIterator::GetRange() const { Range range(colors_.GetRange(color_)); for (size_t i = 0; i < NUM_TEXT_STYLES; ++i) range = range.Intersect(styles_[i].GetRange(style_[i])); return range; } void StyleIterator::UpdatePosition(size_t position) { color_ = colors_.GetBreak(position); for (size_t i = 0; i < NUM_TEXT_STYLES; ++i) style_[i] = styles_[i].GetBreak(position); } LineSegment::LineSegment() : run(0) {} LineSegment::~LineSegment() {} Line::Line() : preceding_heights(0), baseline(0) {} Line::~Line() {} skia::RefPtr<SkTypeface> CreateSkiaTypeface(const std::string& family, int style) { SkTypeface::Style skia_style = ConvertFontStyleToSkiaTypefaceStyle(style); return skia::AdoptRef(SkTypeface::CreateFromName(family.c_str(), skia_style)); } void ApplyRenderParams(const FontRenderParams& params, bool background_is_transparent, SkPaint* paint) { paint->setAntiAlias(params.antialiasing); paint->setLCDRenderText(!background_is_transparent && params.subpixel_rendering != FontRenderParams::SUBPIXEL_RENDERING_NONE); paint->setSubpixelText(params.subpixel_positioning); paint->setAutohinted(params.autohinter); paint->setHinting(FontRenderParamsHintingToSkPaintHinting(params.hinting)); } } // namespace internal RenderText::~RenderText() { } RenderText* RenderText::CreateInstance() { #if defined(OS_MACOSX) static const bool use_harfbuzz = base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableHarfBuzzRenderText); #else static const bool use_harfbuzz = !base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableHarfBuzzRenderText); #endif return use_harfbuzz ? new RenderTextHarfBuzz : CreateNativeInstance(); } RenderText* RenderText::CreateInstanceForEditing() { static const bool use_harfbuzz = !base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableHarfBuzzRenderText); return use_harfbuzz ? new RenderTextHarfBuzz : CreateNativeInstance(); } void RenderText::SetText(const base::string16& text) { DCHECK(!composition_range_.IsValid()); if (text_ == text) return; text_ = text; // Adjust ranged styles and colors to accommodate a new text length. // Clear style ranges as they might break new text graphemes and apply // the first style to the whole text instead. const size_t text_length = text_.length(); colors_.SetMax(text_length); for (size_t style = 0; style < NUM_TEXT_STYLES; ++style) { BreakList<bool>& break_list = styles_[style]; break_list.SetValue(break_list.breaks().begin()->second); break_list.SetMax(text_length); } cached_bounds_and_offset_valid_ = false; // Reset selection model. SetText should always followed by SetSelectionModel // or SetCursorPosition in upper layer. SetSelectionModel(SelectionModel()); // Invalidate the cached text direction if it depends on the text contents. if (directionality_mode_ == DIRECTIONALITY_FROM_TEXT) text_direction_ = base::i18n::UNKNOWN_DIRECTION; obscured_reveal_index_ = -1; UpdateLayoutText(); } void RenderText::SetHorizontalAlignment(HorizontalAlignment alignment) { if (horizontal_alignment_ != alignment) { horizontal_alignment_ = alignment; display_offset_ = Vector2d(); cached_bounds_and_offset_valid_ = false; } } void RenderText::SetFontList(const FontList& font_list) { font_list_ = font_list; const int font_style = font_list.GetFontStyle(); SetStyle(BOLD, (font_style & gfx::Font::BOLD) != 0); SetStyle(ITALIC, (font_style & gfx::Font::ITALIC) != 0); SetStyle(UNDERLINE, (font_style & gfx::Font::UNDERLINE) != 0); baseline_ = kInvalidBaseline; cached_bounds_and_offset_valid_ = false; ResetLayout(); } void RenderText::SetCursorEnabled(bool cursor_enabled) { cursor_enabled_ = cursor_enabled; cached_bounds_and_offset_valid_ = false; } void RenderText::ToggleInsertMode() { insert_mode_ = !insert_mode_; cached_bounds_and_offset_valid_ = false; } void RenderText::SetObscured(bool obscured) { if (obscured != obscured_) { obscured_ = obscured; obscured_reveal_index_ = -1; cached_bounds_and_offset_valid_ = false; UpdateLayoutText(); } } void RenderText::SetObscuredRevealIndex(int index) { if (obscured_reveal_index_ == index) return; obscured_reveal_index_ = index; cached_bounds_and_offset_valid_ = false; UpdateLayoutText(); } void RenderText::SetReplaceNewlineCharsWithSymbols(bool replace) { replace_newline_chars_with_symbols_ = replace; cached_bounds_and_offset_valid_ = false; UpdateLayoutText(); } void RenderText::SetMultiline(bool multiline) { if (multiline != multiline_) { multiline_ = multiline; cached_bounds_and_offset_valid_ = false; lines_.clear(); } } void RenderText::SetElideBehavior(ElideBehavior elide_behavior) { // TODO(skanuj) : Add a test for triggering layout change. if (elide_behavior_ != elide_behavior) { elide_behavior_ = elide_behavior; UpdateLayoutText(); } } void RenderText::SetDisplayRect(const Rect& r) { if (r != display_rect_) { display_rect_ = r; baseline_ = kInvalidBaseline; cached_bounds_and_offset_valid_ = false; lines_.clear(); if (elide_behavior_ != NO_ELIDE) UpdateLayoutText(); } } void RenderText::SetCursorPosition(size_t position) { MoveCursorTo(position, false); } void RenderText::MoveCursor(BreakType break_type, VisualCursorDirection direction, bool select) { SelectionModel cursor(cursor_position(), selection_model_.caret_affinity()); // Cancelling a selection moves to the edge of the selection. if (break_type != LINE_BREAK && !selection().is_empty() && !select) { SelectionModel selection_start = GetSelectionModelForSelectionStart(); int start_x = GetCursorBounds(selection_start, true).x(); int cursor_x = GetCursorBounds(cursor, true).x(); // Use the selection start if it is left (when |direction| is CURSOR_LEFT) // or right (when |direction| is CURSOR_RIGHT) of the selection end. if (direction == CURSOR_RIGHT ? start_x > cursor_x : start_x < cursor_x) cursor = selection_start; // Use the nearest word boundary in the proper |direction| for word breaks. if (break_type == WORD_BREAK) cursor = GetAdjacentSelectionModel(cursor, break_type, direction); // Use an adjacent selection model if the cursor is not at a valid position. if (!IsValidCursorIndex(cursor.caret_pos())) cursor = GetAdjacentSelectionModel(cursor, CHARACTER_BREAK, direction); } else { cursor = GetAdjacentSelectionModel(cursor, break_type, direction); } if (select) cursor.set_selection_start(selection().start()); MoveCursorTo(cursor); } bool RenderText::MoveCursorTo(const SelectionModel& model) { // Enforce valid selection model components. size_t text_length = text().length(); Range range(std::min(model.selection().start(), text_length), std::min(model.caret_pos(), text_length)); // The current model only supports caret positions at valid cursor indices. if (!IsValidCursorIndex(range.start()) || !IsValidCursorIndex(range.end())) return false; SelectionModel sel(range, model.caret_affinity()); bool changed = sel != selection_model_; SetSelectionModel(sel); return changed; } bool RenderText::SelectRange(const Range& range) { Range sel(std::min(range.start(), text().length()), std::min(range.end(), text().length())); // Allow selection bounds at valid indicies amid multi-character graphemes. if (!IsValidLogicalIndex(sel.start()) || !IsValidLogicalIndex(sel.end())) return false; LogicalCursorDirection affinity = (sel.is_reversed() || sel.is_empty()) ? CURSOR_FORWARD : CURSOR_BACKWARD; SetSelectionModel(SelectionModel(sel, affinity)); return true; } bool RenderText::IsPointInSelection(const Point& point) { if (selection().is_empty()) return false; SelectionModel cursor = FindCursorPosition(point); return RangeContainsCaret( selection(), cursor.caret_pos(), cursor.caret_affinity()); } void RenderText::ClearSelection() { SetSelectionModel(SelectionModel(cursor_position(), selection_model_.caret_affinity())); } void RenderText::SelectAll(bool reversed) { const size_t length = text().length(); const Range all = reversed ? Range(length, 0) : Range(0, length); const bool success = SelectRange(all); DCHECK(success); } void RenderText::SelectWord() { if (obscured_) { SelectAll(false); return; } size_t selection_max = selection().GetMax(); base::i18n::BreakIterator iter(text(), base::i18n::BreakIterator::BREAK_WORD); bool success = iter.Init(); DCHECK(success); if (!success) return; size_t selection_min = selection().GetMin(); if (selection_min == text().length() && selection_min != 0) --selection_min; for (; selection_min != 0; --selection_min) { if (iter.IsStartOfWord(selection_min) || iter.IsEndOfWord(selection_min)) break; } if (selection_min == selection_max && selection_max != text().length()) ++selection_max; for (; selection_max < text().length(); ++selection_max) if (iter.IsEndOfWord(selection_max) || iter.IsStartOfWord(selection_max)) break; const bool reversed = selection().is_reversed(); MoveCursorTo(reversed ? selection_max : selection_min, false); MoveCursorTo(reversed ? selection_min : selection_max, true); } const Range& RenderText::GetCompositionRange() const { return composition_range_; } void RenderText::SetCompositionRange(const Range& composition_range) { CHECK(!composition_range.IsValid() || Range(0, text_.length()).Contains(composition_range)); composition_range_.set_end(composition_range.end()); composition_range_.set_start(composition_range.start()); ResetLayout(); } void RenderText::SetColor(SkColor value) { colors_.SetValue(value); } void RenderText::ApplyColor(SkColor value, const Range& range) { colors_.ApplyValue(value, range); } void RenderText::SetStyle(TextStyle style, bool value) { styles_[style].SetValue(value); cached_bounds_and_offset_valid_ = false; ResetLayout(); } void RenderText::ApplyStyle(TextStyle style, bool value, const Range& range) { // Do not change styles mid-grapheme to avoid breaking ligatures. const size_t start = IsValidCursorIndex(range.start()) ? range.start() : IndexOfAdjacentGrapheme(range.start(), CURSOR_BACKWARD); const size_t end = IsValidCursorIndex(range.end()) ? range.end() : IndexOfAdjacentGrapheme(range.end(), CURSOR_FORWARD); styles_[style].ApplyValue(value, Range(start, end)); cached_bounds_and_offset_valid_ = false; ResetLayout(); } bool RenderText::GetStyle(TextStyle style) const { return (styles_[style].breaks().size() == 1) && styles_[style].breaks().front().second; } void RenderText::SetDirectionalityMode(DirectionalityMode mode) { if (mode == directionality_mode_) return; directionality_mode_ = mode; text_direction_ = base::i18n::UNKNOWN_DIRECTION; cached_bounds_and_offset_valid_ = false; ResetLayout(); } base::i18n::TextDirection RenderText::GetTextDirection() { if (text_direction_ == base::i18n::UNKNOWN_DIRECTION) { switch (directionality_mode_) { case DIRECTIONALITY_FROM_TEXT: // Derive the direction from the display text, which differs from text() // in the case of obscured (password) textfields. text_direction_ = base::i18n::GetFirstStrongCharacterDirection(GetLayoutText()); break; case DIRECTIONALITY_FROM_UI: text_direction_ = base::i18n::IsRTL() ? base::i18n::RIGHT_TO_LEFT : base::i18n::LEFT_TO_RIGHT; break; case DIRECTIONALITY_FORCE_LTR: text_direction_ = base::i18n::LEFT_TO_RIGHT; break; case DIRECTIONALITY_FORCE_RTL: text_direction_ = base::i18n::RIGHT_TO_LEFT; break; default: NOTREACHED(); } } return text_direction_; } VisualCursorDirection RenderText::GetVisualDirectionOfLogicalEnd() { return GetTextDirection() == base::i18n::LEFT_TO_RIGHT ? CURSOR_RIGHT : CURSOR_LEFT; } SizeF RenderText::GetStringSizeF() { return GetStringSize(); } float RenderText::GetContentWidthF() { const float string_size = GetStringSizeF().width(); // The cursor is drawn one pixel beyond the int-enclosed text bounds. return cursor_enabled_ ? std::ceil(string_size) + 1 : string_size; } int RenderText::GetContentWidth() { return ToCeiledInt(GetContentWidthF()); } int RenderText::GetBaseline() { if (baseline_ == kInvalidBaseline) baseline_ = DetermineBaselineCenteringText(display_rect(), font_list()); DCHECK_NE(kInvalidBaseline, baseline_); return baseline_; } void RenderText::Draw(Canvas* canvas) { EnsureLayout(); if (clip_to_display_rect()) { Rect clip_rect(display_rect()); clip_rect.Inset(ShadowValue::GetMargin(shadows_)); canvas->Save(); canvas->ClipRect(clip_rect); } if (!text().empty() && focused()) DrawSelection(canvas); if (cursor_enabled() && cursor_visible() && focused()) DrawCursor(canvas, selection_model_); if (!text().empty()) DrawVisualText(canvas); if (clip_to_display_rect()) canvas->Restore(); } void RenderText::DrawCursor(Canvas* canvas, const SelectionModel& position) { // Paint cursor. Replace cursor is drawn as rectangle for now. // TODO(msw): Draw a better cursor with a better indication of association. canvas->FillRect(GetCursorBounds(position, true), cursor_color_); } bool RenderText::IsValidLogicalIndex(size_t index) { // Check that the index is at a valid code point (not mid-surrgate-pair) and // that it's not truncated from the layout text (its glyph may be shown). // // Indices within truncated text are disallowed so users can easily interact // with the underlying truncated text using the ellipsis as a proxy. This lets // users select all text, select the truncated text, and transition from the // last rendered glyph to the end of the text without getting invisible cursor // positions nor needing unbounded arrow key presses to traverse the ellipsis. return index == 0 || index == text().length() || (index < text().length() && (truncate_length_ == 0 || index < truncate_length_) && IsValidCodePointIndex(text(), index)); } Rect RenderText::GetCursorBounds(const SelectionModel& caret, bool insert_mode) { // TODO(ckocagil): Support multiline. This function should return the height // of the line the cursor is on. |GetStringSize()| now returns // the multiline size, eliminate its use here. EnsureLayout(); size_t caret_pos = caret.caret_pos(); DCHECK(IsValidLogicalIndex(caret_pos)); // In overtype mode, ignore the affinity and always indicate that we will // overtype the next character. LogicalCursorDirection caret_affinity = insert_mode ? caret.caret_affinity() : CURSOR_FORWARD; int x = 0, width = 1; Size size = GetStringSize(); if (caret_pos == (caret_affinity == CURSOR_BACKWARD ? 0 : text().length())) { // The caret is attached to the boundary. Always return a 1-dip width caret, // since there is nothing to overtype. if ((GetTextDirection() == base::i18n::RIGHT_TO_LEFT) == (caret_pos == 0)) x = size.width(); } else { size_t grapheme_start = (caret_affinity == CURSOR_FORWARD) ? caret_pos : IndexOfAdjacentGrapheme(caret_pos, CURSOR_BACKWARD); Range xspan(GetGlyphBounds(grapheme_start)); if (insert_mode) { x = (caret_affinity == CURSOR_BACKWARD) ? xspan.end() : xspan.start(); } else { // overtype mode x = xspan.GetMin(); width = xspan.length(); } } return Rect(ToViewPoint(Point(x, 0)), Size(width, size.height())); } const Rect& RenderText::GetUpdatedCursorBounds() { UpdateCachedBoundsAndOffset(); return cursor_bounds_; } size_t RenderText::IndexOfAdjacentGrapheme(size_t index, LogicalCursorDirection direction) { if (index > text().length()) return text().length(); EnsureLayout(); if (direction == CURSOR_FORWARD) { while (index < text().length()) { index++; if (IsValidCursorIndex(index)) return index; } return text().length(); } while (index > 0) { index--; if (IsValidCursorIndex(index)) return index; } return 0; } SelectionModel RenderText::GetSelectionModelForSelectionStart() { const Range& sel = selection(); if (sel.is_empty()) return selection_model_; return SelectionModel(sel.start(), sel.is_reversed() ? CURSOR_BACKWARD : CURSOR_FORWARD); } const Vector2d& RenderText::GetUpdatedDisplayOffset() { UpdateCachedBoundsAndOffset(); return display_offset_; } void RenderText::SetDisplayOffset(int horizontal_offset) { const int extra_content = GetContentWidth() - display_rect_.width(); const int cursor_width = cursor_enabled_ ? 1 : 0; int min_offset = 0; int max_offset = 0; if (extra_content > 0) { switch (GetCurrentHorizontalAlignment()) { case ALIGN_LEFT: min_offset = -extra_content; break; case ALIGN_RIGHT: max_offset = extra_content; break; case ALIGN_CENTER: // The extra space reserved for cursor at the end of the text is ignored // when centering text. So, to calculate the valid range for offset, we // exclude that extra space, calculate the range, and add it back to the // range (if cursor is enabled). min_offset = -(extra_content - cursor_width + 1) / 2 - cursor_width; max_offset = (extra_content - cursor_width) / 2; break; default: break; } } if (horizontal_offset < min_offset) horizontal_offset = min_offset; else if (horizontal_offset > max_offset) horizontal_offset = max_offset; cached_bounds_and_offset_valid_ = true; display_offset_.set_x(horizontal_offset); cursor_bounds_ = GetCursorBounds(selection_model_, insert_mode_); } RenderText::RenderText() : horizontal_alignment_(base::i18n::IsRTL() ? ALIGN_RIGHT : ALIGN_LEFT), directionality_mode_(DIRECTIONALITY_FROM_TEXT), text_direction_(base::i18n::UNKNOWN_DIRECTION), cursor_enabled_(true), cursor_visible_(false), insert_mode_(true), cursor_color_(kDefaultColor), selection_color_(kDefaultColor), selection_background_focused_color_(kDefaultSelectionBackgroundColor), focused_(false), composition_range_(Range::InvalidRange()), colors_(kDefaultColor), styles_(NUM_TEXT_STYLES), composition_and_selection_styles_applied_(false), obscured_(false), obscured_reveal_index_(-1), truncate_length_(0), elide_behavior_(NO_ELIDE), replace_newline_chars_with_symbols_(true), multiline_(false), background_is_transparent_(false), clip_to_display_rect_(true), baseline_(kInvalidBaseline), cached_bounds_and_offset_valid_(false) { } SelectionModel RenderText::GetAdjacentSelectionModel( const SelectionModel& current, BreakType break_type, VisualCursorDirection direction) { EnsureLayout(); if (break_type == LINE_BREAK || text().empty()) return EdgeSelectionModel(direction); if (break_type == CHARACTER_BREAK) return AdjacentCharSelectionModel(current, direction); DCHECK(break_type == WORD_BREAK); return AdjacentWordSelectionModel(current, direction); } SelectionModel RenderText::EdgeSelectionModel( VisualCursorDirection direction) { if (direction == GetVisualDirectionOfLogicalEnd()) return SelectionModel(text().length(), CURSOR_FORWARD); return SelectionModel(0, CURSOR_BACKWARD); } void RenderText::SetSelectionModel(const SelectionModel& model) { DCHECK_LE(model.selection().GetMax(), text().length()); selection_model_ = model; cached_bounds_and_offset_valid_ = false; } const base::string16& RenderText::GetLayoutText() const { return layout_text_; } const BreakList<size_t>& RenderText::GetLineBreaks() { if (line_breaks_.max() != 0) return line_breaks_; const base::string16& layout_text = GetLayoutText(); const size_t text_length = layout_text.length(); line_breaks_.SetValue(0); line_breaks_.SetMax(text_length); base::i18n::BreakIterator iter(layout_text, base::i18n::BreakIterator::BREAK_LINE); const bool success = iter.Init(); DCHECK(success); if (success) { do { line_breaks_.ApplyValue(iter.pos(), Range(iter.pos(), text_length)); } while (iter.Advance()); } return line_breaks_; } void RenderText::ApplyCompositionAndSelectionStyles() { // Save the underline and color breaks to undo the temporary styles later. DCHECK(!composition_and_selection_styles_applied_); saved_colors_ = colors_; saved_underlines_ = styles_[UNDERLINE]; // Apply an underline to the composition range in |underlines|. if (composition_range_.IsValid() && !composition_range_.is_empty()) styles_[UNDERLINE].ApplyValue(true, composition_range_); // Apply the selected text color to the [un-reversed] selection range. if (!selection().is_empty() && focused()) { const Range range(selection().GetMin(), selection().GetMax()); colors_.ApplyValue(selection_color_, range); } composition_and_selection_styles_applied_ = true; } void RenderText::UndoCompositionAndSelectionStyles() { // Restore the underline and color breaks to undo the temporary styles. DCHECK(composition_and_selection_styles_applied_); colors_ = saved_colors_; styles_[UNDERLINE] = saved_underlines_; composition_and_selection_styles_applied_ = false; } Vector2d RenderText::GetLineOffset(size_t line_number) { Vector2d offset = display_rect().OffsetFromOrigin(); // TODO(ckocagil): Apply the display offset for multiline scrolling. if (!multiline()) offset.Add(GetUpdatedDisplayOffset()); else offset.Add(Vector2d(0, lines_[line_number].preceding_heights)); offset.Add(GetAlignmentOffset(line_number)); return offset; } Point RenderText::ToTextPoint(const Point& point) { return point - GetLineOffset(0); // TODO(ckocagil): Convert multiline view space points to text space. } Point RenderText::ToViewPoint(const Point& point) { if (!multiline()) return point + GetLineOffset(0); // TODO(ckocagil): Traverse individual line segments for RTL support. DCHECK(!lines_.empty()); int x = point.x(); size_t line = 0; for (; line < lines_.size() && x > lines_[line].size.width(); ++line) x -= lines_[line].size.width(); return Point(x, point.y()) + GetLineOffset(line); } std::vector<Rect> RenderText::TextBoundsToViewBounds(const Range& x) { std::vector<Rect> rects; if (!multiline()) { rects.push_back(Rect(ToViewPoint(Point(x.GetMin(), 0)), Size(x.length(), GetStringSize().height()))); return rects; } EnsureLayout(); // Each line segment keeps its position in text coordinates. Traverse all line // segments and if the segment intersects with the given range, add the view // rect corresponding to the intersection to |rects|. for (size_t line = 0; line < lines_.size(); ++line) { int line_x = 0; const Vector2d offset = GetLineOffset(line); for (size_t i = 0; i < lines_[line].segments.size(); ++i) { const internal::LineSegment* segment = &lines_[line].segments[i]; const Range intersection = segment->x_range.Intersect(x); if (!intersection.is_empty()) { Rect rect(line_x + intersection.start() - segment->x_range.start(), 0, intersection.length(), lines_[line].size.height()); rects.push_back(rect + offset); } line_x += segment->x_range.length(); } } return rects; } HorizontalAlignment RenderText::GetCurrentHorizontalAlignment() { if (horizontal_alignment_ != ALIGN_TO_HEAD) return horizontal_alignment_; return GetTextDirection() == base::i18n::RIGHT_TO_LEFT ? ALIGN_RIGHT : ALIGN_LEFT; } Vector2d RenderText::GetAlignmentOffset(size_t line_number) { // TODO(ckocagil): Enable |lines_| usage in other platforms. #if defined(OS_WIN) DCHECK_LT(line_number, lines_.size()); #endif Vector2d offset; HorizontalAlignment horizontal_alignment = GetCurrentHorizontalAlignment(); if (horizontal_alignment != ALIGN_LEFT) { #if defined(OS_WIN) const int width = std::ceil(lines_[line_number].size.width()) + (cursor_enabled_ ? 1 : 0); #else const int width = GetContentWidth(); #endif offset.set_x(display_rect().width() - width); // Put any extra margin pixel on the left to match legacy behavior. if (horizontal_alignment == ALIGN_CENTER) offset.set_x((offset.x() + 1) / 2); } // Vertically center the text. if (multiline_) { const int text_height = lines_.back().preceding_heights + lines_.back().size.height(); offset.set_y((display_rect_.height() - text_height) / 2); } else { offset.set_y(GetBaseline() - GetLayoutTextBaseline()); } return offset; } void RenderText::ApplyFadeEffects(internal::SkiaTextRenderer* renderer) { const int width = display_rect().width(); if (multiline() || elide_behavior_ != FADE_TAIL || GetContentWidth() <= width) return; const int gradient_width = CalculateFadeGradientWidth(font_list(), width); if (gradient_width == 0) return; HorizontalAlignment horizontal_alignment = GetCurrentHorizontalAlignment(); Rect solid_part = display_rect(); Rect left_part; Rect right_part; if (horizontal_alignment != ALIGN_LEFT) { left_part = solid_part; left_part.Inset(0, 0, solid_part.width() - gradient_width, 0); solid_part.Inset(gradient_width, 0, 0, 0); } if (horizontal_alignment != ALIGN_RIGHT) { right_part = solid_part; right_part.Inset(solid_part.width() - gradient_width, 0, 0, 0); solid_part.Inset(0, 0, gradient_width, 0); } Rect text_rect = display_rect(); text_rect.Inset(GetAlignmentOffset(0).x(), 0, 0, 0); // TODO(msw): Use the actual text colors corresponding to each faded part. skia::RefPtr<SkShader> shader = CreateFadeShader( text_rect, left_part, right_part, colors_.breaks().front().second); if (shader) renderer->SetShader(shader.get()); } void RenderText::ApplyTextShadows(internal::SkiaTextRenderer* renderer) { skia::RefPtr<SkDrawLooper> looper = CreateShadowDrawLooper(shadows_); renderer->SetDrawLooper(looper.get()); } // static bool RenderText::RangeContainsCaret(const Range& range, size_t caret_pos, LogicalCursorDirection caret_affinity) { // NB: exploits unsigned wraparound (WG14/N1124 section 6.2.5 paragraph 9). size_t adjacent = (caret_affinity == CURSOR_BACKWARD) ? caret_pos - 1 : caret_pos + 1; return range.Contains(Range(caret_pos, adjacent)); } void RenderText::MoveCursorTo(size_t position, bool select) { size_t cursor = std::min(position, text().length()); if (IsValidCursorIndex(cursor)) SetSelectionModel(SelectionModel( Range(select ? selection().start() : cursor, cursor), (cursor == 0) ? CURSOR_FORWARD : CURSOR_BACKWARD)); } void RenderText::UpdateLayoutText() { layout_text_.clear(); line_breaks_.SetMax(0); if (obscured_) { size_t obscured_text_length = static_cast<size_t>(UTF16IndexToOffset(text_, 0, text_.length())); layout_text_.assign(obscured_text_length, kPasswordReplacementChar); if (obscured_reveal_index_ >= 0 && obscured_reveal_index_ < static_cast<int>(text_.length())) { // Gets the index range in |text_| to be revealed. size_t start = obscured_reveal_index_; U16_SET_CP_START(text_.data(), 0, start); size_t end = start; UChar32 unused_char; U16_NEXT(text_.data(), end, text_.length(), unused_char); // Gets the index in |layout_text_| to be replaced. const size_t cp_start = static_cast<size_t>(UTF16IndexToOffset(text_, 0, start)); if (layout_text_.length() > cp_start) layout_text_.replace(cp_start, 1, text_.substr(start, end - start)); } } else { layout_text_ = text_; } const base::string16& text = layout_text_; if (truncate_length_ > 0 && truncate_length_ < text.length()) { // Truncate the text at a valid character break and append an ellipsis. icu::StringCharacterIterator iter(text.c_str()); // Respect ELIDE_HEAD and ELIDE_MIDDLE preferences during truncation. if (elide_behavior_ == ELIDE_HEAD) { iter.setIndex32(text.length() - truncate_length_ + 1); layout_text_.assign(kEllipsisUTF16 + text.substr(iter.getIndex())); } else if (elide_behavior_ == ELIDE_MIDDLE) { iter.setIndex32(truncate_length_ / 2); const size_t ellipsis_start = iter.getIndex(); iter.setIndex32(text.length() - (truncate_length_ / 2)); const size_t ellipsis_end = iter.getIndex(); DCHECK_LE(ellipsis_start, ellipsis_end); layout_text_.assign(text.substr(0, ellipsis_start) + kEllipsisUTF16 + text.substr(ellipsis_end)); } else { iter.setIndex32(truncate_length_ - 1); layout_text_.assign(text.substr(0, iter.getIndex()) + kEllipsisUTF16); } } if (elide_behavior_ != NO_ELIDE && elide_behavior_ != FADE_TAIL && !layout_text_.empty() && GetContentWidth() > display_rect_.width()) { // This doesn't trim styles so ellipsis may get rendered as a different // style than the preceding text. See crbug.com/327850. layout_text_.assign(Elide(layout_text_, static_cast<float>(display_rect_.width()), elide_behavior_)); } // Replace the newline character with a newline symbol in single line mode. static const base::char16 kNewline[] = { '\n', 0 }; static const base::char16 kNewlineSymbol[] = { 0x2424, 0 }; if (!multiline_ && replace_newline_chars_with_symbols_) base::ReplaceChars(layout_text_, kNewline, kNewlineSymbol, &layout_text_); ResetLayout(); } base::string16 RenderText::Elide(const base::string16& text, float available_width, ElideBehavior behavior) { if (available_width <= 0 || text.empty()) return base::string16(); if (behavior == ELIDE_EMAIL) return ElideEmail(text, available_width); // Create a RenderText copy with attributes that affect the rendering width. scoped_ptr<RenderText> render_text = CreateInstanceOfSameType(); render_text->SetFontList(font_list_); render_text->SetDirectionalityMode(directionality_mode_); render_text->SetCursorEnabled(cursor_enabled_); render_text->set_truncate_length(truncate_length_); render_text->styles_ = styles_; render_text->colors_ = colors_; render_text->SetText(text); if (render_text->GetContentWidthF() <= available_width) return text; const base::string16 ellipsis = base::string16(kEllipsisUTF16); const bool insert_ellipsis = (behavior != TRUNCATE); const bool elide_in_middle = (behavior == ELIDE_MIDDLE); const bool elide_at_beginning = (behavior == ELIDE_HEAD); StringSlicer slicer(text, ellipsis, elide_in_middle, elide_at_beginning); render_text->SetText(ellipsis); const float ellipsis_width = render_text->GetContentWidthF(); if (insert_ellipsis && (ellipsis_width > available_width)) return base::string16(); // Use binary search to compute the elided text. size_t lo = 0; size_t hi = text.length() - 1; const base::i18n::TextDirection text_direction = GetTextDirection(); for (size_t guess = (lo + hi) / 2; lo <= hi; guess = (lo + hi) / 2) { // Restore colors. They will be truncated to size by SetText. render_text->colors_ = colors_; base::string16 new_text = slicer.CutString(guess, insert_ellipsis && behavior != ELIDE_TAIL); render_text->SetText(new_text); // This has to be an additional step so that the ellipsis is rendered with // same style as trailing part of the text. if (insert_ellipsis && behavior == ELIDE_TAIL) { // When ellipsis follows text whose directionality is not the same as that // of the whole text, it will be rendered with the directionality of the // whole text. Since we want ellipsis to indicate continuation of the // preceding text, we force the directionality of ellipsis to be same as // the preceding text using LTR or RTL markers. base::i18n::TextDirection trailing_text_direction = base::i18n::GetLastStrongCharacterDirection(new_text); new_text.append(ellipsis); if (trailing_text_direction != text_direction) { if (trailing_text_direction == base::i18n::LEFT_TO_RIGHT) new_text += base::i18n::kLeftToRightMark; else new_text += base::i18n::kRightToLeftMark; } render_text->SetText(new_text); } // Restore styles. Make sure style ranges don't break new text graphemes. render_text->styles_ = styles_; for (size_t style = 0; style < NUM_TEXT_STYLES; ++style) { BreakList<bool>& break_list = render_text->styles_[style]; break_list.SetMax(render_text->text_.length()); Range range; while (range.end() < break_list.max()) { BreakList<bool>::const_iterator current_break = break_list.GetBreak(range.end()); range = break_list.GetRange(current_break); if (range.end() < break_list.max() && !render_text->IsValidCursorIndex(range.end())) { range.set_end(render_text->IndexOfAdjacentGrapheme(range.end(), CURSOR_FORWARD)); break_list.ApplyValue(current_break->second, range); } } } // We check the width of the whole desired string at once to ensure we // handle kerning/ligatures/etc. correctly. const float guess_width = render_text->GetContentWidthF(); if (guess_width == available_width) break; if (guess_width > available_width) { hi = guess - 1; // Move back on the loop terminating condition when the guess is too wide. if (hi < lo) lo = hi; } else { lo = guess + 1; } } return render_text->text(); } base::string16 RenderText::ElideEmail(const base::string16& email, float available_width) { // The returned string will have at least one character besides the ellipsis // on either side of '@'; if that's impossible, a single ellipsis is returned. // If possible, only the username is elided. Otherwise, the domain is elided // in the middle, splitting available width equally with the elided username. // If the username is short enough that it doesn't need half the available // width, the elided domain will occupy that extra width. // Split the email into its local-part (username) and domain-part. The email // spec allows for @ symbols in the username under some special requirements, // but not in the domain part, so splitting at the last @ symbol is safe. const size_t split_index = email.find_last_of('@'); DCHECK_NE(split_index, base::string16::npos); base::string16 username = email.substr(0, split_index); base::string16 domain = email.substr(split_index + 1); DCHECK(!username.empty()); DCHECK(!domain.empty()); // Subtract the @ symbol from the available width as it is mandatory. const base::string16 kAtSignUTF16 = base::ASCIIToUTF16("@"); available_width -= GetStringWidthF(kAtSignUTF16, font_list()); // Check whether eliding the domain is necessary: if eliding the username // is sufficient, the domain will not be elided. const float full_username_width = GetStringWidthF(username, font_list()); const float available_domain_width = available_width - std::min(full_username_width, GetStringWidthF(username.substr(0, 1) + kEllipsisUTF16, font_list())); if (GetStringWidthF(domain, font_list()) > available_domain_width) { // Elide the domain so that it only takes half of the available width. // Should the username not need all the width available in its half, the // domain will occupy the leftover width. // If |desired_domain_width| is greater than |available_domain_width|: the // minimal username elision allowed by the specifications will not fit; thus // |desired_domain_width| must be <= |available_domain_width| at all cost. const float desired_domain_width = std::min<float>(available_domain_width, std::max<float>(available_width - full_username_width, available_width / 2)); domain = Elide(domain, desired_domain_width, ELIDE_MIDDLE); // Failing to elide the domain such that at least one character remains // (other than the ellipsis itself) remains: return a single ellipsis. if (domain.length() <= 1U) return base::string16(kEllipsisUTF16); } // Fit the username in the remaining width (at this point the elided username // is guaranteed to fit with at least one character remaining given all the // precautions taken earlier). available_width -= GetStringWidthF(domain, font_list()); username = Elide(username, available_width, ELIDE_TAIL); return username + kAtSignUTF16 + domain; } void RenderText::UpdateCachedBoundsAndOffset() { if (cached_bounds_and_offset_valid_) return; // TODO(ckocagil): Add support for scrolling multiline text. int delta_x = 0; if (cursor_enabled()) { // When cursor is enabled, ensure it is visible. For this, set the valid // flag true and calculate the current cursor bounds using the stale // |display_offset_|. Then calculate the change in offset needed to move the // cursor into the visible area. cached_bounds_and_offset_valid_ = true; cursor_bounds_ = GetCursorBounds(selection_model_, insert_mode_); // TODO(bidi): Show RTL glyphs at the cursor position for ALIGN_LEFT, etc. if (cursor_bounds_.right() > display_rect_.right()) delta_x = display_rect_.right() - cursor_bounds_.right(); else if (cursor_bounds_.x() < display_rect_.x()) delta_x = display_rect_.x() - cursor_bounds_.x(); } SetDisplayOffset(display_offset_.x() + delta_x); } void RenderText::DrawSelection(Canvas* canvas) { const std::vector<Rect> sel = GetSubstringBounds(selection()); for (std::vector<Rect>::const_iterator i = sel.begin(); i < sel.end(); ++i) canvas->FillRect(*i, selection_background_focused_color_); } } // namespace gfx
mohamed--abdel-maksoud/chromium.src
ui/gfx/render_text.cc
C++
bsd-3-clause
52,158
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2013, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "IECore/NURBSPrimitive.h" #include "IECore/Renderer.h" #include "IECore/MurmurHash.h" using namespace std; using namespace IECore; using namespace Imath; using namespace boost; static IndexedIO::EntryID g_uOrderEntry("uOrder"); static IndexedIO::EntryID g_uKnotEntry("uKnot"); static IndexedIO::EntryID g_uMinEntry("uMin"); static IndexedIO::EntryID g_uMaxEntry("uMax"); static IndexedIO::EntryID g_vOrderEntry("vOrder"); static IndexedIO::EntryID g_vKnotEntry("vKnot"); static IndexedIO::EntryID g_vMinEntry("vMin"); static IndexedIO::EntryID g_vMaxEntry("vMax"); const unsigned int NURBSPrimitive::m_ioVersion = 0; IE_CORE_DEFINEOBJECTTYPEDESCRIPTION(NURBSPrimitive); NURBSPrimitive::NURBSPrimitive() { vector<float> knot; knot.push_back( 0 ); knot.push_back( 0 ); knot.push_back( 0 ); knot.push_back( 0.333 ); knot.push_back( 0.666 ); knot.push_back( 1 ); knot.push_back( 1 ); knot.push_back( 1 ); setTopology( 4, new FloatVectorData( knot ), 0, 1, 4, new FloatVectorData( knot ), 0, 1 ); } NURBSPrimitive::NURBSPrimitive( int uOrder, ConstFloatVectorDataPtr uKnot, float uMin, float uMax, int vOrder, ConstFloatVectorDataPtr vKnot, float vMin, float vMax, ConstV3fVectorDataPtr p ) { setTopology( uOrder, uKnot, uMin, uMax, vOrder, vKnot, vMin, vMax ); if( p ) { V3fVectorDataPtr pData = p->copy(); pData->setInterpretation( GeometricData::Point ); variables.insert( PrimitiveVariableMap::value_type( "P", PrimitiveVariable( PrimitiveVariable::Vertex, pData ) ) ); } } int NURBSPrimitive::uOrder() const { return m_uOrder; } const FloatVectorData *NURBSPrimitive::uKnot() const { return m_uKnot.get(); } float NURBSPrimitive::uMin() const { return m_uMin; } float NURBSPrimitive::uMax() const { return m_uMax; } int NURBSPrimitive::uVertices() const { return m_uKnot->readable().size() - m_uOrder; } int NURBSPrimitive::uSegments() const { return 1 + uVertices() - m_uOrder; } int NURBSPrimitive::vOrder() const { return m_vOrder; } const FloatVectorData *NURBSPrimitive::vKnot() const { return m_vKnot.get(); } float NURBSPrimitive::vMin() const { return m_vMin; } float NURBSPrimitive::vMax() const { return m_vMax; } int NURBSPrimitive::vVertices() const { return m_vKnot->readable().size() - m_vOrder; } int NURBSPrimitive::vSegments() const { return 1 + vVertices() - m_vOrder; } void NURBSPrimitive::setTopology( int uOrder, ConstFloatVectorDataPtr uKnot, float uMin, float uMax, int vOrder, ConstFloatVectorDataPtr vKnot, float vMin, float vMax ) { // check order isn't too small if( uOrder<2 ) { throw Exception( "Order in u direction too small." ); } if( vOrder<2 ) { throw Exception( "Order in v direction too small." ); } // check knots have enough entries for the order. // an order of N demands at least N control points // and numKnots==numControlPoints + order // so we need numKnots>=2*order if( (int)uKnot->readable().size() < uOrder * 2 ) { throw Exception( "Not enough knot values in u direction." ); } if( (int)vKnot->readable().size() < vOrder * 2 ) { throw Exception( "Not enough knot values in v direction." ); } // check knots are monotonically increasing const vector<float> &u = uKnot->readable(); float previous = u[0]; for( unsigned int i=0; i<u.size(); i++ ) { if( u[i]<previous ) { throw Exception( "Knots not monotonically increasing in u direction." ); } previous = u[i]; } const vector<float> &v = vKnot->readable(); previous = v[0]; for( unsigned int i=0; i<v.size(); i++ ) { if( v[i]<previous ) { throw Exception( "Knots not monotonically increasing in v direction." ); } previous = v[i]; } // check min and max parametric values are in range if( uMin > uMax ) { throw Exception( "uMin greater than uMax." ); } if( vMin > vMax ) { throw Exception( "vMin greater than vMax." ); } if( uMin < u[uOrder-2] ) { throw Exception( "uMin too small." ); } if( uMax > u[u.size()-uOrder+1] ) { throw Exception( "uMax too great." ); } if( vMin < v[vOrder-2] ) { throw Exception( "vMin too small." ); } if( vMax > v[v.size()-vOrder+1] ) { throw Exception( "vMax too great." ); } // set everything (taking copies of the data) m_uOrder = uOrder; m_uKnot = uKnot->copy(); m_uMin = uMin; m_uMax = uMax; m_vOrder = vOrder; m_vKnot = vKnot->copy(); m_vMin = vMin; m_vMax = vMax; } size_t NURBSPrimitive::variableSize( PrimitiveVariable::Interpolation interpolation ) const { switch( interpolation ) { case PrimitiveVariable::Constant : return 1; case PrimitiveVariable::Uniform : return uSegments() * vSegments(); case PrimitiveVariable::Vertex : return uVertices() * vVertices(); case PrimitiveVariable::Varying: case PrimitiveVariable::FaceVarying: return (uSegments()+1) * (vSegments()+1); default : return 0; } } void NURBSPrimitive::render( Renderer *renderer ) const { renderer->nurbs( m_uOrder, m_uKnot, m_uMin, m_uMax, m_vOrder, m_vKnot, m_vMin, m_vMax, variables ); } void NURBSPrimitive::copyFrom( const Object *other, IECore::Object::CopyContext *context ) { Primitive::copyFrom( other, context ); const NURBSPrimitive *tOther = static_cast<const NURBSPrimitive *>( other ); m_uOrder = tOther->m_uOrder; m_uKnot = context->copy<FloatVectorData>( tOther->m_uKnot ); m_uMin = tOther->m_uMin; m_uMax = tOther->m_uMax; m_vOrder = tOther->m_vOrder; m_vKnot = context->copy<FloatVectorData>( tOther->m_vKnot ); m_vMin = tOther->m_vMin; m_vMax = tOther->m_vMax; } void NURBSPrimitive::save( IECore::Object::SaveContext *context ) const { Primitive::save(context); IndexedIOPtr container = context->container( staticTypeName(), m_ioVersion ); container->write( g_uOrderEntry, m_uOrder ); context->save( m_uKnot, container, g_uKnotEntry ); container->write( g_uMinEntry, m_uMin ); container->write( g_uMaxEntry, m_uMax ); container->write( g_vOrderEntry, m_vOrder ); context->save( m_vKnot, container, g_vKnotEntry ); container->write( g_vMinEntry, m_vMin ); container->write( g_vMaxEntry, m_vMax ); } void NURBSPrimitive::load( IECore::Object::LoadContextPtr context ) { Primitive::load(context); unsigned int v = m_ioVersion; ConstIndexedIOPtr container = context->container( staticTypeName(), v ); container->read( g_uOrderEntry, m_uOrder ); m_uKnot = context->load<FloatVectorData>( container, g_uKnotEntry ); container->read( g_uMinEntry, m_uMin ); container->read( g_uMaxEntry, m_uMax ); container->read( g_vOrderEntry, m_vOrder ); m_vKnot = context->load<FloatVectorData>( container, g_vKnotEntry ); container->read( g_vMinEntry, m_vMin ); container->read( g_vMaxEntry, m_vMax ); } bool NURBSPrimitive::isEqualTo( const Object *other ) const { if( !Primitive::isEqualTo( other ) ) { return false; } const NURBSPrimitive *tOther = static_cast<const NURBSPrimitive *>( other ); if( m_uOrder!=tOther->m_uOrder ) { return false; } if( m_vOrder!=tOther->m_vOrder ) { return false; } if( m_uMin!=tOther->m_uMin ) { return false; } if( m_vMin!=tOther->m_vMin ) { return false; } if( m_uMax!=tOther->m_uMax ) { return false; } if( m_vMax!=tOther->m_vMax ) { return false; } if( !m_uKnot->isEqualTo( tOther->m_uKnot ) ) { return false; } if( !m_vKnot->isEqualTo( tOther->m_vKnot ) ) { return false; } return true; } void NURBSPrimitive::memoryUsage( Object::MemoryAccumulator &a ) const { Primitive::memoryUsage( a ); a.accumulate( sizeof( m_uOrder ) * 2 ); a.accumulate( sizeof( m_uMin ) * 4 ); a.accumulate( m_uKnot ); a.accumulate( m_vKnot ); } void NURBSPrimitive::hash( MurmurHash &h ) const { Primitive::hash( h ); } void NURBSPrimitive::topologyHash( MurmurHash &h ) const { h.append( m_uOrder ); m_uKnot->hash( h ); h.append( m_uMin ); h.append( m_uMax ); h.append( m_vOrder ); m_vKnot->hash( h ); h.append( m_vMin ); h.append( m_vMax ); }
code-google-com/cortex-vfx
src/IECore/NURBSPrimitive.cpp
C++
bsd-3-clause
9,702
/* YUI 3.17.2 (build 9c3c78e) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ .yui3-skin-sam .yui3-panel-content { -webkit-box-shadow: 0 0 5px #333; -moz-box-shadow: 0 0 5px #333; box-shadow: 0 0 5px #333; border: 1px solid black; background: white; } .yui3-skin-sam .yui3-panel .yui3-widget-hd { padding: 8px 28px 8px 8px; /* Room for close button. */ min-height: 13px; /* For the close button */ _height: 13px; /* IE6 */ color: white; background-color: #3961c5; background: -moz-linear-gradient( 0% 100% 90deg, #2647a0 7%, #3d67ce 50%, #426fd9 100% ); background: -webkit-gradient( linear, left bottom, left top, from(#2647a0), color-stop(0.07, #2647a0), color-stop(0.5, #3d67ce), to(#426fd9) ); /* TODO: Add support for IE and W3C gradients */ } .yui3-skin-sam .yui3-panel .yui3-widget-hd .yui3-widget-buttons { padding: 8px; } .yui3-skin-sam .yui3-panel .yui3-widget-bd { padding: 10px; } .yui3-skin-sam .yui3-panel .yui3-widget-ft { background: #EDF5FF; padding: 8px; text-align: right; } .yui3-skin-sam .yui3-panel .yui3-widget-ft .yui3-button { margin-left: 8px; } /* Support for icon-based [x] "close" button in the header. Nicolas Gallagher: "CSS image replacement with pseudo-elements (NIR)" http://nicolasgallagher.com/css-image-replacement-with-pseudo-elements/ */ .yui3-skin-sam .yui3-panel .yui3-widget-hd .yui3-button-close { /* Reset base button styles */ background: transparent; filter: none; border: none; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; /* Structure */ width: 13px; height: 13px; padding: 0; overflow: hidden; vertical-align: top; /* IE < 8 :( */ *font-size: 0; *line-height: 0; *letter-spacing: -1000px; *color: #86A5EC; *background: url(sprite_icons.png) no-repeat 1px 1px; } .yui3-skin-sam .yui3-panel .yui3-widget-hd .yui3-button-close:before { /* Displays the [x] icon in place of the "Close" text. Note: The `width` of this pseudo element is the same as its "host" element. */ content: url(sprite_icons.png); display: inline-block; text-align: center; font-size: 0; line-height: 0; width: 13px; margin: 1px 0 0 1px; } .yui3-skin-sam .yui3-panel-hidden .yui3-widget-hd .yui3-button-close { /* Required for IE > 7 to deal with pseudo :before element */ display: none; }
ghiringh/Wegas
wegas-resources/src/main/webapp/lib/yui3/build/panel/assets/skins/sam/panel-skin.css
CSS
mit
2,704
--TEST-- Test array_merge_recursive() function : usage variations - common key and value(Bug#43559) --FILE-- <?php /* Prototype : array array_merge_recursive(array $arr1[, array $...]) * Description: Recursively merges elements from passed arrays into one array * Source code: ext/standard/array.c */ /* * Testing the functionality of array_merge_recursive() by passing * arrays having common key and value. */ echo "*** Testing array_merge_recursive() : arrays with common key and value ***\n"; /* initialize the array having duplicate values */ // integer values $arr1 = array("a" => 1, "b" => 2); $arr2 = array("b" => 2, "c" => 4); echo "-- Integer values --\n"; var_dump( array_merge_recursive($arr1, $arr2) ); // float values $arr1 = array("a" => 1.1, "b" => 2.2); $arr2 = array("b" => 2.2, "c" => 3.3); echo "-- Float values --\n"; var_dump( array_merge_recursive($arr1, $arr2) ); // string values $arr1 = array("a" => "hello", "b" => "world"); $arr2 = array("b" => "world", "c" => "string"); echo "-- String values --\n"; var_dump( array_merge_recursive($arr1, $arr2) ); // boolean values $arr1 = array("a" => true, "b" => false); $arr2 = array("b" => false); echo "-- Boolean values --\n"; var_dump( array_merge_recursive($arr1, $arr2) ); // null values $arr1 = array( "a" => NULL); $arr2 = array( "a" => NULL); echo "-- Null values --\n"; var_dump( array_merge_recursive($arr1, $arr2) ); echo "Done"; ?> --EXPECTF-- *** Testing array_merge_recursive() : arrays with common key and value *** -- Integer values -- array(3) { ["a"]=> int(1) ["b"]=> array(2) { [0]=> int(2) [1]=> int(2) } ["c"]=> int(4) } -- Float values -- array(3) { ["a"]=> float(1.1) ["b"]=> array(2) { [0]=> float(2.2) [1]=> float(2.2) } ["c"]=> float(3.3) } -- String values -- array(3) { ["a"]=> string(5) "hello" ["b"]=> array(2) { [0]=> string(5) "world" [1]=> string(5) "world" } ["c"]=> string(6) "string" } -- Boolean values -- array(2) { ["a"]=> bool(true) ["b"]=> array(2) { [0]=> bool(false) [1]=> bool(false) } } -- Null values -- array(1) { ["a"]=> array(2) { [0]=> NULL [1]=> NULL } } Done
ericpp/hippyvm
test_phpt/ext/standard/array/array_merge_recursive_variation9.phpt
PHP
mit
2,233
require 'optparse' require 'uri' require 'puma/server' require 'puma/const' require 'puma/configuration' require 'puma/binder' require 'puma/detect' require 'puma/daemon_ext' require 'puma/util' require 'puma/single' require 'puma/cluster' require 'puma/commonlogger' module Puma class << self # The CLI exports its Puma::Configuration object here to allow # apps to pick it up. An app needs to use it conditionally though # since it is not set if the app is launched via another # mechanism than the CLI class. attr_accessor :cli_config end # Handles invoke a Puma::Server in a command line style. # class CLI # Create a new CLI object using +argv+ as the command line # arguments. # # +stdout+ and +stderr+ can be set to IO-like objects which # this object will report status on. # def initialize(argv, events=Events.stdio) @debug = false @argv = argv @events = events @status = nil @runner = nil @config = nil ENV['NEWRELIC_DISPATCHER'] ||= "Puma" setup_options generate_restart_data @binder = Binder.new(@events) @binder.import_from_env end # The Binder object containing the sockets bound to. attr_reader :binder # The Configuration object used. attr_reader :config # The Hash of options used to configure puma. attr_reader :options # The Events object used to output information. attr_reader :events # Delegate +log+ to +@events+ # def log(str) @events.log str end # Delegate +error+ to +@events+ # def error(str) @events.error str end def debug(str) @events.log "- #{str}" if @options[:debug] end def clustered? @options[:workers] > 0 end def prune_bundler? @options[:prune_bundler] && clustered? && !@options[:preload_app] end def jruby? IS_JRUBY end def windows? RUBY_PLATFORM =~ /mswin32|ming32/ end def env @options[:environment] || ENV['RACK_ENV'] || 'development' end def write_state write_pid path = @options[:state] return unless path state = { 'pid' => Process.pid } cfg = @config.dup [ :logger, :before_worker_shutdown, :before_worker_boot, :before_worker_fork, :after_worker_boot, :on_restart, :lowlevel_error_handler ].each { |k| cfg.options.delete(k) } state['config'] = cfg require 'yaml' File.open(path, 'w') { |f| f.write state.to_yaml } end # If configured, write the pid of the current process out # to a file. # def write_pid path = @options[:pidfile] return unless path File.open(path, 'w') { |f| f.puts Process.pid } cur = Process.pid at_exit do delete_pidfile if cur == Process.pid end end def delete_pidfile path = @options[:pidfile] File.unlink(path) if path && File.exist?(path) end def graceful_stop @runner.stop_blocked log "=== puma shutdown: #{Time.now} ===" log "- Goodbye!" end def jruby_daemon_start require 'puma/jruby_restart' JRubyRestart.daemon_start(@restart_dir, restart_args) end def restart! @options[:on_restart].each do |block| block.call self end if jruby? close_binder_listeners require 'puma/jruby_restart' JRubyRestart.chdir_exec(@restart_dir, restart_args) elsif windows? close_binder_listeners argv = restart_args Dir.chdir(@restart_dir) argv += [redirects] if RUBY_VERSION >= '1.9' Kernel.exec(*argv) else redirects = {:close_others => true} @binder.listeners.each_with_index do |(l, io), i| ENV["PUMA_INHERIT_#{i}"] = "#{io.to_i}:#{l}" redirects[io.to_i] = io.to_i end argv = restart_args Dir.chdir(@restart_dir) argv += [redirects] if RUBY_VERSION >= '1.9' Kernel.exec(*argv) end end # Parse the options, load the rackup, start the server and wait # for it to finish. # def run begin parse_options rescue UnsupportedOption exit 1 end dir = @options[:directory] Dir.chdir(dir) if dir prune_bundler if prune_bundler? set_rack_environment if clustered? @events.formatter = Events::PidFormatter.new @options[:logger] = @events @runner = Cluster.new(self) else @runner = Single.new(self) end setup_signals set_process_title @status = :run @runner.run case @status when :halt log "* Stopping immediately!" when :run, :stop graceful_stop when :restart log "* Restarting..." @runner.before_restart restart! when :exit # nothing end end def stop @status = :stop @runner.stop end def restart @status = :restart @runner.restart end def reload_worker_directory @runner.reload_worker_directory if @runner.respond_to?(:reload_worker_directory) end def phased_restart unless @runner.respond_to?(:phased_restart) and @runner.phased_restart log "* phased-restart called but not available, restarting normally." return restart end true end def redirect_io @runner.redirect_io end def stats @runner.stats end def halt @status = :halt @runner.halt end private def title buffer = "puma #{Puma::Const::VERSION} (#{@options[:binds].join(',')})" buffer << " [#{@options[:tag]}]" if @options[:tag] buffer end def unsupported(str) @events.error(str) raise UnsupportedOption end def restart_args cmd = @options[:restart_cmd] if cmd cmd.split(' ') + @original_argv else @restart_argv end end def set_process_title Process.respond_to?(:setproctitle) ? Process.setproctitle(title) : $0 = title end def find_config if @options[:config_file] == '-' @options[:config_file] = nil else @options[:config_file] ||= %W(config/puma/#{env}.rb config/puma.rb).find { |f| File.exist?(f) } end end # Build the OptionParser object to handle the available options. # def setup_options @options = { :min_threads => 0, :max_threads => 16, :quiet => false, :debug => false, :binds => [], :workers => 0, :daemon => false, :before_worker_shutdown => [], :before_worker_boot => [], :before_worker_fork => [], :after_worker_boot => [] } @parser = OptionParser.new do |o| o.on "-b", "--bind URI", "URI to bind to (tcp://, unix://, ssl://)" do |arg| @options[:binds] << arg end o.on "-C", "--config PATH", "Load PATH as a config file" do |arg| @options[:config_file] = arg end o.on "--control URL", "The bind url to use for the control server", "Use 'auto' to use temp unix server" do |arg| if arg @options[:control_url] = arg elsif jruby? unsupported "No default url available on JRuby" end end o.on "--control-token TOKEN", "The token to use as authentication for the control server" do |arg| @options[:control_auth_token] = arg end o.on "-d", "--daemon", "Daemonize the server into the background" do @options[:daemon] = true @options[:quiet] = true end o.on "--debug", "Log lowlevel debugging information" do @options[:debug] = true end o.on "--dir DIR", "Change to DIR before starting" do |d| @options[:directory] = d.to_s @options[:worker_directory] = d.to_s end o.on "-e", "--environment ENVIRONMENT", "The environment to run the Rack app on (default development)" do |arg| @options[:environment] = arg end o.on "-I", "--include PATH", "Specify $LOAD_PATH directories" do |arg| $LOAD_PATH.unshift(*arg.split(':')) end o.on "-p", "--port PORT", "Define the TCP port to bind to", "Use -b for more advanced options" do |arg| @options[:binds] << "tcp://#{Configuration::DefaultTCPHost}:#{arg}" end o.on "--pidfile PATH", "Use PATH as a pidfile" do |arg| @options[:pidfile] = arg end o.on "--preload", "Preload the app. Cluster mode only" do @options[:preload_app] = true end o.on "--prune-bundler", "Prune out the bundler env if possible" do @options[:prune_bundler] = true end o.on "-q", "--quiet", "Quiet down the output" do @options[:quiet] = true end o.on "-R", "--restart-cmd CMD", "The puma command to run during a hot restart", "Default: inferred" do |cmd| @options[:restart_cmd] = cmd end o.on "-S", "--state PATH", "Where to store the state details" do |arg| @options[:state] = arg end o.on '-t', '--threads INT', "min:max threads to use (default 0:16)" do |arg| min, max = arg.split(":") if max @options[:min_threads] = min @options[:max_threads] = max else @options[:min_threads] = 0 @options[:max_threads] = arg end end o.on "--tcp-mode", "Run the app in raw TCP mode instead of HTTP mode" do @options[:mode] = :tcp end o.on "-V", "--version", "Print the version information" do puts "puma version #{Puma::Const::VERSION}" exit 0 end o.on "-w", "--workers COUNT", "Activate cluster mode: How many worker processes to create" do |arg| @options[:workers] = arg.to_i end o.on "--tag NAME", "Additional text to display in process listing" do |arg| @options[:tag] = arg end o.banner = "puma <options> <rackup file>" o.on_tail "-h", "--help", "Show help" do log o exit 0 end end end def generate_restart_data # Use the same trick as unicorn, namely favor PWD because # it will contain an unresolved symlink, useful for when # the pwd is /data/releases/current. if dir = ENV['PWD'] s_env = File.stat(dir) s_pwd = File.stat(Dir.pwd) if s_env.ino == s_pwd.ino and (jruby? or s_env.dev == s_pwd.dev) @restart_dir = dir @options[:worker_directory] = dir end end @restart_dir ||= Dir.pwd @original_argv = @argv.dup require 'rubygems' # if $0 is a file in the current directory, then restart # it the same, otherwise add -S on there because it was # picked up in PATH. # if File.exist?($0) arg0 = [Gem.ruby, $0] else arg0 = [Gem.ruby, "-S", $0] end # Detect and reinject -Ilib from the command line lib = File.expand_path "lib" arg0[1,0] = ["-I", lib] if $:[0] == lib if defined? Puma::WILD_ARGS @restart_argv = arg0 + Puma::WILD_ARGS + @original_argv else @restart_argv = arg0 + @original_argv end end def set_rack_environment @options[:environment] = env ENV['RACK_ENV'] = env end def setup_signals begin Signal.trap "SIGUSR2" do restart end rescue Exception log "*** SIGUSR2 not implemented, signal based restart unavailable!" end begin Signal.trap "SIGUSR1" do phased_restart end rescue Exception log "*** SIGUSR1 not implemented, signal based restart unavailable!" end begin Signal.trap "SIGTERM" do stop end rescue Exception log "*** SIGTERM not implemented, signal based gracefully stopping unavailable!" end begin Signal.trap "SIGHUP" do redirect_io end rescue Exception log "*** SIGHUP not implemented, signal based logs reopening unavailable!" end if jruby? Signal.trap("INT") do @status = :exit graceful_stop exit end end end def close_binder_listeners @binder.listeners.each do |l, io| io.close uri = URI.parse(l) next unless uri.scheme == 'unix' File.unlink("#{uri.host}#{uri.path}") end end def parse_options @parser.parse! @argv @options[:rackup] = @argv.shift if @argv.last find_config @config = Puma::Configuration.new @options # Advertise the Configuration Puma.cli_config = @config @config.load if clustered? && (jruby? || windows?) unsupported 'worker mode not supported on JRuby or Windows' end if @options[:daemon] && windows? unsupported 'daemon mode not supported on Windows' end end def prune_bundler return unless defined?(Bundler) puma = Bundler.rubygems.loaded_specs("puma") dirs = puma.require_paths.map { |x| File.join(puma.full_gem_path, x) } puma_lib_dir = dirs.detect { |x| File.exist? File.join(x, '../bin/puma-wild') } unless puma_lib_dir log "! Unable to prune Bundler environment, continuing" return end deps = puma.runtime_dependencies.map do |d| spec = Bundler.rubygems.loaded_specs(d.name) "#{d.name}:#{spec.version.to_s}" end log '* Pruning Bundler environment' home = ENV['GEM_HOME'] Bundler.with_clean_env do ENV['GEM_HOME'] = home wild = File.expand_path(File.join(puma_lib_dir, "../bin/puma-wild")) args = [Gem.ruby, wild, '-I', dirs.join(':'), deps.join(',')] + @original_argv Kernel.exec(*args) end end end end
praveenperera/qrideshare
vendor/cache/ruby/2.2.0/gems/puma-2.12.0/lib/puma/cli.rb
Ruby
mit
14,321
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Form\Extension\Core\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Intl\Intl; use Symfony\Component\Locale\Locale; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class LocaleType extends AbstractType { /** * {@inheritdoc} */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'choices' => Intl::getLocaleBundle()->getLocaleNames(), )); } /** * {@inheritdoc} */ public function getParent() { return 'choice'; } /** * {@inheritdoc} */ public function getName() { return 'locale'; } }
Clempops/prenomea
vendor/symfony/symfony/src/Symfony/Component/Form/Extension/Core/Type/LocaleType.php
PHP
mit
1,010
KB.onClick('.accordion-toggle', function (e) { var sectionElement = KB.dom(e.target).parent('.accordion-section'); if (sectionElement) { KB.dom(sectionElement).toggleClass('accordion-collapsed'); } });
Shaxine/kanboard
assets/js/components/accordion.js
JavaScript
mit
223
/* Only eth0 supported for now * * (C) Copyright 2003 * Thomas.Lange@corelatus.se * * SPDX-License-Identifier: GPL-2.0+ */ #include <config.h> #if defined(CONFIG_SYS_DISCOVER_PHY) #error "PHY not supported yet" /* We just assume that we are running 100FD for now */ /* We all use switches, right? ;-) */ #endif /* I assume ethernet behaves like au1000 */ #ifdef CONFIG_SOC_AU1000 /* Base address differ between cpu:s */ #define ETH0_BASE AU1000_ETH0_BASE #define MAC0_ENABLE AU1000_MAC0_ENABLE #else #ifdef CONFIG_SOC_AU1100 #define ETH0_BASE AU1100_ETH0_BASE #define MAC0_ENABLE AU1100_MAC0_ENABLE #else #ifdef CONFIG_SOC_AU1500 #define ETH0_BASE AU1500_ETH0_BASE #define MAC0_ENABLE AU1500_MAC0_ENABLE #else #ifdef CONFIG_SOC_AU1550 #define ETH0_BASE AU1550_ETH0_BASE #define MAC0_ENABLE AU1550_MAC0_ENABLE #else #error "No valid cpu set" #endif #endif #endif #endif #include <common.h> #include <malloc.h> #include <net.h> #include <command.h> #include <asm/io.h> #include <mach/au1x00.h> #if defined(CONFIG_CMD_MII) #include <miiphy.h> #endif /* Ethernet Transmit and Receive Buffers */ #define DBUF_LENGTH 1520 #define PKT_MAXBUF_SIZE 1518 static char txbuf[DBUF_LENGTH]; static int next_tx; static int next_rx; /* 4 rx and 4 tx fifos */ #define NO_OF_FIFOS 4 typedef struct{ u32 status; u32 addr; u32 len; /* Only used for tx */ u32 not_used; } mac_fifo_t; mac_fifo_t mac_fifo[NO_OF_FIFOS]; #define MAX_WAIT 1000 #if defined(CONFIG_CMD_MII) int au1x00_miiphy_read(struct mii_dev *bus, int addr, int devad, int reg) { unsigned short value = 0; volatile u32 *mii_control_reg = (volatile u32*)(ETH0_BASE+MAC_MII_CNTRL); volatile u32 *mii_data_reg = (volatile u32*)(ETH0_BASE+MAC_MII_DATA); u32 mii_control; unsigned int timedout = 20; while (*mii_control_reg & MAC_MII_BUSY) { udelay(1000); if (--timedout == 0) { printf("au1x00_eth: miiphy_read busy timeout!!\n"); return -1; } } mii_control = MAC_SET_MII_SELECT_REG(reg) | MAC_SET_MII_SELECT_PHY(addr) | MAC_MII_READ; *mii_control_reg = mii_control; timedout = 20; while (*mii_control_reg & MAC_MII_BUSY) { udelay(1000); if (--timedout == 0) { printf("au1x00_eth: miiphy_read busy timeout!!\n"); return -1; } } value = *mii_data_reg; return value; } int au1x00_miiphy_write(struct mii_dev *bus, int addr, int devad, int reg, u16 value) { volatile u32 *mii_control_reg = (volatile u32*)(ETH0_BASE+MAC_MII_CNTRL); volatile u32 *mii_data_reg = (volatile u32*)(ETH0_BASE+MAC_MII_DATA); u32 mii_control; unsigned int timedout = 20; while (*mii_control_reg & MAC_MII_BUSY) { udelay(1000); if (--timedout == 0) { printf("au1x00_eth: miiphy_write busy timeout!!\n"); return -1; } } mii_control = MAC_SET_MII_SELECT_REG(reg) | MAC_SET_MII_SELECT_PHY(addr) | MAC_MII_WRITE; *mii_data_reg = value; *mii_control_reg = mii_control; return 0; } #endif static int au1x00_send(struct eth_device *dev, void *packet, int length) { volatile mac_fifo_t *fifo_tx = (volatile mac_fifo_t*)(MAC0_TX_DMA_ADDR+MAC_TX_BUFF0_STATUS); int i; int res; /* tx fifo should always be idle */ fifo_tx[next_tx].len = length; fifo_tx[next_tx].addr = (virt_to_phys(packet))|TX_DMA_ENABLE; au_sync(); udelay(1); i=0; while(!(fifo_tx[next_tx].addr&TX_T_DONE)){ if(i>MAX_WAIT){ printf("TX timeout\n"); break; } udelay(1); i++; } /* Clear done bit */ fifo_tx[next_tx].addr = 0; fifo_tx[next_tx].len = 0; au_sync(); res = fifo_tx[next_tx].status; next_tx++; if(next_tx>=NO_OF_FIFOS){ next_tx=0; } return(res); } static int au1x00_recv(struct eth_device* dev){ volatile mac_fifo_t *fifo_rx = (volatile mac_fifo_t*)(MAC0_RX_DMA_ADDR+MAC_RX_BUFF0_STATUS); int length; u32 status; for(;;){ if(!(fifo_rx[next_rx].addr&RX_T_DONE)){ /* Nothing has been received */ return(-1); } status = fifo_rx[next_rx].status; length = status&0x3FFF; if(status&RX_ERROR){ printf("Rx error 0x%x\n", status); } else { /* Pass the packet up to the protocol layers. */ net_process_received_packet(net_rx_packets[next_rx], length - 4); } fifo_rx[next_rx].addr = (virt_to_phys(net_rx_packets[next_rx])) | RX_DMA_ENABLE; next_rx++; if(next_rx>=NO_OF_FIFOS){ next_rx=0; } } /* for */ return(0); /* Does anyone use this? */ } static int au1x00_init(struct eth_device* dev, bd_t * bd){ volatile u32 *macen = (volatile u32*)MAC0_ENABLE; volatile u32 *mac_ctrl = (volatile u32*)(ETH0_BASE+MAC_CONTROL); volatile u32 *mac_addr_high = (volatile u32*)(ETH0_BASE+MAC_ADDRESS_HIGH); volatile u32 *mac_addr_low = (volatile u32*)(ETH0_BASE+MAC_ADDRESS_LOW); volatile u32 *mac_mcast_high = (volatile u32*)(ETH0_BASE+MAC_MCAST_HIGH); volatile u32 *mac_mcast_low = (volatile u32*)(ETH0_BASE+MAC_MCAST_LOW); volatile mac_fifo_t *fifo_tx = (volatile mac_fifo_t*)(MAC0_TX_DMA_ADDR+MAC_TX_BUFF0_STATUS); volatile mac_fifo_t *fifo_rx = (volatile mac_fifo_t*)(MAC0_RX_DMA_ADDR+MAC_RX_BUFF0_STATUS); int i; next_tx = TX_GET_DMA_BUFFER(fifo_tx[0].addr); next_rx = RX_GET_DMA_BUFFER(fifo_rx[0].addr); /* We have to enable clocks before releasing reset */ *macen = MAC_EN_CLOCK_ENABLE; udelay(10); /* Enable MAC0 */ /* We have to release reset before accessing registers */ *macen = MAC_EN_CLOCK_ENABLE|MAC_EN_RESET0| MAC_EN_RESET1|MAC_EN_RESET2; udelay(10); for(i=0;i<NO_OF_FIFOS;i++){ fifo_tx[i].len = 0; fifo_tx[i].addr = virt_to_phys(&txbuf[0]); fifo_rx[i].addr = (virt_to_phys(net_rx_packets[i])) | RX_DMA_ENABLE; } /* Put mac addr in little endian */ #define ea eth_get_ethaddr() *mac_addr_high = (ea[5] << 8) | (ea[4] ) ; *mac_addr_low = (ea[3] << 24) | (ea[2] << 16) | (ea[1] << 8) | (ea[0] ) ; #undef ea *mac_mcast_low = 0; *mac_mcast_high = 0; /* Make sure the MAC buffer is in the correct endian mode */ #ifdef __LITTLE_ENDIAN *mac_ctrl = MAC_FULL_DUPLEX; udelay(1); *mac_ctrl = MAC_FULL_DUPLEX|MAC_RX_ENABLE|MAC_TX_ENABLE; #else *mac_ctrl = MAC_BIG_ENDIAN|MAC_FULL_DUPLEX; udelay(1); *mac_ctrl = MAC_BIG_ENDIAN|MAC_FULL_DUPLEX|MAC_RX_ENABLE|MAC_TX_ENABLE; #endif return(1); } static void au1x00_halt(struct eth_device* dev){ volatile u32 *macen = (volatile u32*)MAC0_ENABLE; /* Put MAC0 in reset */ *macen = 0; } int au1x00_enet_initialize(bd_t *bis){ struct eth_device* dev; if ((dev = (struct eth_device*)malloc(sizeof *dev)) == NULL) { puts ("malloc failed\n"); return -1; } memset(dev, 0, sizeof *dev); strcpy(dev->name, "Au1X00 ethernet"); dev->iobase = 0; dev->priv = 0; dev->init = au1x00_init; dev->halt = au1x00_halt; dev->send = au1x00_send; dev->recv = au1x00_recv; eth_register(dev); #if defined(CONFIG_CMD_MII) int retval; struct mii_dev *mdiodev = mdio_alloc(); if (!mdiodev) return -ENOMEM; strncpy(mdiodev->name, dev->name, MDIO_NAME_LEN); mdiodev->read = au1x00_miiphy_read; mdiodev->write = au1x00_miiphy_write; retval = mdio_register(mdiodev); if (retval < 0) return retval; #endif return 1; } int cpu_eth_init(bd_t *bis) { au1x00_enet_initialize(bis); return 0; }
guileschool/beagleboard
u-boot/arch/mips/mach-au1x00/au1x00_eth.c
C
mit
7,093
/* Copyright (c) 2006-2007 Christopher J. W. Lloyd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #import <Foundation/NSObject.h> @class NSNotification; @interface NSNotificationObserver : NSObject { id _observer; SEL _selector; } - initWithObserver:object selector:(SEL)selector; - observer; - (void)postNotification:(NSNotification *)note; @end
ruppmatt/cocotron
Foundation/NSNotificationCenter/NSNotificationObserver.h
C
mit
1,342
# psake # Copyright (c) 2010 James Kovacs # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. #Requires -Version 2.0 #-- Public Module Functions --# # .ExternalHelp psake.psm1-help.xml function Invoke-Task { [CmdletBinding()] param( [Parameter(Position=0,Mandatory=1)] [string]$taskName ) Assert $taskName ($msgs.error_invalid_task_name) $taskKey = $taskName.ToLower() if ($currentContext.aliases.Contains($taskKey)) { $taskName = $currentContext.aliases.$taskKey.Name $taskKey = $taskName.ToLower() } $currentContext = $psake.context.Peek() Assert ($currentContext.tasks.Contains($taskKey)) ($msgs.error_task_name_does_not_exist -f $taskName) if ($currentContext.executedTasks.Contains($taskKey)) { return } Assert (!$currentContext.callStack.Contains($taskKey)) ($msgs.error_circular_reference -f $taskName) $currentContext.callStack.Push($taskKey) $task = $currentContext.tasks.$taskKey $precondition_is_valid = & $task.Precondition if (!$precondition_is_valid) { Write-ColoredOutput ($msgs.precondition_was_false -f $taskName) -foregroundcolor Cyan } else { if ($taskKey -ne 'default') { if ($task.PreAction -or $task.PostAction) { Assert ($task.Action -ne $null) ($msgs.error_missing_action_parameter -f $taskName) } if ($task.Action) { try { foreach($childTask in $task.DependsOn) { Invoke-Task $childTask } $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() $currentContext.currentTaskName = $taskName & $currentContext.taskSetupScriptBlock if ($task.PreAction) { & $task.PreAction } if ($currentContext.config.taskNameFormat -is [ScriptBlock]) { & $currentContext.config.taskNameFormat $taskName } else { Write-ColoredOutput ($currentContext.config.taskNameFormat -f $taskName) -foregroundcolor Cyan } foreach ($variable in $task.requiredVariables) { Assert ((test-path "variable:$variable") -and ((get-variable $variable).Value -ne $null)) ($msgs.required_variable_not_set -f $variable, $taskName) } & $task.Action if ($task.PostAction) { & $task.PostAction } & $currentContext.taskTearDownScriptBlock $task.Duration = $stopwatch.Elapsed } catch { if ($task.ContinueOnError) { "-"*70 Write-ColoredOutput ($msgs.continue_on_error -f $taskName,$_) -foregroundcolor Yellow "-"*70 $task.Duration = $stopwatch.Elapsed } else { throw $_ } } } else { # no action was specified but we still execute all the dependencies foreach($childTask in $task.DependsOn) { Invoke-Task $childTask } } } else { foreach($childTask in $task.DependsOn) { Invoke-Task $childTask } } Assert (& $task.Postcondition) ($msgs.postcondition_failed -f $taskName) } $poppedTaskKey = $currentContext.callStack.Pop() Assert ($poppedTaskKey -eq $taskKey) ($msgs.error_corrupt_callstack -f $taskKey,$poppedTaskKey) $currentContext.executedTasks.Push($taskKey) } # .ExternalHelp psake.psm1-help.xml function Exec { [CmdletBinding()] param( [Parameter(Position=0,Mandatory=1)][scriptblock]$cmd, [Parameter(Position=1,Mandatory=0)][string]$errorMessage = ($msgs.error_bad_command -f $cmd) ) & $cmd if ($lastexitcode -ne 0) { throw ("Exec: " + $errorMessage) } } # .ExternalHelp psake.psm1-help.xml function Assert { [CmdletBinding()] param( [Parameter(Position=0,Mandatory=1)]$conditionToCheck, [Parameter(Position=1,Mandatory=1)]$failureMessage ) if (!$conditionToCheck) { throw ("Assert: " + $failureMessage) } } # .ExternalHelp psake.psm1-help.xml function Task { [CmdletBinding()] param( [Parameter(Position=0,Mandatory=1)][string]$name = $null, [Parameter(Position=1,Mandatory=0)][scriptblock]$action = $null, [Parameter(Position=2,Mandatory=0)][scriptblock]$preaction = $null, [Parameter(Position=3,Mandatory=0)][scriptblock]$postaction = $null, [Parameter(Position=4,Mandatory=0)][scriptblock]$precondition = {$true}, [Parameter(Position=5,Mandatory=0)][scriptblock]$postcondition = {$true}, [Parameter(Position=6,Mandatory=0)][switch]$continueOnError = $false, [Parameter(Position=7,Mandatory=0)][string[]]$depends = @(), [Parameter(Position=8,Mandatory=0)][string[]]$requiredVariables = @(), [Parameter(Position=9,Mandatory=0)][string]$description = $null, [Parameter(Position=10,Mandatory=0)][string]$alias = $null ) if ($name -eq 'default') { Assert (!$action) ($msgs.error_default_task_cannot_have_action) } $newTask = @{ Name = $name DependsOn = $depends PreAction = $preaction Action = $action PostAction = $postaction Precondition = $precondition Postcondition = $postcondition ContinueOnError = $continueOnError Description = $description Duration = [System.TimeSpan]::Zero RequiredVariables = $requiredVariables Alias = $alias } $taskKey = $name.ToLower() $currentContext = $psake.context.Peek() Assert (!$currentContext.tasks.ContainsKey($taskKey)) ($msgs.error_duplicate_task_name -f $name) $currentContext.tasks.$taskKey = $newTask if($alias) { $aliasKey = $alias.ToLower() Assert (!$currentContext.aliases.ContainsKey($aliasKey)) ($msgs.error_duplicate_alias_name -f $alias) $currentContext.aliases.$aliasKey = $newTask } } # .ExternalHelp psake.psm1-help.xml function Properties { [CmdletBinding()] param( [Parameter(Position=0,Mandatory=1)][scriptblock]$properties ) $psake.context.Peek().properties += $properties } # .ExternalHelp psake.psm1-help.xml function Include { [CmdletBinding()] param( [Parameter(Position=0,Mandatory=1)][string]$fileNamePathToInclude ) Assert (test-path $fileNamePathToInclude -pathType Leaf) ($msgs.error_invalid_include_path -f $fileNamePathToInclude) $psake.context.Peek().includes.Enqueue((Resolve-Path $fileNamePathToInclude)); } # .ExternalHelp psake.psm1-help.xml function FormatTaskName { [CmdletBinding()] param( [Parameter(Position=0,Mandatory=1)]$format ) $psake.context.Peek().config.taskNameFormat = $format } # .ExternalHelp psake.psm1-help.xml function TaskSetup { [CmdletBinding()] param( [Parameter(Position=0,Mandatory=1)][scriptblock]$setup ) $psake.context.Peek().taskSetupScriptBlock = $setup } # .ExternalHelp psake.psm1-help.xml function TaskTearDown { [CmdletBinding()] param( [Parameter(Position=0,Mandatory=1)][scriptblock]$teardown ) $psake.context.Peek().taskTearDownScriptBlock = $teardown } # .ExternalHelp psake.psm1-help.xml function Framework { [CmdletBinding()] param( [Parameter(Position=0,Mandatory=1)][string]$framework ) $psake.context.Peek().config.framework = $framework } # .ExternalHelp psake.psm1-help.xml function Invoke-psake { [CmdletBinding()] param( [Parameter(Position = 0, Mandatory = 0)][string] $buildFile, [Parameter(Position = 1, Mandatory = 0)][string[]] $taskList = @(), [Parameter(Position = 2, Mandatory = 0)][string] $framework, [Parameter(Position = 3, Mandatory = 0)][switch] $docs = $false, [Parameter(Position = 4, Mandatory = 0)][hashtable] $parameters = @{}, [Parameter(Position = 5, Mandatory = 0)][hashtable] $properties = @{}, [Parameter(Position = 6, Mandatory = 0)][alias("init")][scriptblock] $initialization = {}, [Parameter(Position = 7, Mandatory = 0)][switch] $nologo = $false ) try { if (-not $nologo) { "psake version {0}`nCopyright (c) 2010 James Kovacs`n" -f $psake.version } # If the default.ps1 file exists and the given "buildfile" isn 't found assume that the given # $buildFile is actually the target Tasks to execute in the default.ps1 script. if ($buildFile -and !(test-path $buildFile -pathType Leaf) -and (test-path $psake.config_default.buildFileName -pathType Leaf)) { $taskList = $buildFile.Split(', ') $buildFile = $psake.config_default.buildFileName } # Execute the build file to set up the tasks and defaults Assert (test-path $buildFile -pathType Leaf) ($msgs.error_build_file_not_found -f $buildFile) $psake.build_script_file = get-item $buildFile $psake.build_script_dir = $psake.build_script_file.DirectoryName $psake.build_success = $false $psake.context.push(@{ "taskSetupScriptBlock" = {}; "taskTearDownScriptBlock" = {}; "executedTasks" = new-object System.Collections.Stack; "callStack" = new-object System.Collections.Stack; "originalEnvPath" = $env:path; "originalDirectory" = get-location; "originalErrorActionPreference" = $global:ErrorActionPreference; "tasks" = @{}; "aliases" = @{}; "properties" = @(); "includes" = new-object System.Collections.Queue; "config" = Create-ConfigurationForNewContext $buildFile $framework }) Load-Configuration $psake.build_script_dir Load-Modules $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() set-location $psake.build_script_dir $frameworkOldValue = $framework . $psake.build_script_file.FullName $currentContext = $psake.context.Peek() if ($framework -ne $frameworkOldValue) { write-coloredoutput $msgs.warning_deprecated_framework_variable -foregroundcolor Yellow $currentContext.config.framework = $framework } if ($docs) { Write-Documentation Cleanup-Environment return } Configure-BuildEnvironment while ($currentContext.includes.Count -gt 0) { $includeFilename = $currentContext.includes.Dequeue() . $includeFilename } foreach ($key in $parameters.keys) { if (test-path "variable:\$key") { set-item -path "variable:\$key" -value $parameters.$key | out-null } else { new-item -path "variable:\$key" -value $parameters.$key | out-null } } # The initial dot (.) indicates that variables initialized/modified in the propertyBlock are available in the parent scope. foreach ($propertyBlock in $currentContext.properties) { . $propertyBlock } foreach ($key in $properties.keys) { if (test-path "variable:\$key") { set-item -path "variable:\$key" -value $properties.$key | out-null } } # Simple dot sourcing will not work. We have to force the script block into our # module's scope in order to initialize variables properly. . $MyInvocation.MyCommand.Module $initialization # Execute the list of tasks or the default task if ($taskList) { foreach ($task in $taskList) { invoke-task $task } } elseif ($currentContext.tasks.default) { invoke-task default } else { throw $msgs.error_no_default_task } Write-ColoredOutput ("`n" + $msgs.build_success + "`n") -foregroundcolor Green Write-TaskTimeSummary $stopwatch.Elapsed $psake.build_success = $true } catch { $currentConfig = Get-CurrentConfigurationOrDefault if ($currentConfig.verboseError) { $error_message = "{0}: An Error Occurred. See Error Details Below: `n" -f (Get-Date) $error_message += ("-" * 70) + "`n" $error_message += Resolve-Error $_ $error_message += ("-" * 70) + "`n" $error_message += "Script Variables" + "`n" $error_message += ("-" * 70) + "`n" $error_message += get-variable -scope script | format-table | out-string } else { # ($_ | Out-String) gets error messages with source information included. $error_message = "{0}: An Error Occurred: `n{1}" -f (Get-Date), ($_ | Out-String) } $psake.build_success = $false if (!$psake.run_by_psake_build_tester) { # if we are running in a nested scope (i.e. running a psake script from a psake script) then we need to re-throw the exception # so that the parent script will fail otherwise the parent script will report a successful build $inNestedScope = ($psake.context.count -gt 1) if ( $inNestedScope ) { throw $_ } else { Write-ColoredOutput $error_message -foregroundcolor Red } } } finally { Cleanup-Environment } } #-- Private Module Functions --# function Write-ColoredOutput { param( [string] $message, [System.ConsoleColor] $foregroundcolor ) $currentConfig = Get-CurrentConfigurationOrDefault if ($currentConfig.coloredOutput -eq $true) { if (($Host.UI -ne $null) -and ($Host.UI.RawUI -ne $null)) { $previousColor = $Host.UI.RawUI.ForegroundColor $Host.UI.RawUI.ForegroundColor = $foregroundcolor } } $message if ($previousColor -ne $null) { $Host.UI.RawUI.ForegroundColor = $previousColor } } function Load-Modules { $currentConfig = $psake.context.peek().config if ($currentConfig.modules) { $scope = $currentConfig.moduleScope $global = [string]::Equals($scope, "global", [StringComparison]::CurrentCultureIgnoreCase) $currentConfig.modules | foreach { resolve-path $_ | foreach { "Loading module: $_" $module = import-module $_ -passthru -DisableNameChecking -global:$global if (!$module) { throw ($msgs.error_loading_module -f $_.Name) } } } "" } } function Load-Configuration { param( [string] $configdir = $PSScriptRoot ) $psakeConfigFilePath = (join-path $configdir "psake-config.ps1") if (test-path $psakeConfigFilePath -pathType Leaf) { try { $config = Get-CurrentConfigurationOrDefault . $psakeConfigFilePath } catch { throw "Error Loading Configuration from psake-config.ps1: " + $_ } } } function Get-CurrentConfigurationOrDefault() { if ($psake.context.count -gt 0) { return $psake.context.peek().config } else { return $psake.config_default } } function Create-ConfigurationForNewContext { param( [string] $buildFile, [string] $framework ) $previousConfig = Get-CurrentConfigurationOrDefault $config = new-object psobject -property @{ buildFileName = $previousConfig.buildFileName; framework = $previousConfig.framework; taskNameFormat = $previousConfig.taskNameFormat; verboseError = $previousConfig.verboseError; coloredOutput = $previousConfig.coloredOutput; modules = $previousConfig.modules; moduleScope = $previousConfig.moduleScope; } if ($framework) { $config.framework = $framework; } if ($buildFile) { $config.buildFileName = $buildFile; } return $config } function Configure-BuildEnvironment { $framework = $psake.context.peek().config.framework if ($framework.Length -ne 3 -and $framework.Length -ne 6) { throw ($msgs.error_invalid_framework -f $framework) } $versionPart = $framework.Substring(0, 3) $bitnessPart = $framework.Substring(3) $versions = $null switch ($versionPart) { '1.0' { $versions = @('v1.0.3705') } '1.1' { $versions = @('v1.1.4322') } '2.0' { $versions = @('v2.0.50727') } '3.0' { $versions = @('v2.0.50727') } '3.5' { $versions = @('v3.5', 'v2.0.50727') } '4.0' { $versions = @('v4.0.30319') } default { throw ($msgs.error_unknown_framework -f $versionPart, $framework) } } $bitness = 'Framework' if ($versionPart -ne '1.0' -and $versionPart -ne '1.1') { switch ($bitnessPart) { 'x86' { $bitness = 'Framework' } 'x64' { $bitness = 'Framework64' } { [string]::IsNullOrEmpty($_) } { $ptrSize = [System.IntPtr]::Size switch ($ptrSize) { 4 { $bitness = 'Framework' } 8 { $bitness = 'Framework64' } default { throw ($msgs.error_unknown_pointersize -f $ptrSize) } } } default { throw ($msgs.error_unknown_bitnesspart -f $bitnessPart, $framework) } } } $frameworkDirs = $versions | foreach { "$env:windir\Microsoft.NET\$bitness\$_\" } $frameworkDirs | foreach { Assert (test-path $_ -pathType Container) ($msgs.error_no_framework_install_dir_found -f $_)} $env:path = ($frameworkDirs -join ";") + ";$env:path" # if any error occurs in a PS function then "stop" processing immediately # this does not effect any external programs that return a non-zero exit code $global:ErrorActionPreference = "Stop" } function Cleanup-Environment { if ($psake.context.Count -gt 0) { $currentContext = $psake.context.Peek() $env:path = $currentContext.originalEnvPath Set-Location $currentContext.originalDirectory $global:ErrorActionPreference = $currentContext.originalErrorActionPreference [void] $psake.context.Pop() } } # borrowed from Jeffrey Snover http://blogs.msdn.com/powershell/archive/2006/12/07/resolve-error.aspx function Resolve-Error($ErrorRecord = $Error[0]) { $error_message = "`nErrorRecord:{0}ErrorRecord.InvocationInfo:{1}Exception:{2}" $formatted_errorRecord = $ErrorRecord | format-list * -force | out-string $formatted_invocationInfo = $ErrorRecord.InvocationInfo | format-list * -force | out-string $formatted_exception = "" $Exception = $ErrorRecord.Exception for ($i = 0; $Exception; $i++, ($Exception = $Exception.InnerException)) { $formatted_exception += ("$i" * 70) + "`n" $formatted_exception += $Exception | format-list * -force | out-string $formatted_exception += "`n" } return $error_message -f $formatted_errorRecord, $formatted_invocationInfo, $formatted_exception } function Write-Documentation { $currentContext = $psake.context.Peek() if ($currentContext.tasks.default) { $defaultTaskDependencies = $currentContext.tasks.default.DependsOn } else { $defaultTaskDependencies = @() } $currentContext.tasks.Keys | foreach-object { if ($_ -eq "default") { return } $task = $currentContext.tasks.$_ new-object PSObject -property @{ Name = $task.Name; Description = $task.Description; "Depends On" = $task.DependsOn -join ", " Default = if ($defaultTaskDependencies -contains $task.Name) { $true } } } | sort 'Name' | format-table -autoSize -property Name,Description,"Depends On",Default } function Write-TaskTimeSummary($invokePsakeDuration) { "-" * 70 "Build Time Report" "-" * 70 $list = @() $currentContext = $psake.context.Peek() while ($currentContext.executedTasks.Count -gt 0) { $taskKey = $currentContext.executedTasks.Pop() $task = $currentContext.tasks.$taskKey if ($taskKey -eq "default") { continue } $list += new-object PSObject -property @{ Name = $task.Name; Duration = $task.Duration } } [Array]::Reverse($list) $list += new-object PSObject -property @{ Name = "Total:"; Duration = $invokePsakeDuration } # using "out-string | where-object" to filter out the blank line that format-table prepends $list | format-table -autoSize -property Name,Duration | out-string -stream | where-object { $_ } } DATA msgs { convertfrom-stringdata @' error_invalid_task_name = Task name should not be null or empty string. error_task_name_does_not_exist = Task {0} does not exist. error_circular_reference = Circular reference found for task {0}. error_missing_action_parameter = Action parameter must be specified when using PreAction or PostAction parameters for task {0}. error_corrupt_callstack = Call stack was corrupt. Expected {0}, but got {1}. error_invalid_framework = Invalid .NET Framework version, {0} specified. error_unknown_framework = Unknown .NET Framework version, {0} specified in {1}. error_unknown_pointersize = Unknown pointer size ({0}) returned from System.IntPtr. error_unknown_bitnesspart = Unknown .NET Framework bitness, {0}, specified in {1}. error_no_framework_install_dir_found = No .NET Framework installation directory found at {0}. error_bad_command = Error executing command {0}. error_default_task_cannot_have_action = 'default' task cannot specify an action. error_duplicate_task_name = Task {0} has already been defined. error_duplicate_alias_name = Alias {0} has already been defined. error_invalid_include_path = Unable to include {0}. File not found. error_build_file_not_found = Could not find the build file {0}. error_no_default_task = 'default' task required. error_loading_module = Error loading module {0}. warning_deprecated_framework_variable = Warning: Using global variable $framework to set .NET framework version used is deprecated. Instead use Framework function or configuration file psake-config.ps1. required_variable_not_set = Variable {0} must be set to run task {1}. postcondition_failed = Postcondition failed for task {0}. precondition_was_false = Precondition was false, not executing task {0}. continue_on_error = Error in task {0}. {1} build_success = Build Succeeded! '@ } import-localizeddata -bindingvariable msgs -erroraction silentlycontinue $script:psake = @{} $psake.version = "4.1.0" # contains the current version of psake $psake.context = new-object system.collections.stack # holds onto the current state of all variables $psake.run_by_psake_build_tester = $false # indicates that build is being run by psake-BuildTester $psake.config_default = new-object psobject -property @{ buildFileName = "default.ps1"; framework = "4.0"; taskNameFormat = "Executing {0}"; verboseError = $false; coloredOutput = $true; modules = $null; moduleScope = "local"; } # contains default configuration, can be overriden in psake-config.ps1 in directory with psake.psm1 or in directory with current build script $psake.build_success = $false # indicates that the current build was successful $psake.build_script_file = $null # contains a System.IO.FileInfo for the current build script $psake.build_script_dir = "" # contains a string with fully-qualified path to current build script Load-Configuration export-modulemember -function invoke-psake, invoke-task, task, properties, include, formattaskname, tasksetup, taskteardown, framework, assert, exec -variable psake
deltatre-webplu/NEventStore.Persistence.MongoDB
build/psake.psm1
PowerShell
mit
25,682
alert("foo!");
beni55/unfiltered
netty-server/src/test/resources/files/foo.js
JavaScript
mit
14
/* Copyright (C) 2011 by Ivan Safrin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "PolyCollisionScene.h" #include "PolyCollisionSceneEntity.h" #include "PolyEntity.h" using namespace Polycode; CollisionScene::CollisionScene(Vector3 size, bool virtualScene, bool deferInitCollision) : Scene(Scene::SCENE_3D, virtualScene), world(NULL), collisionConfiguration(NULL), dispatcher(NULL), axisSweep(NULL) { if(!deferInitCollision) { initCollisionScene(size); } } void CollisionScene::initCollisionScene(Vector3 size) { btVector3 worldAabbMin(-size.x * 0.5, -size.y * 0.5, -size.z * 0.5); btVector3 worldAabbMax(size.x * 0.5, size.y * 0.5, size.z * 0.5); collisionConfiguration = new btDefaultCollisionConfiguration(); dispatcher = new btCollisionDispatcher(collisionConfiguration); // dispatcher->setNearCallback(customNearCallback); axisSweep = new btAxisSweep3(worldAabbMin,worldAabbMax); world = new btCollisionWorld(dispatcher,axisSweep,collisionConfiguration); } void CollisionScene::fixedUpdate() { for(int i=0; i < collisionChildren.size(); i++) { if(collisionChildren[i]->enabled) collisionChildren[i]->Update(); } world->performDiscreteCollisionDetection(); for(int i=0; i < collisionChildren.size(); i++) { if(collisionChildren[i]->enabled) collisionChildren[i]->lastPosition = collisionChildren[i]->getEntity()->getPosition(); } Scene::fixedUpdate(); } void CollisionScene::enableCollision(Entity *entity, bool val) { CollisionEntity *cEnt = getCollisionByScreenEntity(entity); if(cEnt) { cEnt->enabled = val; } } void CollisionScene::adjustForCollision(CollisionEntity *collisionEntity) { CollisionResult result; // Number elapsed = CoreServices::getInstance()->getCore()->getElapsed(); result.collided = false; for(int i=0; i < collisionChildren.size(); i++) { if(collisionChildren[i] != collisionEntity) { result = testCollisionOnCollisionChild(collisionEntity, collisionChildren[i]); if(result.collided) { if(result.setOldPosition) { collisionEntity->getEntity()->setPosition(result.newPos); } else { collisionEntity->getEntity()->Translate(result.colNormal.x*result.colDist, result.colNormal.y*result.colDist, result.colNormal.z*result.colDist); } } } } } CollisionEntity *CollisionScene::getCollisionByScreenEntity(Entity *ent) { for(int i=0; i<collisionChildren.size();i++) { if(collisionChildren[i]->getEntity() == ent) return collisionChildren[i]; } return NULL; } bool CollisionScene::isColliding(Entity *ent1) { CollisionEntity *cEnt1 = getCollisionByScreenEntity(ent1); if(cEnt1) { int numManifolds = world->getDispatcher()->getNumManifolds(); for (int i=0;i<numManifolds;i++) { btPersistentManifold* contactManifold = world->getDispatcher()->getManifoldByIndexInternal(i); btCollisionObject* obA = (btCollisionObject*)contactManifold->getBody0(); btCollisionObject* obB = (btCollisionObject*)contactManifold->getBody1(); if(obA == cEnt1->collisionObject || obB == cEnt1->collisionObject) { return true; } } } else { return false; } return false; } CollisionResult CollisionScene::testCollisionOnCollisionChild_Convex(CollisionEntity *cEnt1, CollisionEntity *cEnt2) { CollisionResult result; result.collided = false; result.setOldPosition = false; Vector3 collNormal; result.colNormal.set(0,0,0); result.colDist = 0; int numAdds = 0; int numManifolds = world->getDispatcher()->getNumManifolds(); for (int i=0;i<numManifolds;i++) { btPersistentManifold* contactManifold = world->getDispatcher()->getManifoldByIndexInternal(i); btCollisionObject* obA = (btCollisionObject*)contactManifold->getBody0(); btCollisionObject* obB = (btCollisionObject*)contactManifold->getBody1(); if((obA == cEnt1->collisionObject && obB == cEnt2->collisionObject) || (obA == cEnt2->collisionObject && obB == cEnt1->collisionObject)) { // contactManifold->refreshContactPoints(obA->getWorldTransform(), obB->getWorldTransform()); if(contactManifold->getNumContacts() > 0) { for(int j=0; j < contactManifold->getNumContacts(); j++) { if(contactManifold->getContactPoint(j).getDistance() <= btScalar(0.0)) { btVector3 vec = contactManifold->getContactPoint(j).m_normalWorldOnB; result.colNormal += Vector3(vec.getX(), vec.getY(), vec.getZ()); result.colDist += contactManifold->getContactPoint(j).getDistance(); numAdds++; } } // btVector3 vec = contactManifold->getContactPoint(0).m_normalWorldOnB; // result.colNormal.set(vec.getX(), vec.getY(), vec.getZ()); // result.colDist = contactManifold->getContactPoint(0).getDistance(); result.collided = true; } } } if(numAdds > 0) { result.colNormal = result.colNormal / (Number)numAdds; // result.colNormal = Vector3(0,1,0); // result.colNormal.Normalize(); result.colDist = result.colDist / (Number)numAdds; } return result; // return cEnt1->collisionObject->checkCollideWith(cEnt2->collisionObject); } RayTestResult CollisionScene::getFirstEntityInRay(const Vector3 &origin, const Vector3 &dest) { RayTestResult ret; ret.entity = NULL; btVector3 fromVec(origin.x, origin.y, origin.z); btVector3 toVec(dest.x, dest.y, dest.z); btCollisionWorld::ClosestRayResultCallback cb(fromVec, toVec); world->rayTest (fromVec, toVec, cb); if (cb.hasHit ()) { CollisionEntity *retEnt = getCollisionEntityByObject((btCollisionObject*)cb.m_collisionObject); if(retEnt) { ret.entity = retEnt->getEntity(); ret.position = Vector3(cb.m_hitPointWorld.getX(), cb.m_hitPointWorld.getY(), cb.m_hitPointWorld.getZ()); ret.normal = Vector3(cb.m_hitNormalWorld.getX(), cb.m_hitNormalWorld.getY(), cb.m_hitNormalWorld.getZ()); return ret; } } return ret; } CollisionEntity *CollisionScene::getCollisionEntityByObject(btCollisionObject *collisionObject) { return (CollisionEntity*)collisionObject->getUserPointer(); } CollisionResult CollisionScene::testCollisionOnCollisionChild(CollisionEntity *cEnt1, CollisionEntity *cEnt2) { return testCollisionOnCollisionChild_Convex(cEnt1, cEnt2); } CollisionResult CollisionScene::testCollision(Entity *ent1, Entity *ent2) { CollisionEntity *cEnt1 = getCollisionByScreenEntity(ent1); CollisionEntity *cEnt2 = getCollisionByScreenEntity(ent2); CollisionResult result; result.collided = false; if(cEnt1 == NULL || cEnt2 == NULL) return result; return testCollisionOnCollisionChild(cEnt1, cEnt2); } CollisionScene::~CollisionScene() { for(int i=0; i < collisionChildren.size(); i++) { delete collisionChildren[i]; } delete world; delete axisSweep; delete dispatcher; delete collisionConfiguration; } void CollisionScene::removeCollision(Entity *entity) { CollisionEntity *cEnt = getCollisionByScreenEntity(entity); if(cEnt) { world->removeCollisionObject(cEnt->collisionObject); for(int i=0; i < collisionChildren.size(); i++) { if(collisionChildren[i] == cEnt) { std::vector<CollisionEntity*>::iterator target = collisionChildren.begin()+i; delete *target; collisionChildren.erase(target); } } } } void CollisionScene::removeEntity(Entity *entity) { if(getCollisionByScreenEntity(entity)) { removeCollision(entity); } Scene::removeEntity(entity); } CollisionEntity *CollisionScene::trackCollision(Entity *newEntity, int type, int group) { CollisionEntity *newCollisionEntity = new CollisionEntity(newEntity, type); // if(type == CollisionEntity::CHARACTER_CONTROLLER) { // world->addCollisionObject(newCollisionEntity->collisionObject,btBroadphaseProxy::CharacterFilter, btBroadphaseProxy::StaticFilter|btBroadphaseProxy::DefaultFilter); // } else { newCollisionEntity->collisionObject->setCollisionFlags(btCollisionObject::CF_NO_CONTACT_RESPONSE); world->addCollisionObject(newCollisionEntity->collisionObject, group); // } collisionChildren.push_back(newCollisionEntity); return newCollisionEntity; } CollisionEntity *CollisionScene::addCollisionChild(Entity *newEntity, int type, int group) { addEntity(newEntity); return trackCollision(newEntity, type, group); }
carlosmarti/Polycode
src/modules/physics3D/PolyCollisionScene.cpp
C++
mit
9,249
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // ==++== // // // ==--== #ifndef __util_h__ #define __util_h__ #define LIMITED_METHOD_CONTRACT // So we can use the PAL_TRY_NAKED family of macros without dependencies on utilcode. inline void RestoreSOToleranceState() {} #include <cor.h> #include <corsym.h> #include <clrdata.h> #include <palclr.h> #include <metahost.h> #include <new> #if !defined(FEATURE_PAL) #include <dia2.h> #endif #ifdef STRIKE #if defined(_MSC_VER) #pragma warning(disable:4200) #pragma warning(default:4200) #endif #include "data.h" #endif //STRIKE #include "cordebug.h" #include "static_assert.h" typedef LPCSTR LPCUTF8; typedef LPSTR LPUTF8; DECLARE_HANDLE(OBJECTHANDLE); struct IMDInternalImport; #if defined(_TARGET_WIN64_) #define WIN64_8SPACES "" #define WIN86_8SPACES " " #define POINTERSIZE "16" #define POINTERSIZE_HEX 16 #define POINTERSIZE_BYTES 8 #define POINTERSIZE_TYPE "I64" #else #define WIN64_8SPACES " " #define WIN86_8SPACES "" #define POINTERSIZE "8" #define POINTERSIZE_HEX 8 #define POINTERSIZE_BYTES 4 #define POINTERSIZE_TYPE "I32" #endif #if defined(_MSC_VER) #pragma warning(disable:4510 4512 4610) #endif #ifndef _ASSERTE #ifdef _DEBUG #define _ASSERTE(expr) \ do { if (!(expr) ) { ExtErr("_ASSERTE fired:\n\t%s\n", #expr); if (IsDebuggerPresent()) DebugBreak(); } } while (0) #else #define _ASSERTE(x) #endif #endif // ASSERTE #ifdef _DEBUG #define ASSERT_CHECK(expr, msg, reason) \ do { if (!(expr) ) { ExtOut(reason); ExtOut(msg); ExtOut(#expr); DebugBreak(); } } while (0) #endif // PREFIX macros - Begin // SOS does not have support for Contracts. Therefore we needed to duplicate // some of the PREFIX infrastructure from inc\check.h in here. // Issue - PREFast_:510 v4.51 does not support __assume(0) #if (defined(_MSC_VER) && !defined(_PREFAST_)) || defined(_PREFIX_) #if defined(_AMD64_) // Empty methods that consist of UNREACHABLE() result in a zero-sized declspec(noreturn) method // which causes the pdb file to make the next method declspec(noreturn) as well, thus breaking BBT // Remove when we get a VC compiler that fixes VSW 449170 # define __UNREACHABLE() DebugBreak(); __assume(0); #else # define __UNREACHABLE() __assume(0) #endif #else #define __UNREACHABLE() do { } while(true) #endif #if defined(_PREFAST_) || defined(_PREFIX_) #define COMPILER_ASSUME_MSG(_condition, _message) if (!(_condition)) __UNREACHABLE(); #else #if defined(DACCESS_COMPILE) #define COMPILER_ASSUME_MSG(_condition, _message) do { } while (0) #else #if defined(_DEBUG) #define COMPILER_ASSUME_MSG(_condition, _message) \ ASSERT_CHECK(_condition, _message, "Compiler optimization assumption invalid") #else #define COMPILER_ASSUME_MSG(_condition, _message) __assume(_condition) #endif // _DEBUG #endif // DACCESS_COMPILE #endif // _PREFAST_ || _PREFIX_ #define PREFIX_ASSUME(_condition) \ COMPILER_ASSUME_MSG(_condition, "") // PREFIX macros - End class MethodTable; #define MD_NOT_YET_LOADED ((DWORD_PTR)-1) /* * HANDLES * * The default type of handle is a strong handle. * */ #define HNDTYPE_DEFAULT HNDTYPE_STRONG #define HNDTYPE_WEAK_DEFAULT HNDTYPE_WEAK_LONG #define HNDTYPE_WEAK_SHORT (0) #define HNDTYPE_WEAK_LONG (1) #define HNDTYPE_STRONG (2) #define HNDTYPE_PINNED (3) #define HNDTYPE_VARIABLE (4) #define HNDTYPE_REFCOUNTED (5) #define HNDTYPE_DEPENDENT (6) #define HNDTYPE_ASYNCPINNED (7) #define HNDTYPE_SIZEDREF (8) #define HNDTYPE_WEAK_WINRT (9) // Anything above this we consider abnormal and stop processing heap information const int nMaxHeapSegmentCount = 1000; class BaseObject { MethodTable *m_pMethTab; }; const BYTE gElementTypeInfo[] = { #define TYPEINFO(e,ns,c,s,g,ia,ip,if,im,gv) s, #include "cortypeinfo.h" #undef TYPEINFO }; typedef struct tagLockEntry { tagLockEntry *pNext; // next entry tagLockEntry *pPrev; // prev entry DWORD dwULockID; DWORD dwLLockID; // owning lock WORD wReaderLevel; // reader nesting level } LockEntry; #define MAX_CLASSNAME_LENGTH 1024 enum EEFLAVOR {UNKNOWNEE, MSCOREE, MSCORWKS, MSCOREND}; #include "sospriv.h" extern IXCLRDataProcess *g_clrData; extern ISOSDacInterface *g_sos; #include "dacprivate.h" interface ICorDebugProcess; extern ICorDebugProcess * g_pCorDebugProcess; // This class is templated for easy modification. We may need to update the CachedString // or related classes to use WCHAR instead of char in the future. template <class T, int count, int size> class StaticData { public: StaticData() { for (int i = 0; i < count; ++i) InUse[i] = false; } // Whether the individual data pointers in the cache are in use. bool InUse[count]; // The actual data itself. T Data[count][size]; // The number of arrays in the cache. static const int Count; // The size of each individual array. static const int Size; }; class CachedString { public: CachedString(); CachedString(const CachedString &str); ~CachedString(); const CachedString &operator=(const CachedString &str); // Returns the capacity of this string. size_t GetStrLen() const { return mSize; } // Returns a mutable character pointer. Be sure not to write past the // length of this string. inline operator char *() { return mPtr; } // Returns a const char representation of this string. inline operator const char *() const { return GetPtr(); } // To ensure no AV's, any time a constant pointer is requested, we will // return an empty string "" if we hit an OOM. This will only happen // if we hit an OOM and do not check for it before using the string. // If you request a non-const char pointer out of this class, it may be // null (see operator char *). inline const char *GetPtr() const { if (!mPtr || IsOOM()) return ""; return mPtr; } // Returns true if we ran out of memory trying to allocate the string // or the refcount. bool IsOOM() const { return mIndex == -2; } // allocate a string of the specified size. this will Clear() any // previously allocated string. call IsOOM() to check for failure. void Allocate(int size); private: // Copies rhs into this string. void Copy(const CachedString &rhs); // Clears this string, releasing any underlying memory. void Clear(); // Creates a new string. void Create(); // Sets an out of memory state. void SetOOM(); private: char *mPtr; // The reference count. This may be null if there is only one copy // of this string. mutable unsigned int *mRefCount; // mIndex contains the index of the cached pointer we are using, or: // ~0 - poison value we initialize it to for debugging purposes // -1 - mPtr points to a pointer we have new'ed // -2 - We hit an oom trying to allocate either mCount or mPtr int mIndex; // contains the size of current string int mSize; private: static StaticData<char, 4, 1024> cache; }; // Things in this namespace should not be directly accessed/called outside of // the output-related functions. namespace Output { extern unsigned int g_bSuppressOutput; extern unsigned int g_Indent; extern unsigned int g_DMLEnable; extern bool g_bDbgOutput; extern bool g_bDMLExposed; inline bool IsOutputSuppressed() { return g_bSuppressOutput > 0; } inline void ResetIndent() { g_Indent = 0; } inline void SetDebugOutputEnabled(bool enabled) { g_bDbgOutput = enabled; } inline bool IsDebugOutputEnabled() { return g_bDbgOutput; } inline void SetDMLExposed(bool exposed) { g_bDMLExposed = exposed; } inline bool IsDMLExposed() { return g_bDMLExposed; } enum FormatType { DML_None, DML_MethodTable, DML_MethodDesc, DML_EEClass, DML_Module, DML_IP, DML_Object, DML_Domain, DML_Assembly, DML_ThreadID, DML_ValueClass, DML_DumpHeapMT, DML_ListNearObj, DML_ThreadState, DML_PrintException, DML_RCWrapper, DML_CCWrapper, DML_ManagedVar, }; /**********************************************************************\ * This function builds a DML string for a ValueClass. If DML is * * enabled, this function returns a DML string based on the format * * type. Otherwise this returns a string containing only the hex value * * of addr. * * * * Params: * * mt - the method table of the ValueClass * * addr - the address of the ValueClass * * type - the format type to use to output this object * * fill - whether or not to pad the hex value with zeros * * * \**********************************************************************/ CachedString BuildVCValue(CLRDATA_ADDRESS mt, CLRDATA_ADDRESS addr, FormatType type, bool fill = true); /**********************************************************************\ * This function builds a DML string for an object. If DML is enabled, * * this function returns a DML string based on the format type. * * Otherwise this returns a string containing only the hex value of * * addr. * * * * Params: * * addr - the address of the object * * type - the format type to use to output this object * * fill - whether or not to pad the hex value with zeros * * * \**********************************************************************/ CachedString BuildHexValue(CLRDATA_ADDRESS addr, FormatType type, bool fill = true); /**********************************************************************\ * This function builds a DML string for an managed variable name. * * If DML is enabled, this function returns a DML string that will * * enable the expansion of that managed variable using the !ClrStack * * command to display the variable's fields, otherwise it will just * * return the variable's name as a string. * * * Params: * * expansionName - the current variable expansion string * * frame - the frame that contains the variable of interest * * simpleName - simple name of the managed variable * * * \**********************************************************************/ CachedString BuildManagedVarValue(__in_z LPCWSTR expansionName, ULONG frame, __in_z LPCWSTR simpleName, FormatType type); CachedString BuildManagedVarValue(__in_z LPCWSTR expansionName, ULONG frame, int indexInArray, FormatType type); //used for array indices (simpleName = "[<indexInArray>]") } class NoOutputHolder { public: NoOutputHolder(BOOL bSuppress = TRUE); ~NoOutputHolder(); private: BOOL mSuppress; }; class EnableDMLHolder { public: EnableDMLHolder(BOOL enable); ~EnableDMLHolder(); private: BOOL mEnable; }; size_t CountHexCharacters(CLRDATA_ADDRESS val); // Normal output. void DMLOut(PCSTR format, ...); /* Prints out DML strings. */ void IfDMLOut(PCSTR format, ...); /* Prints given DML string ONLY if DML is enabled; prints nothing otherwise. */ void ExtOut(PCSTR Format, ...); /* Prints out to ExtOut (no DML). */ void ExtWarn(PCSTR Format, ...); /* Prints out to ExtWarn (no DML). */ void ExtErr(PCSTR Format, ...); /* Prints out to ExtErr (no DML). */ void ExtDbgOut(PCSTR Format, ...); /* Prints out to ExtOut in a checked build (no DML). */ void WhitespaceOut(int count); /* Prints out "count" number of spaces in the output. */ // Change indent for ExtOut inline void IncrementIndent() { Output::g_Indent++; } inline void DecrementIndent() { if (Output::g_Indent > 0) Output::g_Indent--; } inline void ExtOutIndent() { WhitespaceOut(Output::g_Indent << 2); } // DML Generation Methods #define DMLListNearObj(addr) Output::BuildHexValue(addr, Output::DML_ListNearObj).GetPtr() #define DMLDumpHeapMT(addr) Output::BuildHexValue(addr, Output::DML_DumpHeapMT).GetPtr() #define DMLMethodTable(addr) Output::BuildHexValue(addr, Output::DML_MethodTable).GetPtr() #define DMLMethodDesc(addr) Output::BuildHexValue(addr, Output::DML_MethodDesc).GetPtr() #define DMLClass(addr) Output::BuildHexValue(addr, Output::DML_EEClass).GetPtr() #define DMLModule(addr) Output::BuildHexValue(addr, Output::DML_Module).GetPtr() #define DMLIP(ip) Output::BuildHexValue(ip, Output::DML_IP).GetPtr() #define DMLObject(addr) Output::BuildHexValue(addr, Output::DML_Object).GetPtr() #define DMLDomain(addr) Output::BuildHexValue(addr, Output::DML_Domain).GetPtr() #define DMLAssembly(addr) Output::BuildHexValue(addr, Output::DML_Assembly).GetPtr() #define DMLThreadID(id) Output::BuildHexValue(id, Output::DML_ThreadID, false).GetPtr() #define DMLValueClass(mt, addr) Output::BuildVCValue(mt, addr, Output::DML_ValueClass).GetPtr() #define DMLRCWrapper(addr) Output::BuildHexValue(addr, Output::DML_RCWrapper).GetPtr() #define DMLCCWrapper(addr) Output::BuildHexValue(addr, Output::DML_CCWrapper).GetPtr() #define DMLManagedVar(expansionName,frame,simpleName) Output::BuildManagedVarValue(expansionName, frame, simpleName, Output::DML_ManagedVar).GetPtr() bool IsDMLEnabled(); #ifndef SOS_Assert #define SOS_Assert(x) #endif void ConvertToLower(__out_ecount(len) char *buffer, size_t len); extern const char * const DMLFormats[]; int GetHex(CLRDATA_ADDRESS addr, __out_ecount(len) char *out, size_t len, bool fill); // A simple string class for mutable strings. We cannot use STL, so this is a stand in replacement // for std::string (though it doesn't use the same interface). template <class T, size_t (__cdecl *LEN)(const T *), errno_t (__cdecl *COPY)(T *, size_t, const T * _Src)> class BaseString { public: BaseString() : mStr(0), mSize(0), mLength(0) { const size_t size = 64; mStr = new T[size]; mSize = size; mStr[0] = 0; } BaseString(const T *str) : mStr(0), mSize(0), mLength(0) { CopyFrom(str, LEN(str)); } BaseString(const BaseString<T, LEN, COPY> &rhs) : mStr(0), mSize(0), mLength(0) { *this = rhs; } ~BaseString() { Clear(); } const BaseString<T, LEN, COPY> &operator=(const BaseString<T, LEN, COPY> &rhs) { Clear(); CopyFrom(rhs.mStr, rhs.mLength); return *this; } const BaseString<T, LEN, COPY> &operator=(const T *str) { Clear(); CopyFrom(str, LEN(str)); return *this; } const BaseString<T, LEN, COPY> &operator +=(const T *str) { size_t len = LEN(str); CopyFrom(str, len); return *this; } const BaseString<T, LEN, COPY> &operator +=(const BaseString<T, LEN, COPY> &str) { CopyFrom(str.mStr, str.mLength); return *this; } BaseString<T, LEN, COPY> operator+(const T *str) const { return BaseString<T, LEN, COPY>(mStr, mLength, str, LEN(str)); } BaseString<T, LEN, COPY> operator+(const BaseString<T, LEN, COPY> &str) const { return BaseString<T, LEN, COPY>(mStr, mLength, str.mStr, str.mLength); } operator const T *() const { return mStr; } const T *c_str() const { return mStr; } size_t GetLength() const { return mLength; } private: BaseString(const T * str1, size_t len1, const T * str2, size_t len2) : mStr(0), mSize(0), mLength(0) { const size_t size = len1 + len2 + 1 + ((len1 + len2) >> 1); mStr = new T[size]; mSize = size; CopyFrom(str1, len1); CopyFrom(str2, len2); } void Clear() { mLength = 0; mSize = 0; if (mStr) { delete [] mStr; mStr = 0; } } void CopyFrom(const T *str, size_t len) { if (mLength + len + 1 >= mSize) Resize(mLength + len + 1); COPY(mStr+mLength, mSize-mLength, str); mLength += len; } void Resize(size_t size) { /* We always resize at least one half bigger than we need. When CopyFrom requests a resize * it asks for the exact size that's needed to concatenate strings. However in practice * it's common to add multiple strings together in a row, e.g.: * String foo = "One " + "Two " + "Three " + "Four " + "\n"; * Ensuring the size of the string is bigger than we need, and that the minimum size is 64, * we will cut down on a lot of needless resizes at the cost of a few bytes wasted in some * cases. */ size += size >> 1; if (size < 64) size = 64; T *newStr = new T[size]; if (mStr) { COPY(newStr, size, mStr); delete [] mStr; } else { newStr[0] = 0; } mStr = newStr; mSize = size; } private: T *mStr; size_t mSize, mLength; }; typedef BaseString<char, strlen, strcpy_s> String; typedef BaseString<WCHAR, _wcslen, wcscpy_s> WString; template<class T> void Flatten(__out_ecount(len) T *data, unsigned int len) { for (unsigned int i = 0; i < len; ++i) if (data[i] < 32 || (data[i] > 126 && data[i] <= 255)) data[i] = '.'; data[len] = 0; } void Flatten(__out_ecount(len) char *data, unsigned int len); /* Formats for the Format class. We support the following formats: * Pointer - Same as %p. * Hex - Same as %x (same as %p, but does not output preceding zeros. * PrefixHex - Same as %x, but prepends 0x. * Decimal - Same as %d. * Strings and wide strings don't use this. */ class Formats { public: enum Format { Default, Pointer, Hex, PrefixHex, Decimal, }; }; enum Alignment { AlignLeft, AlignRight }; namespace Output { /* Defines how a value will be printed. This class understands how to format * and print values according to the format and DML settings provided. * The raw templated class handles the pointer/integer case. Support for * character arrays and wide character arrays are handled by template * specializations. * * Note that this class is not used directly. Instead use the typedefs and * macros which define the type of data you are outputing (for example ObjectPtr, * MethodTablePtr, etc). */ template <class T> class Format { public: Format(T value) : mValue(value), mFormat(Formats::Default), mDml(Output::DML_None) { } Format(T value, Formats::Format format, Output::FormatType dmlType) : mValue(value), mFormat(format), mDml(dmlType) { } Format(const Format<T> &rhs) : mValue(rhs.mValue), mFormat(rhs.mFormat), mDml(rhs.mDml) { } /* Prints out the value according to the Format and DML settings provided. */ void Output() const { if (IsDMLEnabled() && mDml != Output::DML_None) { const int len = GetDMLWidth(mDml); char *buffer = (char*)alloca(len); BuildDML(buffer, len, (CLRDATA_ADDRESS)mValue, mFormat, mDml); DMLOut(buffer); } else { if (mFormat == Formats::Default || mFormat == Formats::Pointer) { ExtOut("%p", (__int64)mValue); } else { const char *format = NULL; if (mFormat == Formats::PrefixHex) { format = "0x%x"; } else if (mFormat == Formats::Hex) { format = "%x"; } else if (mFormat == Formats::Decimal) { format = "%d"; } ExtOut(format, (__int32)mValue); } } } /* Prints out the value based on a specified width and alignment. * Params: * align - Whether the output should be left or right justified. * width - The output width to fill. * Note: * This function guarantees that exactly width will be printed out (so if width is 24, * exactly 24 characters will be printed), even if the output wouldn't normally fit * in the space provided. This function makes no guarantees as to what part of the * data will be printed in the case that width isn't wide enough. */ void OutputColumn(Alignment align, int width) const { bool leftAlign = align == AlignLeft; if (IsDMLEnabled() && mDml != Output::DML_None) { const int len = GetDMLColWidth(mDml, width); char *buffer = (char*)alloca(len); BuildDMLCol(buffer, len, (CLRDATA_ADDRESS)mValue, mFormat, mDml, leftAlign, width); DMLOut(buffer); } else { int precision = GetPrecision(); if (mFormat == Formats::Default || mFormat == Formats::Pointer) { if (precision > width) precision = width; ExtOut(leftAlign ? "%-*.*p" : "%*.*p", width, precision, (__int64)mValue); } else { const char *format = NULL; if (mFormat == Formats::PrefixHex) { format = leftAlign ? "0x%-*.*x" : "0x%*.*x"; width -= 2; } else if (mFormat == Formats::Hex) { format = leftAlign ? "%-*.*x" : "%*.*x"; } else if (mFormat == Formats::Decimal) { format = leftAlign ? "%-*.*d" : "%*.*d"; } if (precision > width) precision = width; ExtOut(format, width, precision, (__int32)mValue); } } } /* Converts this object into a Wide char string. This allows you to write the following code: * WString foo = L"bar " + ObjectPtr(obj); * Where ObjectPtr is a subclass/typedef of this Format class. */ operator WString() const { String str = *this; const char *cstr = (const char *)str; int len = MultiByteToWideChar(CP_ACP, 0, cstr, -1, NULL, 0); WCHAR *buffer = (WCHAR *)alloca(len*sizeof(WCHAR)); MultiByteToWideChar(CP_ACP, 0, cstr, -1, buffer, len); return WString(buffer); } /* Converts this object into a String object. This allows you to write the following code: * String foo = "bar " + ObjectPtr(obj); * Where ObjectPtr is a subclass/typedef of this Format class. */ operator String() const { if (IsDMLEnabled() && mDml != Output::DML_None) { const int len = GetDMLColWidth(mDml, 0); char *buffer = (char*)alloca(len); BuildDMLCol(buffer, len, (CLRDATA_ADDRESS)mValue, mFormat, mDml, false, 0); return buffer; } else { char buffer[64]; if (mFormat == Formats::Default || mFormat == Formats::Pointer) { sprintf_s(buffer, _countof(buffer), "%p", (int *)(SIZE_T)mValue); ConvertToLower(buffer, _countof(buffer)); } else { const char *format = NULL; if (mFormat == Formats::PrefixHex) format = "0x%x"; else if (mFormat == Formats::Hex) format = "%x"; else if (mFormat == Formats::Decimal) format = "%d"; sprintf_s(buffer, _countof(buffer), format, (__int32)mValue); ConvertToLower(buffer, _countof(buffer)); } return buffer; } } private: int GetPrecision() const { if (mFormat == Formats::Hex || mFormat == Formats::PrefixHex) { ULONGLONG val = mValue; int count = 0; while (val) { val >>= 4; count++; } if (count == 0) count = 1; return count; } else if (mFormat == Formats::Decimal) { T val = mValue; int count = (val > 0) ? 0 : 1; while (val) { val /= 10; count++; } return count; } // mFormat == Formats::Pointer return sizeof(int*)*2; } static inline void BuildDML(__out_ecount(len) char *result, int len, CLRDATA_ADDRESS value, Formats::Format format, Output::FormatType dmlType) { BuildDMLCol(result, len, value, format, dmlType, true, 0); } static int GetDMLWidth(Output::FormatType dmlType) { return GetDMLColWidth(dmlType, 0); } static void BuildDMLCol(__out_ecount(len) char *result, int len, CLRDATA_ADDRESS value, Formats::Format format, Output::FormatType dmlType, bool leftAlign, int width) { char hex[64]; int count = GetHex(value, hex, _countof(hex), format != Formats::Hex); int i = 0; if (!leftAlign) { for (; i < width - count; ++i) result[i] = ' '; result[i] = 0; } int written = sprintf_s(result+i, len - i, DMLFormats[dmlType], hex, hex); SOS_Assert(written != -1); if (written != -1) { for (i = i + written; i < width; ++i) result[i] = ' '; result[i] = 0; } } static int GetDMLColWidth(Output::FormatType dmlType, int width) { return 1 + 4*sizeof(int*) + (int)strlen(DMLFormats[dmlType]) + width; } private: T mValue; Formats::Format mFormat; Output::FormatType mDml; }; /* Format class used for strings. */ template <> class Format<const char *> { public: Format(const char *value) : mValue(value) { } Format(const Format<const char *> &rhs) : mValue(rhs.mValue) { } void Output() const { if (IsDMLEnabled()) DMLOut("%s", mValue); else ExtOut("%s", mValue); } void OutputColumn(Alignment align, int width) const { int precision = (int)strlen(mValue); if (precision > width) precision = width; const char *format = align == AlignLeft ? "%-*.*s" : "%*.*s"; if (IsDMLEnabled()) DMLOut(format, width, precision, mValue); else ExtOut(format, width, precision, mValue); } private: const char *mValue; }; /* Format class for wide char strings. */ template <> class Format<const WCHAR *> { public: Format(const WCHAR *value) : mValue(value) { } Format(const Format<const WCHAR *> &rhs) : mValue(rhs.mValue) { } void Output() const { if (IsDMLEnabled()) DMLOut("%S", mValue); else ExtOut("%S", mValue); } void OutputColumn(Alignment align, int width) const { int precision = (int)_wcslen(mValue); if (precision > width) precision = width; const char *format = align == AlignLeft ? "%-*.*S" : "%*.*S"; if (IsDMLEnabled()) DMLOut(format, width, precision, mValue); else ExtOut(format, width, precision, mValue); } private: const WCHAR *mValue; }; template <class T> void InternalPrint(const T &t) { Format<T>(t).Output(); } template <class T> void InternalPrint(const Format<T> &t) { t.Output(); } inline void InternalPrint(const char t[]) { Format<const char *>(t).Output(); } } #define DefineFormatClass(name, format, dml) \ template <class T> \ Output::Format<T> name(T value) \ { return Output::Format<T>(value, format, dml); } DefineFormatClass(EEClassPtr, Formats::Pointer, Output::DML_EEClass); DefineFormatClass(ObjectPtr, Formats::Pointer, Output::DML_Object); DefineFormatClass(ExceptionPtr, Formats::Pointer, Output::DML_PrintException); DefineFormatClass(ModulePtr, Formats::Pointer, Output::DML_Module); DefineFormatClass(MethodDescPtr, Formats::Pointer, Output::DML_MethodDesc); DefineFormatClass(AppDomainPtr, Formats::Pointer, Output::DML_Domain); DefineFormatClass(ThreadState, Formats::Hex, Output::DML_ThreadState); DefineFormatClass(ThreadID, Formats::Hex, Output::DML_ThreadID); DefineFormatClass(RCWrapper, Formats::Pointer, Output::DML_RCWrapper); DefineFormatClass(CCWrapper, Formats::Pointer, Output::DML_CCWrapper); DefineFormatClass(InstructionPtr, Formats::Pointer, Output::DML_IP); DefineFormatClass(Decimal, Formats::Decimal, Output::DML_None); DefineFormatClass(Pointer, Formats::Pointer, Output::DML_None); DefineFormatClass(PrefixHex, Formats::PrefixHex, Output::DML_None); DefineFormatClass(Hex, Formats::Hex, Output::DML_None); #undef DefineFormatClass template <class T0> void Print(const T0 &val0) { Output::InternalPrint(val0); } template <class T0, class T1> void Print(const T0 &val0, const T1 &val1) { Output::InternalPrint(val0); Output::InternalPrint(val1); } template <class T0> void PrintLn(const T0 &val0) { Output::InternalPrint(val0); ExtOut("\n"); } template <class T0, class T1> void PrintLn(const T0 &val0, const T1 &val1) { Output::InternalPrint(val0); Output::InternalPrint(val1); ExtOut("\n"); } template <class T0, class T1, class T2> void PrintLn(const T0 &val0, const T1 &val1, const T2 &val2) { Output::InternalPrint(val0); Output::InternalPrint(val1); Output::InternalPrint(val2); ExtOut("\n"); } /* This class handles the formatting for output which is in a table format. To use this class you define * how the table is formatted by setting the number of columns in the table, the default column width, * the default column alignment, the indentation (whitespace) for the table, and the amount of padding * (whitespace) between each column. Once this has been setup, you output rows at a time or individual * columns to build the output instead of manually tabbing out space. * Also note that this class was built to work with the Format class. When outputing data, use the * predefined output types to specify the format (such as ObjectPtr, MethodDescPtr, Decimal, etc). This * tells the TableOutput class how to display the data, and where applicable, it automatically generates * the appropriate DML output. See the DefineFormatClass macro. */ class TableOutput { public: TableOutput() : mColumns(0), mDefaultWidth(0), mIndent(0), mPadding(0), mCurrCol(0), mDefaultAlign(AlignLeft), mWidths(0), mAlignments(0) { } /* Constructor. * Params: * numColumns - the number of columns the table has * defaultColumnWidth - the default width of each column * alignmentDefault - whether columns are by default left aligned or right aligned * indent - the amount of whitespace to prefix at the start of the row (in characters) * padding - the amount of whitespace to place between each column (in characters) */ TableOutput(int numColumns, int defaultColumnWidth, Alignment alignmentDefault = AlignLeft, int indent = 0, int padding = 1) : mColumns(numColumns), mDefaultWidth(defaultColumnWidth), mIndent(indent), mPadding(padding), mCurrCol(0), mDefaultAlign(alignmentDefault), mWidths(0), mAlignments(0) { } ~TableOutput() { Clear(); } /* See the documentation for the constructor. */ void ReInit(int numColumns, int defaultColumnWidth, Alignment alignmentDefault = AlignLeft, int indent = 0, int padding = 1); /* Sets the amount of whitespace to prefix at the start of the row (in characters). */ void SetIndent(int indent) { SOS_Assert(indent >= 0); mIndent = indent; } /* Sets the exact widths for the the given columns. * Params: * columns - the number of columns you are providing the width for, starting at the first column * ... - an int32 for each column (given by the number of columns in the first parameter). * Example: * If you have 5 columns in the table, you can set their widths like so: * tableOutput.SetWidths(5, 2, 3, 5, 7, 13); * Note: * It's fine to pass a value for "columns" less than the number of columns in the table. This * is useful when you set the default column width to be correct for most of the table, and need * to make a minor adjustment to a few. */ void SetWidths(int columns, ...); /* Individually sets a column to the given width. * Params: * col - the column to set, 0 indexed * width - the width of the column (note this must be non-negative) */ void SetColWidth(int col, int width); /* Individually sets the column alignment. * Params: * col - the column to set, 0 indexed * align - the new alignment (left or right) for the column */ void SetColAlignment(int col, Alignment align); /* The WriteRow family of functions allows you to write an entire row of the table at once. * The common use case for the TableOutput class is to individually output each column after * calculating what the value should contain. However, this would be tedious if you already * knew the contents of the entire row which usually happenes when you are printing out the * header for the table. To use this, simply pass each column as an individual parameter, * for example: * tableOutput.WriteRow("First Column", "Second Column", Decimal(3), PrefixHex(4), "Fifth Column"); */ template <class T0, class T1> void WriteRow(T0 t0, T1 t1) { WriteColumn(0, t0); WriteColumn(1, t1); } template <class T0, class T1, class T2> void WriteRow(T0 t0, T1 t1, T2 t2) { WriteColumn(0, t0); WriteColumn(1, t1); WriteColumn(2, t2); } template <class T0, class T1, class T2, class T3> void WriteRow(T0 t0, T1 t1, T2 t2, T3 t3) { WriteColumn(0, t0); WriteColumn(1, t1); WriteColumn(2, t2); WriteColumn(3, t3); } template <class T0, class T1, class T2, class T3, class T4> void WriteRow(T0 t0, T1 t1, T2 t2, T3 t3, T4 t4) { WriteColumn(0, t0); WriteColumn(1, t1); WriteColumn(2, t2); WriteColumn(3, t3); WriteColumn(4, t4); } template <class T0, class T1, class T2, class T3, class T4, class T5> void WriteRow(T0 t0, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5) { WriteColumn(0, t0); WriteColumn(1, t1); WriteColumn(2, t2); WriteColumn(3, t3); WriteColumn(4, t4); WriteColumn(5, t5); } template <class T0, class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9> void WriteRow(T0 t0, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9) { WriteColumn(0, t0); WriteColumn(1, t1); WriteColumn(2, t2); WriteColumn(3, t3); WriteColumn(4, t4); WriteColumn(5, t5); WriteColumn(6, t6); WriteColumn(7, t7); WriteColumn(8, t8); WriteColumn(9, t9); } /* The WriteColumn family of functions is used to output individual columns in the table. * The intent is that the bulk of the table will be generated in a loop like so: * while (condition) { * int value1 = CalculateFirstColumn(); * table.WriteColumn(0, value1); * * String value2 = CalculateSecondColumn(); * table.WriteColumn(1, value2); * } * Params: * col - the column to write, 0 indexed * t - the value to write * Note: * You should generally use the specific instances of the Format class to generate output. * For example, use the "Decimal", "Pointer", "ObjectPtr", etc. When passing data to this * function. This tells the Table class how to display the value. */ template <class T> void WriteColumn(int col, const Output::Format<T> &t) { SOS_Assert(col >= 0); SOS_Assert(col < mColumns); if (col != mCurrCol) OutputBlankColumns(col); if (col == 0) OutputIndent(); bool lastCol = col == mColumns - 1; if (!lastCol) t.OutputColumn(GetColAlign(col), GetColumnWidth(col)); else t.Output(); ExtOut(lastCol ? "\n" : GetWhitespace(mPadding)); if (lastCol) mCurrCol = 0; else mCurrCol = col+1; } template <class T> void WriteColumn(int col, T t) { WriteColumn(col, Output::Format<T>(t)); } void WriteColumn(int col, const String &str) { WriteColumn(col, Output::Format<const char *>(str)); } void WriteColumn(int col, const WString &str) { WriteColumn(col, Output::Format<const WCHAR *>(str)); } void WriteColumn(int col, __in_z WCHAR *str) { WriteColumn(col, Output::Format<const WCHAR *>(str)); } void WriteColumn(int col, const WCHAR *str) { WriteColumn(col, Output::Format<const WCHAR *>(str)); } inline void WriteColumn(int col, __in_z char *str) { WriteColumn(col, Output::Format<const char *>(str)); } /* Writes a column using a printf style format. You cannot use the Format class with * this function to specify how the output should look, use printf style formatting * with the appropriate parameters instead. */ void WriteColumnFormat(int col, const char *fmt, ...) { SOS_Assert(strstr(fmt, "%S") == NULL); char result[128]; va_list list; va_start(list, fmt); vsprintf_s(result, _countof(result), fmt, list); va_end(list); WriteColumn(col, result); } void WriteColumnFormat(int col, const WCHAR *fmt, ...) { WCHAR result[128]; va_list list; va_start(list, fmt); vswprintf_s(result, _countof(result), fmt, list); va_end(list); WriteColumn(col, result); } /* This function is a shortcut for writing the next column. (That is, the one after the * one you just wrote.) */ template <class T> void WriteColumn(T t) { WriteColumn(mCurrCol, t); } private: void Clear(); void AllocWidths(); int GetColumnWidth(int col); Alignment GetColAlign(int col); const char *GetWhitespace(int amount); void OutputBlankColumns(int col); void OutputIndent(); private: int mColumns, mDefaultWidth, mIndent, mPadding, mCurrCol; Alignment mDefaultAlign; int *mWidths; Alignment *mAlignments; }; HRESULT GetMethodDefinitionsFromName(DWORD_PTR ModulePtr, IXCLRDataModule* mod, const char* name, IXCLRDataMethodDefinition **ppMethodDefinitions, int numMethods, int *numMethodsNeeded); HRESULT GetMethodDescsFromName(DWORD_PTR ModulePtr, IXCLRDataModule* mod, const char* name, DWORD_PTR **pOut, int *numMethodDescs); HRESULT FileNameForModule (DacpModuleData *pModule, __out_ecount (MAX_LONGPATH) WCHAR *fileName); HRESULT FileNameForModule (DWORD_PTR pModuleAddr, __out_ecount (MAX_LONGPATH) WCHAR *fileName); void IP2MethodDesc (DWORD_PTR IP, DWORD_PTR &methodDesc, JITTypes &jitType, DWORD_PTR &gcinfoAddr); const char *ElementTypeName (unsigned type); void DisplayFields (CLRDATA_ADDRESS cdaMT, DacpMethodTableData *pMTD, DacpMethodTableFieldData *pMTFD, DWORD_PTR dwStartAddr = 0, BOOL bFirst=TRUE, BOOL bValueClass=FALSE); int GetObjFieldOffset(CLRDATA_ADDRESS cdaObj, __in_z LPCWSTR wszFieldName, BOOL bFirst=TRUE); int GetObjFieldOffset(CLRDATA_ADDRESS cdaObj, CLRDATA_ADDRESS cdaMT, __in_z LPCWSTR wszFieldName, BOOL bFirst=TRUE); BOOL IsValidToken(DWORD_PTR ModuleAddr, mdTypeDef mb); void NameForToken_s(DacpModuleData *pModule, mdTypeDef mb, __out_ecount (capacity_mdName) WCHAR *mdName, size_t capacity_mdName, bool bClassName=true); void NameForToken_s(DWORD_PTR ModuleAddr, mdTypeDef mb, __out_ecount (capacity_mdName) WCHAR *mdName, size_t capacity_mdName, bool bClassName=true); HRESULT NameForToken_s(mdTypeDef mb, IMetaDataImport *pImport, __out_ecount (capacity_mdName) WCHAR *mdName, size_t capacity_mdName, bool bClassName); HRESULT NameForTokenNew_s(mdTypeDef mb, IMDInternalImport *pImport, __out_ecount (capacity_mdName) WCHAR *mdName, size_t capacity_mdName, bool bClassName); void vmmap(); void vmstat(); #ifndef FEATURE_PAL /////////////////////////////////////////////////////////////////////////////////////////////////// // Support for managed stack tracing // DWORD_PTR GetDebuggerJitInfo(DWORD_PTR md); /////////////////////////////////////////////////////////////////////////////////////////////////// #endif // FEATURE_PAL template <typename SCALAR> inline int bitidx(SCALAR bitflag) { for (int idx = 0; idx < static_cast<int>(sizeof(bitflag))*8; ++idx) { if (bitflag & (1 << idx)) { _ASSERTE((bitflag & (~(1 << idx))) == 0); return idx; } } return -1; } HRESULT DllsName( ULONG_PTR addrContaining, __out_ecount (MAX_LONGPATH) WCHAR *dllName ); inline BOOL IsElementValueType (CorElementType cet) { return (cet >= ELEMENT_TYPE_BOOLEAN && cet <= ELEMENT_TYPE_R8) || cet == ELEMENT_TYPE_VALUETYPE || cet == ELEMENT_TYPE_I || cet == ELEMENT_TYPE_U; } #define safemove(dst, src) \ SafeReadMemory (TO_TADDR(src), &(dst), sizeof(dst), NULL) extern "C" PDEBUG_DATA_SPACES g_ExtData; template <class T> class ArrayHolder { public: ArrayHolder(T *ptr) : mPtr(ptr) { } ~ArrayHolder() { Clear(); } ArrayHolder(const ArrayHolder &rhs) { mPtr = const_cast<ArrayHolder *>(&rhs)->Detach(); } ArrayHolder &operator=(T *ptr) { Clear(); mPtr = ptr; return *this; } const T &operator[](int i) const { return mPtr[i]; } T &operator[](int i) { return mPtr[i]; } operator const T *() const { return mPtr; } operator T *() { return mPtr; } T **operator&() { return &mPtr; } T *GetPtr() { return mPtr; } T *Detach() { T *ret = mPtr; mPtr = NULL; return ret; } private: void Clear() { if (mPtr) { delete [] mPtr; mPtr = NULL; } } private: T *mPtr; }; // This class acts a smart pointer which calls the Release method on any object // you place in it when the ToRelease class falls out of scope. You may use it // just like you would a standard pointer to a COM object (including if (foo), // if (!foo), if (foo == 0), etc) except for two caveats: // 1. This class never calls AddRef and it always calls Release when it // goes out of scope. // 2. You should never use & to try to get a pointer to a pointer unless // you call Release first, or you will leak whatever this object contains // prior to updating its internal pointer. template<class T> class ToRelease { public: ToRelease() : m_ptr(NULL) {} ToRelease(T* ptr) : m_ptr(ptr) {} ~ToRelease() { Release(); } void operator=(T *ptr) { Release(); m_ptr = ptr; } T* operator->() { return m_ptr; } operator T*() { return m_ptr; } T** operator&() { return &m_ptr; } T* GetPtr() const { return m_ptr; } T* Detach() { T* pT = m_ptr; m_ptr = NULL; return pT; } void Release() { if (m_ptr != NULL) { m_ptr->Release(); m_ptr = NULL; } } private: T* m_ptr; }; struct ModuleInfo { ULONG64 baseAddr; ULONG64 size; BOOL hasPdb; }; extern ModuleInfo moduleInfo[]; BOOL InitializeHeapData(); BOOL IsServerBuild (); UINT GetMaxGeneration(); UINT GetGcHeapCount(); BOOL GetGcStructuresValid(); ULONG GetILSize(DWORD_PTR ilAddr); // REturns 0 if error occurs HRESULT DecodeILFromAddress(IMetaDataImport *pImport, TADDR ilAddr); void DecodeIL(IMetaDataImport *pImport, BYTE *buffer, ULONG bufSize); void DecodeDynamicIL(BYTE *data, ULONG Size, DacpObjectData& tokenArray); BOOL IsRetailBuild (size_t base); EEFLAVOR GetEEFlavor (); HRESULT InitCorDebugInterface(); VOID UninitCorDebugInterface(); #ifndef FEATURE_PAL BOOL GetEEVersion(VS_FIXEDFILEINFO *pFileInfo); BOOL GetSOSVersion(VS_FIXEDFILEINFO *pFileInfo); #endif BOOL IsDumpFile (); // IsMiniDumpFile will return true if 1) we are in // a small format minidump, and g_InMinidumpSafeMode is true. extern BOOL g_InMinidumpSafeMode; BOOL IsMiniDumpFile(); void ReportOOM(); BOOL SafeReadMemory (TADDR offset, PVOID lpBuffer, ULONG cb, PULONG lpcbBytesRead); #if !defined(_TARGET_WIN64_) && !defined(_ARM64_) // on 64-bit platforms TADDR and CLRDATA_ADDRESS are identical inline BOOL SafeReadMemory (CLRDATA_ADDRESS offset, PVOID lpBuffer, ULONG cb, PULONG lpcbBytesRead) { return SafeReadMemory(TO_TADDR(offset), lpBuffer, cb, lpcbBytesRead); } #endif BOOL NameForMD_s (DWORD_PTR pMD, __out_ecount (capacity_mdName) WCHAR *mdName, size_t capacity_mdName); BOOL NameForMT_s (DWORD_PTR MTAddr, __out_ecount (capacity_mdName) WCHAR *mdName, size_t capacity_mdName); WCHAR *CreateMethodTableName(TADDR mt, TADDR cmt = NULL); void isRetAddr(DWORD_PTR retAddr, DWORD_PTR* whereCalled); DWORD_PTR GetValueFromExpression (___in __in_z const char *const str); enum ModuleHeapType { ModuleHeapType_ThunkHeap, ModuleHeapType_LookupTableHeap }; HRESULT PrintDomainHeapInfo(const char *name, CLRDATA_ADDRESS adPtr, DWORD_PTR *size, DWORD_PTR *wasted = 0); DWORD_PTR PrintModuleHeapInfo(DWORD_PTR *moduleList, int count, ModuleHeapType type, DWORD_PTR *wasted = 0); void PrintHeapSize(DWORD_PTR total, DWORD_PTR wasted); void DomainInfo(DacpAppDomainData *pDomain); void AssemblyInfo(DacpAssemblyData *pAssembly); DWORD_PTR LoaderHeapInfo(CLRDATA_ADDRESS pLoaderHeapAddr, DWORD_PTR *wasted = 0); DWORD_PTR JitHeapInfo(); DWORD_PTR VSDHeapInfo(CLRDATA_ADDRESS appDomain, DWORD_PTR *wasted = 0); DWORD GetNumComponents(TADDR obj); struct GenUsageStat { size_t allocd; size_t freed; size_t unrooted; }; struct HeapUsageStat { GenUsageStat genUsage[4]; // gen0, 1, 2, LOH }; extern DacpUsefulGlobalsData g_special_usefulGlobals; BOOL GCHeapUsageStats(const DacpGcHeapDetails& heap, BOOL bIncUnreachable, HeapUsageStat *hpUsage); class HeapStat { protected: struct Node { DWORD_PTR data; DWORD count; size_t totalSize; Node* left; Node* right; Node () : data(0), count(0), totalSize(0), left(NULL), right(NULL) { } }; BOOL bHasStrings; Node *head; BOOL fLinear; public: HeapStat () : bHasStrings(FALSE), head(NULL), fLinear(FALSE) {} ~HeapStat() { Delete(); } // TODO: Change the aSize argument to size_t when we start supporting // TODO: object sizes above 4GB void Add (DWORD_PTR aData, DWORD aSize); void Sort (); void Print (const char* label = NULL); void Delete (); void HasStrings(BOOL abHasStrings) { bHasStrings = abHasStrings; } private: int CompareData(DWORD_PTR n1, DWORD_PTR n2); void SortAdd (Node *&root, Node *entry); void LinearAdd (Node *&root, Node *entry); void ReverseLeftMost (Node *root); void Linearize(); }; class CGCDesc; // The information MethodTableCache returns. struct MethodTableInfo { bool IsInitialized() { return BaseSize != 0; } DWORD BaseSize; // Caching BaseSize and ComponentSize for a MethodTable DWORD ComponentSize; // here has HUGE perf benefits in heap traversals. BOOL bContainsPointers; DWORD_PTR* GCInfoBuffer; // Start of memory of GC info CGCDesc* GCInfo; // Just past GC info (which is how it is stored) bool ArrayOfVC; }; class MethodTableCache { protected: struct Node { DWORD_PTR data; // This is the key (the method table pointer) MethodTableInfo info; // The info associated with this MethodTable Node* left; Node* right; Node (DWORD_PTR aData) : data(aData), left(NULL), right(NULL) { info.BaseSize = 0; info.ComponentSize = 0; info.bContainsPointers = false; info.GCInfo = NULL; info.ArrayOfVC = false; info.GCInfoBuffer = NULL; } }; Node *head; public: MethodTableCache () : head(NULL) {} ~MethodTableCache() { Clear(); } // Always succeeds, if it is not present it adds an empty Info struct and returns that // Thus you must call 'IsInitialized' on the returned value before using it MethodTableInfo* Lookup(DWORD_PTR aData); void Clear (); private: int CompareData(DWORD_PTR n1, DWORD_PTR n2); void ReverseLeftMost (Node *root); }; extern MethodTableCache g_special_mtCache; struct DumpArrayFlags { DWORD_PTR startIndex; DWORD_PTR Length; BOOL bDetail; LPSTR strObject; BOOL bNoFieldsForElement; DumpArrayFlags () : startIndex(0), Length((DWORD_PTR)-1), bDetail(FALSE), strObject (0), bNoFieldsForElement(FALSE) {} ~DumpArrayFlags () { if (strObject) delete [] strObject; } }; //DumpArrayFlags // ----------------------------------------------------------------------- #define BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX 0x08000000 #define BIT_SBLK_FINALIZER_RUN 0x40000000 #define BIT_SBLK_SPIN_LOCK 0x10000000 #define SBLK_MASK_LOCK_THREADID 0x000003FF // special value of 0 + 1023 thread ids #define SBLK_MASK_LOCK_RECLEVEL 0x0000FC00 // 64 recursion levels #define SBLK_APPDOMAIN_SHIFT 16 // shift right this much to get appdomain index #define SBLK_MASK_APPDOMAININDEX 0x000007FF // 2048 appdomain indices #define SBLK_RECLEVEL_SHIFT 10 // shift right this much to get recursion level #define BIT_SBLK_IS_HASHCODE 0x04000000 #define MASK_HASHCODE ((1<<HASHCODE_BITS)-1) #define SYNCBLOCKINDEX_BITS 26 #define MASK_SYNCBLOCKINDEX ((1<<SYNCBLOCKINDEX_BITS)-1) HRESULT GetMTOfObject(TADDR obj, TADDR *mt); struct needed_alloc_context { BYTE* alloc_ptr; // starting point for next allocation BYTE* alloc_limit; // ending point for allocation region/quantum }; struct AllocInfo { needed_alloc_context *array; int num; // number of allocation contexts in array AllocInfo() : array(NULL) , num(0) {} void Init() { extern void GetAllocContextPtrs(AllocInfo *pallocInfo); GetAllocContextPtrs(this); } ~AllocInfo() { if (array != NULL) delete[] array; } }; struct GCHandleStatistics { HeapStat hs; DWORD strongHandleCount; DWORD pinnedHandleCount; DWORD asyncPinnedHandleCount; DWORD refCntHandleCount; DWORD weakLongHandleCount; DWORD weakShortHandleCount; DWORD variableCount; DWORD sizedRefCount; DWORD dependentCount; DWORD weakWinRTHandleCount; DWORD unknownHandleCount; GCHandleStatistics() : strongHandleCount(0), pinnedHandleCount(0), asyncPinnedHandleCount(0), refCntHandleCount(0), weakLongHandleCount(0), weakShortHandleCount(0), variableCount(0), sizedRefCount(0), dependentCount(0), weakWinRTHandleCount(0), unknownHandleCount(0) {} ~GCHandleStatistics() { hs.Delete(); } }; struct SegmentLookup { DacpHeapSegmentData *m_segments; int m_iSegmentsSize; int m_iSegmentCount; SegmentLookup(); ~SegmentLookup(); void Clear(); BOOL AddSegment(DacpHeapSegmentData *pData); CLRDATA_ADDRESS GetHeap(CLRDATA_ADDRESS object, BOOL& bFound); }; class GCHeapSnapshot { private: BOOL m_isBuilt; DacpGcHeapDetails *m_heapDetails; DacpGcHeapData m_gcheap; SegmentLookup m_segments; BOOL AddSegments(DacpGcHeapDetails& details); public: GCHeapSnapshot(); BOOL Build(); void Clear(); BOOL IsBuilt() { return m_isBuilt; } DacpGcHeapData *GetHeapData() { return &m_gcheap; } int GetHeapCount() { return m_gcheap.HeapCount; } DacpGcHeapDetails *GetHeap(CLRDATA_ADDRESS objectPointer); int GetGeneration(CLRDATA_ADDRESS objectPointer); }; extern GCHeapSnapshot g_snapshot; BOOL IsSameModuleName (const char *str1, const char *str2); BOOL IsModule (DWORD_PTR moduleAddr); BOOL IsMethodDesc (DWORD_PTR value); BOOL IsMethodTable (DWORD_PTR value); BOOL IsStringObject (size_t obj); BOOL IsObjectArray (DWORD_PTR objPointer); BOOL IsObjectArray (DacpObjectData *pData); /* Returns a list of all modules in the process. * Params: * name - The name of the module you would like. If mName is NULL the all modules are returned. * numModules - The number of modules in the array returned. * Returns: * An array of modules whose length is *numModules, NULL if an error occurred. Note that if this * function succeeds but finds no modules matching the name given, this function returns a valid * array, but *numModules will equal 0. * Note: * You must clean up the return value of this array by calling delete [] on it, or using the * ArrayHolder class. */ DWORD_PTR *ModuleFromName(__in_opt LPSTR name, int *numModules); void GetInfoFromName(DWORD_PTR ModuleAddr, const char* name); void GetInfoFromModule (DWORD_PTR ModuleAddr, ULONG token, DWORD_PTR *ret=NULL); typedef void (*VISITGCHEAPFUNC)(DWORD_PTR objAddr,size_t Size,DWORD_PTR methodTable,LPVOID token); BOOL GCHeapsTraverse(VISITGCHEAPFUNC pFunc, LPVOID token, BOOL verify=true); ///////////////////////////////////////////////////////////////////////////////////////////////////////// struct strobjInfo { size_t methodTable; DWORD m_StringLength; }; // Just to make figuring out which fill pointer element matches a generation // a bit less confusing. This gen_segment function is ported from gc.cpp. inline unsigned int gen_segment (int gen) { return (DAC_NUMBERGENERATIONS - gen - 1); } inline CLRDATA_ADDRESS SegQueue(DacpGcHeapDetails& heapDetails, int seg) { return heapDetails.finalization_fill_pointers[seg - 1]; } inline CLRDATA_ADDRESS SegQueueLimit(DacpGcHeapDetails& heapDetails, int seg) { return heapDetails.finalization_fill_pointers[seg]; } #define FinalizerListSeg (DAC_NUMBERGENERATIONS+1) #define CriticalFinalizerListSeg (DAC_NUMBERGENERATIONS) void GatherOneHeapFinalization(DacpGcHeapDetails& heapDetails, HeapStat *stat, BOOL bAllReady, BOOL bShort); CLRDATA_ADDRESS GetAppDomainForMT(CLRDATA_ADDRESS mtPtr); CLRDATA_ADDRESS GetAppDomain(CLRDATA_ADDRESS objPtr); void GCHeapInfo(const DacpGcHeapDetails &heap, DWORD_PTR &total_size); BOOL GCObjInHeap(TADDR taddrObj, const DacpGcHeapDetails &heap, TADDR_SEGINFO& trngSeg, int& gen, TADDR_RANGE& allocCtx, BOOL &bLarge); BOOL VerifyObject(const DacpGcHeapDetails &heap, const DacpHeapSegmentData &seg, DWORD_PTR objAddr, DWORD_PTR MTAddr, size_t objSize, BOOL bVerifyMember); BOOL VerifyObject(const DacpGcHeapDetails &heap, DWORD_PTR objAddr, DWORD_PTR MTAddr, size_t objSize, BOOL bVerifyMember); BOOL IsMTForFreeObj(DWORD_PTR pMT); void DumpStackObjectsHelper (TADDR StackTop, TADDR StackBottom, BOOL verifyFields); enum ARGTYPE {COBOOL,COSIZE_T,COHEX,COSTRING}; struct CMDOption { const char* name; void *vptr; ARGTYPE type; BOOL hasValue; BOOL hasSeen; }; struct CMDValue { void *vptr; ARGTYPE type; }; BOOL GetCMDOption(const char *string, CMDOption *option, size_t nOption, CMDValue *arg, size_t maxArg, size_t *nArg); void DumpMDInfo(DWORD_PTR dwStartAddr, CLRDATA_ADDRESS dwRequestedIP = 0, BOOL fStackTraceFormat = FALSE); void DumpMDInfoFromMethodDescData(DacpMethodDescData * pMethodDescData, BOOL fStackTraceFormat); void GetDomainList(DWORD_PTR *&domainList, int &numDomain); HRESULT GetThreadList(DWORD_PTR **threadList, int *numThread); CLRDATA_ADDRESS GetCurrentManagedThread(); // returns current managed thread if any void GetAllocContextPtrs(AllocInfo *pallocInfo); void ReloadSymbolWithLineInfo(); size_t FunctionType (size_t EIP); size_t Align (size_t nbytes); // Aligns large objects size_t AlignLarge (size_t nbytes); ULONG OSPageSize (); size_t NextOSPageAddress (size_t addr); // This version of objectsize reduces the lookup of methodtables in the DAC. // It uses g_special_mtCache for it's work. BOOL GetSizeEfficient(DWORD_PTR dwAddrCurrObj, DWORD_PTR dwAddrMethTable, BOOL bLarge, size_t& s, BOOL& bContainsPointers); // ObjSize now uses the methodtable cache for its work too. size_t ObjectSize (DWORD_PTR obj, BOOL fIsLargeObject=FALSE); size_t ObjectSize(DWORD_PTR obj, DWORD_PTR mt, BOOL fIsValueClass, BOOL fIsLargeObject=FALSE); void CharArrayContent(TADDR pos, ULONG num, bool widechar); void StringObjectContent (size_t obj, BOOL fLiteral=FALSE, const int length=-1); // length=-1: dump everything in the string object. UINT FindAllPinnedAndStrong (DWORD_PTR handlearray[],UINT arraySize); void PrintNotReachableInRange(TADDR rngStart, TADDR rngEnd, BOOL bExcludeReadyForFinalization, HeapStat* stat, BOOL bShort); const char *EHTypeName(EHClauseType et); template<typename T> inline const LPCSTR GetTransparency(const T &t) { if (!t.bHasCriticalTransparentInfo) { return "Not calculated"; } else if (t.bIsCritical && !t.bIsTreatAsSafe) { return "Critical"; } else if (t.bIsCritical) { return "Safe critical"; } else { return "Transparent"; } } struct StringHolder { LPSTR data; StringHolder() : data(NULL) { } ~StringHolder() { if(data) delete [] data; } }; ULONG DebuggeeType(); inline BOOL IsKernelDebugger () { return DebuggeeType() == DEBUG_CLASS_KERNEL; } void ResetGlobals(void); HRESULT LoadClrDebugDll(void); extern "C" void UnloadClrDebugDll(void); extern IMetaDataImport* MDImportForModule (DacpModuleData *pModule); extern IMetaDataImport* MDImportForModule (DWORD_PTR pModule); //***************************************************************************** // // **** CQuickBytes // This helper class is useful for cases where 90% of the time you allocate 512 // or less bytes for a data structure. This class contains a 512 byte buffer. // Alloc() will return a pointer to this buffer if your allocation is small // enough, otherwise it asks the heap for a larger buffer which is freed for // you. No mutex locking is required for the small allocation case, making the // code run faster, less heap fragmentation, etc... Each instance will allocate // 520 bytes, so use accordinly. // //***************************************************************************** template <DWORD SIZE, DWORD INCREMENT> class CQuickBytesBase { public: CQuickBytesBase() : pbBuff(0), iSize(0), cbTotal(SIZE) { } void Destroy() { if (pbBuff) { delete[] (BYTE*)pbBuff; pbBuff = 0; } } void *Alloc(SIZE_T iItems) { iSize = iItems; if (iItems <= SIZE) { cbTotal = SIZE; return (&rgData[0]); } else { if (pbBuff) delete[] (BYTE*)pbBuff; pbBuff = new BYTE[iItems]; cbTotal = pbBuff ? iItems : 0; return (pbBuff); } } // This is for conformity to the CQuickBytesBase that is defined by the runtime so // that we can use it inside of some GC code that SOS seems to include as well. // // The plain vanilla "Alloc" version on this CQuickBytesBase doesn't throw either, // so we'll just forward the call. void *AllocNoThrow(SIZE_T iItems) { return Alloc(iItems); } HRESULT ReSize(SIZE_T iItems) { void *pbBuffNew; if (iItems <= cbTotal) { iSize = iItems; return NOERROR; } pbBuffNew = new BYTE[iItems + INCREMENT]; if (!pbBuffNew) return E_OUTOFMEMORY; if (pbBuff) { memcpy(pbBuffNew, pbBuff, cbTotal); delete[] (BYTE*)pbBuff; } else { _ASSERTE(cbTotal == SIZE); memcpy(pbBuffNew, rgData, SIZE); } cbTotal = iItems + INCREMENT; iSize = iItems; pbBuff = pbBuffNew; return NOERROR; } operator PVOID() { return ((pbBuff) ? pbBuff : &rgData[0]); } void *Ptr() { return ((pbBuff) ? pbBuff : &rgData[0]); } SIZE_T Size() { return (iSize); } SIZE_T MaxSize() { return (cbTotal); } void *pbBuff; SIZE_T iSize; // number of bytes used SIZE_T cbTotal; // total bytes allocated in the buffer // use UINT64 to enforce the alignment of the memory UINT64 rgData[(SIZE+sizeof(UINT64)-1)/sizeof(UINT64)]; }; #define CQUICKBYTES_BASE_SIZE 512 #define CQUICKBYTES_INCREMENTAL_SIZE 128 class CQuickBytesNoDtor : public CQuickBytesBase<CQUICKBYTES_BASE_SIZE, CQUICKBYTES_INCREMENTAL_SIZE> { }; class CQuickBytes : public CQuickBytesNoDtor { public: CQuickBytes() { } ~CQuickBytes() { Destroy(); } }; template <DWORD CQUICKBYTES_BASE_SPECIFY_SIZE> class CQuickBytesNoDtorSpecifySize : public CQuickBytesBase<CQUICKBYTES_BASE_SPECIFY_SIZE, CQUICKBYTES_INCREMENTAL_SIZE> { }; template <DWORD CQUICKBYTES_BASE_SPECIFY_SIZE> class CQuickBytesSpecifySize : public CQuickBytesNoDtorSpecifySize<CQUICKBYTES_BASE_SPECIFY_SIZE> { public: CQuickBytesSpecifySize() { } ~CQuickBytesSpecifySize() { CQuickBytesNoDtorSpecifySize<CQUICKBYTES_BASE_SPECIFY_SIZE>::Destroy(); } }; #define STRING_SIZE 10 class CQuickString : public CQuickBytesBase<STRING_SIZE, STRING_SIZE> { public: CQuickString() { } ~CQuickString() { Destroy(); } void *Alloc(SIZE_T iItems) { return CQuickBytesBase<STRING_SIZE, STRING_SIZE>::Alloc(iItems*sizeof(WCHAR)); } HRESULT ReSize(SIZE_T iItems) { return CQuickBytesBase<STRING_SIZE, STRING_SIZE>::ReSize(iItems * sizeof(WCHAR)); } SIZE_T Size() { return CQuickBytesBase<STRING_SIZE, STRING_SIZE>::Size() / sizeof(WCHAR); } SIZE_T MaxSize() { return CQuickBytesBase<STRING_SIZE, STRING_SIZE>::MaxSize() / sizeof(WCHAR); } WCHAR* String() { return (WCHAR*) Ptr(); } }; enum GetSignatureStringResults { GSS_SUCCESS, GSS_ERROR, GSS_INSUFFICIENT_DATA, }; GetSignatureStringResults GetMethodSignatureString (PCCOR_SIGNATURE pbSigBlob, ULONG ulSigBlob, DWORD_PTR dwModuleAddr, CQuickBytes *sigString); GetSignatureStringResults GetSignatureString (PCCOR_SIGNATURE pbSigBlob, ULONG ulSigBlob, DWORD_PTR dwModuleAddr, CQuickBytes *sigString); void GetMethodName(mdMethodDef methodDef, IMetaDataImport * pImport, CQuickBytes *fullName); #ifndef _TARGET_WIN64_ #define itoa_s_ptr _itoa_s #define itow_s_ptr _itow_s #define itoa_ptr _itoa #define itow_ptr _itow #else #define itoa_s_ptr _i64toa_s #define itow_s_ptr _i64tow_s #define itoa_ptr _i64toa #define itow_ptr _i64tow #endif #ifdef FEATURE_PAL extern "C" int _itoa_s( int inValue, char* outBuffer, size_t inDestBufferSize, int inRadix ); extern "C" int _ui64toa_s( unsigned __int64 inValue, char* outBuffer, size_t inDestBufferSize, int inRadix ); #endif // FEATURE_PAL struct MemRange { MemRange (ULONG64 s = NULL, size_t l = 0, MemRange * n = NULL) : start(s), len (l), next (n) {} bool InRange (ULONG64 addr) { return addr >= start && addr < start + len; } ULONG64 start; size_t len; MemRange * next; }; //struct MemRange #ifndef FEATURE_PAL class StressLogMem { private: // use a linked list for now, could be optimazied later MemRange * list; void AddRange (ULONG64 s, size_t l) { list = new MemRange (s, l, list); } public: StressLogMem () : list (NULL) {} ~StressLogMem (); bool Init (ULONG64 stressLogAddr, IDebugDataSpaces* memCallBack); bool IsInStressLog (ULONG64 addr); }; //class StressLogMem // An adapter class that DIA consumes so that it can read PE data from the an image // This implementation gets the backing data from the image loaded in debuggee memory // that has been layed out identical to the disk format (ie not seperated by section) class PEOffsetMemoryReader : IDiaReadExeAtOffsetCallback { public: PEOffsetMemoryReader(TADDR moduleBaseAddress); // IUnknown implementation HRESULT __stdcall QueryInterface(REFIID riid, VOID** ppInterface); ULONG __stdcall AddRef(); ULONG __stdcall Release(); // IDiaReadExeAtOffsetCallback implementation HRESULT __stdcall ReadExecutableAt(DWORDLONG fileOffset, DWORD cbData, DWORD* pcbData, BYTE data[]); private: TADDR m_moduleBaseAddress; volatile ULONG m_refCount; }; // An adapter class that DIA consumes so that it can read PE data from the an image // This implementation gets the backing data from the image loaded in debuggee memory // that has been layed out in LoadLibrary format class PERvaMemoryReader : IDiaReadExeAtRVACallback { public: PERvaMemoryReader(TADDR moduleBaseAddress); // IUnknown implementation HRESULT __stdcall QueryInterface(REFIID riid, VOID** ppInterface); ULONG __stdcall AddRef(); ULONG __stdcall Release(); // IDiaReadExeAtOffsetCallback implementation HRESULT __stdcall ReadExecutableAtRVA(DWORD relativeVirtualAddress, DWORD cbData, DWORD* pcbData, BYTE data[]); private: TADDR m_moduleBaseAddress; volatile ULONG m_refCount; }; #endif // !FEATURE_PAL class SymbolReader { private: #ifndef FEATURE_PAL ISymUnmanagedReader* m_pSymReader; #endif private: HRESULT GetNamedLocalVariable(ISymUnmanagedScope * pScope, ICorDebugILFrame * pILFrame, mdMethodDef methodToken, ULONG localIndex, __inout_ecount(paramNameLen) WCHAR* paramName, ULONG paramNameLen, ICorDebugValue** ppValue); public: #ifndef FEATURE_PAL SymbolReader() : m_pSymReader (NULL) {} ~SymbolReader() { if(m_pSymReader != NULL) { m_pSymReader->Release(); m_pSymReader = NULL; } } #else SymbolReader() {} ~SymbolReader() {} #endif HRESULT LoadSymbols(IMetaDataImport * pMD, ICorDebugModule * pModule); HRESULT LoadSymbols(IMetaDataImport * pMD, ULONG64 baseAddress, __in_z WCHAR* pModuleName, BOOL isInMemory); HRESULT GetNamedLocalVariable(ICorDebugFrame * pFrame, ULONG localIndex, __inout_ecount(paramNameLen) WCHAR* paramName, ULONG paramNameLen, ICorDebugValue** ppValue); HRESULT SymbolReader::ResolveSequencePoint(__in_z WCHAR* pFilename, ULONG32 lineNumber, mdMethodDef* pToken, ULONG32* pIlOffset); }; HRESULT GetLineByOffset( ___in ULONG64 IP, ___out ULONG *pLinenum, __out_ecount(cbFileName) LPSTR lpszFileName, ___in ULONG cbFileName); /// X86 Context #define X86_SIZE_OF_80387_REGISTERS 80 #define X86_MAXIMUM_SUPPORTED_EXTENSION 512 typedef struct { DWORD ControlWord; DWORD StatusWord; DWORD TagWord; DWORD ErrorOffset; DWORD ErrorSelector; DWORD DataOffset; DWORD DataSelector; BYTE RegisterArea[X86_SIZE_OF_80387_REGISTERS]; DWORD Cr0NpxState; } X86_FLOATING_SAVE_AREA; typedef struct { DWORD ContextFlags; DWORD Dr0; DWORD Dr1; DWORD Dr2; DWORD Dr3; DWORD Dr6; DWORD Dr7; X86_FLOATING_SAVE_AREA FloatSave; DWORD SegGs; DWORD SegFs; DWORD SegEs; DWORD SegDs; DWORD Edi; DWORD Esi; DWORD Ebx; DWORD Edx; DWORD Ecx; DWORD Eax; DWORD Ebp; DWORD Eip; DWORD SegCs; DWORD EFlags; DWORD Esp; DWORD SegSs; BYTE ExtendedRegisters[X86_MAXIMUM_SUPPORTED_EXTENSION]; } X86_CONTEXT; typedef struct { ULONGLONG Low; LONGLONG High; } M128A_XPLAT; /// AMD64 Context typedef struct { WORD ControlWord; WORD StatusWord; BYTE TagWord; BYTE Reserved1; WORD ErrorOpcode; DWORD ErrorOffset; WORD ErrorSelector; WORD Reserved2; DWORD DataOffset; WORD DataSelector; WORD Reserved3; DWORD MxCsr; DWORD MxCsr_Mask; M128A_XPLAT FloatRegisters[8]; #if defined(_WIN64) M128A_XPLAT XmmRegisters[16]; BYTE Reserved4[96]; #else M128A_XPLAT XmmRegisters[8]; BYTE Reserved4[220]; DWORD Cr0NpxState; #endif } AMD64_XMM_SAVE_AREA32; typedef struct { DWORD64 P1Home; DWORD64 P2Home; DWORD64 P3Home; DWORD64 P4Home; DWORD64 P5Home; DWORD64 P6Home; DWORD ContextFlags; DWORD MxCsr; WORD SegCs; WORD SegDs; WORD SegEs; WORD SegFs; WORD SegGs; WORD SegSs; DWORD EFlags; DWORD64 Dr0; DWORD64 Dr1; DWORD64 Dr2; DWORD64 Dr3; DWORD64 Dr6; DWORD64 Dr7; DWORD64 Rax; DWORD64 Rcx; DWORD64 Rdx; DWORD64 Rbx; DWORD64 Rsp; DWORD64 Rbp; DWORD64 Rsi; DWORD64 Rdi; DWORD64 R8; DWORD64 R9; DWORD64 R10; DWORD64 R11; DWORD64 R12; DWORD64 R13; DWORD64 R14; DWORD64 R15; DWORD64 Rip; union { AMD64_XMM_SAVE_AREA32 FltSave; struct { M128A_XPLAT Header[2]; M128A_XPLAT Legacy[8]; M128A_XPLAT Xmm0; M128A_XPLAT Xmm1; M128A_XPLAT Xmm2; M128A_XPLAT Xmm3; M128A_XPLAT Xmm4; M128A_XPLAT Xmm5; M128A_XPLAT Xmm6; M128A_XPLAT Xmm7; M128A_XPLAT Xmm8; M128A_XPLAT Xmm9; M128A_XPLAT Xmm10; M128A_XPLAT Xmm11; M128A_XPLAT Xmm12; M128A_XPLAT Xmm13; M128A_XPLAT Xmm14; M128A_XPLAT Xmm15; } DUMMYSTRUCTNAME; } DUMMYUNIONNAME; M128A_XPLAT VectorRegister[26]; DWORD64 VectorControl; DWORD64 DebugControl; DWORD64 LastBranchToRip; DWORD64 LastBranchFromRip; DWORD64 LastExceptionToRip; DWORD64 LastExceptionFromRip; } AMD64_CONTEXT; typedef struct{ __int64 LowPart; __int64 HighPart; } FLOAT128_XPLAT; /// ARM Context #define ARM_MAX_BREAKPOINTS_CONST 8 #define ARM_MAX_WATCHPOINTS_CONST 4 typedef struct { DWORD ContextFlags; DWORD R0; DWORD R1; DWORD R2; DWORD R3; DWORD R4; DWORD R5; DWORD R6; DWORD R7; DWORD R8; DWORD R9; DWORD R10; DWORD R11; DWORD R12; DWORD Sp; DWORD Lr; DWORD Pc; DWORD Cpsr; DWORD Fpscr; union { M128A_XPLAT Q[16]; ULONGLONG D[32]; DWORD S[32]; } DUMMYUNIONNAME; DWORD Bvr[ARM_MAX_BREAKPOINTS_CONST]; DWORD Bcr[ARM_MAX_BREAKPOINTS_CONST]; DWORD Wvr[ARM_MAX_WATCHPOINTS_CONST]; DWORD Wcr[ARM_MAX_WATCHPOINTS_CONST]; } ARM_CONTEXT; // On ARM this mask is or'ed with the address of code to get an instruction pointer #ifndef THUMB_CODE #define THUMB_CODE 1 #endif //ARM64TODO: Verify the correctness of the following for ARM64 ///ARM64 Context #define ARM64_MAX_BREAKPOINTS 8 #define ARM64_MAX_WATCHPOINTS 2 typedef struct { DWORD ContextFlags; DWORD Cpsr; // NZVF + DAIF + CurrentEL + SPSel union { struct { DWORD64 X0; DWORD64 X1; DWORD64 X2; DWORD64 X3; DWORD64 X4; DWORD64 X5; DWORD64 X6; DWORD64 X7; DWORD64 X8; DWORD64 X9; DWORD64 X10; DWORD64 X11; DWORD64 X12; DWORD64 X13; DWORD64 X14; DWORD64 X15; DWORD64 X16; DWORD64 X17; DWORD64 X18; DWORD64 X19; DWORD64 X20; DWORD64 X21; DWORD64 X22; DWORD64 X23; DWORD64 X24; DWORD64 X25; DWORD64 X26; DWORD64 X27; DWORD64 X28; }; DWORD64 X[29]; }; DWORD64 Fp; DWORD64 Lr; DWORD64 Sp; DWORD64 Pc; M128A_XPLAT V[32]; DWORD Fpcr; DWORD Fpsr; DWORD Bcr[ARM64_MAX_BREAKPOINTS]; DWORD64 Bvr[ARM64_MAX_BREAKPOINTS]; DWORD Wcr[ARM64_MAX_WATCHPOINTS]; DWORD64 Wvr[ARM64_MAX_WATCHPOINTS]; } ARM64_CONTEXT; typedef struct _CROSS_PLATFORM_CONTEXT { _CROSS_PLATFORM_CONTEXT() {} union { X86_CONTEXT X86Context; AMD64_CONTEXT Amd64Context; ARM_CONTEXT ArmContext; ARM64_CONTEXT Arm64Context; }; } CROSS_PLATFORM_CONTEXT, *PCROSS_PLATFORM_CONTEXT; WString BuildRegisterOutput(const SOSStackRefData &ref, bool printObj = true); WString MethodNameFromIP(CLRDATA_ADDRESS methodDesc, BOOL bSuppressLines = FALSE, BOOL bAssemblyName = FALSE, BOOL bDisplacement = FALSE); HRESULT GetGCRefs(ULONG osID, SOSStackRefData **ppRefs, unsigned int *pRefCnt, SOSStackRefError **ppErrors, unsigned int *pErrCount); WString GetFrameFromAddress(TADDR frameAddr, IXCLRDataStackWalk *pStackwalk = NULL, BOOL bAssemblyName = FALSE); /* This cache is used to read data from the target process if the reads are known * to be sequential. */ class LinearReadCache { public: LinearReadCache(ULONG pageSize = 0x10000); ~LinearReadCache(); /* Reads an address out of the target process, caching the page of memory read. * Params: * addr - The address to read out of the target process. * t - A pointer to the data to stuff it in. We will read sizeof(T) data * from the process and write it into the location t points to. This * parameter must be non-null. * Returns: * True if the read succeeded. False if it did not, usually as a result * of the memory simply not being present in the target process. * Note: * The state of *t is undefined if this function returns false. We may * have written partial data to it if we return false, so you must * absolutely NOT use it if Read returns false. */ template <class T> bool Read(TADDR addr, T *t, bool update = true) { _ASSERTE(t); // Unfortunately the ctor can fail the alloc for the byte array. In this case // we'll just fall back to non-cached reads. if (mPage == NULL) return MisalignedRead(addr, t); // Is addr on the current page? If not read the page of memory addr is on. // If this fails, we will fall back to a raw read out of the process (which // is what MisalignedRead does). if ((addr < mCurrPageStart) || (addr - mCurrPageStart > mCurrPageSize)) if (!update || !MoveToPage(addr)) return MisalignedRead(addr, t); // If MoveToPage succeeds, we MUST be on the right page. _ASSERTE(addr >= mCurrPageStart); // However, the amount of data requested may fall off of the page. In that case, // fall back to MisalignedRead. TADDR offset = addr - mCurrPageStart; if (offset + sizeof(T) > mCurrPageSize) return MisalignedRead(addr, t); // If we reach here we know we are on the right page of memory in the cache, and // that the read won't fall off of the end of the page. #ifdef _DEBUG mReads++; #endif *t = *reinterpret_cast<T*>(mPage+offset); return true; } void EnsureRangeInCache(TADDR start, unsigned int size) { if (mCurrPageStart == start) { if (size <= mCurrPageSize) return; // Total bytes to read, don't overflow buffer. unsigned int total = size + mCurrPageSize; if (total + mCurrPageSize > mPageSize) total = mPageSize-mCurrPageSize; // Read into the middle of the buffer, update current page size. ULONG read = 0; HRESULT hr = g_ExtData->ReadVirtual(mCurrPageStart+mCurrPageSize, mPage+mCurrPageSize, total, &read); mCurrPageSize += read; if (hr != S_OK) { mCurrPageStart = 0; mCurrPageSize = 0; } } else { MoveToPage(start, size); } } void ClearStats() { #ifdef _DEBUG mMisses = 0; mReads = 0; mMisaligned = 0; #endif } void PrintStats(const char *func) { #ifdef _DEBUG char buffer[1024]; sprintf_s(buffer, _countof(buffer), "Cache (%s): %d reads (%2.1f%% hits), %d misses (%2.1f%%), %d misaligned (%2.1f%%).\n", func, mReads, 100*(mReads-mMisses)/(float)(mReads+mMisaligned), mMisses, 100*mMisses/(float)(mReads+mMisaligned), mMisaligned, 100*mMisaligned/(float)(mReads+mMisaligned)); OutputDebugStringA(buffer); #endif } private: /* Sets the cache to the page specified by addr, or false if we could not move to * that page. */ bool MoveToPage(TADDR addr, unsigned int size = 0x18); /* Attempts to read from the target process if the data is possibly hanging off * the end of a page. */ template<class T> inline bool MisalignedRead(TADDR addr, T *t) { ULONG fetched = 0; HRESULT hr = g_ExtData->ReadVirtual(addr, (BYTE*)t, sizeof(T), &fetched); if (FAILED(hr) || fetched != sizeof(T)) return false; mMisaligned++; return true; } private: TADDR mCurrPageStart; ULONG mPageSize, mCurrPageSize; BYTE *mPage; int mMisses, mReads, mMisaligned; }; /////////////////////////////////////////////////////////////////////////////////////////// // // Methods for creating a database out of the gc heap and it's roots in xml format or CLRProfiler format // #include <unordered_map> #include <unordered_set> #include <list> class TypeTree; enum { FORMAT_XML=0, FORMAT_CLRPROFILER=1 }; enum { TYPE_START=0,TYPE_TYPES=1,TYPE_ROOTS=2,TYPE_OBJECTS=3,TYPE_HIGHEST=4}; class HeapTraverser { private: TypeTree *m_pTypeTree; size_t m_curNID; FILE *m_file; int m_format; // from the enum above size_t m_objVisited; // for UI updates bool m_verify; LinearReadCache mCache; std::unordered_map<TADDR, std::list<TADDR>> mDependentHandleMap; public: HeapTraverser(bool verify); ~HeapTraverser(); FILE *getFile() { return m_file; } BOOL Initialize(); BOOL CreateReport (FILE *fp, int format); private: // First all types are added to a tree void insert(size_t mTable); size_t getID(size_t mTable); // Functions for writing to the output file. void PrintType(size_t ID,LPCWSTR name); void PrintObjectHead(size_t objAddr,size_t typeID,size_t Size); void PrintObjectMember(size_t memberValue, bool dependentHandle); void PrintObjectTail(); void PrintRootHead(); void PrintRoot(LPCWSTR kind,size_t Value); void PrintRootTail(); void PrintSection(int Type,BOOL bOpening); // Root and object member helper functions void FindGCRootOnStacks(); void PrintRefs(size_t obj, size_t methodTable, size_t size); // Callback functions used during traversals static void GatherTypes(DWORD_PTR objAddr,size_t Size,DWORD_PTR methodTable, LPVOID token); static void PrintHeap(DWORD_PTR objAddr,size_t Size,DWORD_PTR methodTable, LPVOID token); static void PrintOutTree(size_t methodTable, size_t ID, LPVOID token); void TraceHandles(); }; class GCRootImpl { private: struct MTInfo { TADDR MethodTable; WCHAR *TypeName; TADDR *Buffer; CGCDesc *GCDesc; bool ArrayOfVC; bool ContainsPointers; size_t BaseSize; size_t ComponentSize; const WCHAR *GetTypeName() { if (!TypeName) TypeName = CreateMethodTableName(MethodTable); if (!TypeName) return W("<error>"); return TypeName; } MTInfo() : MethodTable(0), TypeName(0), Buffer(0), GCDesc(0), ArrayOfVC(false), ContainsPointers(false), BaseSize(0), ComponentSize(0) { } ~MTInfo() { if (Buffer) delete [] Buffer; if (TypeName) delete [] TypeName; } }; struct RootNode { RootNode *Next; RootNode *Prev; TADDR Object; MTInfo *MTInfo; bool FilledRefs; bool FromDependentHandle; RootNode *GCRefs; const WCHAR *GetTypeName() { if (!MTInfo) return W("<unknown>"); return MTInfo->GetTypeName(); } RootNode() : Next(0), Prev(0) { Clear(); } void Clear() { if (Next && Next->Prev == this) Next->Prev = NULL; if (Prev && Prev->Next == this) Prev->Next = NULL; Next = 0; Prev = 0; Object = 0; MTInfo = 0; FilledRefs = false; FromDependentHandle = false; GCRefs = 0; } void Remove(RootNode *&list) { RootNode *curr_next = Next; // We've already considered this object, remove it. if (Prev == NULL) { // If we've filtered out the head, update it. list = curr_next; if (curr_next) curr_next->Prev = NULL; } else { // Otherwise remove the current item from the list Prev->Next = curr_next; if (curr_next) curr_next->Prev = Prev; } } }; public: static void GetDependentHandleMap(std::unordered_map<TADDR, std::list<TADDR>> &map); public: // Finds all objects which root "target" and prints the path from the root // to "target". If all is true, all possible paths to the object are printed. // If all is false, only completely unique paths will be printed. int PrintRootsForObject(TADDR obj, bool all, bool noStacks); // Finds a path from root to target if it exists and prints it out. Returns // true if it found a path, false otherwise. bool PrintPathToObject(TADDR root, TADDR target); // Calculates the size of the closure of objects kept alive by root. size_t ObjSize(TADDR root); // Walks each root, printing out the total amount of memory held alive by it. void ObjSize(); // Returns the set of all live objects in the process. const std::unordered_set<TADDR> &GetLiveObjects(bool excludeFQ = false); // See !FindRoots. int FindRoots(int gen, TADDR target); private: // typedefs typedef void (*ReportCallback)(TADDR root, RootNode *path, bool printHeader); // Book keeping and debug. void ClearAll(); void ClearNodes(); void ClearSizeData(); // Printing roots int PrintRootsOnHandleTable(int gen = -1); int PrintRootsOnAllThreads(); int PrintRootsOnThread(DWORD osThreadId); int PrintRootsOnFQ(bool notReadyForFinalization = false); int PrintRootsInOlderGen(); int PrintRootsInRange(LinearReadCache &cache, TADDR start, TADDR stop, ReportCallback func, bool printHeader); // Calculate gc root RootNode *FilterRoots(RootNode *&list); RootNode *FindPathToTarget(TADDR root); RootNode *GetGCRefs(RootNode *path, RootNode *node); void InitDependentHandleMap(); //Reporting: void ReportOneHandlePath(const SOSHandleData &handle, RootNode *node, bool printHeader); void ReportOnePath(DWORD thread, const SOSStackRefData &stackRef, RootNode *node, bool printThread, bool printFrame); static void ReportOneFQEntry(TADDR root, RootNode *path, bool printHeader); static void ReportOlderGenEntry(TADDR root, RootNode *path, bool printHeader); void ReportSizeInfo(const SOSHandleData &handle, TADDR obj); void ReportSizeInfo(DWORD thread, const SOSStackRefData &ref, TADDR obj); // Data reads: TADDR ReadPointer(TADDR location); TADDR ReadPointerCached(TADDR location); // Object/MT data: MTInfo *GetMTInfo(TADDR mt); DWORD GetComponents(TADDR obj, TADDR mt); size_t GetSizeOfObject(TADDR obj, MTInfo *info); // RootNode management: RootNode *NewNode(TADDR obj = 0, MTInfo *mtinfo = 0, bool fromDependent = false); void DeleteNode(RootNode *node); private: bool mAll, // Print all roots or just unique roots? mSize; // Print rooting information or total size info? std::list<RootNode*> mCleanupList; // A list of RootNode's we've newed up. This is only used to delete all of them later. std::list<RootNode*> mRootNewList; // A list of unused RootNodes that are free to use instead of having to "new" up more. std::unordered_map<TADDR, MTInfo*> mMTs; // The MethodTable cache which maps from MT -> MethodTable data (size, gcdesc, string typename) std::unordered_map<TADDR, RootNode*> mTargets; // The objects that we are searching for. std::unordered_set<TADDR> mConsidered; // A hashtable of objects we've already visited. std::unordered_map<TADDR, size_t> mSizes; // A mapping from object address to total size of data the object roots. std::unordered_map<TADDR, std::list<TADDR>> mDependentHandleMap; LinearReadCache mCache; // A linear cache which stops us from having to read from the target process more than 1-2 times per object. }; // // Helper class used for type-safe bitflags // T - the enum type specifying the individual bit flags // U - the underlying/storage type // Requirement: // sizeof(T) <= sizeof(U) // template <typename T, typename U> struct Flags { typedef T UnderlyingType; typedef U BitFlagEnumType; static_assert_no_msg(sizeof(BitFlagEnumType) <= sizeof(UnderlyingType)); Flags(UnderlyingType v) : m_val(v) { } Flags(BitFlagEnumType v) : m_val(v) { } Flags(const Flags& other) : m_val(other.m_val) { } Flags& operator = (const Flags& other) { m_val = other.m_val; return *this; } Flags operator | (Flags other) const { return Flags<T, U>(m_val | other._val); } void operator |= (Flags other) { m_val |= other.m_val; } Flags operator & (Flags other) const { return Flags<T, U>(m_val & other.m_val); } void operator &= (Flags other) { m_val &= other.m_val; } Flags operator ^ (Flags other) const { return Flags<T, U>(m_val ^ other._val); } void operator ^= (Flags other) { m_val ^= other.m_val; } BOOL operator == (Flags other) const { return m_val == other.m_val; } BOOL operator != (Flags other) const { return m_val != other.m_val; } private: UnderlyingType m_val; }; #ifndef FEATURE_PAL // Flags defining activation policy for COM objects enum CIOptionsBits { cciLatestFx = 0x01, // look in the most recent .NETFx installation cciMatchFx = 0x02, // NYI: Look in the .NETFx installation matching the debuggee's runtime cciAnyFx = 0x04, // look in any .NETFx installation cciFxMask = 0x0f, cciDbiColocated = 0x10, // NYI: Look next to the already loaded DBI module cciDacColocated = 0x20, // Look next to the already loaded DAC module cciDbgPath = 0x40, // Look in all folders in the debuggers symbols and binary path }; typedef Flags<DWORD, CIOptionsBits> CIOptions; /**********************************************************************\ * Routine Description: * * * * CreateInstanceCustom() provides a way to activate a COM object w/o * * triggering the FeatureOnDemand dialog. In order to do this we * * must avoid using the CoCreateInstance() API, which, on a machine * * with v4+ installed and w/o v2, would trigger this. * * CreateInstanceCustom() activates the requested COM object according * * to the specified passed in CIOptions, in the following order * * (skipping the steps not enabled in the CIOptions flags passed in): * * 1. Attempt to activate the COM object using a framework install: * * a. If the debugger machine has a V4+ shell shim use the shim * * to activate the object * * b. Otherwise simply call CoCreateInstance * * 2. If unsuccessful attempt to activate looking for the dllName in * * the same folder as the DAC was loaded from * * 3. If unsuccessful attempt to activate the COM object looking in * * every path specified in the debugger's .exepath and .sympath * \**********************************************************************/ HRESULT CreateInstanceCustom( REFCLSID clsid, REFIID iid, LPCWSTR dllName, CIOptions cciOptions, void** ppItf); //------------------------------------------------------------------------ // A typesafe version of GetProcAddress //------------------------------------------------------------------------ template <typename T> BOOL GetProcAddressT( ___in PCSTR FunctionName, __in_opt PCWSTR DllName, __inout T* OutFunctionPointer, __inout HMODULE* InOutDllHandle ) { _ASSERTE(InOutDllHandle != NULL); _ASSERTE(OutFunctionPointer != NULL); T FunctionPointer = NULL; HMODULE DllHandle = *InOutDllHandle; if (DllHandle == NULL) { DllHandle = LoadLibraryExW(DllName, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); if (DllHandle != NULL) *InOutDllHandle = DllHandle; } if (DllHandle != NULL) { FunctionPointer = (T) GetProcAddress(DllHandle, FunctionName); } *OutFunctionPointer = FunctionPointer; return FunctionPointer != NULL; } #endif // FEATURE_PAL struct ImageInfo { ULONG64 modBase; }; HRESULT GetClrModuleImages( ___in IXCLRDataModule* Module, ___in CLRDataModuleExtentType DesiredType, ___out ImageInfo* FirstAdd); // Helper class used in ClrStackFromPublicInterface() to keep track of explicit EE Frames // (i.e., "internal frames") on the stack. Call Init() with the appropriate // ICorDebugThread3, and this class will initialize itself with the set of internal // frames. You can then call PrintPrecedingInternalFrames during your stack walk to // have this class output any internal frames that "precede" (i.e., that are closer to // the leaf than) the specified ICorDebugFrame. class InternalFrameManager { private: // TODO: Verify constructor AND destructor is called for each array element // TODO: Comment about hard-coding 1000 ToRelease<ICorDebugInternalFrame2> m_rgpInternalFrame2[1000]; ULONG32 m_cInternalFramesActual; ULONG32 m_iInternalFrameCur; public: InternalFrameManager(); HRESULT Init(ICorDebugThread3 * pThread3); HRESULT PrintPrecedingInternalFrames(ICorDebugFrame * pFrame); private: HRESULT PrintCurrentInternalFrame(); }; #endif // __util_h__
sperling/coreclr
src/ToolBox/SOS/Strike/util.h
C
mit
95,942
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="de"> <head> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Class org.apache.commons.lang3.SerializationUtils (Apache Commons Lang 3.4 API)</title> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.commons.lang3.SerializationUtils (Apache Commons Lang 3.4 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/apache/commons/lang3/SerializationUtils.html" title="class in org.apache.commons.lang3">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/commons/lang3/class-use/SerializationUtils.html" target="_top">Frames</a></li> <li><a href="SerializationUtils.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.commons.lang3.SerializationUtils" class="title">Uses of Class<br>org.apache.commons.lang3.SerializationUtils</h2> </div> <div class="classUseContainer">No usage of org.apache.commons.lang3.SerializationUtils</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/apache/commons/lang3/SerializationUtils.html" title="class in org.apache.commons.lang3">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/commons/lang3/class-use/SerializationUtils.html" target="_top">Frames</a></li> <li><a href="SerializationUtils.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2001&#x2013;2015 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p> </body> </html>
andrei128x/NuCS
server_code/commons-lang3-3.4/apidocs/org/apache/commons/lang3/class-use/SerializationUtils.html
HTML
mit
4,370
package org.bouncycastle.crypto.test; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Vector; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.engines.NaccacheSternEngine; import org.bouncycastle.crypto.generators.NaccacheSternKeyPairGenerator; import org.bouncycastle.crypto.params.NaccacheSternKeyGenerationParameters; import org.bouncycastle.crypto.params.NaccacheSternKeyParameters; import org.bouncycastle.crypto.params.NaccacheSternPrivateKeyParameters; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTest; /** * Test case for NaccacheStern cipher. For details on this cipher, please see * * http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf * * Performs the following tests: * <ul> * <li> Toy example from the NaccacheSternPaper </li> * <li> 768 bit test with text "Now is the time for all good men." (ripped from RSA test) and * the same test with the first byte replaced by 0xFF </li> * <li> 1024 bit test analog to 768 bit test </li> * </ul> */ public class NaccacheSternTest extends SimpleTest { static final boolean debug = false; static final NaccacheSternEngine cryptEng = new NaccacheSternEngine(); static final NaccacheSternEngine decryptEng = new NaccacheSternEngine(); static { cryptEng.setDebug(debug); decryptEng.setDebug(debug); } // Values from NaccacheStern paper static final BigInteger a = BigInteger.valueOf(101); static final BigInteger u1 = BigInteger.valueOf(3); static final BigInteger u2 = BigInteger.valueOf(5); static final BigInteger u3 = BigInteger.valueOf(7); static final BigInteger b = BigInteger.valueOf(191); static final BigInteger v1 = BigInteger.valueOf(11); static final BigInteger v2 = BigInteger.valueOf(13); static final BigInteger v3 = BigInteger.valueOf(17); static final BigInteger ONE = BigInteger.valueOf(1); static final BigInteger TWO = BigInteger.valueOf(2); static final BigInteger sigma = u1.multiply(u2).multiply(u3).multiply(v1) .multiply(v2).multiply(v3); static final BigInteger p = TWO.multiply(a).multiply(u1).multiply(u2) .multiply(u3).add(ONE); static final BigInteger q = TWO.multiply(b).multiply(v1).multiply(v2) .multiply(v3).add(ONE); static final BigInteger n = p.multiply(q); static final BigInteger phi_n = p.subtract(ONE).multiply(q.subtract(ONE)); static final BigInteger g = BigInteger.valueOf(131); static final Vector smallPrimes = new Vector(); // static final BigInteger paperTest = BigInteger.valueOf(202); static final String input = "4e6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e"; static final BigInteger paperTest = BigInteger.valueOf(202); // // to check that we handling byte extension by big number correctly. // static final String edgeInput = "ff6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e"; public String getName() { return "NaccacheStern"; } public void performTest() { // Test with given key from NaccacheSternPaper (totally insecure) // First the Parameters from the NaccacheStern Paper // (see http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf ) smallPrimes.addElement(u1); smallPrimes.addElement(u2); smallPrimes.addElement(u3); smallPrimes.addElement(v1); smallPrimes.addElement(v2); smallPrimes.addElement(v3); NaccacheSternKeyParameters pubParameters = new NaccacheSternKeyParameters(false, g, n, sigma.bitLength()); NaccacheSternPrivateKeyParameters privParameters = new NaccacheSternPrivateKeyParameters(g, n, sigma.bitLength(), smallPrimes, phi_n); AsymmetricCipherKeyPair pair = new AsymmetricCipherKeyPair(pubParameters, privParameters); // Initialize Engines with KeyPair if (debug) { System.out.println("initializing encryption engine"); } cryptEng.init(true, pair.getPublic()); if (debug) { System.out.println("initializing decryption engine"); } decryptEng.init(false, pair.getPrivate()); byte[] data = paperTest.toByteArray(); if (!new BigInteger(data).equals(new BigInteger(enDeCrypt(data)))) { fail("failed NaccacheStern paper test"); } // // key generation test // // // 768 Bit test // if (debug) { System.out.println(); System.out.println("768 Bit TEST"); } // specify key generation parameters NaccacheSternKeyGenerationParameters genParam = new NaccacheSternKeyGenerationParameters(new SecureRandom(), 768, 8, 30, debug); // Initialize Key generator and generate key pair NaccacheSternKeyPairGenerator pGen = new NaccacheSternKeyPairGenerator(); pGen.init(genParam); pair = pGen.generateKeyPair(); if (((NaccacheSternKeyParameters)pair.getPublic()).getModulus().bitLength() < 768) { System.out.println("FAILED: key size is <786 bit, exactly " + ((NaccacheSternKeyParameters)pair.getPublic()).getModulus().bitLength() + " bit"); fail("failed key generation (768) length test"); } // Initialize Engines with KeyPair if (debug) { System.out.println("initializing " + genParam.getStrength() + " bit encryption engine"); } cryptEng.init(true, pair.getPublic()); if (debug) { System.out.println("initializing " + genParam.getStrength() + " bit decryption engine"); } decryptEng.init(false, pair.getPrivate()); // Basic data input data = Hex.decode(input); if (!new BigInteger(1, data).equals(new BigInteger(1, enDeCrypt(data)))) { fail("failed encryption decryption (" + genParam.getStrength() + ") basic test"); } // Data starting with FF byte (would be interpreted as negative // BigInteger) data = Hex.decode(edgeInput); if (!new BigInteger(1, data).equals(new BigInteger(1, enDeCrypt(data)))) { fail("failed encryption decryption (" + genParam.getStrength() + ") edgeInput test"); } // // 1024 Bit Test // /* if (debug) { System.out.println(); System.out.println("1024 Bit TEST"); } // specify key generation parameters genParam = new NaccacheSternKeyGenerationParameters(new SecureRandom(), 1024, 8, 40); pGen.init(genParam); pair = pGen.generateKeyPair(); if (((NaccacheSternKeyParameters)pair.getPublic()).getModulus().bitLength() < 1024) { if (debug) { System.out.println("FAILED: key size is <1024 bit, exactly " + ((NaccacheSternKeyParameters)pair.getPublic()).getModulus().bitLength() + " bit"); } fail("failed key generation (1024) length test"); } // Initialize Engines with KeyPair if (debug) { System.out.println("initializing " + genParam.getStrength() + " bit encryption engine"); } cryptEng.init(true, pair.getPublic()); if (debug) { System.out.println("initializing " + genParam.getStrength() + " bit decryption engine"); } decryptEng.init(false, pair.getPrivate()); if (debug) { System.out.println("Data is " + new BigInteger(1, data)); } // Basic data input data = Hex.decode(input); if (!new BigInteger(1, data).equals(new BigInteger(1, enDeCrypt(data)))) { fail("failed encryption decryption (" + genParam.getStrength() + ") basic test"); } // Data starting with FF byte (would be interpreted as negative // BigInteger) data = Hex.decode(edgeInput); if (!new BigInteger(1, data).equals(new BigInteger(1, enDeCrypt(data)))) { fail("failed encryption decryption (" + genParam.getStrength() + ") edgeInput test"); } */ // END OF TEST CASE try { new NaccacheSternEngine().processBlock(new byte[]{ 1 }, 0, 1); fail("failed initialisation check"); } catch (IllegalStateException e) { // expected } catch (InvalidCipherTextException e) { fail("failed initialisation check"); } if (debug) { System.out.println("All tests successful"); } } private byte[] enDeCrypt(byte[] input) { // create work array byte[] data = new byte[input.length]; System.arraycopy(input, 0, data, 0, data.length); // Perform encryption like in the paper from Naccache-Stern if (debug) { System.out.println("encrypting data. Data representation\n" // + "As String:.... " + new String(data) + "\n" + "As BigInteger: " + new BigInteger(1, data)); System.out.println("data length is " + data.length); } try { data = cryptEng.processData(data); } catch (InvalidCipherTextException e) { if (debug) { System.out.println("failed - exception " + e.toString() + "\n" + e.getMessage()); } fail("failed - exception " + e.toString() + "\n" + e.getMessage()); } if (debug) { System.out.println("enrypted data representation\n" // + "As String:.... " + new String(data) + "\n" + "As BigInteger: " + new BigInteger(1, data)); System.out.println("data length is " + data.length); } try { data = decryptEng.processData(data); } catch (InvalidCipherTextException e) { if (debug) { System.out.println("failed - exception " + e.toString() + "\n" + e.getMessage()); } fail("failed - exception " + e.toString() + "\n" + e.getMessage()); } if (debug) { System.out.println("decrypted data representation\n" // + "As String:.... " + new String(data) + "\n" + "As BigInteger: " + new BigInteger(1, data)); System.out.println("data length is " + data.length); } return data; } public static void main(String[] args) { runTest(new NaccacheSternTest()); } }
sake/bouncycastle-java
test/src/org/bouncycastle/crypto/test/NaccacheSternTest.java
Java
mit
11,131
require File.expand_path('../../../spec_helper', __FILE__) describe :rational_quo, shared: true do it "needs to be reviewed for spec completeness" end
askl56/rubyspec
shared/rational/quo.rb
Ruby
mit
154
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Security\Core\Authorization\Voter; /** * Let voters expose the attributes and types they care about. * * By returning false to either `supportsAttribute` or `supportsType`, the * voter will never be called for the specified attribute or subject. * * @author Jérémy Derussé <jeremy@derusse.com> */ interface CacheableVoterInterface extends VoterInterface { public function supportsAttribute(string $attribute): bool; /** * @param string $subjectType The type of the subject inferred by `get_class` or `get_debug_type` */ public function supportsType(string $subjectType): bool; }
Tobion/symfony
src/Symfony/Component/Security/Core/Authorization/Voter/CacheableVoterInterface.php
PHP
mit
879
})(); Clazz._coreLoaded = true;
xavierprat/chemEdData
libs/jsmol/jmol-14.8.0/jsmol/js/core/corebottom.js
JavaScript
mit
44
// Don't need this for our purposes module = function(){}; if(typeof equal != 'undefined') { equals = equal; } ok = function(actual, message) { equal(actual, true, message); } raises = function(fn, expected, message) { raisesError(fn, message); }; asyncTest = function(name, delay, fn) { test(name, fn); } start = function() { // Just pass through... } notStrictEqual = function(a, b, message) { equal(a === b, false, message); } var ensureArray = function(obj) { if(obj === null) { return []; } else if(Object.isArray(obj) && (!obj.indexOf || !obj.lastIndexOf)) { return obj.concat(); } else if(!Object.isArray(obj) && typeof obj == 'object') { return Array.prototype.slice.call(obj); } else { return obj; } } var CompatibleMethods = [ { module: Array.prototype, methods: [ { name: 'first', method: function(arr, n, guard){ if(guard) { return arr[0]; } return ensureArray(arr).first(n); } }, { name: 'last', method: function(arr, n, third){ // This is the same check that Underscore makes to hack // _.last to work with _.map if(third) n = 1; return ensureArray(arr).last(n); } }, { name: 'rest', method: function(arr, n, guard){ if(n === undefined) n = 1; if(guard) { return arr.slice(1); } return ensureArray(arr).from(n); } }, { name: 'compact', method: function(arr){ return ensureArray(arr).compact(true); } }, /* Object.extend is no longer compatible as it has conflict resolution now. { name: 'extend', method: function(){ return Object.SugarMethods['merge'].method.apply(this, arguments); } }, */ /* Array#flatten is no longer compatible as it has levels of flattening (not just deep/shallow) { name: 'flatten', method: function(arr){ return ensureArray(arr).flatten(); } }, */ { name: 'uniq', method: function(arr){ return ensureArray(arr).unique(); } }, { name: 'intersection', method: function(arr){ arr = ensureArray(arr); var args = Array.prototype.slice.call(arguments, 1); return Array.prototype.intersect.apply(arr, args); } }, { name: 'union', method: function(arr, a){ arr = ensureArray(arr); var args = Array.prototype.slice.call(arguments, 1); return Array.prototype.union.apply(arr, args); } }, /* { name: 'difference', method: function(arr, a){ arr = ensureArray(arr); var args = Array.prototype.slice.call(arguments, 1); return Array.prototype.subtract.apply(arr, args); } }, */ { name: 'indexOf', method: function(arr, a){ return ensureArray(arr).indexOf(a); } }, { name: 'lastIndexOf', method: function(arr, a){ return ensureArray(arr).lastIndexOf(a); } }, { name: 'range', method: function(start, stop, step){ if(arguments.length == 1){ stop = arguments[0]; start = 0; } var shift = step < 0 ? 1 : -1; return start.upto(stop + shift, null, step); } }, // Collections // _.each -> Array#forEach OR Object.each // _.map -> Array#map // _.reduce -> Array#reduce // _.reduceRight -> Array#reduceRight // _.invoke is doing some strange tapdancing for passing methods directly... // _.sortedIndex ... no direct equivalent // _.toArray ... no direct equivalent for arguments... Array.create? // _.size ... no direct equivalent for objects... obj.keys().length? { name: 'detect', method: function(arr, fn, context){ return Array.SugarMethods['find'].method.call(arr, fn.bind(context)); } }, { name: 'select', method: function(arr, fn, context){ return Array.SugarMethods['findAll'].method.call(arr, fn.bind(context)); } }, { name: 'reject', method: function(arr, fn, context){ return Array.SugarMethods['exclude'].method.call(arr, fn.bind(context)); } }, { name: 'all', method: function(arr, fn, context){ return Array.SugarMethods['all'].method.call(arr, fn.bind(context)); } }, { name: 'any', method: function(arr, fn, context){ if(!fn) fn = function(a){ return a; }; return Array.SugarMethods['some'].method.call(arr, fn.bind(context)); } }, /* { name: 'include', method: function(arr, val){ return Array.SugarMethods['has'].method.call(arr, val); } }, */ { name: 'pluck', method: function(arr, prop){ return Array.SugarMethods['map'].method.call(arr, prop); } }, { name: 'max', method: function(arr, fn, context){ if(!fn) fn = function(a){ return a; }; return Array.SugarMethods['max'].method.call(arr, fn.bind(context))[0]; } }, { name: 'min', method: function(arr, fn, context){ if(!fn) fn = function(a){ return a; }; return Array.SugarMethods['min'].method.call(arr, fn.bind(context))[0]; } }, { name: 'sortBy', method: function(arr, fn, context){ return Array.SugarMethods['sortBy'].method.call(arr, fn.bind(context)); } }, { name: 'groupBy', method: function(arr, fn){ return Array.SugarMethods['groupBy'].method.call(arr, fn); } }, // Objects // _.functions ... no direct equivalent // _.defaults ... no direct equivalent // _.tap ... no direct equivalent // _.isElement ... no direct equivalent // _.isArguments ... no direct equivalent // _.isNaN ... no direct equivalent // _.isNull ... no direct equivalent // _.isUndefined ... no direct equivalent { name: 'keys', method: function(){ return Object.SugarMethods['keys'].method.apply(this, arguments); } }, { name: 'values', method: function(){ return Object.SugarMethods['values'].method.apply(this, arguments); } }, { name: 'clone', method: function(){ return Object.SugarMethods['clone'].method.apply(this, arguments); } }, { name: 'isEqual', method: function(a, b){ if (a && a._chain) a = a._wrapped; if (b && b._chain) b = b._wrapped; if (a && a.isEqual) return a.isEqual(b); if (b && b.isEqual) return b.isEqual(a); return Object.SugarMethods['equal'].method.apply(this, arguments); } }, { name: 'isEmpty', method: function(){ return Object.SugarMethods['isEmpty'].method.apply(this, arguments); } }, { name: 'isArray', method: function(arr){ return Array.isArray(arr); } }, { name: 'isFunction', method: function(){ return Object.SugarMethods['isFunction'].method.apply(this, arguments); } }, { name: 'isString', method: function(){ return Object.SugarMethods['isString'].method.apply(this, arguments); } }, { name: 'isNumber', method: function(){ if(isNaN(arguments[0])) { // Sugar differs here as it's trying to stay aligned with Javascript and is // checking types only. return false; } return Object.SugarMethods['isNumber'].method.apply(this, arguments); } }, { name: 'isBoolean', method: function(){ return Object.SugarMethods['isBoolean'].method.apply(this, arguments); } }, { name: 'isDate', method: function(){ return Object.SugarMethods['isDate'].method.apply(this, arguments); } }, { name: 'isRegExp', method: function(){ return Object.SugarMethods['isRegExp'].method.apply(this, arguments); } }, // Functions // _.bindAll ... no direct equivalent (similar to bindAsEventListener??) // _.memoize ... no direct equivalent // _.debounce ... no direct equivalent // _.once ... no direct equivalent.. is this not similar to memoize? // _.wrap ... no direct equivalent.. // _.compose ... no direct equivalent.. math stuff { name: 'bind', method: function(fn){ var args = Array.prototype.slice.call(arguments, 1); return Function.prototype.bind.apply(fn, args); } }, { name: 'after', method: function(num, fn){ return Function.prototype.after.apply(fn, [num]); } }, { name: 'delay', method: function(fn){ var args = Array.prototype.slice.call(arguments, 1); return Function.prototype.delay.apply(fn, args); } }, { name: 'defer', method: function(fn){ var args = Array.prototype.slice.call(arguments, 1); return Function.prototype.delay.apply(fn, [1].concat(args)); } }, { name: 'throttle', method: function(fn, wait){ return Function.prototype.lazy.apply(fn, [wait]); } }, // Utility // _.noConflict ... no direct equivalent // _.identity ... no direct equivalent // _.mixin ... no direct equivalent // _.uniqueId ... no direct equivalent // _.template ... no direct equivalent // _.chain ... no direct equivalent // _.value ... no direct equivalent { name: 'times', method: function(n, fn){ return n.times(fn); } } ] } ]; var mapMethods = function() { var proto; CompatibleMethods.forEach(function(cm) { cm.methods.forEach(function(m) { _[m.name] = m.method; }); }); } mapMethods();
D1plo1d/Sugar
unit_tests/environments/underscore/adapter.js
JavaScript
mit
10,615
package aima.core.probability.util; import java.util.HashSet; import java.util.Map; import java.util.Set; import aima.core.probability.RandomVariable; import aima.core.probability.domain.Domain; import aima.core.probability.proposition.TermProposition; /** * Default implementation of the RandomVariable interface. * * Note: Also implements the TermProposition interface so its easy to use * RandomVariables in conjunction with propositions about them in the * Probability Model APIs. * * @author Ciaran O'Reilly */ public class RandVar implements RandomVariable, TermProposition { private String name = null; private Domain domain = null; private Set<RandomVariable> scope = new HashSet<RandomVariable>(); public RandVar(String name, Domain domain) { ProbUtil.checkValidRandomVariableName(name); if (null == domain) { throw new IllegalArgumentException( "Domain of RandomVariable must be specified."); } this.name = name; this.domain = domain; this.scope.add(this); } // // START-RandomVariable @Override public String getName() { return name; } @Override public Domain getDomain() { return domain; } // END-RandomVariable // // // START-TermProposition @Override public RandomVariable getTermVariable() { return this; } @Override public Set<RandomVariable> getScope() { return scope; } @Override public Set<RandomVariable> getUnboundScope() { return scope; } @Override public boolean holds(Map<RandomVariable, Object> possibleWorld) { return possibleWorld.containsKey(getTermVariable()); } // END-TermProposition // @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof RandomVariable)) { return false; } // The name (not the name:domain combination) uniquely identifies a // Random Variable RandomVariable other = (RandomVariable) o; return this.name.equals(other.getName()); } @Override public int hashCode() { return name.hashCode(); } @Override public String toString() { return getName(); } }
aima-java/aima-java
aima-core/src/main/java/aima/core/probability/util/RandVar.java
Java
mit
2,171
/****************************************************************************** * Spine Runtimes Software License * Version 2 * * Copyright (c) 2013, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable and * non-transferable license to install, execute and perform the Spine Runtimes * Software (the "Software") solely for internal use. Without the written * permission of Esoteric Software, you may not (a) modify, translate, adapt or * otherwise create derivative works, improvements of the Software or develop * new applications using the Software or (b) remove, delete, alter or obscure * any trademarks or any copyright, trademark, patent or other intellectual * property or proprietary rights notices on or in the Software, including * any copy thereof. Redistributions in binary or source form must include * this license and terms. THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTARE BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ #include <spine/EventData.h> #include <spine/extension.h> spEventData* spEventData_create (const char* name) { spEventData* self = NEW(spEventData); MALLOC_STR(self->name, name); return self; } void spEventData_dispose (spEventData* self) { FREE(self->stringValue); FREE(self->name); FREE(self); }
RichardRanft/Torque6
src/spine/EventData.c
C
mit
2,042
package aima.core.probability.bayes.exact; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import aima.core.probability.CategoricalDistribution; import aima.core.probability.Factor; import aima.core.probability.RandomVariable; import aima.core.probability.bayes.BayesInference; import aima.core.probability.bayes.BayesianNetwork; import aima.core.probability.bayes.FiniteNode; import aima.core.probability.bayes.Node; import aima.core.probability.proposition.AssignmentProposition; import aima.core.probability.util.ProbabilityTable; /** * Artificial Intelligence A Modern Approach (3rd Edition): Figure 14.11, page * 528.<br> * <br> * * <pre> * function ELIMINATION-ASK(X, e, bn) returns a distribution over X * inputs: X, the query variable * e, observed values for variables E * bn, a Bayesian network specifying joint distribution P(X<sub>1</sub>, ..., X<sub>n</sub>) * * factors <- [] * for each var in ORDER(bn.VARS) do * factors <- [MAKE-FACTOR(var, e) | factors] * if var is hidden variable the factors <- SUM-OUT(var, factors) * return NORMALIZE(POINTWISE-PRODUCT(factors)) * </pre> * * Figure 14.11 The variable elimination algorithm for inference in Bayesian * networks. <br> * <br> * <b>Note:</b> The implementation has been extended to handle queries with * multiple variables. <br> * * @author Ciaran O'Reilly */ public class EliminationAsk implements BayesInference { // private static final ProbabilityTable _identity = new ProbabilityTable( new double[] { 1.0 }); public EliminationAsk() { } // function ELIMINATION-ASK(X, e, bn) returns a distribution over X /** * The ELIMINATION-ASK algorithm in Figure 14.11. * * @param X * the query variables. * @param e * observed values for variables E. * @param bn * a Bayes net with variables {X} &cup; E &cup; Y /* Y = hidden * variables // * @return a distribution over the query variables. */ public CategoricalDistribution eliminationAsk(final RandomVariable[] X, final AssignmentProposition[] e, final BayesianNetwork bn) { Set<RandomVariable> hidden = new HashSet<RandomVariable>(); List<RandomVariable> VARS = new ArrayList<RandomVariable>(); calculateVariables(X, e, bn, hidden, VARS); // factors <- [] List<Factor> factors = new ArrayList<Factor>(); // for each var in ORDER(bn.VARS) do for (RandomVariable var : order(bn, VARS)) { // factors <- [MAKE-FACTOR(var, e) | factors] factors.add(0, makeFactor(var, e, bn)); // if var is hidden variable then factors <- SUM-OUT(var, factors) if (hidden.contains(var)) { factors = sumOut(var, factors, bn); } } // return NORMALIZE(POINTWISE-PRODUCT(factors)) Factor product = pointwiseProduct(factors); // Note: Want to ensure the order of the product matches the // query variables return ((ProbabilityTable) product.pointwiseProductPOS(_identity, X)) .normalize(); } // // START-BayesInference public CategoricalDistribution ask(final RandomVariable[] X, final AssignmentProposition[] observedEvidence, final BayesianNetwork bn) { return this.eliminationAsk(X, observedEvidence, bn); } // END-BayesInference // // // PROTECTED METHODS // /** * <b>Note:</b>Override this method for a more efficient implementation as * outlined in AIMA3e pgs. 527-28. Calculate the hidden variables from the * Bayesian Network. The default implementation does not perform any of * these.<br> * <br> * Two calcuations to be performed here in order to optimize iteration over * the Bayesian Network:<br> * 1. Calculate the hidden variables to be enumerated over. An optimization * (AIMA3e pg. 528) is to remove 'every variable that is not an ancestor of * a query variable or evidence variable as it is irrelevant to the query' * (i.e. sums to 1). 2. The subset of variables from the Bayesian Network to * be retained after irrelevant hidden variables have been removed. * * @param X * the query variables. * @param e * observed values for variables E. * @param bn * a Bayes net with variables {X} &cup; E &cup; Y /* Y = hidden * variables // * @param hidden * to be populated with the relevant hidden variables Y. * @param bnVARS * to be populated with the subset of the random variables * comprising the Bayesian Network with any irrelevant hidden * variables removed. */ protected void calculateVariables(final RandomVariable[] X, final AssignmentProposition[] e, final BayesianNetwork bn, Set<RandomVariable> hidden, Collection<RandomVariable> bnVARS) { bnVARS.addAll(bn.getVariablesInTopologicalOrder()); hidden.addAll(bnVARS); for (RandomVariable x : X) { hidden.remove(x); } for (AssignmentProposition ap : e) { hidden.removeAll(ap.getScope()); } return; } /** * <b>Note:</b>Override this method for a more efficient implementation as * outlined in AIMA3e pgs. 527-28. The default implementation does not * perform any of these.<br> * * @param bn * the Bayesian Network over which the query is being made. Note, * is necessary to provide this in order to be able to determine * the dependencies between variables. * @param vars * a subset of the RandomVariables making up the Bayesian * Network, with any irrelevant hidden variables alreay removed. * @return a possibly opimal ordering for the random variables to be * iterated over by the algorithm. For example, one fairly effective * ordering is a greedy one: eliminate whichever variable minimizes * the size of the next factor to be constructed. */ protected List<RandomVariable> order(BayesianNetwork bn, Collection<RandomVariable> vars) { // Note: Trivial Approach: // For simplicity just return in the reverse order received, // i.e. received will be the default topological order for // the Bayesian Network and we want to ensure the network // is iterated from bottom up to ensure when hidden variables // are come across all the factors dependent on them have // been seen so far. List<RandomVariable> order = new ArrayList<RandomVariable>(vars); Collections.reverse(order); return order; } // // PRIVATE METHODS // private Factor makeFactor(RandomVariable var, AssignmentProposition[] e, BayesianNetwork bn) { Node n = bn.getNode(var); if (!(n instanceof FiniteNode)) { throw new IllegalArgumentException( "Elimination-Ask only works with finite Nodes."); } FiniteNode fn = (FiniteNode) n; List<AssignmentProposition> evidence = new ArrayList<AssignmentProposition>(); for (AssignmentProposition ap : e) { if (fn.getCPT().contains(ap.getTermVariable())) { evidence.add(ap); } } return fn.getCPT().getFactorFor( evidence.toArray(new AssignmentProposition[evidence.size()])); } private List<Factor> sumOut(RandomVariable var, List<Factor> factors, BayesianNetwork bn) { List<Factor> summedOutFactors = new ArrayList<Factor>(); List<Factor> toMultiply = new ArrayList<Factor>(); for (Factor f : factors) { if (f.contains(var)) { toMultiply.add(f); } else { // This factor does not contain the variable // so no need to sum out - see AIMA3e pg. 527. summedOutFactors.add(f); } } summedOutFactors.add(pointwiseProduct(toMultiply).sumOut(var)); return summedOutFactors; } private Factor pointwiseProduct(List<Factor> factors) { Factor product = factors.get(0); for (int i = 1; i < factors.size(); i++) { product = product.pointwiseProduct(factors.get(i)); } return product; } }
aima-java/aima-java
aima-core/src/main/java/aima/core/probability/bayes/exact/EliminationAsk.java
Java
mit
8,132
//--------------------------------------------------------------------- // <copyright file="MessageReaderSettingsArgs.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- namespace Microsoft.OData.Client { using Microsoft.OData.Core; /// <summary> /// Arguments used to configure the odata message reader settings. /// </summary> public class MessageReaderSettingsArgs { /// <summary> /// Initializes a new instance of the <see cref="MessageReaderSettingsArgs"/> class. /// </summary> /// <param name="settings">The settings.</param> public MessageReaderSettingsArgs(ODataMessageReaderSettingsBase settings) { WebUtil.CheckArgumentNull(settings, "settings"); this.Settings = settings; } /// <summary> /// Gets the settings. /// </summary> public ODataMessageReaderSettingsBase Settings { get; private set; } } }
hotchandanisagar/odata.net
src/Microsoft.OData.Client/MessageReaderSettingsArgs.cs
C#
mit
1,175
/*@preserve * Tempus Dominus Bootstrap4 v5.0.0-alpha13 (https://tempusdominus.github.io/bootstrap-4/) * Copyright 2016-2017 Jonathan Peterson * Licensed under MIT (https://github.com/tempusdominus/bootstrap-3/blob/master/LICENSE) */ if (typeof jQuery === 'undefined') { throw new Error('Tempus Dominus Bootstrap4\'s requires jQuery. jQuery must be included before Tempus Dominus Bootstrap4\'s JavaScript.'); } +function ($) { var version = $.fn.jquery.split(' ')[0].split('.'); if ((version[0] < 2 && version[1] < 9) || (version[0] === 1 && version[1] === 9 && version[2] < 1) || (version[0] >= 4)) { throw new Error('Tempus Dominus Bootstrap4\'s requires at least jQuery v1.9.1 but less than v4.0.0'); } }(jQuery); if (typeof moment === 'undefined') { throw new Error('Tempus Dominus Bootstrap4\'s requires moment.js. Moment.js must be included before Tempus Dominus Bootstrap4\'s JavaScript.'); } var version = moment.version.split('.') if ((version[0] <= 2 && version[1] < 17) || (version[0] >= 3)) { throw new Error('Tempus Dominus Bootstrap4\'s requires at least moment.js v2.17.0 but less than v3.0.0'); } +function () { var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } // ReSharper disable once InconsistentNaming var DateTimePicker = function ($, moment) { // ReSharper disable InconsistentNaming var NAME = 'datetimepicker', VERSION = '5.0.0-alpha7', DATA_KEY = '' + NAME, EVENT_KEY = '.' + DATA_KEY, EMIT_EVENT_KEY = DATA_KEY + '.', DATA_API_KEY = '.data-api', Selector = { DATA_TOGGLE: '[data-toggle="' + DATA_KEY + '"]' }, ClassName = { INPUT: NAME + '-input' }, Event = { CHANGE: 'change' + EVENT_KEY, BLUR: 'blur' + EVENT_KEY, KEYUP: 'keyup' + EVENT_KEY, KEYDOWN: 'keydown' + EVENT_KEY, FOCUS: 'focus' + EVENT_KEY, CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY, //emitted UPDATE: EMIT_EVENT_KEY + 'update', ERROR: EMIT_EVENT_KEY + 'error', HIDE: EMIT_EVENT_KEY + 'hide', SHOW: EMIT_EVENT_KEY + 'show' }, Default = { timeZone: '', format: false, dayViewHeaderFormat: 'MMMM YYYY', extraFormats: false, stepping: 1, minDate: false, maxDate: false, useCurrent: true, collapse: true, locale: moment.locale(), defaultDate: false, disabledDates: false, enabledDates: false, icons: { time: 'fa fa-clock-o', date: 'fa fa-calendar', up: 'fa fa-arrow-up', down: 'fa fa-arrow-down', previous: 'fa fa-chevron-left', next: 'fa fa-chevron-right', today: 'fa fa-calendar-check-o', clear: 'fa fa-delete', close: 'fa fa-times' }, tooltips: { today: 'Go to today', clear: 'Clear selection', close: 'Close the picker', selectMonth: 'Select Month', prevMonth: 'Previous Month', nextMonth: 'Next Month', selectYear: 'Select Year', prevYear: 'Previous Year', nextYear: 'Next Year', selectDecade: 'Select Decade', prevDecade: 'Previous Decade', nextDecade: 'Next Decade', prevCentury: 'Previous Century', nextCentury: 'Next Century', pickHour: 'Pick Hour', incrementHour: 'Increment Hour', decrementHour: 'Decrement Hour', pickMinute: 'Pick Minute', incrementMinute: 'Increment Minute', decrementMinute: 'Decrement Minute', pickSecond: 'Pick Second', incrementSecond: 'Increment Second', decrementSecond: 'Decrement Second', togglePeriod: 'Toggle Period', selectTime: 'Select Time', selectDate: 'Select Date' }, useStrict: false, sideBySide: false, daysOfWeekDisabled: false, calendarWeeks: false, viewMode: 'days', toolbarPlacement: 'default', buttons: { showToday: false, showClear: false, showClose: false }, widgetPositioning: { horizontal: 'auto', vertical: 'auto' }, widgetParent: null, ignoreReadonly: false, keepOpen: false, focusOnShow: true, inline: false, keepInvalid: false, keyBinds: { up: function up() { if (!this.widget) { return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().subtract(7, 'd')); } else { this.date(d.clone().add(this.stepping(), 'm')); } return true; }, down: function down() { if (!this.widget) { this.show(); return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().add(7, 'd')); } else { this.date(d.clone().subtract(this.stepping(), 'm')); } return true; }, 'control up': function controlUp() { if (!this.widget) { return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().subtract(1, 'y')); } else { this.date(d.clone().add(1, 'h')); } return true; }, 'control down': function controlDown() { if (!this.widget) { return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().add(1, 'y')); } else { this.date(d.clone().subtract(1, 'h')); } return true; }, left: function left() { if (!this.widget) { return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().subtract(1, 'd')); } return true; }, right: function right() { if (!this.widget) { return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().add(1, 'd')); } return true; }, pageUp: function pageUp() { if (!this.widget) { return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().subtract(1, 'M')); } return true; }, pageDown: function pageDown() { if (!this.widget) { return false; } var d = this._dates[0] || this.getMoment(); if (this.widget.find('.datepicker').is(':visible')) { this.date(d.clone().add(1, 'M')); } return true; }, enter: function enter() { this.hide(); return true; }, escape: function escape() { if (!this.widget) { return false; } this.hide(); return true; }, 'control space': function controlSpace() { if (!this.widget) { return false; } if (this.widget.find('.timepicker').is(':visible')) { this.widget.find('.btn[data-action="togglePeriod"]').click(); } return true; }, t: function t() { this.date(this.getMoment()); return true; }, 'delete': function _delete() { if (!this.widget) { return false; } this.clear(); return true; } }, debug: false, allowInputToggle: false, disabledTimeIntervals: false, disabledHours: false, enabledHours: false, viewDate: false, allowMultidate: false, multidateSeparator: ',' }, DatePickerModes = [{ CLASS_NAME: 'days', NAV_FUNCTION: 'M', NAV_STEP: 1 }, { CLASS_NAME: 'months', NAV_FUNCTION: 'y', NAV_STEP: 1 }, { CLASS_NAME: 'years', NAV_FUNCTION: 'y', NAV_STEP: 10 }, { CLASS_NAME: 'decades', NAV_FUNCTION: 'y', NAV_STEP: 100 }], KeyMap = { 'up': 38, 38: 'up', 'down': 40, 40: 'down', 'left': 37, 37: 'left', 'right': 39, 39: 'right', 'tab': 9, 9: 'tab', 'escape': 27, 27: 'escape', 'enter': 13, 13: 'enter', 'pageUp': 33, 33: 'pageUp', 'pageDown': 34, 34: 'pageDown', 'shift': 16, 16: 'shift', 'control': 17, 17: 'control', 'space': 32, 32: 'space', 't': 84, 84: 't', 'delete': 46, 46: 'delete' }, ViewModes = ['times', 'days', 'months', 'years', 'decades'], keyState = {}, keyPressHandled = {}; var MinViewModeNumber = 0; // ReSharper restore InconsistentNaming // ReSharper disable once DeclarationHides // ReSharper disable once InconsistentNaming var DateTimePicker = function () { /** @namespace eData.dateOptions */ /** @namespace moment.tz */ function DateTimePicker(element, options) { _classCallCheck(this, DateTimePicker); this._options = this._getOptions(options); this._element = element; this._dates = []; this._datesFormatted = []; this._viewDate = null; this.unset = true; this.component = false; this.widget = false; this.use24Hours = null; this.actualFormat = null; this.parseFormats = null; this.currentViewMode = null; this._int(); } /** * @return {string} */ //private DateTimePicker.prototype._int = function _int() { var targetInput = this._element.data('target-input'); if (this._element.is('input')) { this.input = this._element; } else if (targetInput !== undefined) { if (targetInput === 'nearest') { this.input = this._element.find('input'); } else { this.input = $(targetInput); } } this._dates = []; this._dates[0] = this.getMoment(); this._viewDate = this.getMoment().clone(); $.extend(true, this._options, this._dataToOptions()); this.options(this._options); this._initFormatting(); if (this.input !== undefined && this.input.is('input') && this.input.val().trim().length !== 0) { this._setValue(this._parseInputDate(this.input.val().trim()), 0); } else if (this._options.defaultDate && this.input !== undefined && this.input.attr('placeholder') === undefined) { this._setValue(this._options.defaultDate, 0); } if (this._options.inline) { this.show(); } }; DateTimePicker.prototype._update = function _update() { if (!this.widget) { return; } this._fillDate(); this._fillTime(); }; DateTimePicker.prototype._setValue = function _setValue(targetMoment, index) { var oldDate = this.unset ? null : this._dates[index]; var outpValue = ''; // case of calling setValue(null or false) if (!targetMoment) { if (!this._options.allowMultidate || this._dates.length === 1) { this.unset = true; this._dates = []; this._datesFormatted = []; } else { outpValue = this._element.data('date') + ','; outpValue = outpValue.replace(oldDate.format(this.actualFormat) + ',', '').replace(',,', '').replace(/,\s*$/, ''); this._dates.splice(index, 1); this._datesFormatted.splice(index, 1); } if (this.input !== undefined) { this.input.val(outpValue); this.input.trigger('input'); } this._element.data('date', outpValue); this._notifyEvent({ type: DateTimePicker.Event.CHANGE, date: false, oldDate: oldDate }); this._update(); return; } targetMoment = targetMoment.clone().locale(this._options.locale); if (this._hasTimeZone()) { targetMoment.tz(this._options.timeZone); } if (this._options.stepping !== 1) { targetMoment.minutes(Math.round(targetMoment.minutes() / this._options.stepping) * this._options.stepping).seconds(0); } if (this._isValid(targetMoment)) { this._dates[index] = targetMoment; this._datesFormatted[index] = targetMoment.format('YYYY-MM-DD'); this._viewDate = targetMoment.clone(); if (this._options.allowMultidate && this._dates.length > 1) { for (var i = 0; i < this._dates.length; i++) { outpValue += '' + this._dates[i].format(this.actualFormat) + this._options.multidateSeparator; } outpValue = outpValue.replace(/,\s*$/, ''); } else { outpValue = this._dates[index].format(this.actualFormat); } if (this.input !== undefined) { this.input.val(outpValue); this.input.trigger('input'); } this._element.data('date', outpValue); this.unset = false; this._update(); this._notifyEvent({ type: DateTimePicker.Event.CHANGE, date: this._dates[index].clone(), oldDate: oldDate }); } else { if (!this._options.keepInvalid) { if (this.input !== undefined) { this.input.val('' + (this.unset ? '' : this._dates[index].format(this.actualFormat))); this.input.trigger('input'); } } else { this._notifyEvent({ type: DateTimePicker.Event.CHANGE, date: targetMoment, oldDate: oldDate }); } this._notifyEvent({ type: DateTimePicker.Event.ERROR, date: targetMoment, oldDate: oldDate }); } }; DateTimePicker.prototype._change = function _change(e) { var val = $(e.target).val().trim(), parsedDate = val ? this._parseInputDate(val) : null; this._setValue(parsedDate); e.stopImmediatePropagation(); return false; }; //noinspection JSMethodCanBeStatic DateTimePicker.prototype._getOptions = function _getOptions(options) { options = $.extend(true, {}, Default, options); return options; }; DateTimePicker.prototype._hasTimeZone = function _hasTimeZone() { return moment.tz !== undefined && this._options.timeZone !== undefined && this._options.timeZone !== null && this._options.timeZone !== ''; }; DateTimePicker.prototype._isEnabled = function _isEnabled(granularity) { if (typeof granularity !== 'string' || granularity.length > 1) { throw new TypeError('isEnabled expects a single character string parameter'); } switch (granularity) { case 'y': return this.actualFormat.indexOf('Y') !== -1; case 'M': return this.actualFormat.indexOf('M') !== -1; case 'd': return this.actualFormat.toLowerCase().indexOf('d') !== -1; case 'h': case 'H': return this.actualFormat.toLowerCase().indexOf('h') !== -1; case 'm': return this.actualFormat.indexOf('m') !== -1; case 's': return this.actualFormat.indexOf('s') !== -1; default: return false; } }; DateTimePicker.prototype._hasTime = function _hasTime() { return this._isEnabled('h') || this._isEnabled('m') || this._isEnabled('s'); }; DateTimePicker.prototype._hasDate = function _hasDate() { return this._isEnabled('y') || this._isEnabled('M') || this._isEnabled('d'); }; DateTimePicker.prototype._dataToOptions = function _dataToOptions() { var eData = this._element.data(); var dataOptions = {}; if (eData.dateOptions && eData.dateOptions instanceof Object) { dataOptions = $.extend(true, dataOptions, eData.dateOptions); } $.each(this._options, function (key) { var attributeName = 'date' + key.charAt(0).toUpperCase() + key.slice(1); //todo data api key if (eData[attributeName] !== undefined) { dataOptions[key] = eData[attributeName]; } else { delete dataOptions[key]; } }); return dataOptions; }; DateTimePicker.prototype._notifyEvent = function _notifyEvent(e) { if (e.type === DateTimePicker.Event.CHANGE && e.date && e.date.isSame(e.oldDate) || !e.date && !e.oldDate) { return; } this._element.trigger(e); }; DateTimePicker.prototype._viewUpdate = function _viewUpdate(e) { if (e === 'y') { e = 'YYYY'; } this._notifyEvent({ type: DateTimePicker.Event.UPDATE, change: e, viewDate: this._viewDate.clone() }); }; DateTimePicker.prototype._showMode = function _showMode(dir) { if (!this.widget) { return; } if (dir) { this.currentViewMode = Math.max(MinViewModeNumber, Math.min(3, this.currentViewMode + dir)); } this.widget.find('.datepicker > div').hide().filter('.datepicker-' + DatePickerModes[this.currentViewMode].CLASS_NAME).show(); }; DateTimePicker.prototype._isInDisabledDates = function _isInDisabledDates(testDate) { return this._options.disabledDates[testDate.format('YYYY-MM-DD')] === true; }; DateTimePicker.prototype._isInEnabledDates = function _isInEnabledDates(testDate) { return this._options.enabledDates[testDate.format('YYYY-MM-DD')] === true; }; DateTimePicker.prototype._isInDisabledHours = function _isInDisabledHours(testDate) { return this._options.disabledHours[testDate.format('H')] === true; }; DateTimePicker.prototype._isInEnabledHours = function _isInEnabledHours(testDate) { return this._options.enabledHours[testDate.format('H')] === true; }; DateTimePicker.prototype._isValid = function _isValid(targetMoment, granularity) { if (!targetMoment.isValid()) { return false; } if (this._options.disabledDates && granularity === 'd' && this._isInDisabledDates(targetMoment)) { return false; } if (this._options.enabledDates && granularity === 'd' && !this._isInEnabledDates(targetMoment)) { return false; } if (this._options.minDate && targetMoment.isBefore(this._options.minDate, granularity)) { return false; } if (this._options.maxDate && targetMoment.isAfter(this._options.maxDate, granularity)) { return false; } if (this._options.daysOfWeekDisabled && granularity === 'd' && this._options.daysOfWeekDisabled.indexOf(targetMoment.day()) !== -1) { return false; } if (this._options.disabledHours && (granularity === 'h' || granularity === 'm' || granularity === 's') && this._isInDisabledHours(targetMoment)) { return false; } if (this._options.enabledHours && (granularity === 'h' || granularity === 'm' || granularity === 's') && !this._isInEnabledHours(targetMoment)) { return false; } if (this._options.disabledTimeIntervals && (granularity === 'h' || granularity === 'm' || granularity === 's')) { var found = false; $.each(this._options.disabledTimeIntervals, function () { if (targetMoment.isBetween(this[0], this[1])) { found = true; return false; } }); if (found) { return false; } } return true; }; DateTimePicker.prototype._parseInputDate = function _parseInputDate(inputDate) { if (this._options.parseInputDate === undefined) { if (!moment.isMoment(inputDate)) { inputDate = this.getMoment(inputDate); } } else { inputDate = this._options.parseInputDate(inputDate); } //inputDate.locale(this.options.locale); return inputDate; }; DateTimePicker.prototype._keydown = function _keydown(e) { var handler = null, index = void 0, index2 = void 0, keyBindKeys = void 0, allModifiersPressed = void 0; var pressedKeys = [], pressedModifiers = {}, currentKey = e.which, pressed = 'p'; keyState[currentKey] = pressed; for (index in keyState) { if (keyState.hasOwnProperty(index) && keyState[index] === pressed) { pressedKeys.push(index); if (parseInt(index, 10) !== currentKey) { pressedModifiers[index] = true; } } } for (index in this._options.keyBinds) { if (this._options.keyBinds.hasOwnProperty(index) && typeof this._options.keyBinds[index] === 'function') { keyBindKeys = index.split(' '); if (keyBindKeys.length === pressedKeys.length && KeyMap[currentKey] === keyBindKeys[keyBindKeys.length - 1]) { allModifiersPressed = true; for (index2 = keyBindKeys.length - 2; index2 >= 0; index2--) { if (!(KeyMap[keyBindKeys[index2]] in pressedModifiers)) { allModifiersPressed = false; break; } } if (allModifiersPressed) { handler = this._options.keyBinds[index]; break; } } } } if (handler) { if (handler.call(this.widget)) { e.stopPropagation(); e.preventDefault(); } } }; //noinspection JSMethodCanBeStatic,SpellCheckingInspection DateTimePicker.prototype._keyup = function _keyup(e) { keyState[e.which] = 'r'; if (keyPressHandled[e.which]) { keyPressHandled[e.which] = false; e.stopPropagation(); e.preventDefault(); } }; DateTimePicker.prototype._indexGivenDates = function _indexGivenDates(givenDatesArray) { // Store given enabledDates and disabledDates as keys. // This way we can check their existence in O(1) time instead of looping through whole array. // (for example: options.enabledDates['2014-02-27'] === true) var givenDatesIndexed = {}, self = this; $.each(givenDatesArray, function () { var dDate = self._parseInputDate(this); if (dDate.isValid()) { givenDatesIndexed[dDate.format('YYYY-MM-DD')] = true; } }); return Object.keys(givenDatesIndexed).length ? givenDatesIndexed : false; }; DateTimePicker.prototype._indexGivenHours = function _indexGivenHours(givenHoursArray) { // Store given enabledHours and disabledHours as keys. // This way we can check their existence in O(1) time instead of looping through whole array. // (for example: options.enabledHours['2014-02-27'] === true) var givenHoursIndexed = {}; $.each(givenHoursArray, function () { givenHoursIndexed[this] = true; }); return Object.keys(givenHoursIndexed).length ? givenHoursIndexed : false; }; DateTimePicker.prototype._initFormatting = function _initFormatting() { var format = this._options.format || 'L LT', self = this; this.actualFormat = format.replace(/(\[[^\[]*])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, function (formatInput) { return self._dates[0].localeData().longDateFormat(formatInput) || formatInput; //todo taking the first date should be ok }); this.parseFormats = this._options.extraFormats ? this._options.extraFormats.slice() : []; if (this.parseFormats.indexOf(format) < 0 && this.parseFormats.indexOf(this.actualFormat) < 0) { this.parseFormats.push(this.actualFormat); } this.use24Hours = this.actualFormat.toLowerCase().indexOf('a') < 1 && this.actualFormat.replace(/\[.*?]/g, '').indexOf('h') < 1; if (this._isEnabled('y')) { MinViewModeNumber = 2; } if (this._isEnabled('M')) { MinViewModeNumber = 1; } if (this._isEnabled('d')) { MinViewModeNumber = 0; } this.currentViewMode = Math.max(MinViewModeNumber, this.currentViewMode); if (!this.unset) { this._setValue(this._dates[0], 0); } }; DateTimePicker.prototype._getLastPickedDate = function _getLastPickedDate() { return this._dates[this._getLastPickedDateIndex()]; }; DateTimePicker.prototype._getLastPickedDateIndex = function _getLastPickedDateIndex() { return this._dates.length - 1; }; //public DateTimePicker.prototype.getMoment = function getMoment(d) { var returnMoment = void 0; if (d === undefined || d === null) { returnMoment = moment(); //TODO should this use format? and locale? } else if (this._hasTimeZone()) { // There is a string to parse and a default time zone // parse with the tz function which takes a default time zone if it is not in the format string returnMoment = moment.tz(d, this.parseFormats, this._options.useStrict, this._options.timeZone); } else { returnMoment = moment(d, this.parseFormats, this._options.useStrict); } if (this._hasTimeZone()) { returnMoment.tz(this._options.timeZone); } return returnMoment; }; DateTimePicker.prototype.toggle = function toggle() { return this.widget ? this.hide() : this.show(); }; DateTimePicker.prototype.ignoreReadonly = function ignoreReadonly(_ignoreReadonly) { if (arguments.length === 0) { return this._options.ignoreReadonly; } if (typeof _ignoreReadonly !== 'boolean') { throw new TypeError('ignoreReadonly () expects a boolean parameter'); } this._options.ignoreReadonly = _ignoreReadonly; }; DateTimePicker.prototype.options = function options(newOptions) { if (arguments.length === 0) { return $.extend(true, {}, this._options); } if (!(newOptions instanceof Object)) { throw new TypeError('options() this.options parameter should be an object'); } $.extend(true, this._options, newOptions); var self = this; $.each(this._options, function (key, value) { if (self[key] !== undefined) { self[key](value); } }); }; DateTimePicker.prototype.date = function date(newDate, index) { index = index || 0; if (arguments.length === 0) { if (this.unset) { return null; } if (this._options.allowMultidate) { return this._dates.join(this._options.multidateSeparator); } else { return this._dates[index].clone(); } } if (newDate !== null && typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) { throw new TypeError('date() parameter must be one of [null, string, moment or Date]'); } this._setValue(newDate === null ? null : this._parseInputDate(newDate), index); }; DateTimePicker.prototype.format = function format(newFormat) { ///<summary>test su</summary> ///<param name="newFormat">info about para</param> ///<returns type="string|boolean">returns foo</returns> if (arguments.length === 0) { return this._options.format; } if (typeof newFormat !== 'string' && (typeof newFormat !== 'boolean' || newFormat !== false)) { throw new TypeError('format() expects a string or boolean:false parameter ' + newFormat); } this._options.format = newFormat; if (this.actualFormat) { this._initFormatting(); // reinitialize formatting } }; DateTimePicker.prototype.timeZone = function timeZone(newZone) { if (arguments.length === 0) { return this._options.timeZone; } if (typeof newZone !== 'string') { throw new TypeError('newZone() expects a string parameter'); } this._options.timeZone = newZone; }; DateTimePicker.prototype.dayViewHeaderFormat = function dayViewHeaderFormat(newFormat) { if (arguments.length === 0) { return this._options.dayViewHeaderFormat; } if (typeof newFormat !== 'string') { throw new TypeError('dayViewHeaderFormat() expects a string parameter'); } this._options.dayViewHeaderFormat = newFormat; }; DateTimePicker.prototype.extraFormats = function extraFormats(formats) { if (arguments.length === 0) { return this._options.extraFormats; } if (formats !== false && !(formats instanceof Array)) { throw new TypeError('extraFormats() expects an array or false parameter'); } this._options.extraFormats = formats; if (this.parseFormats) { this._initFormatting(); // reinit formatting } }; DateTimePicker.prototype.disabledDates = function disabledDates(dates) { if (arguments.length === 0) { return this._options.disabledDates ? $.extend({}, this._options.disabledDates) : this._options.disabledDates; } if (!dates) { this._options.disabledDates = false; this._update(); return true; } if (!(dates instanceof Array)) { throw new TypeError('disabledDates() expects an array parameter'); } this._options.disabledDates = this._indexGivenDates(dates); this._options.enabledDates = false; this._update(); }; DateTimePicker.prototype.enabledDates = function enabledDates(dates) { if (arguments.length === 0) { return this._options.enabledDates ? $.extend({}, this._options.enabledDates) : this._options.enabledDates; } if (!dates) { this._options.enabledDates = false; this._update(); return true; } if (!(dates instanceof Array)) { throw new TypeError('enabledDates() expects an array parameter'); } this._options.enabledDates = this._indexGivenDates(dates); this._options.disabledDates = false; this._update(); }; DateTimePicker.prototype.daysOfWeekDisabled = function daysOfWeekDisabled(_daysOfWeekDisabled) { if (arguments.length === 0) { return this._options.daysOfWeekDisabled.splice(0); } if (typeof _daysOfWeekDisabled === 'boolean' && !_daysOfWeekDisabled) { this._options.daysOfWeekDisabled = false; this._update(); return true; } if (!(_daysOfWeekDisabled instanceof Array)) { throw new TypeError('daysOfWeekDisabled() expects an array parameter'); } this._options.daysOfWeekDisabled = _daysOfWeekDisabled.reduce(function (previousValue, currentValue) { currentValue = parseInt(currentValue, 10); if (currentValue > 6 || currentValue < 0 || isNaN(currentValue)) { return previousValue; } if (previousValue.indexOf(currentValue) === -1) { previousValue.push(currentValue); } return previousValue; }, []).sort(); if (this._options.useCurrent && !this._options.keepInvalid) { for (var i = 0; i < this._dates.length; i++) { var tries = 0; while (!this._isValid(this._dates[i], 'd')) { this._dates[i].add(1, 'd'); if (tries === 31) { throw 'Tried 31 times to find a valid date'; } tries++; } this._setValue(this._dates[i], i); } } this._update(); }; DateTimePicker.prototype.maxDate = function maxDate(_maxDate) { if (arguments.length === 0) { return this._options.maxDate ? this._options.maxDate.clone() : this._options.maxDate; } if (typeof _maxDate === 'boolean' && _maxDate === false) { this._options.maxDate = false; this._update(); return true; } if (typeof _maxDate === 'string') { if (_maxDate === 'now' || _maxDate === 'moment') { _maxDate = this.getMoment(); } } var parsedDate = this._parseInputDate(_maxDate); if (!parsedDate.isValid()) { throw new TypeError('maxDate() Could not parse date parameter: ' + _maxDate); } if (this._options.minDate && parsedDate.isBefore(this._options.minDate)) { throw new TypeError('maxDate() date parameter is before this.options.minDate: ' + parsedDate.format(this.actualFormat)); } this._options.maxDate = parsedDate; for (var i = 0; i < this._dates.length; i++) { if (this._options.useCurrent && !this._options.keepInvalid && this._dates[i].isAfter(_maxDate)) { this._setValue(this._options.maxDate, i); } } if (this._viewDate.isAfter(parsedDate)) { this._viewDate = parsedDate.clone().subtract(this._options.stepping, 'm'); } this._update(); }; DateTimePicker.prototype.minDate = function minDate(_minDate) { if (arguments.length === 0) { return this._options.minDate ? this._options.minDate.clone() : this._options.minDate; } if (typeof _minDate === 'boolean' && _minDate === false) { this._options.minDate = false; this._update(); return true; } if (typeof _minDate === 'string') { if (_minDate === 'now' || _minDate === 'moment') { _minDate = this.getMoment(); } } var parsedDate = this._parseInputDate(_minDate); if (!parsedDate.isValid()) { throw new TypeError('minDate() Could not parse date parameter: ' + _minDate); } if (this._options.maxDate && parsedDate.isAfter(this._options.maxDate)) { throw new TypeError('minDate() date parameter is after this.options.maxDate: ' + parsedDate.format(this.actualFormat)); } this._options.minDate = parsedDate; for (var i = 0; i < this._dates.length; i++) { if (this._options.useCurrent && !this._options.keepInvalid && this._dates[i].isBefore(_minDate)) { this._setValue(this._options.minDate, i); } } if (this._viewDate.isBefore(parsedDate)) { this._viewDate = parsedDate.clone().add(this._options.stepping, 'm'); } this._update(); }; DateTimePicker.prototype.defaultDate = function defaultDate(_defaultDate) { if (arguments.length === 0) { return this._options.defaultDate ? this._options.defaultDate.clone() : this._options.defaultDate; } if (!_defaultDate) { this._options.defaultDate = false; return true; } if (typeof _defaultDate === 'string') { if (_defaultDate === 'now' || _defaultDate === 'moment') { _defaultDate = this.getMoment(); } else { _defaultDate = this.getMoment(_defaultDate); } } var parsedDate = this._parseInputDate(_defaultDate); if (!parsedDate.isValid()) { throw new TypeError('defaultDate() Could not parse date parameter: ' + _defaultDate); } if (!this._isValid(parsedDate)) { throw new TypeError('defaultDate() date passed is invalid according to component setup validations'); } this._options.defaultDate = parsedDate; if (this._options.defaultDate && this._options.inline || this.input !== undefined && this.input.val().trim() === '') { this._setValue(this._options.defaultDate, 0); } }; DateTimePicker.prototype.locale = function locale(_locale) { if (arguments.length === 0) { return this._options.locale; } if (!moment.localeData(_locale)) { throw new TypeError('locale() locale ' + _locale + ' is not loaded from moment locales!'); } for (var i = 0; i < this._dates.length; i++) { this._dates[i].locale(this._options.locale); } this._viewDate.locale(this._options.locale); if (this.actualFormat) { this._initFormatting(); // reinitialize formatting } if (this.widget) { this.hide(); this.show(); } }; DateTimePicker.prototype.stepping = function stepping(_stepping) { if (arguments.length === 0) { return this._options.stepping; } _stepping = parseInt(_stepping, 10); if (isNaN(_stepping) || _stepping < 1) { _stepping = 1; } this._options.stepping = _stepping; }; DateTimePicker.prototype.useCurrent = function useCurrent(_useCurrent) { var useCurrentOptions = ['year', 'month', 'day', 'hour', 'minute']; if (arguments.length === 0) { return this._options.useCurrent; } if (typeof _useCurrent !== 'boolean' && typeof _useCurrent !== 'string') { throw new TypeError('useCurrent() expects a boolean or string parameter'); } if (typeof _useCurrent === 'string' && useCurrentOptions.indexOf(_useCurrent.toLowerCase()) === -1) { throw new TypeError('useCurrent() expects a string parameter of ' + useCurrentOptions.join(', ')); } this._options.useCurrent = _useCurrent; }; DateTimePicker.prototype.collapse = function collapse(_collapse) { if (arguments.length === 0) { return this._options.collapse; } if (typeof _collapse !== 'boolean') { throw new TypeError('collapse() expects a boolean parameter'); } if (this._options.collapse === _collapse) { return true; } this._options.collapse = _collapse; if (this.widget) { this.hide(); this.show(); } }; DateTimePicker.prototype.icons = function icons(_icons) { if (arguments.length === 0) { return $.extend({}, this._options.icons); } if (!(_icons instanceof Object)) { throw new TypeError('icons() expects parameter to be an Object'); } $.extend(this._options.icons, _icons); if (this.widget) { this.hide(); this.show(); } }; DateTimePicker.prototype.tooltips = function tooltips(_tooltips) { if (arguments.length === 0) { return $.extend({}, this._options.tooltips); } if (!(_tooltips instanceof Object)) { throw new TypeError('tooltips() expects parameter to be an Object'); } $.extend(this._options.tooltips, _tooltips); if (this.widget) { this.hide(); this.show(); } }; DateTimePicker.prototype.useStrict = function useStrict(_useStrict) { if (arguments.length === 0) { return this._options.useStrict; } if (typeof _useStrict !== 'boolean') { throw new TypeError('useStrict() expects a boolean parameter'); } this._options.useStrict = _useStrict; }; DateTimePicker.prototype.sideBySide = function sideBySide(_sideBySide) { if (arguments.length === 0) { return this._options.sideBySide; } if (typeof _sideBySide !== 'boolean') { throw new TypeError('sideBySide() expects a boolean parameter'); } this._options.sideBySide = _sideBySide; if (this.widget) { this.hide(); this.show(); } }; DateTimePicker.prototype.viewMode = function viewMode(_viewMode) { if (arguments.length === 0) { return this._options.viewMode; } if (typeof _viewMode !== 'string') { throw new TypeError('viewMode() expects a string parameter'); } if (DateTimePicker.ViewModes.indexOf(_viewMode) === -1) { throw new TypeError('viewMode() parameter must be one of (' + DateTimePicker.ViewModes.join(', ') + ') value'); } this._options.viewMode = _viewMode; this.currentViewMode = Math.max(DateTimePicker.ViewModes.indexOf(_viewMode) - 1, DateTimePicker.MinViewModeNumber); this._showMode(); }; DateTimePicker.prototype.calendarWeeks = function calendarWeeks(_calendarWeeks) { if (arguments.length === 0) { return this._options.calendarWeeks; } if (typeof _calendarWeeks !== 'boolean') { throw new TypeError('calendarWeeks() expects parameter to be a boolean value'); } this._options.calendarWeeks = _calendarWeeks; this._update(); }; DateTimePicker.prototype.buttons = function buttons(_buttons) { if (arguments.length === 0) { return $.extend({}, this._options.buttons); } if (!(_buttons instanceof Object)) { throw new TypeError('buttons() expects parameter to be an Object'); } $.extend(this._options.buttons, _buttons); if (typeof this._options.buttons.showToday !== 'boolean') { throw new TypeError('buttons.showToday expects a boolean parameter'); } if (typeof this._options.buttons.showClear !== 'boolean') { throw new TypeError('buttons.showClear expects a boolean parameter'); } if (typeof this._options.buttons.showClose !== 'boolean') { throw new TypeError('buttons.showClose expects a boolean parameter'); } if (this.widget) { this.hide(); this.show(); } }; DateTimePicker.prototype.keepOpen = function keepOpen(_keepOpen) { if (arguments.length === 0) { return this._options.keepOpen; } if (typeof _keepOpen !== 'boolean') { throw new TypeError('keepOpen() expects a boolean parameter'); } this._options.keepOpen = _keepOpen; }; DateTimePicker.prototype.focusOnShow = function focusOnShow(_focusOnShow) { if (arguments.length === 0) { return this._options.focusOnShow; } if (typeof _focusOnShow !== 'boolean') { throw new TypeError('focusOnShow() expects a boolean parameter'); } this._options.focusOnShow = _focusOnShow; }; DateTimePicker.prototype.inline = function inline(_inline) { if (arguments.length === 0) { return this._options.inline; } if (typeof _inline !== 'boolean') { throw new TypeError('inline() expects a boolean parameter'); } this._options.inline = _inline; }; DateTimePicker.prototype.clear = function clear() { this._setValue(null); //todo }; DateTimePicker.prototype.keyBinds = function keyBinds(_keyBinds) { if (arguments.length === 0) { return this._options.keyBinds; } this._options.keyBinds = _keyBinds; }; DateTimePicker.prototype.debug = function debug(_debug) { if (typeof _debug !== 'boolean') { throw new TypeError('debug() expects a boolean parameter'); } this._options.debug = _debug; }; DateTimePicker.prototype.allowInputToggle = function allowInputToggle(_allowInputToggle) { if (arguments.length === 0) { return this._options.allowInputToggle; } if (typeof _allowInputToggle !== 'boolean') { throw new TypeError('allowInputToggle() expects a boolean parameter'); } this._options.allowInputToggle = _allowInputToggle; }; DateTimePicker.prototype.keepInvalid = function keepInvalid(_keepInvalid) { if (arguments.length === 0) { return this._options.keepInvalid; } if (typeof _keepInvalid !== 'boolean') { throw new TypeError('keepInvalid() expects a boolean parameter'); } this._options.keepInvalid = _keepInvalid; }; DateTimePicker.prototype.datepickerInput = function datepickerInput(_datepickerInput) { if (arguments.length === 0) { return this._options.datepickerInput; } if (typeof _datepickerInput !== 'string') { throw new TypeError('datepickerInput() expects a string parameter'); } this._options.datepickerInput = _datepickerInput; }; DateTimePicker.prototype.parseInputDate = function parseInputDate(_parseInputDate2) { if (arguments.length === 0) { return this._options.parseInputDate; } if (typeof _parseInputDate2 !== 'function') { throw new TypeError('parseInputDate() should be as function'); } this._options.parseInputDate = _parseInputDate2; }; DateTimePicker.prototype.disabledTimeIntervals = function disabledTimeIntervals(_disabledTimeIntervals) { if (arguments.length === 0) { return this._options.disabledTimeIntervals ? $.extend({}, this._options.disabledTimeIntervals) : this._options.disabledTimeIntervals; } if (!_disabledTimeIntervals) { this._options.disabledTimeIntervals = false; this._update(); return true; } if (!(_disabledTimeIntervals instanceof Array)) { throw new TypeError('disabledTimeIntervals() expects an array parameter'); } this._options.disabledTimeIntervals = _disabledTimeIntervals; this._update(); }; DateTimePicker.prototype.disabledHours = function disabledHours(hours) { if (arguments.length === 0) { return this._options.disabledHours ? $.extend({}, this._options.disabledHours) : this._options.disabledHours; } if (!hours) { this._options.disabledHours = false; this._update(); return true; } if (!(hours instanceof Array)) { throw new TypeError('disabledHours() expects an array parameter'); } this._options.disabledHours = this._indexGivenHours(hours); this._options.enabledHours = false; if (this._options.useCurrent && !this._options.keepInvalid) { for (var i = 0; i < this._dates.length; i++) { var tries = 0; while (!this._isValid(this._dates[i], 'h')) { this._dates[i].add(1, 'h'); if (tries === 24) { throw 'Tried 24 times to find a valid date'; } tries++; } this._setValue(this._dates[i], i); } } this._update(); }; DateTimePicker.prototype.enabledHours = function enabledHours(hours) { if (arguments.length === 0) { return this._options.enabledHours ? $.extend({}, this._options.enabledHours) : this._options.enabledHours; } if (!hours) { this._options.enabledHours = false; this._update(); return true; } if (!(hours instanceof Array)) { throw new TypeError('enabledHours() expects an array parameter'); } this._options.enabledHours = this._indexGivenHours(hours); this._options.disabledHours = false; if (this._options.useCurrent && !this._options.keepInvalid) { for (var i = 0; i < this._dates.length; i++) { var tries = 0; while (!this._isValid(this._dates[i], 'h')) { this._dates[i].add(1, 'h'); if (tries === 24) { throw 'Tried 24 times to find a valid date'; } tries++; } this._setValue(this._dates[i], i); } } this._update(); }; DateTimePicker.prototype.viewDate = function viewDate(newDate) { if (arguments.length === 0) { return this._viewDate.clone(); } if (!newDate) { this._viewDate = (this._dates[0] || this.getMoment()).clone(); return true; } if (typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) { throw new TypeError('viewDate() parameter must be one of [string, moment or Date]'); } this._viewDate = this._parseInputDate(newDate); this._viewUpdate(); }; DateTimePicker.prototype.allowMultidate = function allowMultidate(_allowMultidate) { if (typeof _allowMultidate !== 'boolean') { throw new TypeError('allowMultidate() expects a boolean parameter'); } this._options.allowMultidate = _allowMultidate; }; DateTimePicker.prototype.multidateSeparator = function multidateSeparator(_multidateSeparator) { if (arguments.length === 0) { return this._options.multidateSeparator; } if (typeof _multidateSeparator !== 'string' || _multidateSeparator.length > 1) { throw new TypeError('multidateSeparator expects a single character string parameter'); } this._options.multidateSeparator = _multidateSeparator; }; _createClass(DateTimePicker, null, [{ key: 'NAME', get: function get() { return NAME; } /** * @return {string} */ }, { key: 'VERSION', get: function get() { return VERSION; } /** * @return {string} */ }, { key: 'DATA_KEY', get: function get() { return DATA_KEY; } /** * @return {string} */ }, { key: 'EVENT_KEY', get: function get() { return EVENT_KEY; } /** * @return {string} */ }, { key: 'DATA_API_KEY', get: function get() { return DATA_API_KEY; } }, { key: 'DatePickerModes', get: function get() { return DatePickerModes; } }, { key: 'ViewModes', get: function get() { return ViewModes; } /** * @return {number} */ }, { key: 'MinViewModeNumber', get: function get() { return MinViewModeNumber; } }, { key: 'Event', get: function get() { return Event; } }, { key: 'Selector', get: function get() { return Selector; } }, { key: 'Default', get: function get() { return Default; } }, { key: 'ClassName', get: function get() { return ClassName; } }]); return DateTimePicker; }(); return DateTimePicker; }(jQuery, moment); //noinspection JSUnusedGlobalSymbols /* global DateTimePicker */ var TempusDominusBootstrap4 = function ($) { // eslint-disable-line no-unused-vars // ReSharper disable once InconsistentNaming var JQUERY_NO_CONFLICT = $.fn[DateTimePicker.NAME], verticalModes = ['top', 'bottom', 'auto'], horizontalModes = ['left', 'right', 'auto'], toolbarPlacements = ['default', 'top', 'bottom'], getSelectorFromElement = function getSelectorFromElement($element) { var selector = $element.data('target'), $selector = void 0; if (!selector) { selector = $element.attr('href') || ''; selector = /^#[a-z]/i.test(selector) ? selector : null; } $selector = $(selector); if ($selector.length === 0) { return $selector; } if (!$selector.data(DateTimePicker.DATA_KEY)) { $.extend({}, $selector.data(), $(this).data()); } return $selector; }; // ReSharper disable once InconsistentNaming var TempusDominusBootstrap4 = function (_DateTimePicker) { _inherits(TempusDominusBootstrap4, _DateTimePicker); function TempusDominusBootstrap4(element, options) { _classCallCheck(this, TempusDominusBootstrap4); var _this = _possibleConstructorReturn(this, _DateTimePicker.call(this, element, options)); _this._init(); return _this; } TempusDominusBootstrap4.prototype._init = function _init() { if (this._element.hasClass('input-group')) { // in case there is more then one 'input-group-addon' Issue #48 var datepickerButton = this._element.find('.datepickerbutton'); if (datepickerButton.length === 0) { this.component = this._element.find('.input-group-addon'); } else { this.component = datepickerButton; } } }; TempusDominusBootstrap4.prototype._getDatePickerTemplate = function _getDatePickerTemplate() { var headTemplate = $('<thead>').append($('<tr>').append($('<th>').addClass('prev').attr('data-action', 'previous').append($('<span>').addClass(this._options.icons.previous))).append($('<th>').addClass('picker-switch').attr('data-action', 'pickerSwitch').attr('colspan', '' + (this._options.calendarWeeks ? '6' : '5'))).append($('<th>').addClass('next').attr('data-action', 'next').append($('<span>').addClass(this._options.icons.next)))), contTemplate = $('<tbody>').append($('<tr>').append($('<td>').attr('colspan', '' + (this._options.calendarWeeks ? '8' : '7')))); return [$('<div>').addClass('datepicker-days').append($('<table>').addClass('table table-sm').append(headTemplate).append($('<tbody>'))), $('<div>').addClass('datepicker-months').append($('<table>').addClass('table-condensed').append(headTemplate.clone()).append(contTemplate.clone())), $('<div>').addClass('datepicker-years').append($('<table>').addClass('table-condensed').append(headTemplate.clone()).append(contTemplate.clone())), $('<div>').addClass('datepicker-decades').append($('<table>').addClass('table-condensed').append(headTemplate.clone()).append(contTemplate.clone()))]; }; TempusDominusBootstrap4.prototype._getTimePickerMainTemplate = function _getTimePickerMainTemplate() { var topRow = $('<tr>'), middleRow = $('<tr>'), bottomRow = $('<tr>'); if (this._isEnabled('h')) { topRow.append($('<td>').append($('<a>').attr({ href: '#', tabindex: '-1', 'title': this._options.tooltips.incrementHour }).addClass('btn').attr('data-action', 'incrementHours').append($('<span>').addClass(this._options.icons.up)))); middleRow.append($('<td>').append($('<span>').addClass('timepicker-hour').attr({ 'data-time-component': 'hours', 'title': this._options.tooltips.pickHour }).attr('data-action', 'showHours'))); bottomRow.append($('<td>').append($('<a>').attr({ href: '#', tabindex: '-1', 'title': this._options.tooltips.decrementHour }).addClass('btn').attr('data-action', 'decrementHours').append($('<span>').addClass(this._options.icons.down)))); } if (this._isEnabled('m')) { if (this._isEnabled('h')) { topRow.append($('<td>').addClass('separator')); middleRow.append($('<td>').addClass('separator').html(':')); bottomRow.append($('<td>').addClass('separator')); } topRow.append($('<td>').append($('<a>').attr({ href: '#', tabindex: '-1', 'title': this._options.tooltips.incrementMinute }).addClass('btn').attr('data-action', 'incrementMinutes').append($('<span>').addClass(this._options.icons.up)))); middleRow.append($('<td>').append($('<span>').addClass('timepicker-minute').attr({ 'data-time-component': 'minutes', 'title': this._options.tooltips.pickMinute }).attr('data-action', 'showMinutes'))); bottomRow.append($('<td>').append($('<a>').attr({ href: '#', tabindex: '-1', 'title': this._options.tooltips.decrementMinute }).addClass('btn').attr('data-action', 'decrementMinutes').append($('<span>').addClass(this._options.icons.down)))); } if (this._isEnabled('s')) { if (this._isEnabled('m')) { topRow.append($('<td>').addClass('separator')); middleRow.append($('<td>').addClass('separator').html(':')); bottomRow.append($('<td>').addClass('separator')); } topRow.append($('<td>').append($('<a>').attr({ href: '#', tabindex: '-1', 'title': this._options.tooltips.incrementSecond }).addClass('btn').attr('data-action', 'incrementSeconds').append($('<span>').addClass(this._options.icons.up)))); middleRow.append($('<td>').append($('<span>').addClass('timepicker-second').attr({ 'data-time-component': 'seconds', 'title': this._options.tooltips.pickSecond }).attr('data-action', 'showSeconds'))); bottomRow.append($('<td>').append($('<a>').attr({ href: '#', tabindex: '-1', 'title': this._options.tooltips.decrementSecond }).addClass('btn').attr('data-action', 'decrementSeconds').append($('<span>').addClass(this._options.icons.down)))); } if (!this.use24Hours) { topRow.append($('<td>').addClass('separator')); middleRow.append($('<td>').append($('<button>').addClass('btn btn-primary').attr({ 'data-action': 'togglePeriod', tabindex: '-1', 'title': this._options.tooltips.togglePeriod }))); bottomRow.append($('<td>').addClass('separator')); } return $('<div>').addClass('timepicker-picker').append($('<table>').addClass('table-condensed').append([topRow, middleRow, bottomRow])); }; TempusDominusBootstrap4.prototype._getTimePickerTemplate = function _getTimePickerTemplate() { var hoursView = $('<div>').addClass('timepicker-hours').append($('<table>').addClass('table-condensed')), minutesView = $('<div>').addClass('timepicker-minutes').append($('<table>').addClass('table-condensed')), secondsView = $('<div>').addClass('timepicker-seconds').append($('<table>').addClass('table-condensed')), ret = [this._getTimePickerMainTemplate()]; if (this._isEnabled('h')) { ret.push(hoursView); } if (this._isEnabled('m')) { ret.push(minutesView); } if (this._isEnabled('s')) { ret.push(secondsView); } return ret; }; TempusDominusBootstrap4.prototype._getToolbar = function _getToolbar() { var row = []; if (this._options.buttons.showToday) { row.push($('<td>').append($('<a>').attr({ 'data-action': 'today', 'title': this._options.tooltips.today }).append($('<span>').addClass(this._options.icons.today)))); } if (!this._options.sideBySide && this._hasDate() && this._hasTime()) { row.push($('<td>').append($('<a>').attr({ 'data-action': 'togglePicker', 'title': this._options.tooltips.selectTime }).append($('<span>').addClass(this._options.icons.time)))); } if (this._options.buttons.showClear) { row.push($('<td>').append($('<a>').attr({ 'data-action': 'clear', 'title': this._options.tooltips.clear }).append($('<span>').addClass(this._options.icons.clear)))); } if (this._options.buttons.showClose) { row.push($('<td>').append($('<a>').attr({ 'data-action': 'close', 'title': this._options.tooltips.close }).append($('<span>').addClass(this._options.icons.close)))); } return row.length === 0 ? '' : $('<table>').addClass('table-condensed').append($('<tbody>').append($('<tr>').append(row))); }; TempusDominusBootstrap4.prototype._getTemplate = function _getTemplate() { var template = $('<div>').addClass('bootstrap-datetimepicker-widget dropdown-menu'), dateView = $('<div>').addClass('datepicker').append(this._getDatePickerTemplate()), timeView = $('<div>').addClass('timepicker').append(this._getTimePickerTemplate()), content = $('<ul>').addClass('list-unstyled'), toolbar = $('<li>').addClass('picker-switch' + (this._options.collapse ? ' accordion-toggle' : '')).append(this._getToolbar()); if (this._options.inline) { template.removeClass('dropdown-menu'); } if (this.use24Hours) { template.addClass('usetwentyfour'); } if (this._isEnabled('s') && !this.use24Hours) { template.addClass('wider'); } if (this._options.sideBySide && this._hasDate() && this._hasTime()) { template.addClass('timepicker-sbs'); if (this._options.toolbarPlacement === 'top') { template.append(toolbar); } template.append($('<div>').addClass('row').append(dateView.addClass('col-md-6')).append(timeView.addClass('col-md-6'))); if (this._options.toolbarPlacement === 'bottom' || this._options.toolbarPlacement === 'default') { template.append(toolbar); } return template; } if (this._options.toolbarPlacement === 'top') { content.append(toolbar); } if (this._hasDate()) { content.append($('<li>').addClass(this._options.collapse && this._hasTime() ? 'collapse' : '').addClass(this._options.collapse && this._hasTime() && this._options.viewMode === 'time' ? '' : 'show').append(dateView)); } if (this._options.toolbarPlacement === 'default') { content.append(toolbar); } if (this._hasTime()) { content.append($('<li>').addClass(this._options.collapse && this._hasDate() ? 'collapse' : '').addClass(this._options.collapse && this._hasDate() && this._options.viewMode === 'time' ? 'show' : '').append(timeView)); } if (this._options.toolbarPlacement === 'bottom') { content.append(toolbar); } return template.append(content); }; TempusDominusBootstrap4.prototype._place = function _place(e) { var self = e && e.data && e.data.picker || this, vertical = self._options.widgetPositioning.vertical, horizontal = self._options.widgetPositioning.horizontal, parent = void 0; var position = (self.component || self._element).position(), offset = (self.component || self._element).offset(); if (self._options.widgetParent) { parent = self._options.widgetParent.append(self.widget); } else if (self._element.is('input')) { parent = self._element.after(self.widget).parent(); } else if (self._options.inline) { parent = self._element.append(self.widget); return; } else { parent = self._element; self._element.children().first().after(self.widget); } // Top and bottom logic if (vertical === 'auto') { //noinspection JSValidateTypes if (offset.top + self.widget.height() * 1.5 >= $(window).height() + $(window).scrollTop() && self.widget.height() + self._element.outerHeight() < offset.top) { vertical = 'top'; } else { vertical = 'bottom'; } } // Left and right logic if (horizontal === 'auto') { if (parent.width() < offset.left + self.widget.outerWidth() / 2 && offset.left + self.widget.outerWidth() > $(window).width()) { horizontal = 'right'; } else { horizontal = 'left'; } } if (vertical === 'top') { self.widget.addClass('top').removeClass('bottom'); } else { self.widget.addClass('bottom').removeClass('top'); } if (horizontal === 'right') { self.widget.addClass('float-right'); } else { self.widget.removeClass('float-right'); } // find the first parent element that has a relative css positioning if (parent.css('position') !== 'relative') { parent = parent.parents().filter(function () { return $(this).css('position') === 'relative'; }).first(); } if (parent.length === 0) { throw new Error('datetimepicker component should be placed within a relative positioned container'); } self.widget.css({ top: vertical === 'top' ? 'auto' : position.top + self._element.outerHeight() + 'px', bottom: vertical === 'top' ? parent.outerHeight() - (parent === self._element ? 0 : position.top) + 'px' : 'auto', left: horizontal === 'left' ? (parent === self._element ? 0 : position.left) + 'px' : 'auto', right: horizontal === 'left' ? 'auto' : parent.outerWidth() - self._element.outerWidth() - (parent === self._element ? 0 : position.left) + 'px' }); }; TempusDominusBootstrap4.prototype._fillDow = function _fillDow() { var row = $('<tr>'), currentDate = this._viewDate.clone().startOf('w').startOf('d'); if (this._options.calendarWeeks === true) { row.append($('<th>').addClass('cw').text('#')); } while (currentDate.isBefore(this._viewDate.clone().endOf('w'))) { row.append($('<th>').addClass('dow').text(currentDate.format('dd'))); currentDate.add(1, 'd'); } this.widget.find('.datepicker-days thead').append(row); }; TempusDominusBootstrap4.prototype._fillMonths = function _fillMonths() { var spans = [], monthsShort = this._viewDate.clone().startOf('y').startOf('d'); while (monthsShort.isSame(this._viewDate, 'y')) { spans.push($('<span>').attr('data-action', 'selectMonth').addClass('month').text(monthsShort.format('MMM'))); monthsShort.add(1, 'M'); } this.widget.find('.datepicker-months td').empty().append(spans); }; TempusDominusBootstrap4.prototype._updateMonths = function _updateMonths() { var monthsView = this.widget.find('.datepicker-months'), monthsViewHeader = monthsView.find('th'), months = monthsView.find('tbody').find('span'), self = this; monthsViewHeader.eq(0).find('span').attr('title', this._options.tooltips.prevYear); monthsViewHeader.eq(1).attr('title', this._options.tooltips.selectYear); monthsViewHeader.eq(2).find('span').attr('title', this._options.tooltips.nextYear); monthsView.find('.disabled').removeClass('disabled'); if (!this._isValid(this._viewDate.clone().subtract(1, 'y'), 'y')) { monthsViewHeader.eq(0).addClass('disabled'); } monthsViewHeader.eq(1).text(this._viewDate.year()); if (!this._isValid(this._viewDate.clone().add(1, 'y'), 'y')) { monthsViewHeader.eq(2).addClass('disabled'); } months.removeClass('active'); if (this._getLastPickedDate().isSame(this._viewDate, 'y') && !this.unset) { months.eq(this._getLastPickedDate().month()).addClass('active'); } months.each(function (index) { if (!self._isValid(self._viewDate.clone().month(index), 'M')) { $(this).addClass('disabled'); } }); }; TempusDominusBootstrap4.prototype._getStartEndYear = function _getStartEndYear(factor, year) { var step = factor / 10, startYear = Math.floor(year / factor) * factor, endYear = startYear + step * 9, focusValue = Math.floor(year / step) * step; return [startYear, endYear, focusValue]; }; TempusDominusBootstrap4.prototype._updateYears = function _updateYears() { var yearsView = this.widget.find('.datepicker-years'), yearsViewHeader = yearsView.find('th'), yearCaps = this._getStartEndYear(10, this._viewDate.year()), startYear = this._viewDate.clone().year(yearCaps[0]), endYear = this._viewDate.clone().year(yearCaps[1]); var html = ''; yearsViewHeader.eq(0).find('span').attr('title', this._options.tooltips.prevDecade); yearsViewHeader.eq(1).attr('title', this._options.tooltips.selectDecade); yearsViewHeader.eq(2).find('span').attr('title', this._options.tooltips.nextDecade); yearsView.find('.disabled').removeClass('disabled'); if (this._options.minDate && this._options.minDate.isAfter(startYear, 'y')) { yearsViewHeader.eq(0).addClass('disabled'); } yearsViewHeader.eq(1).text(startYear.year() + '-' + endYear.year()); if (this._options.maxDate && this._options.maxDate.isBefore(endYear, 'y')) { yearsViewHeader.eq(2).addClass('disabled'); } html += '<span data-action="selectYear" class="year old">' + (startYear.year() - 1) + '</span>'; while (!startYear.isAfter(endYear, 'y')) { html += '<span data-action="selectYear" class="year' + (startYear.isSame(this._getLastPickedDate(), 'y') && !this.unset ? ' active' : '') + (!this._isValid(startYear, 'y') ? ' disabled' : '') + '">' + startYear.year() + '</span>'; startYear.add(1, 'y'); } html += '<span data-action="selectYear" class="year old">' + startYear.year() + '</span>'; yearsView.find('td').html(html); }; TempusDominusBootstrap4.prototype._updateDecades = function _updateDecades() { var decadesView = this.widget.find('.datepicker-decades'), decadesViewHeader = decadesView.find('th'), yearCaps = this._getStartEndYear(100, this._viewDate.year()), startDecade = this._viewDate.clone().year(yearCaps[0]), endDecade = this._viewDate.clone().year(yearCaps[1]); var minDateDecade = false, maxDateDecade = false, endDecadeYear = void 0, html = ''; decadesViewHeader.eq(0).find('span').attr('title', this._options.tooltips.prevCentury); decadesViewHeader.eq(2).find('span').attr('title', this._options.tooltips.nextCentury); decadesView.find('.disabled').removeClass('disabled'); if (startDecade.year() === 0 || this._options.minDate && this._options.minDate.isAfter(startDecade, 'y')) { decadesViewHeader.eq(0).addClass('disabled'); } decadesViewHeader.eq(1).text(startDecade.year() + '-' + endDecade.year()); if (this._options.maxDate && this._options.maxDate.isBefore(endDecade, 'y')) { decadesViewHeader.eq(2).addClass('disabled'); } if (startDecade.year() - 10 < 0) { html += '<span>&nbsp;</span>'; } else { html += '<span data-action="selectDecade" class="decade old" data-selection="' + (startDecade.year() + 6) + '">' + (startDecade.year() - 10) + '</span>'; } while (!startDecade.isAfter(endDecade, 'y')) { endDecadeYear = startDecade.year() + 11; minDateDecade = this._options.minDate && this._options.minDate.isAfter(startDecade, 'y') && this._options.minDate.year() <= endDecadeYear; maxDateDecade = this._options.maxDate && this._options.maxDate.isAfter(startDecade, 'y') && this._options.maxDate.year() <= endDecadeYear; html += '<span data-action="selectDecade" class="decade' + (this._getLastPickedDate().isAfter(startDecade) && this._getLastPickedDate().year() <= endDecadeYear ? ' active' : '') + (!this._isValid(startDecade, 'y') && !minDateDecade && !maxDateDecade ? ' disabled' : '') + '" data-selection="' + (startDecade.year() + 6) + '">' + startDecade.year() + '</span>'; startDecade.add(10, 'y'); } html += '<span data-action="selectDecade" class="decade old" data-selection="' + (startDecade.year() + 6) + '">' + startDecade.year() + '</span>'; decadesView.find('td').html(html); }; TempusDominusBootstrap4.prototype._fillDate = function _fillDate() { var daysView = this.widget.find('.datepicker-days'), daysViewHeader = daysView.find('th'), html = []; var currentDate = void 0, row = void 0, clsName = void 0, i = void 0; if (!this._hasDate()) { return; } daysViewHeader.eq(0).find('span').attr('title', this._options.tooltips.prevMonth); daysViewHeader.eq(1).attr('title', this._options.tooltips.selectMonth); daysViewHeader.eq(2).find('span').attr('title', this._options.tooltips.nextMonth); daysView.find('.disabled').removeClass('disabled'); daysViewHeader.eq(1).text(this._viewDate.format(this._options.dayViewHeaderFormat)); if (!this._isValid(this._viewDate.clone().subtract(1, 'M'), 'M')) { daysViewHeader.eq(0).addClass('disabled'); } if (!this._isValid(this._viewDate.clone().add(1, 'M'), 'M')) { daysViewHeader.eq(2).addClass('disabled'); } currentDate = this._viewDate.clone().startOf('M').startOf('w').startOf('d'); for (i = 0; i < 42; i++) { //always display 42 days (should show 6 weeks) if (currentDate.weekday() === 0) { row = $('<tr>'); if (this._options.calendarWeeks) { row.append('<td class="cw">' + currentDate.week() + '</td>'); } html.push(row); } clsName = ''; if (currentDate.isBefore(this._viewDate, 'M')) { clsName += ' old'; } if (currentDate.isAfter(this._viewDate, 'M')) { clsName += ' new'; } if (this._options.allowMultidate) { var index = this._datesFormatted.indexOf(currentDate.format('YYYY-MM-DD')); if (index !== -1) { if (currentDate.isSame(this._datesFormatted[index], 'd') && !this.unset) { clsName += ' active'; } } } else { if (currentDate.isSame(this._getLastPickedDate(), 'd') && !this.unset) { clsName += ' active'; } } if (!this._isValid(currentDate, 'd')) { clsName += ' disabled'; } if (currentDate.isSame(this.getMoment(), 'd')) { clsName += ' today'; } if (currentDate.day() === 0 || currentDate.day() === 6) { clsName += ' weekend'; } row.append('<td data-action="selectDay" data-day="' + currentDate.format('L') + '" class="day' + clsName + '">' + currentDate.date() + '</td>'); currentDate.add(1, 'd'); } daysView.find('tbody').empty().append(html); this._updateMonths(); this._updateYears(); this._updateDecades(); }; TempusDominusBootstrap4.prototype._fillHours = function _fillHours() { var table = this.widget.find('.timepicker-hours table'), currentHour = this._viewDate.clone().startOf('d'), html = []; var row = $('<tr>'); if (this._viewDate.hour() > 11 && !this.use24Hours) { currentHour.hour(12); } while (currentHour.isSame(this._viewDate, 'd') && (this.use24Hours || this._viewDate.hour() < 12 && currentHour.hour() < 12 || this._viewDate.hour() > 11)) { if (currentHour.hour() % 4 === 0) { row = $('<tr>'); html.push(row); } row.append('<td data-action="selectHour" class="hour' + (!this._isValid(currentHour, 'h') ? ' disabled' : '') + '">' + currentHour.format(this.use24Hours ? 'HH' : 'hh') + '</td>'); currentHour.add(1, 'h'); } table.empty().append(html); }; TempusDominusBootstrap4.prototype._fillMinutes = function _fillMinutes() { var table = this.widget.find('.timepicker-minutes table'), currentMinute = this._viewDate.clone().startOf('h'), html = [], step = this._options.stepping === 1 ? 5 : this._options.stepping; var row = $('<tr>'); while (this._viewDate.isSame(currentMinute, 'h')) { if (currentMinute.minute() % (step * 4) === 0) { row = $('<tr>'); html.push(row); } row.append('<td data-action="selectMinute" class="minute' + (!this._isValid(currentMinute, 'm') ? ' disabled' : '') + '">' + currentMinute.format('mm') + '</td>'); currentMinute.add(step, 'm'); } table.empty().append(html); }; TempusDominusBootstrap4.prototype._fillSeconds = function _fillSeconds() { var table = this.widget.find('.timepicker-seconds table'), currentSecond = this._viewDate.clone().startOf('m'), html = []; var row = $('<tr>'); while (this._viewDate.isSame(currentSecond, 'm')) { if (currentSecond.second() % 20 === 0) { row = $('<tr>'); html.push(row); } row.append('<td data-action="selectSecond" class="second' + (!this._isValid(currentSecond, 's') ? ' disabled' : '') + '">' + currentSecond.format('ss') + '</td>'); currentSecond.add(5, 's'); } table.empty().append(html); }; TempusDominusBootstrap4.prototype._fillTime = function _fillTime() { var toggle = void 0, newDate = void 0; var timeComponents = this.widget.find('.timepicker span[data-time-component]'); if (!this.use24Hours) { toggle = this.widget.find('.timepicker [data-action=togglePeriod]'); newDate = this._getLastPickedDate().clone().add(this._getLastPickedDate().hours() >= 12 ? -12 : 12, 'h'); toggle.text(this._getLastPickedDate().format('A')); if (this._isValid(newDate, 'h')) { toggle.removeClass('disabled'); } else { toggle.addClass('disabled'); } } timeComponents.filter('[data-time-component=hours]').text(this._getLastPickedDate().format('' + (this.use24Hours ? 'HH' : 'hh'))); timeComponents.filter('[data-time-component=minutes]').text(this._getLastPickedDate().format('mm')); timeComponents.filter('[data-time-component=seconds]').text(this._getLastPickedDate().format('ss')); this._fillHours(); this._fillMinutes(); this._fillSeconds(); }; TempusDominusBootstrap4.prototype._doAction = function _doAction(e, action) { var lastPicked = this._getLastPickedDate(); if ($(e.currentTarget).is('.disabled')) { return false; } action = action || $(e.currentTarget).data('action'); switch (action) { case 'next': { var navFnc = DateTimePicker.DatePickerModes[this.currentViewMode].NAV_FUNCTION; this._viewDate.add(DateTimePicker.DatePickerModes[this.currentViewMode].NAV_STEP, navFnc); this._fillDate(); this._viewUpdate(navFnc); break; } case 'previous': { var _navFnc = DateTimePicker.DatePickerModes[this.currentViewMode].NAV_FUNCTION; this._viewDate.subtract(DateTimePicker.DatePickerModes[this.currentViewMode].NAV_STEP, _navFnc); this._fillDate(); this._viewUpdate(_navFnc); break; } case 'pickerSwitch': this._showMode(1); break; case 'selectMonth': { var month = $(e.target).closest('tbody').find('span').index($(e.target)); this._viewDate.month(month); if (this.currentViewMode === DateTimePicker.MinViewModeNumber) { this._setValue(lastPicked.clone().year(this._viewDate.year()).month(this._viewDate.month()), this._getLastPickedDateIndex()); if (!this._options.inline) { this.hide(); } } else { this._showMode(-1); this._fillDate(); } this._viewUpdate('M'); break; } case 'selectYear': { var year = parseInt($(e.target).text(), 10) || 0; this._viewDate.year(year); if (this.currentViewMode === DateTimePicker.MinViewModeNumber) { this._setValue(lastPicked.clone().year(this._viewDate.year()), this._getLastPickedDateIndex()); if (!this._options.inline) { this.hide(); } } else { this._showMode(-1); this._fillDate(); } this._viewUpdate('YYYY'); break; } case 'selectDecade': { var _year = parseInt($(e.target).data('selection'), 10) || 0; this._viewDate.year(_year); if (this.currentViewMode === DateTimePicker.MinViewModeNumber) { this._setValue(lastPicked.clone().year(this._viewDate.year()), this._getLastPickedDateIndex()); if (!this._options.inline) { this.hide(); } } else { this._showMode(-1); this._fillDate(); } this._viewUpdate('YYYY'); break; } case 'selectDay': { var day = this._viewDate.clone(); if ($(e.target).is('.old')) { day.subtract(1, 'M'); } if ($(e.target).is('.new')) { day.add(1, 'M'); } this._setValue(day.date(parseInt($(e.target).text(), 10)), this._getLastPickedDateIndex()); if (!this._hasTime() && !this._options.keepOpen && !this._options.inline) { this.hide(); } break; } case 'incrementHours': { var newDate = lastPicked.clone().add(1, 'h'); if (this._isValid(newDate, 'h')) { this._setValue(newDate, this._getLastPickedDateIndex()); } break; } case 'incrementMinutes': { var _newDate = lastPicked.clone().add(this._options.stepping, 'm'); if (this._isValid(_newDate, 'm')) { this._setValue(_newDate, this._getLastPickedDateIndex()); } break; } case 'incrementSeconds': { var _newDate2 = lastPicked.clone().add(1, 's'); if (this._isValid(_newDate2, 's')) { this._setValue(_newDate2, this._getLastPickedDateIndex()); } break; } case 'decrementHours': { var _newDate3 = lastPicked.clone().subtract(1, 'h'); if (this._isValid(_newDate3, 'h')) { this._setValue(_newDate3, this._getLastPickedDateIndex()); } break; } case 'decrementMinutes': { var _newDate4 = lastPicked.clone().subtract(this._options.stepping, 'm'); if (this._isValid(_newDate4, 'm')) { this._setValue(_newDate4, this._getLastPickedDateIndex()); } break; } case 'decrementSeconds': { var _newDate5 = lastPicked.clone().subtract(1, 's'); if (this._isValid(_newDate5, 's')) { this._setValue(_newDate5, this._getLastPickedDateIndex()); } break; } case 'togglePeriod': { this._setValue(lastPicked.clone().add(lastPicked.hours() >= 12 ? -12 : 12, 'h'), this._getLastPickedDateIndex()); break; } case 'togglePicker': { var $this = $(e.target), $link = $this.closest('a'), $parent = $this.closest('ul'), expanded = $parent.find('.show'), closed = $parent.find('.collapse:not(.show)'), $span = $this.is('span') ? $this : $this.find('span'); var collapseData = void 0; if (expanded && expanded.length) { collapseData = expanded.data('collapse'); if (collapseData && collapseData.transitioning) { return true; } if (expanded.collapse) { // if collapse plugin is available through bootstrap.js then use it expanded.collapse('hide'); closed.collapse('show'); } else { // otherwise just toggle in class on the two views expanded.removeClass('show'); closed.addClass('show'); } $span.toggleClass(this._options.icons.time + ' ' + this._options.icons.date); if ($span.hasClass(this._options.icons.date)) { $link.attr('title', this._options.tooltips.selectDate); } else { $link.attr('title', this._options.tooltips.selectTime); } } } break; case 'showPicker': this.widget.find('.timepicker > div:not(.timepicker-picker)').hide(); this.widget.find('.timepicker .timepicker-picker').show(); break; case 'showHours': this.widget.find('.timepicker .timepicker-picker').hide(); this.widget.find('.timepicker .timepicker-hours').show(); break; case 'showMinutes': this.widget.find('.timepicker .timepicker-picker').hide(); this.widget.find('.timepicker .timepicker-minutes').show(); break; case 'showSeconds': this.widget.find('.timepicker .timepicker-picker').hide(); this.widget.find('.timepicker .timepicker-seconds').show(); break; case 'selectHour': { var hour = parseInt($(e.target).text(), 10); if (!this.use24Hours) { if (lastPicked.hours() >= 12) { if (hour !== 12) { hour += 12; } } else { if (hour === 12) { hour = 0; } } } this._setValue(lastPicked.clone().hours(hour), this._getLastPickedDateIndex()); this._doAction(e, 'showPicker'); break; } case 'selectMinute': this._setValue(lastPicked.clone().minutes(parseInt($(e.target).text(), 10)), this._getLastPickedDateIndex()); this._doAction(e, 'showPicker'); break; case 'selectSecond': this._setValue(lastPicked.clone().seconds(parseInt($(e.target).text(), 10)), this._getLastPickedDateIndex()); this._doAction(e, 'showPicker'); break; case 'clear': this.clear(); break; case 'today': { var todaysDate = this.getMoment(); if (this._isValid(todaysDate, 'd')) { this._setValue(todaysDate, this._getLastPickedDateIndex()); } break; } } return false; }; //public TempusDominusBootstrap4.prototype.hide = function hide() { var transitioning = false; if (!this.widget) { return; } // Ignore event if in the middle of a picker transition this.widget.find('.collapse').each(function () { var collapseData = $(this).data('collapse'); if (collapseData && collapseData.transitioning) { transitioning = true; return false; } return true; }); if (transitioning) { return; } if (this.component && this.component.hasClass('btn')) { this.component.toggleClass('active'); } this.widget.hide(); $(window).off('resize', this._place()); this.widget.off('click', '[data-action]'); this.widget.off('mousedown', false); this.widget.remove(); this.widget = false; this._notifyEvent({ type: DateTimePicker.Event.HIDE, date: this._getLastPickedDate().clone() }); if (this.input !== undefined) { this.input.blur(); } this._viewDate = this._getLastPickedDate().clone(); }; TempusDominusBootstrap4.prototype.show = function show() { var currentMoment = void 0; var useCurrentGranularity = { 'year': function year(m) { return m.month(0).date(1).hours(0).seconds(0).minutes(0); }, 'month': function month(m) { return m.date(1).hours(0).seconds(0).minutes(0); }, 'day': function day(m) { return m.hours(0).seconds(0).minutes(0); }, 'hour': function hour(m) { return m.seconds(0).minutes(0); }, 'minute': function minute(m) { return m.seconds(0); } }; if (this.input !== undefined) { if (this.input.prop('disabled') || !this._options.ignoreReadonly && this.input.prop('readonly') || this.widget) { return; } if (this.input.val() !== undefined && this.input.val().trim().length !== 0) { this._setValue(this._parseInputDate(this.input.val().trim()), 0); } else if (this.unset && this._options.useCurrent) { currentMoment = this.getMoment(); if (typeof this._options.useCurrent === 'string') { currentMoment = useCurrentGranularity[this._options.useCurrent](currentMoment); } this._setValue(currentMoment, 0); } } else if (this.unset && this._options.useCurrent) { currentMoment = this.getMoment(); if (typeof this._options.useCurrent === 'string') { currentMoment = useCurrentGranularity[this._options.useCurrent](currentMoment); } this._setValue(currentMoment, 0); } this.widget = this._getTemplate(); this._fillDow(); this._fillMonths(); this.widget.find('.timepicker-hours').hide(); this.widget.find('.timepicker-minutes').hide(); this.widget.find('.timepicker-seconds').hide(); this._update(); this._showMode(); $(window).on('resize', { picker: this }, this._place); this.widget.on('click', '[data-action]', $.proxy(this._doAction, this)); // this handles clicks on the widget this.widget.on('mousedown', false); if (this.component && this.component.hasClass('btn')) { this.component.toggleClass('active'); } this._place(); this.widget.show(); if (this.input !== undefined && this._options.focusOnShow && !this.input.is(':focus')) { this.input.focus(); } this._notifyEvent({ type: DateTimePicker.Event.SHOW }); }; TempusDominusBootstrap4.prototype.destroy = function destroy() { this.hide(); //todo doc off? this._element.removeData(DateTimePicker.DATA_KEY); this._element.removeData('date'); }; TempusDominusBootstrap4.prototype.disable = function disable() { this.hide(); if (this.component && this.component.hasClass('btn')) { this.component.addClass('disabled'); } if (this.input !== undefined) { this.input.prop('disabled', true); //todo disable this/comp if input is null } }; TempusDominusBootstrap4.prototype.enable = function enable() { if (this.component && this.component.hasClass('btn')) { this.component.removeClass('disabled'); } if (this.input !== undefined) { this.input.prop('disabled', false); //todo enable comp/this if input is null } }; TempusDominusBootstrap4.prototype.toolbarPlacement = function toolbarPlacement(_toolbarPlacement) { if (arguments.length === 0) { return this._options.toolbarPlacement; } if (typeof _toolbarPlacement !== 'string') { throw new TypeError('toolbarPlacement() expects a string parameter'); } if (toolbarPlacements.indexOf(_toolbarPlacement) === -1) { throw new TypeError('toolbarPlacement() parameter must be one of (' + toolbarPlacements.join(', ') + ') value'); } this._options.toolbarPlacement = _toolbarPlacement; if (this.widget) { this.hide(); this.show(); } }; TempusDominusBootstrap4.prototype.widgetPositioning = function widgetPositioning(_widgetPositioning) { if (arguments.length === 0) { return $.extend({}, this._options.widgetPositioning); } if ({}.toString.call(_widgetPositioning) !== '[object Object]') { throw new TypeError('widgetPositioning() expects an object variable'); } if (_widgetPositioning.horizontal) { if (typeof _widgetPositioning.horizontal !== 'string') { throw new TypeError('widgetPositioning() horizontal variable must be a string'); } _widgetPositioning.horizontal = _widgetPositioning.horizontal.toLowerCase(); if (horizontalModes.indexOf(_widgetPositioning.horizontal) === -1) { throw new TypeError('widgetPositioning() expects horizontal parameter to be one of (' + horizontalModes.join(', ') + ')'); } this._options.widgetPositioning.horizontal = _widgetPositioning.horizontal; } if (_widgetPositioning.vertical) { if (typeof _widgetPositioning.vertical !== 'string') { throw new TypeError('widgetPositioning() vertical variable must be a string'); } _widgetPositioning.vertical = _widgetPositioning.vertical.toLowerCase(); if (verticalModes.indexOf(_widgetPositioning.vertical) === -1) { throw new TypeError('widgetPositioning() expects vertical parameter to be one of (' + verticalModes.join(', ') + ')'); } this._options.widgetPositioning.vertical = _widgetPositioning.vertical; } this._update(); }; TempusDominusBootstrap4.prototype.widgetParent = function widgetParent(_widgetParent) { if (arguments.length === 0) { return this._options.widgetParent; } if (typeof _widgetParent === 'string') { _widgetParent = $(_widgetParent); } if (_widgetParent !== null && typeof _widgetParent !== 'string' && !(_widgetParent instanceof $)) { throw new TypeError('widgetParent() expects a string or a jQuery object parameter'); } this._options.widgetParent = _widgetParent; if (this.widget) { this.hide(); this.show(); } }; //static TempusDominusBootstrap4._jQueryHandleThis = function _jQueryHandleThis(me, option, argument) { var data = $(me).data(DateTimePicker.DATA_KEY); if ((typeof option === 'undefined' ? 'undefined' : _typeof(option)) === 'object') { $.extend({}, DateTimePicker.Default, option); } if (!data) { data = new TempusDominusBootstrap4($(me), option); $(me).data(DateTimePicker.DATA_KEY, data); } if (typeof option === 'string') { if (data[option] === undefined) { throw new Error('No method named "' + option + '"'); } if (argument === undefined) { return data[option](); } else { return data[option](argument); } } }; TempusDominusBootstrap4._jQueryInterface = function _jQueryInterface(option, argument) { if (this.length === 1) { return TempusDominusBootstrap4._jQueryHandleThis(this[0], option, argument); } return this.each(function () { TempusDominusBootstrap4._jQueryHandleThis(this, option, argument); }); }; return TempusDominusBootstrap4; }(DateTimePicker); /** * ------------------------------------------------------------------------ * jQuery * ------------------------------------------------------------------------ */ $(document).on(DateTimePicker.Event.CLICK_DATA_API, DateTimePicker.Selector.DATA_TOGGLE, function () { var $target = getSelectorFromElement($(this)); if ($target.length === 0) { return; } TempusDominusBootstrap4._jQueryInterface.call($target, 'toggle'); }).on(DateTimePicker.Event.CHANGE, '.' + DateTimePicker.ClassName.INPUT, function (event) { var $target = getSelectorFromElement($(this)); if ($target.length === 0) { return; } TempusDominusBootstrap4._jQueryInterface.call($target, '_change', event); }).on(DateTimePicker.Event.BLUR, '.' + DateTimePicker.ClassName.INPUT, function (event) { var $target = getSelectorFromElement($(this)), config = $target.data(DateTimePicker.DATA_KEY); if ($target.length === 0) { return; } if (config._options.debug || window.debug) { return; } TempusDominusBootstrap4._jQueryInterface.call($target, 'hide', event); }).on(DateTimePicker.Event.KEYDOWN, '.' + DateTimePicker.ClassName.INPUT, function (event) { var $target = getSelectorFromElement($(this)); if ($target.length === 0) { return; } TempusDominusBootstrap4._jQueryInterface.call($target, '_keydown', event); }).on(DateTimePicker.Event.KEYUP, '.' + DateTimePicker.ClassName.INPUT, function (event) { var $target = getSelectorFromElement($(this)); if ($target.length === 0) { return; } TempusDominusBootstrap4._jQueryInterface.call($target, '_keyup', event); }).on(DateTimePicker.Event.FOCUS, '.' + DateTimePicker.ClassName.INPUT, function (event) { var $target = getSelectorFromElement($(this)), config = $target.data(DateTimePicker.DATA_KEY); if ($target.length === 0) { return; } if (!config._options.allowInputToggle) { return; } TempusDominusBootstrap4._jQueryInterface.call($target, config, event); }); $.fn[DateTimePicker.NAME] = TempusDominusBootstrap4._jQueryInterface; $.fn[DateTimePicker.NAME].Constructor = TempusDominusBootstrap4; $.fn[DateTimePicker.NAME].noConflict = function () { $.fn[DateTimePicker.NAME] = JQUERY_NO_CONFLICT; return TempusDominusBootstrap4._jQueryInterface; }; return TempusDominusBootstrap4; }(jQuery); }();
sashberd/cdnjs
ajax/libs/tempusdominus-bootstrap-4/5.0.0-alpha13/js/tempusdominus-bootstrap-4.js
JavaScript
mit
114,603
// Created by Monte Hurd on 11/10/14. // Copyright (c) 2014 Wikimedia Foundation. Provided under MIT-style license; please copy and modify! #import <UIKit/UIKit.h> @interface UIView (WMF_RoundCorners) /** * @warning Watch out for race conditions with auto layout when using these methods! Be sure to call them after layout, * e.g. in @c viewDidLayoutSubviews. */ /// Round all corners of the receiver, making it circular. - (void)wmf_makeCircular; /** * Round the given corners of the receiver. * @param corners The corners to apply rounding to. * @param radius The radius to apply to @c corners. */ - (void)wmf_roundCorners:(UIRectCorner)corners toRadius:(float)radius; @end
jindulys/Wikipedia
Wikipedia/Code/UIView+WMFRoundCorners.h
C
mit
696
The Elixir and Phoenix communities are friendly and welcoming. All questions and comments are valuable, so please come join the discussion! There are a number of places to connect with community members at all experience levels. * We're on freenode IRC in [\#elixir-lang](http://webchat.freenode.net/?channels=elixir-lang) channel. * We have a [Slack channel](https://elixir-slackin.herokuapp.com/). * The Phoenix repo has an [issue tracker](https://github.com/phoenixframework/phoenix/issues). * For general Phoenix questions, email the [phoenix-talk mailing list](http://groups.google.com/group/phoenix-talk). * To discuss new features in the framework, email the [phoenix-core mailing list](http://groups.google.com/group/phoenix-core). * Ask or answer questions about Phoenix on [stackoverflow](http://stackoverflow.com/questions/tagged/phoenix-framework). * Follow the Phoenix Framework on [Twitter](https://twitter.com/elixirphoenix). * For questions about these guides, please report an [issue](https://github.com/phoenixframework/phoenix_guides/issues) or open a [pull request](https://github.com/phoenixframework/phoenix_guides/pulls).
CultivateHQ/phoenix_guides
introduction/L_community.md
Markdown
mit
1,147
/** * A network library for processing which supports UDP, TCP and Multicast. * * (c) 2004-2011 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA * * @author Andreas Schlegel http://www.sojamo.de/libraries/oscP5 * @modified 12/19/2011 * @version 0.9.8 */ package netP5; import java.net.DatagramPacket; import java.util.Vector; /** * * @author andreas schlegel * */ public class UdpServer extends AbstractUdpServer implements UdpPacketListener { protected Object _myParent; protected NetPlug _myNetPlug; /** * new UDP server. * by default the buffersize of a udp packet is 1536 bytes. you can set * your own individual buffersize with the third parameter int in the constructor. * @param theObject Object * @param thePort int * @param theBufferSize int */ public UdpServer( final Object theObject, final int thePort, final int theBufferSize) { super(null, thePort, theBufferSize); _myParent = theObject; _myListener = this; _myNetPlug = new NetPlug(_myParent); start(); } public UdpServer( final Object theObject, final int thePort) { super(null, thePort, 1536); _myParent = theObject; _myListener = this; _myNetPlug = new NetPlug(_myParent); start(); } /** * @invisible * @param theListener * @param thePort * @param theBufferSize */ public UdpServer( final UdpPacketListener theListener, final int thePort, final int theBufferSize) { super(theListener, thePort, theBufferSize); } /** * @invisible * @param theListener * @param theAddress * @param thePort * @param theBufferSize */ protected UdpServer( final UdpPacketListener theListener, final String theAddress, final int thePort, final int theBufferSize) { super(theListener, theAddress, thePort, theBufferSize); } /** * @invisible * @param thePacket DatagramPacket * @param thePort int */ public void process(DatagramPacket thePacket, int thePort) { _myNetPlug.process(thePacket,thePort); } /** * add a listener to the udp server. each incoming packet will be forwarded * to the listener. * @param theListener * @related NetListener */ public void addListener(NetListener theListener) { _myNetPlug.addListener(theListener); } /** * * @param theListener * @related NetListener */ public void removeListener(NetListener theListener) { _myNetPlug.removeListener(theListener); } /** * * @param theIndex * @related NetListener * @return */ public NetListener getListener(int theIndex) { return _myNetPlug.getListener(theIndex); } /** * @related NetListener * @return */ public Vector getListeners() { return _myNetPlug.getListeners(); } }
Avnerus/pulse-midburn
oscP5/src/netP5/UdpServer.java
Java
mit
3,640
/** * Copyright (c) 2010-2018 by the respective copyright holders. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.innogysmarthome.internal.listener; import org.openhab.binding.innogysmarthome.internal.InnogyWebSocket; /** * The {@link EventListener} is called by the {@link InnogyWebSocket} on new Events and if the {@link InnogyWebSocket} * closed the connection. * * @author Oliver Kuhl - Initial contribution */ public interface EventListener { /** * This method is called, whenever a new event comes from the innogy service (like a device change for example). * * @param msg */ public void onEvent(String msg); /** * This method is called, when the evenRunner stops abnormally (statuscode <> 1000). */ public void connectionClosed(); }
johannrichard/openhab2-addons
addons/binding/org.openhab.binding.innogysmarthome/src/main/java/org/openhab/binding/innogysmarthome/internal/listener/EventListener.java
Java
epl-1.0
1,030
from sys import * from pdflib_py import * p = PDF_new() PDF_open_file(p, "gradients.pdf") PDF_set_parameter(p, "usercoordinates", "true") PDF_set_value(p, "compress", 0) PDF_set_info(p, "Author", "pdflib") PDF_set_info(p, "Creator", "pdflib_py") PDF_set_info(p, "Title", "gradients") width = 1024 height = 800 PDF_begin_page(p, width, height) type,x,params = "radial",0,"r0=0 r1=320" y = 0 PDF_setcolor(p, "fill", "rgb", 0.0, 0.0, 0.0, 1.0) shading = PDF_shading(p, type, 160+x,160+y, 160+x, 160+y, 1.0, 1.0, 1.0, 1.0, params) #axial|radial pattern = PDF_shading_pattern(p,shading,"") PDF_setcolor(p, "fill", "pattern", pattern,0,0,0) PDF_moveto(p, x,y) PDF_curveto(p, x+80, y+80, x+80, y+240, x, y+320) PDF_curveto(p, x+80, y+240, x+240, y+240, x+320, y+320) PDF_curveto(p, x+240, y+240, x+240, y+80, x+320, y) PDF_curveto(p, x+240, y+80, x+80, y+80, x, y) PDF_fill(p) PDF_moveto(p, x,y) PDF_curveto(p, x+80, y+80, x+80, y+240, x, y+320) PDF_curveto(p, x+80, y+240, x+240, y+240, x+320, y+320) PDF_curveto(p, x+240, y+240, x+240, y+80, x+320, y) PDF_curveto(p, x+240, y+80, x+80, y+80, x, y) PDF_stroke(p) type,x,params = "axial",200,"" y = 0 PDF_setcolor(p, "fill", "rgb", 0.0, 0.0, 0.4, 1.0) shading = PDF_shading(p, type, 0+x,0+y, 320+x,320+y, 1.0, 1.0, 1.0, 1.0, params) #axial|radial pattern = PDF_shading_pattern(p,shading,"") PDF_setcolor(p, "fill", "pattern", pattern,0,0,0) PDF_moveto(p, x,y) PDF_curveto(p, x+80, y+80, x+80, y+240, x, y+320) PDF_curveto(p, x+80, y+240, x+240, y+240, x+320, y+320) PDF_curveto(p, x+240, y+240, x+240, y+80, x+320, y) PDF_curveto(p, x+240, y+80, x+80, y+80, x, y) PDF_fill(p) PDF_moveto(p, x,y) PDF_curveto(p, x+80, y+80, x+80, y+240, x, y+320) PDF_curveto(p, x+80, y+240, x+240, y+240, x+320, y+320) PDF_curveto(p, x+240, y+240, x+240, y+80, x+320, y) PDF_curveto(p, x+240, y+80, x+80, y+80, x, y) PDF_stroke(p) type,x,params = "radial",500,"r0=0 r1=220" y = 0 PDF_setcolor(p, "fill", "rgb", 0.0, 0.0, 0.4, 1.0) shading = PDF_shading(p, type, 120+x, 340+y, 120+x, 340+y, 1.0, 1.0, 1.0, 1.0, params) #axial|radial pattern = PDF_shading_pattern(p,shading,"") PDF_setcolor(p, "fill", "pattern", pattern,0,0,0) PDF_moveto(p, x+80, y+80) PDF_lineto(p, x+80, y+640) PDF_lineto(p, x+160, y+640) PDF_lineto(p, x+160, y+80) PDF_lineto(p, x+80, y+80) PDF_fill(p) PDF_moveto(p, x+80, y+80) PDF_lineto(p, x+80, y+640) PDF_lineto(p, x+160, y+640) PDF_lineto(p, x+160, y+80) PDF_lineto(p, x+80, y+80) PDF_stroke(p) type,x,params = "axial",600,"" y = 0 PDF_setcolor(p, "fill", "rgb", 0.0, 0.0, 0.4, 1.0) shading = PDF_shading(p, type, 80+x, 80+y, 80+x, 640+y, 1.0, 1.0, 1.0, 1.0, params) #axial|radial pattern = PDF_shading_pattern(p,shading,"") PDF_setcolor(p, "fill", "pattern", pattern,0,0,0) PDF_moveto(p, x+80, y+80) PDF_lineto(p, x+80, y+640) PDF_lineto(p, x+160, y+640) PDF_lineto(p, x+160, y+80) PDF_lineto(p, x+80, y+80) PDF_fill(p) PDF_moveto(p, x+80, y+80) PDF_lineto(p, x+80, y+640) PDF_lineto(p, x+160, y+640) PDF_lineto(p, x+160, y+80) PDF_lineto(p, x+80, y+80) PDF_stroke(p) type,x,params = "axial",50,"" y = 300 PDF_setcolor(p, "fill", "rgb", 0.0, 0.0, 0.4, 1.0) shading = PDF_shading(p, type, 80+x, 80+y, 400+x, 80+y, 1.0, 1.0, 1.0, 1.0, params) #axial|radial pattern = PDF_shading_pattern(p,shading,"") PDF_setcolor(p, "fill", "pattern", pattern,0,0,0) PDF_moveto(p, x+80, y+80) PDF_lineto(p, x+80, y+160) PDF_lineto(p, x+400, y+160) PDF_lineto(p, x+400, y+80) PDF_lineto(p, x+80, y+80) PDF_fill(p) PDF_moveto(p, x+80, y+80) PDF_lineto(p, x+80, y+160) PDF_lineto(p, x+400, y+160) PDF_lineto(p, x+400, y+80) PDF_lineto(p, x+80, y+80) PDF_stroke(p) PDF_end_page(p) PDF_close(p) PDF_delete(p);
brad/swftools
spec/gradients.py
Python
gpl-2.0
3,650
<?php /** * Types_Page_Hidden_Helper * * @since 2.0 */ class Types_Page_Hidden_Helper extends Types_Page_Abstract { private static $instance; private $redirect_url = false; public static function get_instance() { if( null == self::$instance ) { self::$instance = new self(); self::$instance->add_sneaky_hidden_helper(); } } public function add_sneaky_hidden_helper() { add_submenu_page( 'options.php', // hidden $this->get_title(), $this->get_title(), $this->get_required_capability(), $this->get_page_name(), array( $this, $this->get_load_callback() ) ); } public function get_title() { return 'Loading...'; } public function get_render_callback() { return null; } public function get_load_callback() { return 'route'; } public function get_page_name() { return Types_Admin_Menu::PAGE_NAME_HELPER; } public function get_required_capability() { return 'manage_options'; } public function route() { $this->redirect_url = false; if( isset( $_GET['action'] ) && isset( $_GET['type'] ) ) { switch( $_GET['action'] ) { case 'new-form': $this->redirect_url = $this->new_form_action( $_GET['type'] ); break; case 'new-view': $this->redirect_url = $this->new_view_action( $_GET['type'] ); break; case 'new-layout-template': $this->redirect_url = $this->new_layout_template_action( $_GET['type'] ); break; case 'new-content-template': $this->redirect_url = $this->new_content_template_action( $_GET['type'] ); break; case 'new-wordpress-archive': $this->redirect_url = $this->new_wordpress_archive_action( $_GET['type'] ); break; case 'new-post-field-group': $this->redirect_url = $this->new_post_field_group_action( $_GET['type'] ); break; } } $this->redirect_url = $this->add_params_to_url( $this->redirect_url ); $this->redirect(); } private function new_form_action( $type ) { $new_form = new Types_Helper_Create_Form(); if( $id = $new_form->for_post( $type ) ) { return get_edit_post_link( $id, 'Please WordPress, be so nice and do not encode &.' ); } return false; } private function new_view_action( $type ) { $new_view = new Types_Helper_Create_View(); if( $id = $new_view->for_post( $type ) ) { return admin_url() . 'admin.php?page=views-editor&view_id='.$id; } return false; } private function new_layout_template_action( $type ) { $new_layout = new Types_Helper_Create_Layout(); if( $id = $new_layout->for_post( $type ) ) { return admin_url() . 'admin.php?page=dd_layouts_edit&action=edit&layout_id='.$id; } return false; } private function new_content_template_action( $type ) { $new_layout = new Types_Helper_Create_Content_Template(); if( $id = $new_layout->for_post( $type ) ) { return admin_url() . 'admin.php?page=ct-editor&ct_id='.$id; } return false; } private function new_wordpress_archive_action( $type ) { $new_wordpress_archive = new Types_Helper_Create_Wordpress_Archive(); if( $id = $new_wordpress_archive->for_post( $type ) ) { return admin_url() . 'admin.php?page=view-archives-editor&view_id='.$id; } return false; } private function new_post_field_group_action( $type ) { $type_object = get_post_type_object( $type ); $title = sprintf( __( 'Field Group for %s', 'types' ), $type_object->labels->name ); $name = sanitize_title( $title ); $new_post_field_group = Types_Field_Group_Post_Factory::get_instance()->create( $name, $title, 'publish' ); if( ! $new_post_field_group ) return false; $new_post_field_group->assign_post_type( $type ); $url = isset( $_GET['ref'] ) ? 'admin.php?page=wpcf-edit&group_id='.$new_post_field_group->get_id().'&ref='.$_GET['ref'] : 'admin.php?page=wpcf-edit&group_id='.$new_post_field_group->get_id(); return admin_url( $url ); } private function add_params_to_url( $url ) { // forward parameter toolset_help_video if( isset( $_GET['toolset_help_video'] ) ) $url = add_query_arg( 'toolset_help_video', $_GET['toolset_help_video'], $url ); // forward parameter ref if( isset( $_GET['ref'] ) ) $url = add_query_arg( 'ref', $_GET['ref'], $url ); return $url; } /** * hidden page, but only when redirect after doing what we have to do */ private function redirect() { // shouldn't happen but if we have no redirect_url here: goto admin main page. if( ! $this->redirect_url ) $this->redirect_url = admin_url(); die( '<script type="text/javascript">'.'window.location = "' . $this->redirect_url . '";'.'</script>' ); } }
Analytical-Engine-Interactive/loopylogic
wp-content/plugins/types/application/controllers/page/hidden/helper.php
PHP
gpl-2.0
4,598
/* * $Id:$ * * Copyright (C) 2012 Piotr Esden-Tempski <piotr@esden.net> * * This file is part of paparazzi. * * paparazzi is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * paparazzi is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with paparazzi; see the file COPYING. If not, write to * the Free Software Foundation, 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "mcu.h" #include "mcu_periph/sys_time.h" #include "led.h" #include "subsystems/datalink/downlink.h" #include "mcu_periph/uart.h" #include "mcu_periph/can.h" static inline void main_init( void ); static inline void main_periodic_task( void ); static inline void main_event_task( void ); void main_on_can_msg(uint32_t id, uint8_t *data, int len); uint8_t tx_data[8]; uint8_t rx_data[8]; bool new_can_data = false; int main(void) { main_init(); tx_data[0] = 0; tx_data[1] = 0; tx_data[2] = 0; tx_data[3] = 0; tx_data[4] = 0; tx_data[5] = 0; tx_data[6] = 0; tx_data[7] = 0; new_can_data = false; while(1) { if (sys_time_check_and_ack_timer(0)) main_periodic_task(); main_event_task(); } return 0; } static inline void main_init( void ) { mcu_init(); sys_time_register_timer((0.5/PERIODIC_FREQUENCY), NULL); ppz_can_init(main_on_can_msg); } static inline void main_periodic_task( void ) { tx_data[0]+=1; ppz_can_transmit(0, tx_data, 8); LED_PERIODIC(); DOWNLINK_SEND_ALIVE(DefaultChannel, DefaultDevice, 16, MD5SUM); } static inline void main_event_task( void ) { if (new_can_data) { if (rx_data[0] & 0x10) { LED_ON(2); } else { LED_OFF(2); } } if (new_can_data) { if (rx_data[0] & 0x20) { LED_ON(3); } else { LED_OFF(3); } } if (new_can_data) { if (rx_data[0] & 0x40) { LED_ON(4); } else { LED_OFF(4); } } if (new_can_data) { if (rx_data[0] & 0x80) { LED_ON(5); } else { LED_OFF(5); } } } void main_on_can_msg(uint32_t id, uint8_t *data, int len) { for (int i = 0; i<8; i++) { rx_data[i] = data[i]; } new_can_data = true; }
arbuzarbuz/paparazzi
sw/airborne/lisa/test_can.c
C
gpl-2.0
2,489
// Copyright (C) 2015 Conrad Sanderson // Copyright (C) 2015 NICTA (www.nicta.com.au) // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. //! \addtogroup spdiagview //! @{ //! Class for storing data required to extract and set the diagonals of a sparse matrix template<typename eT> class spdiagview : public Base<eT, spdiagview<eT> > { public: typedef eT elem_type; typedef typename get_pod_type<eT>::result pod_type; arma_aligned const SpMat<eT>& m; static const bool is_row = false; static const bool is_col = true; const uword row_offset; const uword col_offset; const uword n_rows; // equal to n_elem const uword n_elem; static const uword n_cols = 1; protected: arma_inline spdiagview(const SpMat<eT>& in_m, const uword in_row_offset, const uword in_col_offset, const uword len); public: inline ~spdiagview(); inline void operator=(const spdiagview& x); inline void operator+=(const eT val); inline void operator-=(const eT val); inline void operator*=(const eT val); inline void operator/=(const eT val); template<typename T1> inline void operator= (const Base<eT,T1>& x); template<typename T1> inline void operator+=(const Base<eT,T1>& x); template<typename T1> inline void operator-=(const Base<eT,T1>& x); template<typename T1> inline void operator%=(const Base<eT,T1>& x); template<typename T1> inline void operator/=(const Base<eT,T1>& x); template<typename T1> inline void operator= (const SpBase<eT,T1>& x); template<typename T1> inline void operator+=(const SpBase<eT,T1>& x); template<typename T1> inline void operator-=(const SpBase<eT,T1>& x); template<typename T1> inline void operator%=(const SpBase<eT,T1>& x); template<typename T1> inline void operator/=(const SpBase<eT,T1>& x); inline eT at_alt (const uword ii) const; inline SpValProxy< SpMat<eT> > operator[](const uword ii); inline eT operator[](const uword ii) const; inline SpValProxy< SpMat<eT> > at(const uword ii); inline eT at(const uword ii) const; inline SpValProxy< SpMat<eT> > operator()(const uword ii); inline eT operator()(const uword ii) const; inline SpValProxy< SpMat<eT> > at(const uword in_n_row, const uword); inline eT at(const uword in_n_row, const uword) const; inline SpValProxy< SpMat<eT> > operator()(const uword in_n_row, const uword in_n_col); inline eT operator()(const uword in_n_row, const uword in_n_col) const; inline void fill(const eT val); inline void zeros(); inline void ones(); inline void randu(); inline void randn(); inline static void extract(Mat<eT>& out, const spdiagview& in); private: friend class SpMat<eT>; spdiagview(); }; //! @}
srinix07/pairing_3p2
lib/armadillo_5_1/include/armadillo_bits/spdiagview_bones.hpp
C++
gpl-2.0
3,101
/* Copyright (c) 2010-2011, Code Aurora Forum. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/module.h> #include <mach/irqs.h> #include <asm/mach-types.h> #include <mach/gpiomux.h> #include "gpiomux_lge_325.h" #include "devices_lge_325.h" #ifdef CONFIG_LGE_PM_CURRENT_CONSUMPTION_FIX #ifdef CONFIG_MACH_LGE_325_BOARD_VZW static struct gpiomux_setting msm_gpio81_cfg_suspend2 = /* BOOT_CONFIG_0 */ { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_NONE, }; static struct msm_gpiomux_config msm8x60_current_configs[] __initdata = { /* BOOT_CONFIG_0 */ { .gpio = 81, .settings = { [GPIOMUX_SUSPENDED] = &msm_gpio81_cfg_suspend2, }, }, }; #else static struct gpiomux_setting msm_gpio81_cfg_suspend2 = /* BOOT_CONFIG_0 */ { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_UP, }; static struct gpiomux_setting msm_gpio84_cfg_suspend2 = /* BOOT_CONFIG_1 */ { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_UP, }; static struct gpiomux_setting msm_gpio76_cfg_suspend2 = /* BOOT_CONFIG_6*/ { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_UP, }; static struct msm_gpiomux_config msm8x60_current_configs[] __initdata = { /* BOOT_CONFIG_0 */ { .gpio = 81, .settings = { [GPIOMUX_SUSPENDED] = &msm_gpio81_cfg_suspend2, }, }, /* BOOT_CONFIG_1 */ { .gpio = 84, .settings = { [GPIOMUX_SUSPENDED] = &msm_gpio84_cfg_suspend2, }, }, /* BOOT_CONFIG_6*/ { .gpio = 76, .settings = { [GPIOMUX_SUSPENDED] = &msm_gpio76_cfg_suspend2, }, }, }; //for atnt rock_bottom end #endif #endif static struct gpiomux_setting console_uart = { .func = GPIOMUX_FUNC_2, .drv = GPIOMUX_DRV_8MA, .pull = GPIOMUX_PULL_NONE, }; // static struct gpiomux_setting wifi_active = { .func = GPIOMUX_FUNC_1, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_UP, }; // /* The SPI configurations apply to GSBI1 and GSBI10 */ static struct gpiomux_setting spi_active = { .func = GPIOMUX_FUNC_1, .drv = GPIOMUX_DRV_8MA, .pull = GPIOMUX_PULL_NONE, }; static struct gpiomux_setting spi_suspended_config = { .func = GPIOMUX_FUNC_1, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_DOWN, }; static struct gpiomux_setting spi_suspended_cs_config = { .func = GPIOMUX_FUNC_1, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_NONE, }; /* This I2C active configuration applies to GSBI3 and GSBI4 */ static struct gpiomux_setting i2c_active = { .func = GPIOMUX_FUNC_1, .drv = GPIOMUX_DRV_8MA, .pull = GPIOMUX_PULL_NONE, }; #ifdef CONFIG_LGE_FUEL_GAUGE static struct gpiomux_setting gsbi5 = { .func = GPIOMUX_FUNC_1, .drv = GPIOMUX_DRV_8MA, .pull = GPIOMUX_PULL_NONE, }; #endif static struct gpiomux_setting i2c_active_gsbi7 = { .func = GPIOMUX_FUNC_1, .drv = GPIOMUX_DRV_12MA, .pull = GPIOMUX_PULL_NONE, }; /* This I2C suspended configuration applies to GSBI3, GSBI4 and GSBI7 */ static struct gpiomux_setting i2c_suspended_config = { .func = GPIOMUX_FUNC_1, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_NONE, }; static struct gpiomux_setting gsbi8 = { .func = GPIOMUX_FUNC_1, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_NONE, }; #ifdef CONFIG_LGE_IRDA static struct gpiomux_setting gsbi8_irda = { .func = GPIOMUX_FUNC_1, .drv = GPIOMUX_DRV_8MA, .pull = GPIOMUX_PULL_DOWN, }; static struct gpiomux_setting gsbi8_irda_active = { .func = GPIOMUX_FUNC_1, .drv = GPIOMUX_DRV_8MA, .pull = GPIOMUX_PULL_DOWN, }; static struct gpiomux_setting irda_pwdn_suspended = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_NONE, .dir = GPIOMUX_OUT_HIGH, }; /* static struct gpiomux_setting irda_pwdn_active = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_UP, .dir = GPIOMUX_OUT_HIGH, }; */ #endif #ifdef CONFIG_LGE_FELICA static struct gpiomux_setting uart10dm_active = { .func = GPIOMUX_FUNC_1, .drv = GPIOMUX_DRV_8MA , .pull = GPIOMUX_PULL_DOWN, }; #endif static struct gpiomux_setting gsbi10 = { .func = GPIOMUX_FUNC_1, .drv = GPIOMUX_DRV_8MA, .pull = GPIOMUX_PULL_NONE, }; #if defined(CONFIG_LGE_BROADCAST_DCM) || defined(CONFIG_LGE_BROADCAST_TDMB) static struct gpiomux_setting gsbi11 = { .func = GPIOMUX_FUNC_2, .drv = GPIOMUX_DRV_8MA, .pull = GPIOMUX_PULL_NONE, }; static struct gpiomux_setting bcast_ctrl_pin = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_8MA, .pull = GPIOMUX_PULL_NONE, }; #if defined (CONFIG_LGE_BROADCAST_TDMB) static struct gpiomux_setting DMB_INT = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_8MA, .pull = GPIOMUX_PULL_NONE, }; #endif #endif #if defined (CONFIG_LGE_WIRELESS_CHARGER_MAX8971) || defined (CONFIG_LGE_WIRELESS_CHARGER_BQ24160) static struct gpiomux_setting gsbi11 = { .func = GPIOMUX_FUNC_2, .drv = GPIOMUX_DRV_8MA, .pull = GPIOMUX_PULL_NONE, }; #endif static struct gpiomux_setting gsbi12 = { .func = GPIOMUX_FUNC_1, .drv = GPIOMUX_DRV_8MA, .pull = GPIOMUX_PULL_NONE, }; static struct gpiomux_setting ps_hold = { .func = GPIOMUX_FUNC_1, .drv = GPIOMUX_DRV_12MA, .pull = GPIOMUX_PULL_NONE, }; static struct gpiomux_setting msm_snddev_active_config = { .func = GPIOMUX_FUNC_1, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_NONE, }; static struct gpiomux_setting msm_snddev_suspend_config = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_DOWN, }; static struct gpiomux_setting sdcc1_dat_0_3_cmd_actv_cfg = { .func = GPIOMUX_FUNC_1, .drv = GPIOMUX_DRV_10MA, .pull = GPIOMUX_PULL_UP, }; static struct gpiomux_setting sdcc1_dat_4_7_cmd_actv_cfg = { .func = GPIOMUX_FUNC_1, .drv = GPIOMUX_DRV_10MA, .pull = GPIOMUX_PULL_UP, }; static struct gpiomux_setting sdcc1_clk_actv_cfg = { .func = GPIOMUX_FUNC_1, .drv = GPIOMUX_DRV_16MA, .pull = GPIOMUX_PULL_NONE, }; static struct gpiomux_setting sdcc1_suspend_config = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_UP, }; static struct gpiomux_setting sdcc2_dat_0_3_cmd_actv_cfg = { .func = GPIOMUX_FUNC_2, .drv = GPIOMUX_DRV_10MA, .pull = GPIOMUX_PULL_UP, }; static struct gpiomux_setting sdcc2_dat_4_7_cmd_actv_cfg = { .func = GPIOMUX_FUNC_2, .drv = GPIOMUX_DRV_10MA, .pull = GPIOMUX_PULL_UP, }; static struct gpiomux_setting sdcc2_clk_actv_cfg = { .func = GPIOMUX_FUNC_2, .drv = GPIOMUX_DRV_16MA, .pull = GPIOMUX_PULL_NONE, }; static struct gpiomux_setting sdcc2_suspend_config = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_UP, }; static struct gpiomux_setting sdcc5_dat_0_3_cmd_actv_cfg = { .func = GPIOMUX_FUNC_2, .drv = GPIOMUX_DRV_10MA, .pull = GPIOMUX_PULL_UP, }; static struct gpiomux_setting sdcc5_clk_actv_cfg = { .func = GPIOMUX_FUNC_2, .drv = GPIOMUX_DRV_16MA, .pull = GPIOMUX_PULL_NONE, }; static struct gpiomux_setting sdcc5_suspend_config = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_UP, }; static struct gpiomux_setting aux_pcm_active_config = { .func = GPIOMUX_FUNC_1, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_NONE, }; static struct gpiomux_setting aux_pcm_suspend_config = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_NONE, }; static struct gpiomux_setting uart1dm_active = { .func = GPIOMUX_FUNC_1, .drv = GPIOMUX_DRV_8MA, .pull = GPIOMUX_PULL_NONE, }; static struct gpiomux_setting uart1dm_suspended = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_DOWN, }; static struct gpiomux_setting mdp_vsync_suspend_cfg = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_DOWN, }; static struct gpiomux_setting hdmi_suspend_cfg = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_DOWN, }; static struct gpiomux_setting mdm2ap_status_active_cfg = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_NONE, }; static struct gpiomux_setting mdm2ap_status_suspend_cfg = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_NONE, }; static struct gpiomux_setting mdm2ap_sync_active_cfg = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_NONE, }; static struct gpiomux_setting mdm2ap_sync_suspend_cfg = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_NONE, }; static struct gpiomux_setting mdp_vsync_active_cfg = { .func = GPIOMUX_FUNC_1, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_NONE, }; static struct gpiomux_setting hdmi_active_1_cfg = { .func = GPIOMUX_FUNC_1, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_UP, }; static struct gpiomux_setting hdmi_active_2_cfg = { .func = GPIOMUX_FUNC_1, .drv = GPIOMUX_DRV_16MA, .pull = GPIOMUX_PULL_NONE, }; static struct gpiomux_setting hdmi_active_3_cfg = { .func = GPIOMUX_FUNC_1, .drv = GPIOMUX_DRV_16MA, .pull = GPIOMUX_PULL_DOWN, }; static struct gpiomux_setting pmic_suspended_cfg = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_NONE, }; #ifdef CONFIG_MSM_GSBI9_UART static struct gpiomux_setting uart9dm_active = { .func = GPIOMUX_FUNC_1, .drv = GPIOMUX_DRV_8MA , .pull = GPIOMUX_PULL_DOWN, }; static struct gpiomux_setting gsbi9 = { .func = GPIOMUX_FUNC_1, .drv = GPIOMUX_DRV_8MA, .pull = GPIOMUX_PULL_NONE, }; #endif static struct gpiomux_setting ap2mdm_cfg = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_8MA, .pull = GPIOMUX_PULL_DOWN, }; static struct gpiomux_setting mdm2ap_status_cfg = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_8MA, .pull = GPIOMUX_PULL_NONE, }; static struct gpiomux_setting mdm2ap_vfr_active_cfg = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_8MA, .pull = GPIOMUX_PULL_UP, }; static struct gpiomux_setting mdm2ap_vfr_suspend_cfg = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_8MA, .pull = GPIOMUX_PULL_DOWN, }; static struct gpiomux_setting mdm2ap_errfatal_cfg = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_16MA, .pull = GPIOMUX_PULL_DOWN, }; static struct gpiomux_setting ap2mdm_kpdpwr_n_cfg = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_8MA, .pull = GPIOMUX_PULL_NONE, }; #ifdef CONFIG_LGE_AUDIO #if 0 /* error CAMCORDER_MIC_EN180 greater than max:173 */ static struct gpiomux_setting camcorder_mic_en_cfg = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_NONE, .dir = GPIOMUX_OUT_LOW, }; #endif static struct gpiomux_setting motor_en_cfg = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_NONE, .dir = GPIOMUX_OUT_LOW, }; static struct gpiomux_setting lin_motor_pwm_cfg = { .func = GPIOMUX_FUNC_2, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_NONE, // .dir = GPIOMUX_OUT_LOW, }; #ifdef CONFIG_LGE_HEADSET_DETECTION_FSA8008 static struct gpiomux_setting ear_mic_en_cfg = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_NONE, .dir = GPIOMUX_OUT_LOW, }; static struct gpiomux_setting earpole_detect_cfg = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_NONE, .dir = GPIOMUX_IN, }; #endif #endif static struct gpiomux_setting mdm2ap_vddmin_active_cfg = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_NONE, }; static struct gpiomux_setting mdm2ap_vddmin_suspend_cfg = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_NONE, }; #ifdef CONFIG_LGE_FELICA static struct gpiomux_setting felica_pon_cfg = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_NONE, }; static struct gpiomux_setting felica_lockcont_cfg = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_NONE, }; #endif // #if defined(CONFIG_LGE_NFC_PN544_C2) static struct gpiomux_setting nfc_pn544pn65n_ven_cfg = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_8MA, .pull = GPIOMUX_PULL_DOWN, .dir = GPIOMUX_OUT_LOW, }; static struct gpiomux_setting nfc_pn544pn65n_irq_cfg = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_8MA, .pull = GPIOMUX_PULL_DOWN, .dir = GPIOMUX_IN, }; static struct gpiomux_setting nfc_pn544pn65n_firm_cfg = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_8MA, .pull = GPIOMUX_PULL_DOWN, .dir = GPIOMUX_OUT_LOW, }; #endif // #ifdef CONFIG_LGE_MHL_SII9244 static struct gpiomux_setting mhl_detect_cfg = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_NONE, .dir = GPIOMUX_IN, }; static struct gpiomux_setting mhl_reset_n_cfg = { .func = GPIOMUX_FUNC_GPIO, .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_NONE, .dir = GPIOMUX_OUT_LOW, }; static struct msm_gpiomux_config msm8x60_mhl_configs[] __initdata = { /* MHL_INT */ { .gpio = 30, .settings = { [GPIOMUX_SUSPENDED] = &mhl_detect_cfg, }, }, /* USB_MHL_SEL */ #if defined(CONFIG_MACH_LGE_325_BOARD_LGU) || defined(CONFIG_MACH_LGE_325_BOARD_VZW) { .gpio = 33, .settings = { [GPIOMUX_SUSPENDED] = &mhl_reset_n_cfg, }, }, #else { .gpio = 139, .settings = { [GPIOMUX_SUSPENDED] = &mhl_reset_n_cfg, }, }, #endif /* MHL_RESET_N */ { .gpio = 142, .settings = { [GPIOMUX_SUSPENDED] = &mhl_reset_n_cfg, }, }, /* MHL_WAKE_UP */ { .gpio = 153, .settings = { [GPIOMUX_SUSPENDED] = &mhl_reset_n_cfg, }, }, }; #endif static struct msm_gpiomux_config msm8x60_gsbi_configs[] __initdata = { #if defined(CONFIG_MACH_LGE_325_BOARD_LGU) || defined(CONFIG_MACH_LGE_325_BOARD_VZW) #ifndef CONFIG_LGE_MHL_SII9244 { .gpio = 33, .settings = { [GPIOMUX_SUSPENDED] = &spi_suspended_config, [GPIOMUX_ACTIVE] = &spi_active, }, }, #endif #else { .gpio = 33, .settings = { [GPIOMUX_SUSPENDED] = &spi_suspended_config, [GPIOMUX_ACTIVE] = &spi_active, }, }, #endif { .gpio = 34, .settings = { // //[GPIOMUX_SUSPENDED] = &spi_suspended_config, //[GPIOMUX_ACTIVE] = &spi_active, [GPIOMUX_ACTIVE] = &wifi_active, [GPIOMUX_SUSPENDED] = &wifi_active, }, }, { .gpio = 35, .settings = { [GPIOMUX_SUSPENDED] = &spi_suspended_cs_config, [GPIOMUX_ACTIVE] = &spi_active, }, }, { .gpio = 36, .settings = { [GPIOMUX_SUSPENDED] = &spi_suspended_config, [GPIOMUX_ACTIVE] = &spi_active, }, }, { .gpio = 43, .settings = { [GPIOMUX_SUSPENDED] = &i2c_suspended_config, [GPIOMUX_ACTIVE] = &i2c_active, }, }, { .gpio = 44, .settings = { [GPIOMUX_SUSPENDED] = &i2c_suspended_config, [GPIOMUX_ACTIVE] = &i2c_active, }, }, // #if defined(CONFIG_LGE_NFC_PN544_C2) { .gpio = 46, .settings = { [GPIOMUX_SUSPENDED] = &nfc_pn544pn65n_firm_cfg, }, }, #endif // { .gpio = 47, .settings = { [GPIOMUX_SUSPENDED] = &i2c_suspended_config, [GPIOMUX_ACTIVE] = &i2c_active, }, }, { .gpio = 48, .settings = { [GPIOMUX_SUSPENDED] = &i2c_suspended_config, [GPIOMUX_ACTIVE] = &i2c_active, }, }, #ifdef CONFIG_LGE_FUEL_GAUGE { .gpio = 51, .settings = { [GPIOMUX_SUSPENDED] = &gsbi5, }, }, { .gpio = 52, .settings = { [GPIOMUX_SUSPENDED] = &gsbi5, }, }, #endif { .gpio = 59, .settings = { [GPIOMUX_SUSPENDED] = &i2c_suspended_config, [GPIOMUX_ACTIVE] = &i2c_active_gsbi7, }, }, { .gpio = 60, .settings = { [GPIOMUX_SUSPENDED] = &i2c_suspended_config, [GPIOMUX_ACTIVE] = &i2c_active_gsbi7, }, }, { .gpio = 64, .settings = { [GPIOMUX_SUSPENDED] = &gsbi8, }, }, { .gpio = 65, .settings = { [GPIOMUX_SUSPENDED] = &gsbi8, }, }, #ifdef CONFIG_LGE_SENSOR_ACCELEROMETER { .gpio = 72, .settings = { [GPIOMUX_SUSPENDED] = &gsbi10, }, }, { .gpio = 73, .settings = { [GPIOMUX_SUSPENDED] = &gsbi10, }, }, #endif // 2011-05-05 ella.hwang added for 1Seg Driver SPI porting - [Ends] { .gpio = 115, .settings = { [GPIOMUX_SUSPENDED] = &gsbi12, }, }, { .gpio = 116, .settings = { [GPIOMUX_SUSPENDED] = &gsbi12, }, }, #ifdef CONFIG_LGE_FELICA /* FELICA PON */ { .gpio = 107, .settings = { [GPIOMUX_SUSPENDED] = &felica_pon_cfg, }, }, /* FELICA RFS */ { .gpio = 128, .settings = { [GPIOMUX_SUSPENDED] = &felica_pon_cfg, }, }, /* FELICA INT */ { .gpio = 125, .settings = { [GPIOMUX_SUSPENDED] = &felica_pon_cfg, }, }, /* FELICA CEN */ { .gpio = 123, .settings = { [GPIOMUX_SUSPENDED] = &felica_lockcont_cfg, }, }, #endif // 2011-05-05 ella.hwang added for 1Seg Driver SPI porting - [Begins] #if defined(CONFIG_LGE_BROADCAST_DCM) || defined(CONFIG_LGE_BROADCAST_TDMB) /* DTV_RESET */ { .gpio = 101, .settings = { [GPIOMUX_SUSPENDED] = &bcast_ctrl_pin, }, }, /* DTV EN */ { .gpio = 102, .settings = { [GPIOMUX_SUSPENDED] = &bcast_ctrl_pin, }, }, /* DTV SPI CLOCK */ { .gpio = 103, .settings = { [GPIOMUX_SUSPENDED] = &gsbi11, }, }, /* DTV SPI CS */ { .gpio = 104, .settings = { [GPIOMUX_SUSPENDED] = &gsbi11, }, }, /* DTV SPI MISO */ { .gpio = 105, .settings = { [GPIOMUX_SUSPENDED] = &gsbi11, }, }, /* DTV SPI MOSI */ { .gpio = 106, .settings = { [GPIOMUX_SUSPENDED] = &gsbi11, }, }, #if defined(CONFIG_LGE_BROADCAST_TDMB) /* DMB_INT_N */ { .gpio = 107, .settings = { [GPIOMUX_SUSPENDED] = &DMB_INT, }, }, #endif #endif }; // #if defined(CONFIG_LGE_NFC_PN544_C2) static struct msm_gpiomux_config msm8x60_ebi2_configs[] __initdata = { { .gpio = 123, .settings = { [GPIOMUX_SUSPENDED] = &nfc_pn544pn65n_irq_cfg, }, }, { .gpio = 130, .settings = { [GPIOMUX_SUSPENDED] = &nfc_pn544pn65n_ven_cfg, }, }, }; // #endif #if defined(CONFIG_USB_PEHCI_HCD) || defined(CONFIG_USB_PEHCI_HCD_MODULE) #endif static struct msm_gpiomux_config msm8x60_uart_configs[] __initdata = { { /* UARTDM_TX */ .gpio = 53, .settings = { [GPIOMUX_ACTIVE] = &uart1dm_active, [GPIOMUX_SUSPENDED] = &uart1dm_suspended, }, }, { /* UARTDM_RX */ .gpio = 54, .settings = { [GPIOMUX_ACTIVE] = &uart1dm_active, [GPIOMUX_SUSPENDED] = &uart1dm_suspended, }, }, { /* UARTDM_CTS */ .gpio = 55, .settings = { [GPIOMUX_ACTIVE] = &uart1dm_active, [GPIOMUX_SUSPENDED] = &uart1dm_suspended, }, }, { /* UARTDM_RFR */ .gpio = 56, .settings = { [GPIOMUX_ACTIVE] = &uart1dm_active, [GPIOMUX_SUSPENDED] = &uart1dm_suspended, }, }, { .gpio = 115, .settings = { [GPIOMUX_SUSPENDED] = &console_uart, }, }, { .gpio = 116, .settings = { [GPIOMUX_SUSPENDED] = &console_uart, }, }, #if !defined(CONFIG_USB_PEHCI_HCD) && !defined(CONFIG_USB_PEHCI_HCD_MODULE) /* USB ISP1763 may also use 117 GPIO */ { .gpio = 117, .settings = { [GPIOMUX_SUSPENDED] = &console_uart, }, }, #endif { .gpio = 118, .settings = { [GPIOMUX_SUSPENDED] = &console_uart, }, }, }; #ifdef CONFIG_MSM_GSBI9_UART static struct msm_gpiomux_config msm8x60_charm_uart_configs[] __initdata = { { /* UART9DM RX */ .gpio = 66, .settings = { [GPIOMUX_ACTIVE] = &uart9dm_active, [GPIOMUX_SUSPENDED] = &gsbi9, }, }, { /* UART9DM TX */ .gpio = 67, .settings = { [GPIOMUX_ACTIVE] = &uart9dm_active, [GPIOMUX_SUSPENDED] = &gsbi9, }, }, }; #endif #ifdef CONFIG_LGE_IRDA static struct msm_gpiomux_config msm8x60_irda_uart_configs[] __initdata = { { .gpio = 62, .settings = { [GPIOMUX_ACTIVE] = &gsbi8_irda_active, [GPIOMUX_SUSPENDED] = &gsbi8_irda, }, }, { .gpio = 63, .settings = { [GPIOMUX_ACTIVE] = &gsbi8_irda_active, [GPIOMUX_SUSPENDED] = &gsbi8_irda, }, }, { .gpio = 169, .settings = { [GPIOMUX_SUSPENDED] = &irda_pwdn_suspended, // [GPIOMUX_ACTIVE] =&irda_pwdn_active, }, }, }; #endif #ifdef CONFIG_LGE_FELICA static struct msm_gpiomux_config msm8x60_felica_uart_configs[] __initdata = { { /* UART10DM RX */ .gpio = 70, .settings = { [GPIOMUX_ACTIVE] = &uart10dm_active, [GPIOMUX_SUSPENDED] = &gsbi10, }, }, { /* UART10DM TX */ .gpio = 71, .settings = { [GPIOMUX_ACTIVE] = &uart10dm_active, [GPIOMUX_SUSPENDED] = &gsbi10, }, }, }; #endif static struct msm_gpiomux_config msm8x60_aux_pcm_configs[] __initdata = { { .gpio = 111, .settings = { [GPIOMUX_ACTIVE] = &aux_pcm_active_config, [GPIOMUX_SUSPENDED] = &aux_pcm_suspend_config, }, }, { .gpio = 112, .settings = { [GPIOMUX_ACTIVE] = &aux_pcm_active_config, [GPIOMUX_SUSPENDED] = &aux_pcm_suspend_config, }, }, { .gpio = 113, .settings = { [GPIOMUX_ACTIVE] = &aux_pcm_active_config, [GPIOMUX_SUSPENDED] = &aux_pcm_suspend_config, }, }, { .gpio = 114, .settings = { [GPIOMUX_ACTIVE] = &aux_pcm_active_config, [GPIOMUX_SUSPENDED] = &aux_pcm_suspend_config, }, }, }; static struct msm_gpiomux_config msm8x60_sdc_configs[] __initdata = { /* SDCC1 data[0] */ { .gpio = 159, .settings = { [GPIOMUX_ACTIVE] = &sdcc1_dat_0_3_cmd_actv_cfg, [GPIOMUX_SUSPENDED] = &sdcc1_suspend_config, }, }, /* SDCC1 data[1] */ { .gpio = 160, .settings = { [GPIOMUX_ACTIVE] = &sdcc1_dat_0_3_cmd_actv_cfg, [GPIOMUX_SUSPENDED] = &sdcc1_suspend_config, }, }, /* SDCC1 data[2] */ { .gpio = 161, .settings = { [GPIOMUX_ACTIVE] = &sdcc1_dat_0_3_cmd_actv_cfg, [GPIOMUX_SUSPENDED] = &sdcc1_suspend_config, }, }, /* SDCC1 data[3] */ { .gpio = 162, .settings = { [GPIOMUX_ACTIVE] = &sdcc1_dat_0_3_cmd_actv_cfg, [GPIOMUX_SUSPENDED] = &sdcc1_suspend_config, }, }, /* SDCC1 data[4] */ { .gpio = 163, .settings = { [GPIOMUX_ACTIVE] = &sdcc1_dat_4_7_cmd_actv_cfg, [GPIOMUX_SUSPENDED] = &sdcc1_suspend_config, }, }, /* SDCC1 data[5] */ { .gpio = 164, .settings = { [GPIOMUX_ACTIVE] = &sdcc1_dat_4_7_cmd_actv_cfg, [GPIOMUX_SUSPENDED] = &sdcc1_suspend_config, }, }, /* SDCC1 data[6] */ { .gpio = 165, .settings = { [GPIOMUX_ACTIVE] = &sdcc1_dat_4_7_cmd_actv_cfg, [GPIOMUX_SUSPENDED] = &sdcc1_suspend_config, }, }, /* SDCC1 data[7] */ { .gpio = 166, .settings = { [GPIOMUX_ACTIVE] = &sdcc1_dat_4_7_cmd_actv_cfg, [GPIOMUX_SUSPENDED] = &sdcc1_suspend_config, }, }, /* SDCC1 CLK */ { .gpio = 167, .settings = { [GPIOMUX_ACTIVE] = &sdcc1_clk_actv_cfg, [GPIOMUX_SUSPENDED] = &sdcc1_suspend_config, }, }, /* SDCC1 CMD */ { .gpio = 168, .settings = { [GPIOMUX_ACTIVE] = &sdcc1_dat_0_3_cmd_actv_cfg, [GPIOMUX_SUSPENDED] = &sdcc1_suspend_config, }, }, }; static struct msm_gpiomux_config msm8x60_charm_sdc_configs[] __initdata = { /* SDCC5 cmd */ { .gpio = 95, .settings = { [GPIOMUX_ACTIVE] = &sdcc5_dat_0_3_cmd_actv_cfg, [GPIOMUX_SUSPENDED] = &sdcc5_suspend_config, }, }, /* SDCC5 data[3]*/ { .gpio = 96, .settings = { [GPIOMUX_ACTIVE] = &sdcc5_dat_0_3_cmd_actv_cfg, [GPIOMUX_SUSPENDED] = &sdcc5_suspend_config, }, }, /* SDCC5 clk */ { .gpio = 97, .settings = { [GPIOMUX_ACTIVE] = &sdcc5_clk_actv_cfg, [GPIOMUX_SUSPENDED] = &sdcc5_suspend_config, }, }, /* SDCC5 data[2]*/ { .gpio = 98, .settings = { [GPIOMUX_ACTIVE] = &sdcc5_dat_0_3_cmd_actv_cfg, [GPIOMUX_SUSPENDED] = &sdcc5_suspend_config, }, }, /* SDCC5 data[1]*/ { .gpio = 99, .settings = { [GPIOMUX_ACTIVE] = &sdcc5_dat_0_3_cmd_actv_cfg, [GPIOMUX_SUSPENDED] = &sdcc5_suspend_config, }, }, /* SDCC5 data[0]*/ { .gpio = 100, .settings = { [GPIOMUX_ACTIVE] = &sdcc5_dat_0_3_cmd_actv_cfg, [GPIOMUX_SUSPENDED] = &sdcc5_suspend_config, }, }, /* MDM2AP_SYNC */ { .gpio = 129, .settings = { [GPIOMUX_ACTIVE] = &mdm2ap_sync_active_cfg, [GPIOMUX_SUSPENDED] = &mdm2ap_sync_suspend_cfg, }, }, /* MDM2AP_VDDMIN */ { .gpio = 140, .settings = { [GPIOMUX_ACTIVE] = &mdm2ap_vddmin_active_cfg, [GPIOMUX_SUSPENDED] = &mdm2ap_vddmin_suspend_cfg, }, }, /* SDCC2 data[0] */ { .gpio = 143, .settings = { [GPIOMUX_ACTIVE] = &sdcc2_dat_0_3_cmd_actv_cfg, [GPIOMUX_SUSPENDED] = &sdcc2_suspend_config, }, }, /* SDCC2 data[1] */ { .gpio = 144, .settings = { [GPIOMUX_ACTIVE] = &sdcc2_dat_0_3_cmd_actv_cfg, [GPIOMUX_SUSPENDED] = &sdcc2_suspend_config, }, }, /* SDCC2 data[2] */ { .gpio = 145, .settings = { [GPIOMUX_ACTIVE] = &sdcc2_dat_0_3_cmd_actv_cfg, [GPIOMUX_SUSPENDED] = &sdcc2_suspend_config, }, }, /* SDCC2 data[3] */ { .gpio = 146, .settings = { [GPIOMUX_ACTIVE] = &sdcc2_dat_0_3_cmd_actv_cfg, [GPIOMUX_SUSPENDED] = &sdcc2_suspend_config, }, }, /* SDCC2 data[4] */ { .gpio = 147, .settings = { [GPIOMUX_ACTIVE] = &sdcc2_dat_4_7_cmd_actv_cfg, [GPIOMUX_SUSPENDED] = &sdcc2_suspend_config, }, }, /* SDCC2 data[5] */ { .gpio = 148, .settings = { [GPIOMUX_ACTIVE] = &sdcc2_dat_4_7_cmd_actv_cfg, [GPIOMUX_SUSPENDED] = &sdcc2_suspend_config, }, }, /* SDCC2 data[6] */ { .gpio = 149, .settings = { [GPIOMUX_ACTIVE] = &sdcc2_dat_4_7_cmd_actv_cfg, [GPIOMUX_SUSPENDED] = &sdcc2_suspend_config, }, }, /* SDCC2 data[7] */ { .gpio = 150, .settings = { [GPIOMUX_ACTIVE] = &sdcc2_dat_4_7_cmd_actv_cfg, [GPIOMUX_SUSPENDED] = &sdcc2_suspend_config, }, }, /* SDCC2 CMD */ { .gpio = 151, .settings = { [GPIOMUX_ACTIVE] = &sdcc2_dat_0_3_cmd_actv_cfg, [GPIOMUX_SUSPENDED] = &sdcc2_suspend_config, }, }, /* SDCC2 CLK */ { .gpio = 152, .settings = { [GPIOMUX_ACTIVE] = &sdcc2_clk_actv_cfg, [GPIOMUX_SUSPENDED] = &sdcc2_suspend_config, }, }, }; static struct msm_gpiomux_config msm8x60_snd_configs[] __initdata = { { .gpio = 108, .settings = { [GPIOMUX_ACTIVE] = &msm_snddev_active_config, [GPIOMUX_SUSPENDED] = &msm_snddev_suspend_config, }, }, { .gpio = 109, .settings = { [GPIOMUX_ACTIVE] = &msm_snddev_active_config, [GPIOMUX_SUSPENDED] = &msm_snddev_suspend_config, }, }, }; static struct msm_gpiomux_config msm8x60_mdp_vsync_configs[] __initdata = { { .gpio = 28, .settings = { [GPIOMUX_ACTIVE] = &mdp_vsync_active_cfg, [GPIOMUX_SUSPENDED] = &mdp_vsync_suspend_cfg, }, }, }; static struct msm_gpiomux_config msm8x60_hdmi_configs[] __initdata = { { .gpio = 169, .settings = { [GPIOMUX_ACTIVE] = &hdmi_active_1_cfg, [GPIOMUX_SUSPENDED] = &hdmi_suspend_cfg, }, }, { .gpio = 170, .settings = { [GPIOMUX_ACTIVE] = &hdmi_active_2_cfg, [GPIOMUX_SUSPENDED] = &hdmi_suspend_cfg, }, }, { .gpio = 171, .settings = { [GPIOMUX_ACTIVE] = &hdmi_active_2_cfg, [GPIOMUX_SUSPENDED] = &hdmi_suspend_cfg, }, }, { .gpio = 172, .settings = { [GPIOMUX_ACTIVE] = &hdmi_active_3_cfg, [GPIOMUX_SUSPENDED] = &hdmi_suspend_cfg, }, }, }; /* Because PMIC drivers do not use gpio-management routines and PMIC * gpios must never sleep, a "good enough" config is obtained by placing * the active config in the 'suspended' slot and leaving the active * config invalid: the suspended config will be installed at boot * and never replaced. */ static struct msm_gpiomux_config msm8x60_pmic_configs[] __initdata = { { .gpio = 88, .settings = { [GPIOMUX_SUSPENDED] = &pmic_suspended_cfg, }, }, { .gpio = 91, .settings = { [GPIOMUX_SUSPENDED] = &pmic_suspended_cfg, }, }, }; static struct msm_gpiomux_config msm8x60_common_configs[] __initdata = { /* MDM2AP_STATUS */ { .gpio = 77, .settings = { [GPIOMUX_ACTIVE] = &mdm2ap_status_active_cfg, [GPIOMUX_SUSPENDED] = &mdm2ap_status_suspend_cfg, }, }, /* PS_HOLD */ { .gpio = 92, .settings = { [GPIOMUX_SUSPENDED] = &ps_hold, }, }, }; static struct msm_gpiomux_config msm8x60_charm_configs[] __initdata = { /* AP2MDM_WAKEUP */ { .gpio = 135, .settings = { [GPIOMUX_SUSPENDED] = &ap2mdm_cfg, } }, /* MDM2AP_VFR */ { .gpio = 94, .settings = { [GPIOMUX_ACTIVE] = &mdm2ap_vfr_active_cfg, [GPIOMUX_SUSPENDED] = &mdm2ap_vfr_suspend_cfg, } }, /* AP2MDM_STATUS */ { .gpio = 136, .settings = { [GPIOMUX_SUSPENDED] = &ap2mdm_cfg, } }, /* MDM2AP_STATUS */ { .gpio = 134, .settings = { [GPIOMUX_SUSPENDED] = &mdm2ap_status_cfg, } }, /* MDM2AP_WAKEUP */ { .gpio = 40, .settings = { [GPIOMUX_SUSPENDED] = &ap2mdm_cfg, } }, /* MDM2AP_ERRFATAL */ { .gpio = 133, .settings = { [GPIOMUX_SUSPENDED] = &mdm2ap_errfatal_cfg, } }, /* AP2MDM_ERRFATAL */ { .gpio = 93, .settings = { [GPIOMUX_SUSPENDED] = &ap2mdm_cfg, } }, /* AP2MDM_KPDPWR_N */ { .gpio = 132, .settings = { [GPIOMUX_SUSPENDED] = &ap2mdm_kpdpwr_n_cfg, } }, /* AP2MDM_PMIC_RESET_N */ { .gpio = 131, .settings = { [GPIOMUX_SUSPENDED] = &ap2mdm_kpdpwr_n_cfg, } } }; #ifdef CONFIG_LGE_AUDIO static struct msm_gpiomux_config msm8x60_audio_configs[] __initdata = { #if 0 /* error CAMCORDER_MIC_EN180 greater than max:173 */ /* CAMCORDER_MIC_EN */ { .gpio = GPIO_CAMCORDER_MIC_EN, .settings = { [GPIOMUX_SUSPENDED] = &camcorder_mic_en_cfg, } }, #endif /* MOTOR_EN*/ { .gpio = GPIO_LIN_MOTOR_EN, .settings = { [GPIOMUX_SUSPENDED] = &motor_en_cfg, } }, /* LIN_MOTOR_PWM*/ { .gpio = GPIO_LIN_MOTOR_PWM, .settings = { [GPIOMUX_SUSPENDED] = &lin_motor_pwm_cfg, } }, #ifdef CONFIG_LGE_HEADSET_DETECTION_FSA8008 /* EAR_MIC_EN */ { .gpio = GPIO_EAR_MIC_EN, .settings = { [GPIOMUX_SUSPENDED] = &ear_mic_en_cfg, } }, /* EARPOL_DETECT */ { .gpio = GPIO_EARPOL_DETECT, .settings = { [GPIOMUX_SUSPENDED] = &earpole_detect_cfg, } }, #endif }; #endif #if 0 struct msm_gpiomux_configs msm8x60_charm_gpiomux_cfgs[] __initdata = { {msm8x60_gsbi_configs, ARRAY_SIZE(msm8x60_gsbi_configs)}, {msm8x60_uart_configs, ARRAY_SIZE(msm8x60_uart_configs)}, #ifdef CONFIG_MSM_GSBI9_UART {msm8x60_charm_uart_configs, ARRAY_SIZE(msm8x60_charm_uart_configs)}, #endif #ifdef CONFIG_LGE_FELICA {msm8x60_felica_uart_configs, ARRAY_SIZE(msm8x60_felica_uart_configs)}, #endif {msm8x60_ts_configs, ARRAY_SIZE(msm8x60_ts_configs)}, {msm8x60_aux_pcm_configs, ARRAY_SIZE(msm8x60_aux_pcm_configs)}, {msm8x60_sdc_configs, ARRAY_SIZE(msm8x60_sdc_configs)}, {msm8x60_snd_configs, ARRAY_SIZE(msm8x60_snd_configs)}, {msm8x60_mi2s_configs, ARRAY_SIZE(msm8x60_mi2s_configs)}, {msm8x60_lcdc_configs, ARRAY_SIZE(msm8x60_lcdc_configs)}, {msm8x60_mdp_vsync_configs, ARRAY_SIZE(msm8x60_mdp_vsync_configs)}, {msm8x60_hdmi_configs, ARRAY_SIZE(msm8x60_hdmi_configs)}, {msm8x60_pmic_configs, ARRAY_SIZE(msm8x60_pmic_configs)}, {msm8x60_common_configs, ARRAY_SIZE(msm8x60_common_configs)}, {msm8x60_cam_configs, ARRAY_SIZE(msm8x60_cam_configs)}, {msm8x60_tmg200_configs, ARRAY_SIZE(msm8x60_tmg200_configs)}, {msm8x60_charm_sdc_configs, ARRAY_SIZE(msm8x60_charm_sdc_configs)}, {msm8x60_charm_configs, ARRAY_SIZE(msm8x60_charm_configs)}, {NULL, 0}, }; #endif struct msm_gpiomux_configs msm8x60_lge_325_gpiomux_cfgs[] __initdata = { #ifdef CONFIG_LGE_PM_CURRENT_CONSUMPTION_FIX {msm8x60_current_configs, ARRAY_SIZE(msm8x60_current_configs)}, //for rock_bottom #endif #ifdef CONFIG_LGE_MHL_SII9244 {msm8x60_mhl_configs, ARRAY_SIZE(msm8x60_mhl_configs)}, #endif {msm8x60_gsbi_configs, ARRAY_SIZE(msm8x60_gsbi_configs)}, {msm8x60_uart_configs, ARRAY_SIZE(msm8x60_uart_configs)}, #ifdef CONFIG_MSM_GSBI9_UART {msm8x60_charm_uart_configs, ARRAY_SIZE(msm8x60_charm_uart_configs)}, #endif #ifdef CONFIG_LGE_IRDA {msm8x60_irda_uart_configs, ARRAY_SIZE(msm8x60_irda_uart_configs)}, #endif {msm8x60_aux_pcm_configs, ARRAY_SIZE(msm8x60_aux_pcm_configs)}, {msm8x60_sdc_configs, ARRAY_SIZE(msm8x60_sdc_configs)}, {msm8x60_snd_configs, ARRAY_SIZE(msm8x60_snd_configs)}, {msm8x60_mdp_vsync_configs, ARRAY_SIZE(msm8x60_mdp_vsync_configs)}, {msm8x60_hdmi_configs, ARRAY_SIZE(msm8x60_hdmi_configs)}, {msm8x60_pmic_configs, ARRAY_SIZE(msm8x60_pmic_configs)}, {msm8x60_common_configs, ARRAY_SIZE(msm8x60_common_configs)}, {msm8x60_charm_sdc_configs, ARRAY_SIZE(msm8x60_charm_sdc_configs)}, {msm8x60_charm_configs, ARRAY_SIZE(msm8x60_charm_configs)}, #ifdef CONFIG_LGE_AUDIO {msm8x60_audio_configs, ARRAY_SIZE(msm8x60_audio_configs)}, #endif #if defined(CONFIG_LGE_FELICA) {msm8x60_felica_uart_configs, ARRAY_SIZE(msm8x60_felica_uart_configs)}, #endif #if defined(CONFIG_LGE_NFC_PN544_C2) // {msm8x60_ebi2_configs, ARRAY_SIZE(msm8x60_ebi2_configs)}, #endif // {NULL, 0}, }; void __init msm8x60_init_gpiomux(struct msm_gpiomux_configs *cfgs) { int rc; rc = msm_gpiomux_init(NR_GPIO_IRQS); if (rc) { pr_err("%s failure: %d\n", __func__, rc); return; } while (cfgs->cfg) { msm_gpiomux_install(cfgs->cfg, cfgs->ncfg); ++cfgs; } }
lyfkevin/Wind_iproj_JB_kernel_old
lge/lge_board/batman/gpiomux_lge_325.c
C
gpl-2.0
33,789
/* { dg-final { check-function-bodies "**" "" "-DCHECK_ASM" } } */ #include "test_sve_acle.h" /* ** qdmlalt_lane_0_s64_tied1: ** sqdmlalt z0\.d, z4\.s, z5\.s\[0\] ** ret */ TEST_DUAL_Z (qdmlalt_lane_0_s64_tied1, svint64_t, svint32_t, z0 = svqdmlalt_lane_s64 (z0, z4, z5, 0), z0 = svqdmlalt_lane (z0, z4, z5, 0)) /* ** qdmlalt_lane_0_s64_tied2: ** mov (z[0-9]+)\.d, z0\.d ** movprfx z0, z4 ** sqdmlalt z0\.d, \1\.s, z1\.s\[0\] ** ret */ TEST_DUAL_Z_REV (qdmlalt_lane_0_s64_tied2, svint64_t, svint32_t, z0_res = svqdmlalt_lane_s64 (z4, z0, z1, 0), z0_res = svqdmlalt_lane (z4, z0, z1, 0)) /* ** qdmlalt_lane_0_s64_tied3: ** mov (z[0-9]+)\.d, z0\.d ** movprfx z0, z4 ** sqdmlalt z0\.d, z1\.s, \1\.s\[0\] ** ret */ TEST_DUAL_Z_REV (qdmlalt_lane_0_s64_tied3, svint64_t, svint32_t, z0_res = svqdmlalt_lane_s64 (z4, z1, z0, 0), z0_res = svqdmlalt_lane (z4, z1, z0, 0)) /* ** qdmlalt_lane_0_s64_untied: ** movprfx z0, z1 ** sqdmlalt z0\.d, z4\.s, z5\.s\[0\] ** ret */ TEST_DUAL_Z (qdmlalt_lane_0_s64_untied, svint64_t, svint32_t, z0 = svqdmlalt_lane_s64 (z1, z4, z5, 0), z0 = svqdmlalt_lane (z1, z4, z5, 0)) /* ** qdmlalt_lane_z15_s64: ** str d15, \[sp, -16\]! ** sqdmlalt z0\.d, z1\.s, z15\.s\[1\] ** ldr d15, \[sp\], 16 ** ret */ TEST_DUAL_LANE_REG (qdmlalt_lane_z15_s64, svint64_t, svint32_t, z15, z0 = svqdmlalt_lane_s64 (z0, z1, z15, 1), z0 = svqdmlalt_lane (z0, z1, z15, 1)) /* ** qdmlalt_lane_z16_s64: ** mov (z[0-9]|z1[0-5])\.d, z16\.d ** sqdmlalt z0\.d, z1\.s, \1\.s\[1\] ** ret */ TEST_DUAL_LANE_REG (qdmlalt_lane_z16_s64, svint64_t, svint32_t, z16, z0 = svqdmlalt_lane_s64 (z0, z1, z16, 1), z0 = svqdmlalt_lane (z0, z1, z16, 1))
Gurgel100/gcc
gcc/testsuite/gcc.target/aarch64/sve2/acle/asm/qdmlalt_lane_s64.c
C
gpl-2.0
1,699
/* RxRPC point-to-point transport session management * * Copyright (C) 2007 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/module.h> #include <linux/net.h> #include <linux/skbuff.h> #include <linux/slab.h> #include <net/sock.h> #include <net/af_rxrpc.h> #include "ar-internal.h" static void rxrpc_transport_reaper(struct work_struct *work); static LIST_HEAD(rxrpc_transports); static DEFINE_RWLOCK(rxrpc_transport_lock); static unsigned long rxrpc_transport_timeout = 3600 * 24; static DECLARE_DELAYED_WORK(rxrpc_transport_reap, rxrpc_transport_reaper); /* * allocate a new transport session manager */ static struct rxrpc_transport *rxrpc_alloc_transport(struct rxrpc_local *local, struct rxrpc_peer *peer, gfp_t gfp) { struct rxrpc_transport *trans; _enter(""); trans = kzalloc(sizeof(struct rxrpc_transport), gfp); if (trans) { trans->local = local; trans->peer = peer; INIT_LIST_HEAD(&trans->link); trans->bundles = RB_ROOT; trans->client_conns = RB_ROOT; trans->server_conns = RB_ROOT; skb_queue_head_init(&trans->error_queue); spin_lock_init(&trans->client_lock); rwlock_init(&trans->conn_lock); atomic_set(&trans->usage, 1); trans->debug_id = atomic_inc_return_unchecked(&rxrpc_debug_id); if (peer->srx.transport.family == AF_INET) { switch (peer->srx.transport_type) { case SOCK_DGRAM: INIT_WORK(&trans->error_handler, rxrpc_UDP_error_handler); break; default: BUG(); break; } } else { BUG(); } } _leave(" = %p", trans); return trans; } /* * obtain a transport session for the nominated endpoints */ struct rxrpc_transport *rxrpc_get_transport(struct rxrpc_local *local, struct rxrpc_peer *peer, gfp_t gfp) { struct rxrpc_transport *trans, *candidate; const char *new = "old"; int usage; _enter("{%pI4+%hu},{%pI4+%hu},", &local->srx.transport.sin.sin_addr, ntohs(local->srx.transport.sin.sin_port), &peer->srx.transport.sin.sin_addr, ntohs(peer->srx.transport.sin.sin_port)); /* search the transport list first */ read_lock_bh(&rxrpc_transport_lock); list_for_each_entry(trans, &rxrpc_transports, link) { if (trans->local == local && trans->peer == peer) goto found_extant_transport; } read_unlock_bh(&rxrpc_transport_lock); /* not yet present - create a candidate for a new record and then * redo the search */ candidate = rxrpc_alloc_transport(local, peer, gfp); if (!candidate) { _leave(" = -ENOMEM"); return ERR_PTR(-ENOMEM); } write_lock_bh(&rxrpc_transport_lock); list_for_each_entry(trans, &rxrpc_transports, link) { if (trans->local == local && trans->peer == peer) goto found_extant_second; } /* we can now add the new candidate to the list */ trans = candidate; candidate = NULL; usage = atomic_read(&trans->usage); rxrpc_get_local(trans->local); atomic_inc(&trans->peer->usage); list_add_tail(&trans->link, &rxrpc_transports); write_unlock_bh(&rxrpc_transport_lock); new = "new"; success: _net("TRANSPORT %s %d local %d -> peer %d", new, trans->debug_id, trans->local->debug_id, trans->peer->debug_id); _leave(" = %p {u=%d}", trans, usage); return trans; /* we found the transport in the list immediately */ found_extant_transport: usage = atomic_inc_return(&trans->usage); read_unlock_bh(&rxrpc_transport_lock); goto success; /* we found the transport on the second time through the list */ found_extant_second: usage = atomic_inc_return(&trans->usage); write_unlock_bh(&rxrpc_transport_lock); kfree(candidate); goto success; } /* * find the transport connecting two endpoints */ struct rxrpc_transport *rxrpc_find_transport(struct rxrpc_local *local, struct rxrpc_peer *peer) { struct rxrpc_transport *trans; _enter("{%pI4+%hu},{%pI4+%hu},", &local->srx.transport.sin.sin_addr, ntohs(local->srx.transport.sin.sin_port), &peer->srx.transport.sin.sin_addr, ntohs(peer->srx.transport.sin.sin_port)); /* search the transport list */ read_lock_bh(&rxrpc_transport_lock); list_for_each_entry(trans, &rxrpc_transports, link) { if (trans->local == local && trans->peer == peer) goto found_extant_transport; } read_unlock_bh(&rxrpc_transport_lock); _leave(" = NULL"); return NULL; found_extant_transport: atomic_inc(&trans->usage); read_unlock_bh(&rxrpc_transport_lock); _leave(" = %p", trans); return trans; } /* * release a transport session */ void rxrpc_put_transport(struct rxrpc_transport *trans) { _enter("%p{u=%d}", trans, atomic_read(&trans->usage)); ASSERTCMP(atomic_read(&trans->usage), >, 0); trans->put_time = get_seconds(); if (unlikely(atomic_dec_and_test(&trans->usage))) { _debug("zombie"); /* let the reaper determine the timeout to avoid a race with * overextending the timeout if the reaper is running at the * same time */ rxrpc_queue_delayed_work(&rxrpc_transport_reap, 0); } _leave(""); } /* * clean up a transport session */ static void rxrpc_cleanup_transport(struct rxrpc_transport *trans) { _net("DESTROY TRANS %d", trans->debug_id); rxrpc_purge_queue(&trans->error_queue); rxrpc_put_local(trans->local); rxrpc_put_peer(trans->peer); kfree(trans); } /* * reap dead transports that have passed their expiry date */ static void rxrpc_transport_reaper(struct work_struct *work) { struct rxrpc_transport *trans, *_p; unsigned long now, earliest, reap_time; LIST_HEAD(graveyard); _enter(""); now = get_seconds(); earliest = ULONG_MAX; /* extract all the transports that have been dead too long */ write_lock_bh(&rxrpc_transport_lock); list_for_each_entry_safe(trans, _p, &rxrpc_transports, link) { _debug("reap TRANS %d { u=%d t=%ld }", trans->debug_id, atomic_read(&trans->usage), (long) now - (long) trans->put_time); if (likely(atomic_read(&trans->usage) > 0)) continue; reap_time = trans->put_time + rxrpc_transport_timeout; if (reap_time <= now) list_move_tail(&trans->link, &graveyard); else if (reap_time < earliest) earliest = reap_time; } write_unlock_bh(&rxrpc_transport_lock); if (earliest != ULONG_MAX) { _debug("reschedule reaper %ld", (long) earliest - now); ASSERTCMP(earliest, >, now); rxrpc_queue_delayed_work(&rxrpc_transport_reap, (earliest - now) * HZ); } /* then destroy all those pulled out */ while (!list_empty(&graveyard)) { trans = list_entry(graveyard.next, struct rxrpc_transport, link); list_del_init(&trans->link); ASSERTCMP(atomic_read(&trans->usage), ==, 0); rxrpc_cleanup_transport(trans); } _leave(""); } /* * preemptively destroy all the transport session records rather than waiting * for them to time out */ void __exit rxrpc_destroy_all_transports(void) { _enter(""); rxrpc_transport_timeout = 0; cancel_delayed_work(&rxrpc_transport_reap); rxrpc_queue_delayed_work(&rxrpc_transport_reap, 0); _leave(""); }
ircncl/linux-grsec-incremental
net/rxrpc/ar-transport.c
C
gpl-2.0
7,246
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="en"><head><title>PCAP New Generation Dump File Format</title> <meta name="description" content="PCAP New Generation Dump File Format"> <meta name="keywords" content="Internet-Draft, Libpcap, dump file format"> <meta name="generator" content="xml2rfc v1.22 (http://xml.resource.org/)"> <style type='text/css'> <!-- body { font-family: verdana, charcoal, helvetica, arial, sans-serif; font-size: small ; color: #000000 ; background-color: #ffffff ; } .title { color: #990000; font-size: x-large ; font-weight: bold; text-align: right; font-family: helvetica, monaco, "MS Sans Serif", arial, sans-serif; background-color: transparent; } .filename { color: #666666; font-size: 18px; line-height: 28px; font-weight: bold; text-align: right; font-family: helvetica, arial, sans-serif; background-color: transparent; } td.rfcbug { background-color: #000000 ; width: 30px ; height: 30px ; text-align: justify; vertical-align: middle ; padding-top: 2px ; } td.rfcbug span.RFC { color: #666666; font-weight: bold; text-decoration: none; background-color: #000000 ; font-family: monaco, charcoal, geneva, "MS Sans Serif", helvetica, verdana, sans-serif; font-size: x-small ; } td.rfcbug span.hotText { color: #ffffff; font-weight: normal; text-decoration: none; text-align: center ; font-family: charcoal, monaco, geneva, "MS Sans Serif", helvetica, verdana, sans-serif; font-size: x-small ; background-color: #000000; } A { font-weight: bold; } A:link { color: #990000; background-color: transparent ; } A:visited { color: #333333; background-color: transparent ; } A:active { color: #333333; background-color: transparent ; } p { margin-left: 2em; margin-right: 2em; } p.copyright { font-size: x-small ; } p.toc { font-size: small ; font-weight: bold ; margin-left: 3em ;} span.emph { font-style: italic; } span.strong { font-weight: bold; } span.verb { font-family: "Courier New", Courier, monospace ; } ol.text { margin-left: 2em; margin-right: 2em; } ul.text { margin-left: 2em; margin-right: 2em; } li { margin-left: 3em; } pre { margin-left: 3em; color: #333333; background-color: transparent; font-family: "Courier New", Courier, monospace ; font-size: small ; } h3 { color: #333333; font-size: medium ; font-family: helvetica, arial, sans-serif ; background-color: transparent; } h4 { font-size: small; font-family: helvetica, arial, sans-serif ; } table.bug { width: 30px ; height: 15px ; } td.bug { color: #ffffff ; background-color: #990000 ; text-align: center ; width: 30px ; height: 15px ; } td.bug A.link2 { color: #ffffff ; font-weight: bold; text-decoration: none; font-family: monaco, charcoal, geneva, "MS Sans Serif", helvetica, sans-serif; font-size: x-small ; background-color: transparent } td.header { color: #ffffff; font-size: x-small ; font-family: arial, helvetica, sans-serif; vertical-align: top; background-color: #666666 ; width: 33% ; } td.author { font-weight: bold; margin-left: 4em; font-size: x-small ; } td.author-text { font-size: x-small; } table.data { vertical-align: top ; border-collapse: collapse ; border-style: solid solid solid solid ; border-color: black black black black ; font-size: small ; text-align: center ; } table.data th { font-weight: bold ; border-style: solid solid solid solid ; border-color: black black black black ; } table.data td { border-style: solid solid solid solid ; border-color: #333333 #333333 #333333 #333333 ; } hr { height: 1px } --> </style> </head> <body> <table summary="layout" cellpadding="0" cellspacing="2" class="bug" align="right"><tr><td class="bug"><a href="#toc" class="link2">&nbsp;TOC&nbsp;</a></td></tr></table> <table summary="layout" width="66%" border="0" cellpadding="0" cellspacing="0"><tr><td><table summary="layout" width="100%" border="0" cellpadding="2" cellspacing="1"> <tr><td class="header">Network Working Group</td><td class="header">L. Degioanni</td></tr> <tr><td class="header">Internet-Draft</td><td class="header">F. Risso</td></tr> <tr><td class="header">Expires: August 30, 2004</td><td class="header">Politecnico di Torino</td></tr> <tr><td class="header">&nbsp;</td><td class="header">March 2004</td></tr> </table></td></tr></table> <div align="right"><span class="title"><br />PCAP New Generation Dump File Format</span></div> <div align="right"><span class="title"><br />pcap</span></div> <h3>Status of this Memo</h3> <p> This document is an Internet-Draft and is in full conformance with all provisions of Section 10 of RFC2026.</p> <p> Internet-Drafts are working documents of the Internet Engineering Task Force (IETF), its areas, and its working groups. Note that other groups may also distribute working documents as Internet-Drafts.</p> <p> Internet-Drafts are draft documents valid for a maximum of six months and may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to use Internet-Drafts as reference material or to cite them other than as "work in progress."</p> <p> The list of current Internet-Drafts can be accessed at <a href='http://www.ietf.org/ietf/1id-abstracts.txt'>http://www.ietf.org/ietf/1id-abstracts.txt</a>.</p> <p> The list of Internet-Draft Shadow Directories can be accessed at <a href='http://www.ietf.org/shadow.html'>http://www.ietf.org/shadow.html</a>.</p> <p> This Internet-Draft will expire on August 30, 2004.</p> <h3>Copyright Notice</h3> <p> Copyright (C) The Internet Society (2004). All Rights Reserved.</p> <h3>Abstract</h3> <p>This document describes a format to dump captured packets on a file. This format is extensible and it is currently proposed for implementation in the libpcap/WinPcap packet capture library. </p><a name="toc"></a><br /><hr /> <h3>Table of Contents</h3> <p class="toc"> <a href="#anchor1">1.</a>&nbsp; Objectives<br /> <a href="#anchor2">2.</a>&nbsp; General File Structure<br /> <a href="#sectionblock">2.1</a>&nbsp; General Block Structure<br /> <a href="#anchor3">2.2</a>&nbsp; Block Types<br /> <a href="#anchor4">2.3</a>&nbsp; Block Hierarchy and Precedence<br /> <a href="#anchor5">2.4</a>&nbsp; Data format<br /> <a href="#anchor6">3.</a>&nbsp; Block Definition<br /> <a href="#sectionshb">3.1</a>&nbsp; Section Header Block (mandatory)<br /> <a href="#sectionidb">3.2</a>&nbsp; Interface Description Block (mandatory)<br /> <a href="#sectionpb">3.3</a>&nbsp; Packet Block (optional)<br /> <a href="#anchor7">3.4</a>&nbsp; Simple Packet Block (optional)<br /> <a href="#anchor8">3.5</a>&nbsp; Name Resolution Block (optional)<br /> <a href="#anchor9">3.6</a>&nbsp; Interface Statistics Block (optional)<br /> <a href="#sectionopt">4.</a>&nbsp; Options<br /> <a href="#anchor10">5.</a>&nbsp; Experimental Blocks (deserved to a further investigation)<br /> <a href="#anchor11">5.1</a>&nbsp; Other Packet Blocks (experimental)<br /> <a href="#anchor12">5.2</a>&nbsp; Compression Block (experimental)<br /> <a href="#anchor13">5.3</a>&nbsp; Encryption Block (experimental)<br /> <a href="#anchor14">5.4</a>&nbsp; Fixed Length Block (experimental)<br /> <a href="#anchor15">5.5</a>&nbsp; Directory Block (experimental)<br /> <a href="#anchor16">5.6</a>&nbsp; Traffic Statistics and Monitoring Blocks (experimental)<br /> <a href="#anchor17">5.7</a>&nbsp; Event/Security Block (experimental)<br /> <a href="#anchor18">6.</a>&nbsp; Conclusions<br /> <a href="#anchor19">7.</a>&nbsp; Most important open issues<br /> <a href="#rfc.copyright">&#167;</a>&nbsp; Intellectual Property and Copyright Statements<br /> </p> <br clear="all" /> <a name="anchor1"></a><br /><hr /> <table summary="layout" cellpadding="0" cellspacing="2" class="bug" align="right"><tr><td class="bug"><a href="#toc" class="link2">&nbsp;TOC&nbsp;</a></td></tr></table> <a name="rfc.section.1"></a><h3>1.&nbsp;Objectives</h3> <p>The problem of exchanging packet traces becomes more and more critical every day; unfortunately, no standard solutions exist for this task right now. One of the most accepted packet interchange formats is the one defined by libpcap, which is rather old and does not fit for some of the nowadays applications especially in terms of extensibility. </p> <p>This document proposes a new format for dumping packet traces. The following goals are being pursued: </p> <ul class="text"> <li>Extensibility: aside of some common functionalities, third parties should be able to enrich the information embedded in the file with proprietary extensions, which will be ignored by tools that are not able to understand them. </li> <li>Portability: a capture trace must contain all the information needed to read data independently from network, hardware and operating system of the machine that made the capture. </li> <li>Merge/Append data: it should be possible to add data at the end of a given file, and the resulting file must still be readable. </li> </ul> <a name="anchor2"></a><br /><hr /> <table summary="layout" cellpadding="0" cellspacing="2" class="bug" align="right"><tr><td class="bug"><a href="#toc" class="link2">&nbsp;TOC&nbsp;</a></td></tr></table> <a name="rfc.section.2"></a><h3>2.&nbsp;General File Structure</h3> <a name="rfc.section.2.1"></a><h4><a name="sectionblock">2.1</a>&nbsp;General Block Structure</h4> <p>A capture file is organized in blocks, that are appended one to another to form the file. All the blocks share a common format, which is shown in <a href="#formatblock">Figure 1</a>. </p><br /><hr /> <a name="formatblock"></a> <pre> 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Block Type | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Block Total Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ / Block Body / / /* variable length, aligned to 32 bits */ / +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Block Total Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ </pre> <table border="0" cellpadding="0" cellspacing="2" align="center"><tr><td align="center"><font face="monaco, MS Sans Serif" size="1"><b>&nbsp;Basic block structure.&nbsp;</b></font><br /></td></tr></table><hr size="1" shade="0"> <p>The fields have the following meaning: </p> <ul class="text"> <li>Block Type (32 bits): unique value that identifies the block. Values whose Most Significant Bit (MSB) is equal to 1 are reserved for local use. They allow to save private data to the file and to extend the file format. </li> <li>Block Total Length: total size of this block, in bytes. For instance, a block that does not have a body has a length of 12 bytes. </li> <li>Block Body: content of the block. </li> <li>Block Total Length: total size of this block, in bytes. This field is duplicated for permitting backward file navigation. </li> </ul> <p>This structure, shared among all blocks, makes easy to process a file and to skip unneeded or unknown blocks. Blocks can be nested one inside the others (NOTE: needed?). Some of the blocks are mandatory, i.e. a dump file is not valid if they are not present, other are optional. </p> <p>The structure of the blocks allows to define other blocks if needed. A parser that does non understand them can simply ignore their content. </p> <a name="rfc.section.2.2"></a><h4><a name="anchor3">2.2</a>&nbsp;Block Types</h4> <p>The currently defined blocks are the following: </p> <ol class="text"> <li>Section Header Block: it defines the most important characteristics of the capture file. </li> <li>Interface Description Block: it defines the most important characteristics of the interface(s) used for capturing traffic. </li> <li>Packet Block: it contains a single captured packet, or a portion of it. </li> <li>Simple Packet Block: it contains a single captured packet, or a portion of it, with only a minimal set of information about it. </li> <li>Name Resolution Block: it defines the mapping from numeric addresses present in the packet dump and the canonical name counterpart. </li> <li>Capture Statistics Block: it defines how to store some statistical data (e.g. packet dropped, etc) which can be useful to undestand the conditions in which the capture has been made. </li> <li>Compression Marker Block: TODO </li> <li>Encryption Marker Block: TODO </li> <li>Fixed Length Marker Block: TODO </li> </ol> <p>The following blocks instead are considered interesting but the authors believe that they deserve more in-depth discussion before being defined: </p> <ol class="text"> <li>Further Packet Blocks </li> <li>Directory Block </li> <li>Traffic Statistics and Monitoring Blocks </li> <li>Alert and Security Blocks </li> </ol> <p>TODO Currently standardized Block Type codes are specified in Appendix 1. </p> <a name="rfc.section.2.3"></a><h4><a name="anchor4">2.3</a>&nbsp;Block Hierarchy and Precedence</h4> <p>The file must begin with a Section Header Block. However, more than one Section Header Block can be present on the dump, each one covering the data following it till the next one (or the end of file). A Section includes the data delimited by two Section Header Blocks (or by a Section Header Block and the end of the file), including the first Section Header Block. </p> <p>In case an application cannot read a Section because of different version number, it must skip everything until the next Section Header Block. Note that, in order to properly skip the blocks until the next section, all blocks must have the fields Type and Length at the beginning. This is a mandatory requirement that must be maintained in future versions of the block format. </p> <p><a href="#fssample-SHB">Figure 2</a> shows two valid files: the first has a typical configuration, with a single Section Header that covers the whole file. The second one contains three headers, and is normally the result of file concatenation. An application that understands only version 1.0 of the file format skips the intermediate section and restart processing the packets after the third Section Header. </p><br /><hr /> <a name="fssample-SHB"></a> <pre> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | SHB v1.0 | Data | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Typical configuration with a single Section Header Block |-- 1st Section --|-- 2nd Section --|-- 3rd Section --| | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | SHB v1.0 | Data | SHB V1.1 | Data | SHB V1.0 | Data | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Configuration with three different Section Header Blocks </pre> <table border="0" cellpadding="0" cellspacing="2" align="center"><tr><td align="center"><font face="monaco, MS Sans Serif" size="1"><b>&nbsp;File structure example: the Section Header Block.&nbsp;</b></font><br /></td></tr></table><hr size="1" shade="0"> <p>NOTE: TO BE COMPLETED with some examples of other blocks </p> <a name="rfc.section.2.4"></a><h4><a name="anchor5">2.4</a>&nbsp;Data format</h4> <p>Data contained in each section will always be saved according to the characteristics (little endian / big endian) of the dumping machine. This refers to all fields that are saved as numbers and that span over two or more bytes. </p> <p>The approach of having each section saved in the native format of the generating host is more efficient because it avoids translation of data when reading / writing on the host itself, which is the most common case when generating/processing capture dumps. </p> <p>TODO Probably we have to specify something more here. Is what we're saying enough to avoid any kind of ambiguity?. </p> <a name="anchor6"></a><br /><hr /> <table summary="layout" cellpadding="0" cellspacing="2" class="bug" align="right"><tr><td class="bug"><a href="#toc" class="link2">&nbsp;TOC&nbsp;</a></td></tr></table> <a name="rfc.section.3"></a><h3>3.&nbsp;Block Definition</h3> <p>This section details the format of the body of the blocks currently defined. </p> <a name="rfc.section.3.1"></a><h4><a name="sectionshb">3.1</a>&nbsp;Section Header Block (mandatory)</h4> <p>The Section Header Block is mandatory. It identifies the beginning of a section of the capture dump file. Its format is shown in <a href="#formatSHB">Figure 3</a>. </p><br /><hr /> <a name="formatSHB"></a> <pre> 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Magic | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Major | Minor | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ / / / Options (variable) / / / +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ </pre> <table border="0" cellpadding="0" cellspacing="2" align="center"><tr><td align="center"><font face="monaco, MS Sans Serif" size="1"><b>&nbsp;Section Header Block format.&nbsp;</b></font><br /></td></tr></table><hr size="1" shade="0"> <p>The meaning of the fields is: </p> <ul class="text"> <li>Magic: magic number, whose value is the hexadecimal number 0x1A2B3C4D. This number can be used to distinguish section that have been saved on little-endian machines from the one saved on big-endian machines. </li> <li>Major: number of the current mayor version of the format. Current value is 1. </li> <li>Minor: number of the current minor version of the format. Current value is 0. </li> <li>Options: optionally, a list of options (formatted according to the rules defined in <a href="#sectionopt">Section 4</a>) can be present. </li> </ul> <p>Aside form the options defined in <a href="#sectionopt">Section 4</a>, the following options are valid within this block: </p><a name="InterfaceOptions1"></a> <table class="data" align="center" border="1" cellpadding="2" cellspacing="2"> <tr> <th align="left" width="25%">Name</th> <th align="left" width="25%">Code</th> <th align="left" width="25%">Length</th> <th align="left" width="25%">Description</th> </tr> <tr> <td align="left">Hardware</td> <td align="left">2</td> <td align="left">variable</td> <td align="left">An ascii string containing the description of the hardware used to create this section.</td> </tr> <tr> <td align="left">Operating System</td> <td align="left">3</td> <td align="left">variable</td> <td align="left">An ascii string containing the name of the operating system used to create this section.</td> </tr> <tr> <td align="left">User Application</td> <td align="left">3</td> <td align="left">variable</td> <td align="left">An ascii string containing the name of the application used to create this section.</td> </tr> </table> <p>The Section Header Block does not contain data but it rather identifies a list of blocks (interfaces, packets) that are logically correlated. This block does not contain any reference to the size of the section it is currently delimiting, therefore the reader cannot skip a whole section at once. In case a section must be skipped, the user has to repeatedly skip all the blocks contained within it; this makes the parsing of the file slower but it permits to append several capture dumps at the same file. </p> <a name="rfc.section.3.2"></a><h4><a name="sectionidb">3.2</a>&nbsp;Interface Description Block (mandatory)</h4> <p>The Interface Description Block is mandatory. This block is needed to specify the characteristics of the network interface on which the capture has been made. In order to properly associate the captured data to the corresponding interface, the Interface Description Block must be defined before any other block that uses it; therefore, this block is usually placed immediately after the Section Header Block. </p> <p>An Interface Description Block is valid only inside the section which it belongs to. The structure of a Interface Description Block is shown in <a href="#formatidb">Figure 4</a>. </p><br /><hr /> <a name="formatidb"></a> <pre> 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Interface ID | LinkType | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | SnapLen | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ / / / Options (variable) / / / +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ </pre> <table border="0" cellpadding="0" cellspacing="2" align="center"><tr><td align="center"><font face="monaco, MS Sans Serif" size="1"><b>&nbsp;Interface Description Block format.&nbsp;</b></font><br /></td></tr></table><hr size="1" shade="0"> <p>The meaning of the fields is: </p> <ul class="text"> <li>Interface ID: a progressive number that identifies uniquely any interface inside current section. Two Interface Description Blocks can have the same Interface ID only if they are in different sections of the file. The Interface ID is referenced by the packet blocks. </li> <li>LinkType: a value that defines the link layer type of this interface. </li> <li>SnapLen: maximum number of bytes dumped from each packet. The portion of each packet that exceeds this value will not be stored in the file. </li> <li>Options: optionally, a list of options (formatted according to the rules defined in <a href="#sectionopt">Section 4</a>) can be present. </li> </ul> <p>In addition to the options defined in <a href="#sectionopt">Section 4</a>, the following options are valid within this block: </p><a name="InterfaceOptions2"></a> <table class="data" align="center" border="1" cellpadding="2" cellspacing="2"> <tr> <th align="left" width="25%">Name</th> <th align="left" width="25%">Code</th> <th align="left" width="25%">Length</th> <th align="left" width="25%">Description</th> </tr> <tr> <td align="left">if_name</td> <td align="left">2</td> <td align="left">Variable</td> <td align="left">Name of the device used to capture data.</td> </tr> <tr> <td align="left">if_IPv4addr</td> <td align="left">3</td> <td align="left">8</td> <td align="left">Interface network address and netmask.</td> </tr> <tr> <td align="left">if_IPv6addr</td> <td align="left">4</td> <td align="left">17</td> <td align="left">Interface network address and prefix length (stored in the last byte).</td> </tr> <tr> <td align="left">if_MACaddr</td> <td align="left">5</td> <td align="left">6</td> <td align="left">Interface Hardware MAC address (48 bits).</td> </tr> <tr> <td align="left">if_EUIaddr</td> <td align="left">6</td> <td align="left">8</td> <td align="left">Interface Hardware EUI address (64 bits), if available.</td> </tr> <tr> <td align="left">if_speed</td> <td align="left">7</td> <td align="left">8</td> <td align="left">Interface speed (in bps).</td> </tr> <tr> <td align="left">if_tsaccur</td> <td align="left">8</td> <td align="left">1</td> <td align="left">Precision of timestamps. If the Most Significant Bit is equal to zero, the remaining bits indicates the accuracy as as a negative power of 10 (e.g. 6 means microsecond accuracy). If the Most Significant Bit is equal to zero, the remaining bits indicates the accuracy as as negative power of 2 (e.g. 10 means 1/1024 of second). If this option is not present, a precision of 10^-6 is assumed.</td> </tr> <tr> <td align="left">if_tzone</td> <td align="left">9</td> <td align="left">4</td> <td align="left">Time zone for GMT support (TODO: specify better).</td> </tr> <tr> <td align="left">if_flags</td> <td align="left">10</td> <td align="left">4</td> <td align="left">Interface flags. (TODO: specify better. Possible flags: promiscuous, inbound/outbound, traffic filtered during capture).</td> </tr> <tr> <td align="left">if_filter</td> <td align="left">11</td> <td align="left">variable</td> <td align="left">The filter (e.g. "capture only TCP traffic") used to capture traffic. The first byte of the Option Data keeps a code of the filter used (e.g. if this is a libpcap string, or BPF bytecode, and more). More details about this format will be presented in Appendix XXX (TODO).</td> </tr> <tr> <td align="left">if_opersystem</td> <td align="left">12</td> <td align="left">variable</td> <td align="left">An ascii string containing the name of the operating system of the machine that hosts this interface. This can be different from the same information that can be contained by the Section Header Block (<a href="#sectionshb">Section 3.1</a>) because the capture can have been done on a remote machine.</td> </tr> </table> <a name="rfc.section.3.3"></a><h4><a name="sectionpb">3.3</a>&nbsp;Packet Block (optional)</h4> <p>A Packet Block is the standard container for storing the packets coming from the network. The Packet Block is optional because packets can be stored either by means of this block or the Simple Packet Block, which can be used to speed up dump generation. The format of a packet block is shown in <a href="#formatpb">Figure 5</a>. </p><br /><hr /> <a name="formatpb"></a> <pre> 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Interface ID | Drops Count | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Timestamp (High) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Timestamp (Low) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Captured Len | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Packet Len | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | | Packet Data | | | | /* variable length, byte-aligned */ | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ / / / Options (variable) / / / +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ </pre> <table border="0" cellpadding="0" cellspacing="2" align="center"><tr><td align="center"><font face="monaco, MS Sans Serif" size="1"><b>&nbsp;Packet Block format.&nbsp;</b></font><br /></td></tr></table><hr size="1" shade="0"> <p>The Packet Block has the following fields: </p> <ul class="text"> <li>Interface ID: Specifies the interface this packet comes from, and corresponds to the ID of one of the Interface Description Blocks present in this section of the file (see <a href="#formatidb">Figure 4</a>). </li> <li>Drops Count: a local drop counter. It specified the number of packets lost (by the interface and the operating system) between this packet and the preceding one. The value xFFFF (in hexadecimal) is reserved for those systems in which this information is not available. </li> <li>Timestamp (High): the most significative part of the timestamp. in standard Unix format, i.e. from 1/1/1970. </li> <li>Timestamp (Low): the less significative part of the timestamp. The way to interpret this field is specified by the 'ts_accur' option (see <a href="#formatidb">Figure 4</a>) of the Interface Description block referenced by this packet. If the Interface Description block does not contain a 'ts_accur' option, then this field is expressed in microseconds. </li> <li>Captured Len: number of bytes captured from the packet (i.e. the length of the Packet Data field). It will be the minimum value among the actual Packet Length and the snapshot length (defined in <a href="#formatidb">Figure 4</a>). </li> <li>Packet Len: actual length of the packet when it was transmitted on the network. Can be different from Captured Len if the user wants only a snapshot of the packet. </li> <li>Packet Data: the data coming from the network, including link-layer headers. The length of this field is Captured Len. The format of the link-layer headers depends on the LinkType field specified in the Interface Description Block (see <a href="#sectionidb">Section 3.2</a>) and it is specified in Appendix XXX (TODO). </li> <li>Options: optionally, a list of options (formatted according to the rules defined in <a href="#sectionopt">Section 4</a>) can be present. </li> </ul> <p> </p> <a name="rfc.section.3.4"></a><h4><a name="anchor7">3.4</a>&nbsp;Simple Packet Block (optional)</h4> <p>The Simple Packet Block is a lightweight container for storing the packets coming from the network. Its presence is optional. </p> <p>A Simple Packet Block is similar to a Packet Block (see <a href="#sectionpb">Section 3.3</a>), but it is smaller, simpler to process and contains only a minimal set of information. This block is preferred to the standard Packet Block when performance or space occupation are critical factors, such as in sustained traffic dump applications. A capture file can contain both Packet Blocks and Simple Packet Blocks: for example, a capture tool could switch from Packet Blocks to Simple Packet Blocks when the hardware resources become critical. </p> <p>The Simple Packet Block does not contain the Interface ID field. Therefore, it must be assumed that all the Simple Packet Blocks have been captured on the interface previously specified in the Interface Description Block. </p> <p><a href="#formatpbs">Figure 6</a> shows the format of the Simple Packet Block. </p><br /><hr /> <a name="formatpbs"></a> <pre> 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Packet Len | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | | Packet Data | | | | /* variable length, byte-aligned */ | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ </pre> <table border="0" cellpadding="0" cellspacing="2" align="center"><tr><td align="center"><font face="monaco, MS Sans Serif" size="1"><b>&nbsp;Simple Packet Block format.&nbsp;</b></font><br /></td></tr></table><hr size="1" shade="0"> <p>The Packet Block has the following fields: </p> <ul class="text"> <li>Packet Len: actual length of the packet when it was transmitted on the network. Can be different from captured len if the packet has been truncated. </li> <li>Packet data: the data coming from the network, including link-layers headers. The length of this field can be derived from the field Block Total Length, present in the Block Header. </li> </ul> <p>The Simple Packet Block does not contain the timestamp because this is one of the most costly operations on PCs. Additionally, there are applications that do not require it; e.g. an Intrusion Detection System is interested in packets, not in their timestamp. </p> <p>The Simple Packet Block is very efficient in term of disk space: a snapshot of length 100 bytes requires only 16 bytes of overhead, which corresponds to an efficiency of more than 86%. </p> <a name="rfc.section.3.5"></a><h4><a name="anchor8">3.5</a>&nbsp;Name Resolution Block (optional)</h4> <p>The Name Resolution Block is used to support the correlation of numeric addresses (present in the captured packets) and their corresponding canonical names and it is optional. Having the literal names saved in the file, this prevents the need of a name resolution in a delayed time, when the association between names and addresses can be different from the one in use at capture time. Moreover, The Name Resolution Block avoids the need of issuing a lot of DNS requests every time the trace capture is opened, and allows to have name resolution also when reading the capture with a machine not connected to the network. </p> <p>The format of the Name Resolution Block is shown in <a href="#formatnrb">Figure 7</a>. </p><br /><hr /> <a name="formatnrb"></a> <pre> 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Record Type | Record Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Record Value | | /* variable length, byte-aligned */ | | + + + + + + + + + + + + + + + + + + + + + + + + + | | | | | +-+-+-+-+-+-+-+-+ + + + + + + + + + + + + + + + + + + + + + + + + . . . other records . . . | Record Type == end_of_recs | Record Length == 00 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ / / / Options (variable) / / / +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ </pre> <table border="0" cellpadding="0" cellspacing="2" align="center"><tr><td align="center"><font face="monaco, MS Sans Serif" size="1"><b>&nbsp;Name Resolution Block format.&nbsp;</b></font><br /></td></tr></table><hr size="1" shade="0"> <p>A Name Resolution Block is a zero-terminated list of records (in the TLV format), each of which contains an association between a network address and a name. There are three possible types of records: </p><a name="nrrecords"></a> <table class="data" align="center" border="1" cellpadding="2" cellspacing="2"> <tr> <th align="left" width="25%">Name</th> <th align="left" width="25%">Code</th> <th align="left" width="25%">Length</th> <th align="left" width="25%">Description</th> </tr> <tr> <td align="left">end_of_recs</td> <td align="left">0</td> <td align="left">0</td> <td align="left">End of records</td> </tr> <tr> <td align="left">ip4_rec</td> <td align="left">1</td> <td align="left">Variable</td> <td align="left">Specifies an IPv4 address (contained in the first 4 bytes), followed by one or more zero-terminated strings containing the DNS entries for that address.</td> </tr> <tr> <td align="left">ip6_rec</td> <td align="left">1</td> <td align="left">Variable</td> <td align="left">Specifies an IPv6 address (contained in the first 16 bytes), followed by one or more zero-terminated strings containing the DNS entries for that address.</td> </tr> </table> <p>After the list or Name Resolution Records, optionally, a list of options (formatted according to the rules defined in <a href="#sectionopt">Section 4</a>) can be present. </p> <p>A Name Resolution Block is normally placed at the beginning of the file, but no assumptions can be taken about its position. Name Resolution Blocks can be added in a second time by tools that process the file, like network analyzers. </p> <p>In addiction to the options defined in <a href="#sectionopt">Section 4</a>, the following options are valid within this block: </p><table class="data" align="center" border="1" cellpadding="2" cellspacing="2"> <tr> <th align="left" width="25%">Name</th> <th align="left" width="25%">Code</th> <th align="left" width="25%">Length</th> <th align="left" width="25%">Description</th> </tr> <tr> <td align="left">ns_dnsname</td> <td align="left">2</td> <td align="left">Variable</td> <td align="left">An ascii string containing the name of the machine (DNS server) used to perform the name resolution.</td> </tr> </table> <a name="rfc.section.3.6"></a><h4><a name="anchor9">3.6</a>&nbsp;Interface Statistics Block (optional)</h4> <p>The Interface Statistics Block contains the capture statistics for a given interface and it is optional. The statistics are referred to the interface defined in the current Section identified by the Interface ID field. </p> <p>The format of the Interface Statistics Block is shown in <a href="#formatisb">Figure 8</a>. </p><br /><hr /> <a name="formatisb"></a> <pre> 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | IfRecv | | (high + low) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | IfDrop | | (high + low) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | FilterAccept | | (high + low) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | OSDrop | | (high + low) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | UsrDelivered | | (high + low) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Interface ID | Reserved | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ / / / Options (variable) / / / +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ </pre> <table border="0" cellpadding="0" cellspacing="2" align="center"><tr><td align="center"><font face="monaco, MS Sans Serif" size="1"><b>&nbsp;Interface Statistics Block format.&nbsp;</b></font><br /></td></tr></table><hr size="1" shade="0"> <p>The fields have the following meaning: </p> <ul class="text"> <li>IfRecv: number of packets received from the interface during the capture. This number is reported as a 64 bits value, in which the most significat bits are located in the first four bytes of the field. </li> <li>IfDrop: number of packets dropped by the interface during the capture due to lack of resources. </li> <li>FilterAccept: number of packets accepeted by filter during current capture. </li> <li>OSDrop: number of packets dropped by the operating system during the capture. </li> <li>UsrDelivered: number of packets delivered to the user. UsrDelivered can be different from the value 'FilterAccept - OSDropped' because some packets could still lay in the OS buffers when the capture ended. </li> <li>Interface ID: reference to an Interface Description Block. </li> <li>Reserved: Reserved to future use. </li> <li>Options: optionally, a list of options (formatted according to the rules defined in <a href="#sectionopt">Section 4</a>) can be present. </li> </ul> <p>In addiction to the options defined in <a href="#sectionopt">Section 4</a>, the following options are valid within this block: </p><table class="data" align="center" border="1" cellpadding="2" cellspacing="2"> <tr> <th align="left" width="25%">Name</th> <th align="left" width="25%">Code</th> <th align="left" width="25%">Length</th> <th align="left" width="25%">Description</th> </tr> <tr> <td align="left">isb_starttime</td> <td align="left">2</td> <td align="left">8</td> <td align="left">Time in which the capture started; time will be stored in two blocks of four bytes each, containing the timestamp in seconds and nanoseconds.</td> </tr> <tr> <td align="left">isb_endtime</td> <td align="left">3</td> <td align="left">8</td> <td align="left">Time in which the capture started; time will be stored in two blocks of four bytes each, containing the timestamp in seconds and nanoseconds.</td> </tr> </table> <a name="sectionopt"></a><br /><hr /> <table summary="layout" cellpadding="0" cellspacing="2" class="bug" align="right"><tr><td class="bug"><a href="#toc" class="link2">&nbsp;TOC&nbsp;</a></td></tr></table> <a name="rfc.section.4"></a><h3>4.&nbsp;Options</h3> <p>Almost all blocks have the possibility to embed optional fields. Optional fields can be used to insert some information that may be useful when reading data, but that it is not really needed for packet processing. Therefore, each tool can be either read the content of the optional fields (if any), or skip them at once. </p> <p>Skipping all the optional fields at once is straightforward because most of the blocks have a fixed length, therefore the field Block Length (present in the General Block Structure, see <a href="#sectionblock">Section 2.1</a>) can be used to skip everything till the next block. </p> <p>Options are a list of Type - Length - Value fields, each one containing a single value: </p> <ul class="text"> <li>Option Type (2 bytes): it contains the code that specifies the type of the current TLV record. Option types whose Most Significant Bit is equal to one are reserved for local use; therefore, there is no guarantee that the code used is unique among all capture files (generated by other applications). In case of vendor-specific extensions that have to be identified uniquely, vendors must request an Option Code whose MSB is equal to zero. </li> <li>Option Length (2 bytes): it contains the length of the following 'Option Value' field. </li> <li>Option Value (variable length): it contains the value of the given option. The length of this field as been specified by the Option Length field. </li> </ul> <p>Options may be repeated several times (e.g. an interface that has several IP addresses associated to it). The option list is terminated by a special code which is the 'End of Option'. </p> <p>The format of the optional fields is shown in <a href="#formatopt">Figure 9</a>. </p><br /><hr /> <a name="formatopt"></a> <pre> 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Option Code | Option Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Option Value | | /* variable length, byte-aligned */ | | + + + + + + + + + + + + + + + + + + + + + + + + + | / / / | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ / / / . . . other options . . . / / / +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Option Code == opt_endofopt | Option Length == 0 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ </pre> <table border="0" cellpadding="0" cellspacing="2" align="center"><tr><td align="center"><font face="monaco, MS Sans Serif" size="1"><b>&nbsp;Options format.&nbsp;</b></font><br /></td></tr></table><hr size="1" shade="0"> <p>The following codes can always be present in any optional field: </p><table class="data" align="center" border="1" cellpadding="2" cellspacing="2"> <tr> <th align="left" width="25%">Name</th> <th align="left" width="25%">Code</th> <th align="left" width="25%">Length</th> <th align="left" width="25%">Description</th> </tr> <tr> <td align="left">opt_endofopt</td> <td align="left">0</td> <td align="left">0</td> <td align="left">End of options: it is used to delimit the end of the optional fields. This block cannot be repeated within a given list of options.</td> </tr> <tr> <td align="left">opt_comment</td> <td align="left">1</td> <td align="left">variable</td> <td align="left">Comment: it is an ascii string containing a comment that is associated to the current block.</td> </tr> </table> <a name="anchor10"></a><br /><hr /> <table summary="layout" cellpadding="0" cellspacing="2" class="bug" align="right"><tr><td class="bug"><a href="#toc" class="link2">&nbsp;TOC&nbsp;</a></td></tr></table> <a name="rfc.section.5"></a><h3>5.&nbsp;Experimental Blocks (deserved to a further investigation)</h3> <a name="rfc.section.5.1"></a><h4><a name="anchor11">5.1</a>&nbsp;Other Packet Blocks (experimental)</h4> <p>Can some other packet blocks (besides the two described in the previous paragraphs) be useful? </p> <a name="rfc.section.5.2"></a><h4><a name="anchor12">5.2</a>&nbsp;Compression Block (experimental)</h4> <p>The Compression Block is optional. A file can contain an arbitrary number of these blocks. A Compression Block, as the name says, is used to store compressed data. Its format is shown in <a href="#formatcb">Figure 10</a>. </p><br /><hr /> <a name="formatcb"></a> <pre> 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Compr. Type | | +-+-+-+-+-+-+-+-+ | | | | Compressed Data | | | | /* variable length, byte-aligned */ | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ </pre> <table border="0" cellpadding="0" cellspacing="2" align="center"><tr><td align="center"><font face="monaco, MS Sans Serif" size="1"><b>&nbsp;Compression Block format.&nbsp;</b></font><br /></td></tr></table><hr size="1" shade="0"> <p>The fields have the following meaning: </p> <ul class="text"> <li>Compression Type: specifies the compression algorithm. Possible values for this field are 0 (uncompressed), 1 (Lempel Ziv), 2 (Gzip), other?? Probably some kind of dumb and fast compression algorithm could be effective with some types of traffic (for example web), but which? </li> <li>Compressed Data: data of this block. Once decompressed, it is made of other blocks. </li> </ul> <a name="rfc.section.5.3"></a><h4><a name="anchor13">5.3</a>&nbsp;Encryption Block (experimental)</h4> <p>The Encryption Block is optional. A file can contain an arbitrary number of these blocks. An Encryption Block is used to sotre encrypted data. Its format is shown in <a href="#formateb">Figure 11</a>. </p><br /><hr /> <a name="formateb"></a> <pre> 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Encr. Type | | +-+-+-+-+-+-+-+-+ | | | | Compressed Data | | | | /* variable length, byte-aligned */ | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ </pre> <table border="0" cellpadding="0" cellspacing="2" align="center"><tr><td align="center"><font face="monaco, MS Sans Serif" size="1"><b>&nbsp;Encryption Block format.&nbsp;</b></font><br /></td></tr></table><hr size="1" shade="0"> <p>The fields have the following meaning: </p> <ul class="text"> <li>Compression Type: specifies the encryption algorithm. Possible values for this field are ??? NOTE: this block should probably contain other fields, depending on the encryption algorithm. To be define precisely. </li> <li>Encrypted Data: data of this block. Once decripted, it consists of other blocks. </li> </ul> <a name="rfc.section.5.4"></a><h4><a name="anchor14">5.4</a>&nbsp;Fixed Length Block (experimental)</h4> <p>The Fixed Length Block is optional. A file can contain an arbitrary number of these blocks. A Fixed Length Block can be used to optimize the access to the file. Its format is shown in <a href="#formatflm">Figure 12</a>. A Fixed Length Block stores records with constant size. It contains a set of Blocks (normally Packet Blocks or Simple Packet Blocks), of wihich it specifies the size. Knowing this size a priori helps to scan the file and to load some portions of it without truncating a block, and is particularly useful with cell-based networks like ATM. </p><br /><hr /> <a name="formatflm"></a> <pre> 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Cell Size | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | | | Fixed Size Data | | | | /* variable length, byte-aligned */ | | | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ </pre> <table border="0" cellpadding="0" cellspacing="2" align="center"><tr><td align="center"><font face="monaco, MS Sans Serif" size="1"><b>&nbsp;Fixed Length Block format.&nbsp;</b></font><br /></td></tr></table><hr size="1" shade="0"> <p>The fields have the following meaning: </p> <ul class="text"> <li>Cell size: the size of the blocks contained in the data field. </li> <li>Fixed Size Data: data of this block. </li> </ul> <a name="rfc.section.5.5"></a><h4><a name="anchor15">5.5</a>&nbsp;Directory Block (experimental)</h4> <p>If present, this block contains the following information: </p> <ul class="text"> <li>number of indexed packets (N) </li> <li>table with position and length of any indexed packet (N entries) </li> </ul> <p>A directory block must be followed by at least N packets, otherwise it must be considered invalid. It can be used to efficiently load portions of the file to memory and to support operations on memory mapped files. This block can be added by tools like network analyzers as a consequence of file processing. </p> <a name="rfc.section.5.6"></a><h4><a name="anchor16">5.6</a>&nbsp;Traffic Statistics and Monitoring Blocks (experimental)</h4> <p>One or more blocks could be defined to contain network statistics or traffic monitoring information. They could be use to store data collected from RMON or Netflow probes, or from other network monitoring tools. </p> <a name="rfc.section.5.7"></a><h4><a name="anchor17">5.7</a>&nbsp;Event/Security Block (experimental)</h4> <p>This block could be used to store events. Events could contain generic information (for example network load over 50%, server down...) or security alerts. An event could be: </p> <ul class="text"> <li>skipped, if the application doesn't know how to do with it </li> <li>processed independently by the packets. In other words, the applications skips the packets and processes only the alerts </li> <li>processed in relation to packets: for example, a security tool could load only the packets of the file that are near a security alert; a monitorg tool could skip the packets captured while the server was down. </li> </ul> <a name="anchor18"></a><br /><hr /> <table summary="layout" cellpadding="0" cellspacing="2" class="bug" align="right"><tr><td class="bug"><a href="#toc" class="link2">&nbsp;TOC&nbsp;</a></td></tr></table> <a name="rfc.section.6"></a><h3>6.&nbsp;Conclusions</h3> <p>The file format proposed in this document should be very versatile and satisfy a wide range of applications. In the simplest case, it can contain a raw dump of the network data, made of a series of Simple Packet Blocks. In the most complex case, it can be used as a repository for heterogeneous information. In every case, the file remains easy to parse and an application can always skip the data it is not interested in; at the same time, different applications can share the file, and each of them can benfit of the information produced by the others. Two or more files can be concatenated obtaining another valid file. </p> <a name="anchor19"></a><br /><hr /> <table summary="layout" cellpadding="0" cellspacing="2" class="bug" align="right"><tr><td class="bug"><a href="#toc" class="link2">&nbsp;TOC&nbsp;</a></td></tr></table> <a name="rfc.section.7"></a><h3>7.&nbsp;Most important open issues</h3> <ul class="text"> <li>Data, in the file, must be byte or word aligned? Currently, the structure of this document is not consistent with respect to this point. </li> </ul><a name="rfc.copyright"></a><br /><hr /> <table summary="layout" cellpadding="0" cellspacing="2" class="bug" align="right"><tr><td class="bug"><a href="#toc" class="link2">&nbsp;TOC&nbsp;</a></td></tr></table> <h3>Intellectual Property Statement</h3> <p class='copyright'> The IETF takes no position regarding the validity or scope of any intellectual property or other rights that might be claimed to pertain to the implementation or use of the technology described in this document or the extent to which any license under such rights might or might not be available; neither does it represent that it has made any effort to identify any such rights. Information on the IETF's procedures with respect to rights in standards-track and standards-related documentation can be found in BCP-11. Copies of claims of rights made available for publication and any assurances of licenses to be made available, or the result of an attempt made to obtain a general license or permission for the use of such proprietary rights by implementors or users of this specification can be obtained from the IETF Secretariat.</p> <p class='copyright'> The IETF invites any interested party to bring to its attention any copyrights, patents or patent applications, or other proprietary rights which may cover technology that may be required to practice this standard. Please address the information to the IETF Executive Director.</p> <h3>Full Copyright Statement</h3> <p class='copyright'> Copyright (C) The Internet Society (2004). All Rights Reserved.</p> <p class='copyright'> This document and translations of it may be copied and furnished to others, and derivative works that comment on or otherwise explain it or assist in its implementation may be prepared, copied, published and distributed, in whole or in part, without restriction of any kind, provided that the above copyright notice and this paragraph are included on all such copies and derivative works. However, this document itself may not be modified in any way, such as by removing the copyright notice or references to the Internet Society or other Internet organizations, except as needed for the purpose of developing Internet standards in which case the procedures for copyrights defined in the Internet Standards process must be followed, or as required to translate it into languages other than English.</p> <p class='copyright'> The limited permissions granted above are perpetual and will not be revoked by the Internet Society or its successors or assignees.</p> <p class='copyright'> This document and the information contained herein is provided on an &quot;AS IS&quot; basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.</p> <h3>Acknowledgment</h3> <p class='copyright'> Funding for the RFC Editor function is currently provided by the Internet Society.</p> </body></html>
pfq/PFQ
user/lib/libpcap-1.8.1-fanout/doc/pcap.html
HTML
gpl-2.0
58,387
////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // // copyright : (C) 2008 by Eran Ifrah // file name : depends_dlg.h // // ------------------------------------------------------------------------- // A // _____ _ _ _ _ // / __ \ | | | | (_) | // | / \/ ___ __| | ___| | _| |_ ___ // | | / _ \ / _ |/ _ \ | | | __/ _ ) // | \__/\ (_) | (_| | __/ |___| | || __/ // \____/\___/ \__,_|\___\_____/_|\__\___| // // F i l e // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// #ifndef __depends_dlg__ #define __depends_dlg__ #include <wx/wx.h> #include <wx/choicebk.h> #include <wx/statline.h> #include <wx/button.h> /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /// Class DependenciesDlg /////////////////////////////////////////////////////////////////////////////// class DependenciesDlg : public wxDialog { private: protected: wxChoicebook* m_book; wxStaticLine* m_staticline1; wxButton* m_buttonOK; wxButton* m_buttonCancel; wxString m_projectName; void Init(); void DoSelectProject(); virtual void OnButtonOK(wxCommandEvent& event); virtual void OnButtonCancel(wxCommandEvent& event); public: DependenciesDlg(wxWindow* parent, const wxString& projectName, int id = wxID_ANY, wxString title = _("Build Order"), wxPoint pos = wxDefaultPosition, wxSize size = wxSize(700, 450), int style = wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER); virtual ~DependenciesDlg(); }; #endif //__depends_dlg__
pattisahusiwa/codelite
LiteEditor/depends_dlg.h
C
gpl-2.0
2,345
/* * Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.graalvm.compiler.jtt.optimize; import org.junit.Test; import org.graalvm.compiler.jtt.JTTTest; /* * Test case for local load elimination. It makes sure that the second field store is not eliminated, because * it is recognized that the first store changes the field "field1", so it is no longer guaranteed that it * has its default value 0. */ public class LLE_01 extends JTTTest { private static class TestClass { int field1; } public static int test() { TestClass o = new TestClass(); o.field1 = 1; o.field1 = 0; return o.field1; } @Test public void run0() throws Throwable { runTest("test"); } }
YouDiSN/OpenJDK-Research
jdk9/hotspot/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.jtt/src/org/graalvm/compiler/jtt/optimize/LLE_01.java
Java
gpl-2.0
1,754
<?php namespace TYPO3\CMS\Core\Log\Writer; /** * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ /** * Abstract implementation of a log writer * * @author Ingo Renner <ingo@typo3.org> */ abstract class AbstractWriter implements \TYPO3\CMS\Core\Log\Writer\WriterInterface { /** * Constructs this log writer * * @param array $options Configuration options - depends on the actual log writer * @throws \InvalidArgumentException */ public function __construct(array $options = array()) { foreach ($options as $optionKey => $optionValue) { $methodName = 'set' . ucfirst($optionKey); if (method_exists($this, $methodName)) { $this->{$methodName}($optionValue); } else { throw new \InvalidArgumentException('Invalid log writer option "' . $optionKey . '" for log writer of type "' . get_class($this) . '"', 1321696152); } } } }
TimboDynamite/TYPO3-Testprojekt
typo3/sysext/core/Classes/Log/Writer/AbstractWriter.php
PHP
gpl-2.0
1,233
/* * Glide64 - Glide video plugin for Nintendo 64 emulators. * Copyright (c) 2002 Dave2001 * Copyright (c) 2003-2009 Sergey 'Gonetz' Lipski * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ //**************************************************************** // // Glide64 - Glide Plugin for Nintendo 64 emulators // Project started on December 29th, 2001 // // Authors: // Dave2001, original author, founded the project in 2001, left it in 2002 // Gugaman, joined the project in 2002, left it in 2002 // Sergey 'Gonetz' Lipski, joined the project in 2002, main author since fall of 2002 // Hiroshi 'KoolSmoky' Morii, joined the project in 2007 // //**************************************************************** // // To modify Glide64: // * Write your name and (optional)email, commented by your work, so I know who did it, and so that you can find which parts you modified when it comes time to send it to me. // * Do NOT send me the whole project or file that you modified. Take out your modified code sections, and tell me where to put them. If people sent the whole thing, I would have many different versions, but no idea how to combine them all. // //**************************************************************** // // Created by Gonetz, 2008 // //**************************************************************** /******************Turbo3D microcode*************************/ struct t3dGlobState { wxUint16 pad0; wxUint16 perspNorm; wxUint32 flag; wxUint32 othermode0; wxUint32 othermode1; wxUint32 segBases[16]; /* the viewport to use */ short vsacle1; short vsacle0; short vsacle3; short vsacle2; short vtrans1; short vtrans0; short vtrans3; short vtrans2; wxUint32 rdpCmds; }; struct t3dState { wxUint32 renderState; /* render state */ wxUint32 textureState; /* texture state */ wxUint8 flag; wxUint8 triCount; /* how many tris? */ wxUint8 vtxV0; /* where to load verts? */ wxUint8 vtxCount; /* how many verts? */ wxUint32 rdpCmds; /* ptr (segment address) to RDP DL */ wxUint32 othermode0; wxUint32 othermode1; }; struct t3dTriN{ wxUint8 flag, v2, v1, v0; /* flag is which one for flat shade */ }; static void t3dProcessRDP(wxUint32 a) { if (a) { rdp.LLE = 1; rdp.cmd0 = ((wxUint32*)gfx.RDRAM)[a++]; rdp.cmd1 = ((wxUint32*)gfx.RDRAM)[a++]; while (rdp.cmd0 + rdp.cmd1) { gfx_instruction[0][rdp.cmd0>>24] (); rdp.cmd0 = ((wxUint32*)gfx.RDRAM)[a++]; rdp.cmd1 = ((wxUint32*)gfx.RDRAM)[a++]; wxUint32 cmd = rdp.cmd0>>24; if (cmd == 0xE4 || cmd == 0xE5) { rdp.cmd2 = ((wxUint32*)gfx.RDRAM)[a++]; rdp.cmd3 = ((wxUint32*)gfx.RDRAM)[a++]; } } rdp.LLE = 0; } } static void t3dLoadGlobState(wxUint32 pgstate) { t3dGlobState *gstate = (t3dGlobState*)&gfx.RDRAM[segoffset(pgstate)]; FRDP ("Global state. pad0: %04lx, perspNorm: %04lx, flag: %08lx\n", gstate->pad0, gstate->perspNorm, gstate->flag); rdp.cmd0 = gstate->othermode0; rdp.cmd1 = gstate->othermode1; rdp_setothermode(); for (int s = 0; s < 16; s++) { rdp.segment[s] = gstate->segBases[s]; FRDP ("segment: %08lx -> seg%d\n", rdp.segment[s], s); } short scale_x = gstate->vsacle0 / 4; short scale_y = gstate->vsacle1 / 4;; short scale_z = gstate->vsacle2; short trans_x = gstate->vtrans0 / 4; short trans_y = gstate->vtrans1 / 4; short trans_z = gstate->vtrans2; rdp.view_scale[0] = scale_x * rdp.scale_x; rdp.view_scale[1] = -scale_y * rdp.scale_y; rdp.view_scale[2] = 32.0f * scale_z; rdp.view_trans[0] = trans_x * rdp.scale_x; rdp.view_trans[1] = trans_y * rdp.scale_y; rdp.view_trans[2] = 32.0f * trans_z; rdp.update |= UPDATE_VIEWPORT; FRDP ("viewport scale(%d, %d, %d), trans(%d, %d, %d)\n", scale_x, scale_y, scale_z, trans_x, trans_y, trans_z); t3dProcessRDP(segoffset(gstate->rdpCmds) >> 2); } static void t3d_vertex(wxUint32 addr, wxUint32 v0, wxUint32 n) { float x, y, z; rdp.v0 = v0; // Current vertex rdp.vn = n; // Number of vertices to copy n <<= 4; for (wxUint32 i=0; i < n; i+=16) { VERTEX *v = &rdp.vtx[v0 + (i>>4)]; x = (float)((short*)gfx.RDRAM)[(((addr+i) >> 1) + 0)^1]; y = (float)((short*)gfx.RDRAM)[(((addr+i) >> 1) + 1)^1]; z = (float)((short*)gfx.RDRAM)[(((addr+i) >> 1) + 2)^1]; v->flags = ((wxUint16*)gfx.RDRAM)[(((addr+i) >> 1) + 3)^1]; v->ou = 2.0f * (float)((short*)gfx.RDRAM)[(((addr+i) >> 1) + 4)^1]; v->ov = 2.0f * (float)((short*)gfx.RDRAM)[(((addr+i) >> 1) + 5)^1]; v->uv_scaled = 0; v->r = ((wxUint8*)gfx.RDRAM)[(addr+i + 12)^3]; v->g = ((wxUint8*)gfx.RDRAM)[(addr+i + 13)^3]; v->b = ((wxUint8*)gfx.RDRAM)[(addr+i + 14)^3]; v->a = ((wxUint8*)gfx.RDRAM)[(addr+i + 15)^3]; v->x = x*rdp.combined[0][0] + y*rdp.combined[1][0] + z*rdp.combined[2][0] + rdp.combined[3][0]; v->y = x*rdp.combined[0][1] + y*rdp.combined[1][1] + z*rdp.combined[2][1] + rdp.combined[3][1]; v->z = x*rdp.combined[0][2] + y*rdp.combined[1][2] + z*rdp.combined[2][2] + rdp.combined[3][2]; v->w = x*rdp.combined[0][3] + y*rdp.combined[1][3] + z*rdp.combined[2][3] + rdp.combined[3][3]; if (fabs(v->w) < 0.001) v->w = 0.001f; v->oow = 1.0f / v->w; v->x_w = v->x * v->oow; v->y_w = v->y * v->oow; v->z_w = v->z * v->oow; v->uv_calculated = 0xFFFFFFFF; v->screen_translated = 0; v->shade_mod = 0; v->scr_off = 0; if (v->x < -v->w) v->scr_off |= 1; if (v->x > v->w) v->scr_off |= 2; if (v->y < -v->w) v->scr_off |= 4; if (v->y > v->w) v->scr_off |= 8; if (v->w < 0.1f) v->scr_off |= 16; #ifdef EXTREME_LOGGING FRDP ("v%d - x: %f, y: %f, z: %f, w: %f, u: %f, v: %f, f: %f, z_w: %f, r=%d, g=%d, b=%d, a=%d\n", i>>4, v->x, v->y, v->z, v->w, v->ou*rdp.tiles[rdp.cur_tile].s_scale, v->ov*rdp.tiles[rdp.cur_tile].t_scale, v->f, v->z_w, v->r, v->g, v->b, v->a); #endif } } static void t3dLoadObject(wxUint32 pstate, wxUint32 pvtx, wxUint32 ptri) { LRDP("Loading Turbo3D object\n"); t3dState *ostate = (t3dState*)&gfx.RDRAM[segoffset(pstate)]; rdp.cur_tile = (ostate->textureState)&7; FRDP("tile: %d\n", rdp.cur_tile); if (rdp.tiles[rdp.cur_tile].s_scale < 0.001f) rdp.tiles[rdp.cur_tile].s_scale = 0.015625; if (rdp.tiles[rdp.cur_tile].t_scale < 0.001f) rdp.tiles[rdp.cur_tile].t_scale = 0.015625; #ifdef EXTREME_LOGGING FRDP("renderState: %08lx, textureState: %08lx, othermode0: %08lx, othermode1: %08lx, rdpCmds: %08lx, triCount : %d, v0: %d, vn: %d\n", ostate->renderState, ostate->textureState, ostate->othermode0, ostate->othermode1, ostate->rdpCmds, ostate->triCount, ostate->vtxV0, ostate->vtxCount); #endif rdp.cmd0 = ostate->othermode0; rdp.cmd1 = ostate->othermode1; rdp_setothermode(); rdp.cmd1 = ostate->renderState; uc0_setgeometrymode(); if (!(ostate->flag&1)) //load matrix { wxUint32 addr = segoffset(pstate+sizeof(t3dState)) & BMASK; load_matrix(rdp.combined, addr); #ifdef EXTREME_LOGGING FRDP ("{%f,%f,%f,%f}\n", rdp.combined[0][0], rdp.combined[0][1], rdp.combined[0][2], rdp.combined[0][3]); FRDP ("{%f,%f,%f,%f}\n", rdp.combined[1][0], rdp.combined[1][1], rdp.combined[1][2], rdp.combined[1][3]); FRDP ("{%f,%f,%f,%f}\n", rdp.combined[2][0], rdp.combined[2][1], rdp.combined[2][2], rdp.combined[2][3]); FRDP ("{%f,%f,%f,%f}\n", rdp.combined[3][0], rdp.combined[3][1], rdp.combined[3][2], rdp.combined[3][3]); #endif } rdp.geom_mode &= ~0x00020000; rdp.geom_mode |= 0x00000200; if (pvtx) //load vtx t3d_vertex(segoffset(pvtx) & BMASK, ostate->vtxV0, ostate->vtxCount); t3dProcessRDP(segoffset(ostate->rdpCmds) >> 2); if (ptri) { update (); wxUint32 a = segoffset(ptri); for (int t=0; t < ostate->triCount; t++) { t3dTriN * tri = (t3dTriN*)&gfx.RDRAM[a]; a += 4; FRDP("tri #%d - %d, %d, %d\n", t, tri->v0, tri->v1, tri->v2); VERTEX *v[3] = { &rdp.vtx[tri->v0], &rdp.vtx[tri->v1], &rdp.vtx[tri->v2] }; if (cull_tri(v)) rdp.tri_n ++; else { draw_tri (v); rdp.tri_n ++; } } } } static void Turbo3D() { LRDP("Start Turbo3D microcode\n"); settings.ucode = ucode_Fast3D; wxUint32 a = 0, pgstate = 0, pstate = 0, pvtx = 0, ptri = 0; do { a = rdp.pc[rdp.pc_i] & BMASK; pgstate = ((wxUint32*)gfx.RDRAM)[a>>2]; pstate = ((wxUint32*)gfx.RDRAM)[(a>>2)+1]; pvtx = ((wxUint32*)gfx.RDRAM)[(a>>2)+2]; ptri = ((wxUint32*)gfx.RDRAM)[(a>>2)+3]; FRDP("GlobalState: %08lx, Object: %08lx, Vertices: %08lx, Triangles: %08lx\n", pgstate, pstate, pvtx, ptri); if (!pstate) { rdp.halt = 1; break; } if (pgstate) t3dLoadGlobState(pgstate); t3dLoadObject(pstate, pvtx, ptri); // Go to the next instruction rdp.pc[rdp.pc_i] += 16; } while (pstate); // rdp_fullsync(); settings.ucode = ucode_Turbo3d; }
Gillou68310/mupen64plus-video-glide64mk2
src/Glide64/turbo3D.h
C
gpl-2.0
9,666
/* * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.graalvm.compiler.hotspot.replacements; import java.lang.reflect.Method; import java.util.EnumMap; import org.graalvm.compiler.api.directives.GraalDirectives; import org.graalvm.compiler.api.replacements.Snippet; import org.graalvm.compiler.debug.GraalError; import org.graalvm.compiler.hotspot.replacements.arraycopy.ArrayCopyCallNode; import org.graalvm.compiler.nodes.java.DynamicNewArrayNode; import org.graalvm.compiler.nodes.java.NewArrayNode; import org.graalvm.compiler.replacements.Snippets; import jdk.vm.ci.meta.JavaKind; public class ObjectCloneSnippets implements Snippets { public static final EnumMap<JavaKind, Method> arrayCloneMethods = new EnumMap<>(JavaKind.class); static { arrayCloneMethods.put(JavaKind.Boolean, getCloneMethod("booleanArrayClone", boolean[].class)); arrayCloneMethods.put(JavaKind.Byte, getCloneMethod("byteArrayClone", byte[].class)); arrayCloneMethods.put(JavaKind.Char, getCloneMethod("charArrayClone", char[].class)); arrayCloneMethods.put(JavaKind.Short, getCloneMethod("shortArrayClone", short[].class)); arrayCloneMethods.put(JavaKind.Int, getCloneMethod("intArrayClone", int[].class)); arrayCloneMethods.put(JavaKind.Float, getCloneMethod("floatArrayClone", float[].class)); arrayCloneMethods.put(JavaKind.Long, getCloneMethod("longArrayClone", long[].class)); arrayCloneMethods.put(JavaKind.Double, getCloneMethod("doubleArrayClone", double[].class)); arrayCloneMethods.put(JavaKind.Object, getCloneMethod("objectArrayClone", Object[].class)); } private static Method getCloneMethod(String name, Class<?> param) { try { return ObjectCloneSnippets.class.getDeclaredMethod(name, param); } catch (SecurityException | NoSuchMethodException e) { throw new GraalError(e); } } @Snippet public static boolean[] booleanArrayClone(boolean[] src) { boolean[] result = (boolean[]) NewArrayNode.newUninitializedArray(Boolean.TYPE, src.length); ArrayCopyCallNode.disjointArraycopy(src, 0, result, 0, src.length, JavaKind.Boolean); return result; } @Snippet public static byte[] byteArrayClone(byte[] src) { byte[] result = (byte[]) NewArrayNode.newUninitializedArray(Byte.TYPE, src.length); ArrayCopyCallNode.disjointArraycopy(src, 0, result, 0, src.length, JavaKind.Byte); return result; } @Snippet public static short[] shortArrayClone(short[] src) { short[] result = (short[]) NewArrayNode.newUninitializedArray(Short.TYPE, src.length); ArrayCopyCallNode.disjointArraycopy(src, 0, result, 0, src.length, JavaKind.Short); return result; } @Snippet public static char[] charArrayClone(char[] src) { char[] result = (char[]) NewArrayNode.newUninitializedArray(Character.TYPE, src.length); ArrayCopyCallNode.disjointArraycopy(src, 0, result, 0, src.length, JavaKind.Char); return result; } @Snippet public static int[] intArrayClone(int[] src) { int[] result = (int[]) NewArrayNode.newUninitializedArray(Integer.TYPE, src.length); ArrayCopyCallNode.disjointArraycopy(src, 0, result, 0, src.length, JavaKind.Int); return result; } @Snippet public static float[] floatArrayClone(float[] src) { float[] result = (float[]) NewArrayNode.newUninitializedArray(Float.TYPE, src.length); ArrayCopyCallNode.disjointArraycopy(src, 0, result, 0, src.length, JavaKind.Float); return result; } @Snippet public static long[] longArrayClone(long[] src) { long[] result = (long[]) NewArrayNode.newUninitializedArray(Long.TYPE, src.length); ArrayCopyCallNode.disjointArraycopy(src, 0, result, 0, src.length, JavaKind.Long); return result; } @Snippet public static double[] doubleArrayClone(double[] src) { double[] result = (double[]) NewArrayNode.newUninitializedArray(Double.TYPE, src.length); ArrayCopyCallNode.disjointArraycopy(src, 0, result, 0, src.length, JavaKind.Double); return result; } @Snippet public static Object[] objectArrayClone(Object[] src) { /* Since this snippet is lowered early the array must be initialized */ Object[] result = (Object[]) DynamicNewArrayNode.newArray(GraalDirectives.guardingNonNull(src.getClass().getComponentType()), src.length, JavaKind.Object); ArrayCopyCallNode.disjointUninitializedArraycopy(src, 0, result, 0, src.length, JavaKind.Object); return result; } }
YouDiSN/OpenJDK-Research
jdk9/hotspot/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/replacements/ObjectCloneSnippets.java
Java
gpl-2.0
5,679
/* Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved. * * HTC: elite machine driver which defines board-specific data * Copy from sound/soc/msm/msm8960.c * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/clk.h> #include <linux/delay.h> #include <linux/gpio.h> #include <linux/mfd/pm8xxx/pm8921.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <sound/core.h> #include <sound/soc.h> #include <sound/soc-dapm.h> #include <sound/pcm.h> #include <sound/jack.h> #include <asm/mach-types.h> #include <mach/socinfo.h> #include <linux/mfd/wcd9xxx/core.h> #include "../../../sound/soc/codecs/wcd9310.h" #include "../sound/soc/msm/msm-pcm-routing.h" #include "board-elite.h" #include <mach/cable_detect.h> #include <mach/board.h> #define MSM_SPK_ON 1 #define MSM_SPK_OFF 0 #define MSM_SLIM_0_RX_MAX_CHANNELS 2 #define MSM_SLIM_0_TX_MAX_CHANNELS 4 #define SAMPLE_RATE_8KHZ 8000 #define SAMPLE_RATE_16KHZ 16000 #define BOTTOM_SPK_AMP_POS 0x1 #define BOTTOM_SPK_AMP_NEG 0x2 #define TOP_SPK_AMP_POS 0x4 #define TOP_SPK_AMP_NEG 0x8 #define DOCK_SPK_AMP_POS 0x10 #define DOCK_SPK_AMP_NEG 0x20 #define GPIO_AUX_PCM_DOUT 63 #define GPIO_AUX_PCM_DIN 64 #define GPIO_AUX_PCM_SYNC 65 #define GPIO_AUX_PCM_CLK 66 #define TABLA_EXT_CLK_RATE 12288000 #define ELITE_AUD_STEREO_REC (PM8921_GPIO_PM_TO_SYS(3)) #define top_spk_pamp_gpio (PM8921_GPIO_PM_TO_SYS(19)) #define bottom_spk_pamp_gpio (PM8921_GPIO_PM_TO_SYS(18)) #define DOCK_SPK_PAMP_GPIO (PM8921_GPIO_PM_TO_SYS(1)) #define USB_ID_ADC_GPIO (PM8921_GPIO_PM_TO_SYS(4)) static int msm_spk_control; static int msm_ext_bottom_spk_pamp; static int msm_ext_top_spk_pamp; static int msm_ext_dock_spk_pamp; static int msm_slim_0_rx_ch = 1; static int msm_slim_0_tx_ch = 1; static int msm_btsco_rate = SAMPLE_RATE_8KHZ; static int msm_btsco_ch = 1; static int msm_auxpcm_rate = SAMPLE_RATE_8KHZ; static int elite_stereo_control; static struct clk *codec_clk; static int clk_users; extern void msm_release_audio_dock_lock(void); static struct snd_soc_jack hs_jack; static struct snd_soc_jack button_jack; static int msm_enable_codec_ext_clk(struct snd_soc_codec *codec, int enable, bool dapm); extern void release_audio_dock_lock(void); static struct mutex cdc_mclk_mutex; static void msm_ext_spk_power_amp_off(u32); static void audio_dock_notifier_func(enum usb_connect_type online) { if (cable_get_accessory_type() != DOCK_STATE_AUDIO_DOCK) { pr_debug("accessory is not AUDIO_DOCK\n"); return; } switch(online) { case CONNECT_TYPE_NONE: pr_debug("%s, VBUS is removed\n", __func__); msm_ext_spk_power_amp_off(DOCK_SPK_AMP_POS|DOCK_SPK_AMP_NEG); release_audio_dock_lock(); break; default: break; } return; } static struct mutex audio_notifier_lock; static struct t_cable_status_notifier audio_dock_notifier = { .name = "elite_audio_8960", .func = audio_dock_notifier_func, }; static void msm_enable_ext_spk_amp_gpio(u32 spk_amp_gpio) { int ret = 0; struct pm_gpio param = { .direction = PM_GPIO_DIR_OUT, .output_buffer = PM_GPIO_OUT_BUF_CMOS, .output_value = 1, .pull = PM_GPIO_PULL_NO, .vin_sel = PM_GPIO_VIN_S4, .out_strength = PM_GPIO_STRENGTH_MED, .function = PM_GPIO_FUNC_NORMAL, }; if (spk_amp_gpio == bottom_spk_pamp_gpio) { ret = gpio_request(bottom_spk_pamp_gpio, "BOTTOM_SPK_AMP"); if (ret) { pr_err("%s: Error requesting BOTTOM SPK AMP GPIO %u\n", __func__, bottom_spk_pamp_gpio); return; } ret = pm8xxx_gpio_config(bottom_spk_pamp_gpio, &param); if (ret) pr_err("%s: Failed to configure Bottom Spk Ampl" " gpio %u\n", __func__, bottom_spk_pamp_gpio); else { pr_debug("%s: enable Bottom spkr amp gpio\n", __func__); gpio_direction_output(bottom_spk_pamp_gpio, 1); } } else if (spk_amp_gpio == top_spk_pamp_gpio) { ret = gpio_request(top_spk_pamp_gpio, "TOP_SPK_AMP"); if (ret) { pr_err("%s: Error requesting GPIO %d\n", __func__, top_spk_pamp_gpio); return; } ret = pm8xxx_gpio_config(top_spk_pamp_gpio, &param); if (ret) pr_err("%s: Failed to configure Top Spk Ampl" " gpio %u\n", __func__, top_spk_pamp_gpio); else { pr_debug("%s: enable Top spkr amp gpio\n", __func__); gpio_direction_output(top_spk_pamp_gpio, 1); } } else if (spk_amp_gpio == DOCK_SPK_PAMP_GPIO) { ret = gpio_request(DOCK_SPK_PAMP_GPIO, "DOCK_SPK_AMP"); if (ret) { pr_err("%s: Error requesting GPIO %d\n", __func__, DOCK_SPK_PAMP_GPIO); return; } ret = pm8xxx_gpio_config(DOCK_SPK_PAMP_GPIO, &param); if (ret) pr_err("%s: Failed to configure Dock Spk Ampl" " gpio %u\n", __func__, DOCK_SPK_PAMP_GPIO); else { pr_debug("%s: enable dock amp gpio\n", __func__); gpio_direction_output(DOCK_SPK_PAMP_GPIO, 1); } ret = gpio_request(USB_ID_ADC_GPIO, "USB_ID_ADC"); if (ret) { pr_err("%s: Error requesting USB_ID_ADC PMIC GPIO %u\n", __func__, USB_ID_ADC_GPIO); return; } ret = pm8xxx_gpio_config(USB_ID_ADC_GPIO, &param); if (ret) pr_err("%s: Failed to configure USB_ID_ADC PMIC" " gpio %u\n", __func__, USB_ID_ADC_GPIO); } else { pr_err("%s: ERROR : Invalid External Speaker Ampl GPIO." " gpio = %u\n", __func__, spk_amp_gpio); return; } } static void msm_ext_spk_power_amp_on(u32 spk) { if (spk & (BOTTOM_SPK_AMP_POS | BOTTOM_SPK_AMP_NEG)) { if ((msm_ext_bottom_spk_pamp & BOTTOM_SPK_AMP_POS) && (msm_ext_bottom_spk_pamp & BOTTOM_SPK_AMP_NEG)) { pr_debug("%s() External Bottom Speaker Ampl already " "turned on. spk = 0x%08x\n", __func__, spk); return; } msm_ext_bottom_spk_pamp |= spk; if ((msm_ext_bottom_spk_pamp & BOTTOM_SPK_AMP_POS) && (msm_ext_bottom_spk_pamp & BOTTOM_SPK_AMP_NEG)) { msm_enable_ext_spk_amp_gpio(bottom_spk_pamp_gpio); pr_debug("%s: slepping 4 ms after turning on external " " Bottom Speaker Ampl\n", __func__); usleep_range(4000, 4000); } } else if (spk & (TOP_SPK_AMP_POS | TOP_SPK_AMP_NEG)) { if ((msm_ext_top_spk_pamp & TOP_SPK_AMP_POS) && (msm_ext_top_spk_pamp & TOP_SPK_AMP_NEG)) { pr_debug("%s() External Top Speaker Ampl already" "turned on. spk = 0x%08x\n", __func__, spk); return; } msm_ext_top_spk_pamp |= spk; if ((msm_ext_top_spk_pamp & TOP_SPK_AMP_POS) && (msm_ext_top_spk_pamp & TOP_SPK_AMP_NEG)) { msm_enable_ext_spk_amp_gpio(top_spk_pamp_gpio); pr_debug("%s: sleeping 4 ms after turning on " " external HAC Ampl\n", __func__); usleep_range(4000, 4000); } } else if (spk & (DOCK_SPK_AMP_POS | DOCK_SPK_AMP_NEG)) { mutex_lock(&audio_notifier_lock); if ((msm_ext_dock_spk_pamp & DOCK_SPK_AMP_POS) && (msm_ext_dock_spk_pamp & DOCK_SPK_AMP_NEG)) { pr_debug("%s() External Dock Speaker Ampl already" "turned on. spk = 0x%08x\n", __func__, spk); return; } msm_ext_dock_spk_pamp |= spk; if ((msm_ext_dock_spk_pamp & DOCK_SPK_AMP_POS) && (msm_ext_dock_spk_pamp & DOCK_SPK_AMP_NEG)) { msm_enable_ext_spk_amp_gpio(DOCK_SPK_PAMP_GPIO); pr_debug("%s: sleeping 4 ms after turning on " " external DOCK Ampl\n", __func__); usleep_range(4000, 4000); } mutex_unlock(&audio_notifier_lock); } else { pr_err("%s: ERROR : Invalid External Speaker Ampl. spk = 0x%08x\n", __func__, spk); return; } } static void msm_ext_spk_power_amp_off(u32 spk) { struct pm_gpio param = { .direction = PM_GPIO_DIR_IN, .output_buffer = PM_GPIO_OUT_BUF_CMOS, .pull = PM_GPIO_PULL_NO, .vin_sel = PM_GPIO_VIN_S4, .out_strength = PM_GPIO_STRENGTH_MED, .function = PM_GPIO_FUNC_NORMAL, }; pr_debug("%s, spk = %d\n", __func__, spk); if (spk & (BOTTOM_SPK_AMP_POS | BOTTOM_SPK_AMP_NEG)) { if (!msm_ext_bottom_spk_pamp) return; gpio_direction_output(bottom_spk_pamp_gpio, 0); gpio_free(bottom_spk_pamp_gpio); msm_ext_bottom_spk_pamp = 0; pr_debug("%s: sleeping 4 ms after turning off external Bottom" " Speaker Ampl\n", __func__); usleep_range(4000, 4000); } else if (spk & (TOP_SPK_AMP_POS | TOP_SPK_AMP_NEG)) { if (!msm_ext_top_spk_pamp) return; gpio_direction_output(top_spk_pamp_gpio, 0); gpio_free(top_spk_pamp_gpio); msm_ext_top_spk_pamp = 0; pr_debug("%s: sleeping 4 ms after turning off external" " HAC Ampl\n", __func__); usleep_range(4000, 4000); } else if (spk & (DOCK_SPK_AMP_POS | DOCK_SPK_AMP_NEG)) { mutex_lock(&audio_notifier_lock); if (!msm_ext_dock_spk_pamp) { mutex_unlock(&audio_notifier_lock); return; } gpio_direction_input(DOCK_SPK_PAMP_GPIO); gpio_free(DOCK_SPK_PAMP_GPIO); gpio_direction_input(USB_ID_ADC_GPIO); if (pm8xxx_gpio_config(USB_ID_ADC_GPIO, &param)) pr_err("%s: Failed to configure USB_ID_ADC PMIC" " gpio %u\n", __func__, USB_ID_ADC_GPIO); gpio_free(USB_ID_ADC_GPIO); msm_ext_dock_spk_pamp = 0; mutex_unlock(&audio_notifier_lock); pr_debug("%s: sleeping 4 ms after turning off external" " DOCK Ampl\n", __func__); usleep_range(4000, 4000); } else { pr_err("%s: ERROR : Invalid Ext Spk Ampl. spk = 0x%08x\n", __func__, spk); return; } } static void msm_ext_control(struct snd_soc_codec *codec) { struct snd_soc_dapm_context *dapm = &codec->dapm; mutex_lock(&dapm->codec->mutex); pr_debug("%s: msm_spk_control = %d", __func__, msm_spk_control); if (msm_spk_control == MSM_SPK_ON) { snd_soc_dapm_enable_pin(dapm, "Ext Spk Bottom Pos"); snd_soc_dapm_enable_pin(dapm, "Ext Spk Bottom Neg"); snd_soc_dapm_enable_pin(dapm, "Ext Spk Top Pos"); snd_soc_dapm_enable_pin(dapm, "Ext Spk Top Neg"); snd_soc_dapm_enable_pin(dapm, "Dock Spk Pos"); snd_soc_dapm_enable_pin(dapm, "Dock Spk Neg"); } else { snd_soc_dapm_disable_pin(dapm, "Ext Spk Bottom Pos"); snd_soc_dapm_disable_pin(dapm, "Ext Spk Bottom Neg"); snd_soc_dapm_disable_pin(dapm, "Ext Spk Top Pos"); snd_soc_dapm_disable_pin(dapm, "Ext Spk Top Neg"); snd_soc_dapm_disable_pin(dapm, "Dock Spk Pos"); snd_soc_dapm_disable_pin(dapm, "Dock Spk Neg"); } snd_soc_dapm_sync(dapm); mutex_unlock(&dapm->codec->mutex); } static int msm_get_spk(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { pr_debug("%s: msm_spk_control = %d", __func__, msm_spk_control); ucontrol->value.integer.value[0] = msm_spk_control; return 0; } static int msm_set_spk(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); pr_debug("%s()\n", __func__); if (msm_spk_control == ucontrol->value.integer.value[0]) return 0; msm_spk_control = ucontrol->value.integer.value[0]; msm_ext_control(codec); return 1; } static int msm_spkramp_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *k, int event) { pr_debug("%s() %x\n", __func__, SND_SOC_DAPM_EVENT_ON(event)); if (SND_SOC_DAPM_EVENT_ON(event)) { if (!strncmp(w->name, "Ext Spk Bottom Pos", 18)) msm_ext_spk_power_amp_on(BOTTOM_SPK_AMP_POS); else if (!strncmp(w->name, "Ext Spk Bottom Neg", 18)) msm_ext_spk_power_amp_on(BOTTOM_SPK_AMP_NEG); else if (!strncmp(w->name, "Ext Spk Top Pos", 15)) msm_ext_spk_power_amp_on(TOP_SPK_AMP_POS); else if (!strncmp(w->name, "Ext Spk Top Neg", 15)) msm_ext_spk_power_amp_on(TOP_SPK_AMP_NEG); else if (!strncmp(w->name, "Dock Spk Pos", 12)) msm_ext_spk_power_amp_on(DOCK_SPK_AMP_POS); else if (!strncmp(w->name, "Dock Spk Neg", 12)) msm_ext_spk_power_amp_on(DOCK_SPK_AMP_NEG); else { pr_err("%s() Invalid Speaker Widget = %s\n", __func__, w->name); return -EINVAL; } } else { if (!strncmp(w->name, "Ext Spk Bottom Pos", 18)) msm_ext_spk_power_amp_off(BOTTOM_SPK_AMP_POS); else if (!strncmp(w->name, "Ext Spk Bottom Neg", 18)) msm_ext_spk_power_amp_off(BOTTOM_SPK_AMP_NEG); else if (!strncmp(w->name, "Ext Spk Top Pos", 15)) msm_ext_spk_power_amp_off(TOP_SPK_AMP_POS); else if (!strncmp(w->name, "Ext Spk Top Neg", 15)) msm_ext_spk_power_amp_off(TOP_SPK_AMP_NEG); else if (!strncmp(w->name, "Dock Spk Pos", 12)) msm_ext_spk_power_amp_off(DOCK_SPK_AMP_POS); else if (!strncmp(w->name, "Dock Spk Neg", 12)) msm_ext_spk_power_amp_off(DOCK_SPK_AMP_NEG); else { pr_err("%s() Invalid Speaker Widget = %s\n", __func__, w->name); return -EINVAL; } } return 0; } static int msm_enable_codec_ext_clk(struct snd_soc_codec *codec, int enable, bool dapm) { int r = 0; pr_debug("%s: enable = %d\n", __func__, enable); mutex_lock(&cdc_mclk_mutex); if (enable) { clk_users++; pr_debug("%s: clk_users = %d\n", __func__, clk_users); if (clk_users == 1) { if (codec_clk) { clk_set_rate(codec_clk, TABLA_EXT_CLK_RATE); clk_prepare_enable(codec_clk); tabla_mclk_enable(codec, 1, dapm); } else { pr_err("%s: Error setting Tabla MCLK\n", __func__); clk_users--; r = -EINVAL; } } } else { if (clk_users > 0) { clk_users--; pr_debug("%s: clk_users = %d\n", __func__, clk_users); if (clk_users == 0) { pr_debug("%s: disabling MCLK. clk_users = %d\n", __func__, clk_users); tabla_mclk_enable(codec, 0, dapm); clk_disable_unprepare(codec_clk); } } else { pr_err("%s: Error releasing Tabla MCLK\n", __func__); r = -EINVAL; } } mutex_unlock(&cdc_mclk_mutex); return r; } static int msm_mclk_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { pr_debug("%s: event = %d\n", __func__, event); switch (event) { case SND_SOC_DAPM_PRE_PMU: return msm_enable_codec_ext_clk(w->codec, 1, true); case SND_SOC_DAPM_POST_PMD: return msm_enable_codec_ext_clk(w->codec, 0, true); } return 0; } enum { RX_SWITCH_INDEX = 0, TX_SWITCH_INDEX, SWITCH_MAX, }; static const struct snd_kcontrol_new extspk_switch_controls = SOC_DAPM_SINGLE("Switch", RX_SWITCH_INDEX, 0, 1, 0); static const struct snd_kcontrol_new earamp_switch_controls = SOC_DAPM_SINGLE("Switch", RX_SWITCH_INDEX, 0, 1, 0); static const struct snd_kcontrol_new spkamp_switch_controls = SOC_DAPM_SINGLE("Switch", RX_SWITCH_INDEX, 0, 1, 0); static const struct snd_kcontrol_new micbias3_switch_controls = SOC_DAPM_SINGLE("Switch", TX_SWITCH_INDEX, 0, 1, 0); static const struct snd_soc_dapm_widget elite_dapm_widgets[] = { SND_SOC_DAPM_MIXER("Lineout Mixer", SND_SOC_NOPM, 0, 0, NULL, 0), SND_SOC_DAPM_MIXER("SPK AMP EN", SND_SOC_NOPM, 0, 0, &spkamp_switch_controls, 1), SND_SOC_DAPM_MIXER("HAC AMP EN", SND_SOC_NOPM, 0, 0, &earamp_switch_controls, 1), SND_SOC_DAPM_MIXER("DOCK AMP EN", SND_SOC_NOPM, 0, 0, &extspk_switch_controls, 1), SND_SOC_DAPM_MIXER("DUAL MICBIAS", SND_SOC_NOPM, 0, 0, &micbias3_switch_controls, 1), }; static const struct snd_soc_dapm_widget msm_dapm_widgets[] = { SND_SOC_DAPM_SUPPLY("MCLK", SND_SOC_NOPM, 0, 0, msm_mclk_event, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_SPK("Ext Spk Bottom Pos", msm_spkramp_event), SND_SOC_DAPM_SPK("Ext Spk Bottom Neg", msm_spkramp_event), SND_SOC_DAPM_SPK("Ext Spk Top Pos", msm_spkramp_event), SND_SOC_DAPM_SPK("Ext Spk Top Neg", msm_spkramp_event), SND_SOC_DAPM_SPK("Dock Spk Pos", msm_spkramp_event), SND_SOC_DAPM_SPK("Dock Spk Neg", msm_spkramp_event), SND_SOC_DAPM_MIC("Handset Mic", NULL), SND_SOC_DAPM_MIC("Headset Mic", NULL), SND_SOC_DAPM_MIC("Back Mic", NULL), SND_SOC_DAPM_MIC("Digital Mic1", NULL), SND_SOC_DAPM_MIC("ANCRight Headset Mic", NULL), SND_SOC_DAPM_MIC("ANCLeft Headset Mic", NULL), SND_SOC_DAPM_MIC("Digital Mic1", NULL), SND_SOC_DAPM_MIC("Digital Mic2", NULL), SND_SOC_DAPM_MIC("Digital Mic3", NULL), SND_SOC_DAPM_MIC("Digital Mic4", NULL), SND_SOC_DAPM_MIC("Digital Mic5", NULL), SND_SOC_DAPM_MIC("Digital Mic6", NULL), }; static const struct snd_soc_dapm_route tabla_1_x_audio_map[] = { {"Lineout Mixer", NULL, "LINEOUT2"}, {"Lineout Mixer", NULL, "LINEOUT1"}, }; static const struct snd_soc_dapm_route tabla_2_x_audio_map[] = { {"Lineout Mixer", NULL, "LINEOUT3"}, {"Lineout Mixer", NULL, "LINEOUT1"}, }; static const struct snd_soc_dapm_route common_audio_map[] = { {"RX_BIAS", NULL, "MCLK"}, {"LDO_H", NULL, "MCLK"}, {"Ext Spk Bottom Pos", NULL, "SPK AMP EN"}, {"Ext Spk Bottom Neg", NULL, "SPK AMP EN"}, {"SPK AMP EN", "Switch", "Lineout Mixer"}, {"Ext Spk Top Pos", NULL, "HAC AMP EN"}, {"Ext Spk Top Neg", NULL, "HAC AMP EN"}, {"HAC AMP EN", "Switch", "Lineout Mixer"}, {"Dock Spk Pos", NULL, "DOCK AMP EN"}, {"Dock Spk Neg", NULL, "DOCK AMP EN"}, {"DOCK AMP EN", "Switch", "Lineout Mixer"}, {"AMIC1", NULL, "DUAL MICBIAS"}, {"DUAL MICBIAS", NULL, "MIC BIAS1 External"}, {"MIC BIAS1 External", NULL, "Handset Mic"}, {"DUAL MICBIAS", "Switch", "MIC BIAS3 External"}, {"AMIC2", NULL, "MIC BIAS2 External"}, {"MIC BIAS2 External", NULL, "Headset Mic"}, {"AMIC3", NULL, "MIC BIAS3 External"}, {"MIC BIAS3 External", NULL, "Back Mic"}, {"HEADPHONE", NULL, "LDO_H"}, }; static const char *spk_function[] = {"Off", "On"}; static const char *slim0_rx_ch_text[] = {"One", "Two"}; static const char *slim0_tx_ch_text[] = {"One", "Two", "Three", "Four"}; static const struct soc_enum msm_enum[] = { SOC_ENUM_SINGLE_EXT(2, spk_function), SOC_ENUM_SINGLE_EXT(2, slim0_rx_ch_text), SOC_ENUM_SINGLE_EXT(4, slim0_tx_ch_text), }; static const char *stereo_mic_voice[] = {"Off", "On"}; static const struct soc_enum elite_msm_enum[] = { SOC_ENUM_SINGLE_EXT(2, stereo_mic_voice), }; static const char *btsco_rate_text[] = {"8000", "16000"}; static const struct soc_enum msm_btsco_enum[] = { SOC_ENUM_SINGLE_EXT(2, btsco_rate_text), }; static const char *auxpcm_rate_text[] = {"rate_8000", "rate_16000"}; static const struct soc_enum msm_auxpcm_enum[] = { SOC_ENUM_SINGLE_EXT(2, auxpcm_rate_text), }; static int msm_slim_0_rx_ch_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { pr_debug("%s: msm_slim_0_rx_ch = %d\n", __func__, msm_slim_0_rx_ch); ucontrol->value.integer.value[0] = msm_slim_0_rx_ch - 1; return 0; } static int msm_slim_0_rx_ch_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { msm_slim_0_rx_ch = ucontrol->value.integer.value[0] + 1; pr_debug("%s: msm_slim_0_rx_ch = %d\n", __func__, msm_slim_0_rx_ch); return 1; } static int msm_slim_0_tx_ch_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { pr_debug("%s: msm_slim_0_tx_ch = %d\n", __func__, msm_slim_0_tx_ch); ucontrol->value.integer.value[0] = msm_slim_0_tx_ch - 1; return 0; } static int msm_slim_0_tx_ch_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { msm_slim_0_tx_ch = ucontrol->value.integer.value[0] + 1; pr_debug("%s: msm_slim_0_tx_ch = %d\n", __func__, msm_slim_0_tx_ch); return 1; } static int elite_stereo_voice_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { pr_debug("%s: elite_stereo_control = %d\n", __func__, elite_stereo_control); ucontrol->value.integer.value[0] = elite_stereo_control; return 0; } static int elite_stereo_voice_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { int ret = 0; struct pm_gpio param = { .direction = PM_GPIO_DIR_OUT, .output_buffer = PM_GPIO_OUT_BUF_CMOS, .output_value = 1, .pull = PM_GPIO_PULL_NO, .vin_sel = PM_GPIO_VIN_L17, .out_strength = PM_GPIO_STRENGTH_MED, .function = PM_GPIO_FUNC_NORMAL, }; if (elite_stereo_control == ucontrol->value.integer.value[0]) return 0; elite_stereo_control = ucontrol->value.integer.value[0]; pr_debug("%s: elite_stereo_control = %d\n", __func__, elite_stereo_control); switch (ucontrol->value.integer.value[0]) { case 0: gpio_direction_output(ELITE_AUD_STEREO_REC, 1); gpio_free(ELITE_AUD_STEREO_REC); break; case 1: ret = gpio_request(ELITE_AUD_STEREO_REC, "A1028_SWITCH"); if (ret) { pr_err("%s: Failed to request gpio %d\n", __func__, ELITE_AUD_STEREO_REC); return ret; } ret = pm8xxx_gpio_config(ELITE_AUD_STEREO_REC, &param); if (ret) pr_err("%s: Failed to configure gpio %d\n", __func__, ELITE_AUD_STEREO_REC); else gpio_direction_output(ELITE_AUD_STEREO_REC, 0); break; } return ret; } static int msm_btsco_rate_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { pr_debug("%s: msm_btsco_rate = %d", __func__, msm_btsco_rate); ucontrol->value.integer.value[0] = msm_btsco_rate; return 0; } static int msm_btsco_rate_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { switch (ucontrol->value.integer.value[0]) { case 0: msm_btsco_rate = SAMPLE_RATE_8KHZ; break; case 1: msm_btsco_rate = SAMPLE_RATE_16KHZ; break; default: msm_btsco_rate = SAMPLE_RATE_8KHZ; break; } pr_debug("%s: msm_btsco_rate = %d\n", __func__, msm_btsco_rate); return 0; } static int msm_auxpcm_rate_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { pr_debug("%s: msm_auxpcm_rate = %d", __func__, msm_auxpcm_rate); ucontrol->value.integer.value[0] = msm_auxpcm_rate; return 0; } static int msm_auxpcm_rate_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { switch (ucontrol->value.integer.value[0]) { case 0: msm_auxpcm_rate = SAMPLE_RATE_8KHZ; break; case 1: msm_auxpcm_rate = SAMPLE_RATE_16KHZ; break; default: msm_auxpcm_rate = SAMPLE_RATE_8KHZ; break; } pr_debug("%s: msm_auxpcm_rate = %d" "ucontrol->value.integer.value[0] = %d\n", __func__, msm_auxpcm_rate, (int)ucontrol->value.integer.value[0]); return 0; } static const struct snd_kcontrol_new tabla_msm_controls[] = { SOC_ENUM_EXT("Speaker Function", msm_enum[0], msm_get_spk, msm_set_spk), SOC_ENUM_EXT("SLIM_0_RX Channels", msm_enum[1], msm_slim_0_rx_ch_get, msm_slim_0_rx_ch_put), SOC_ENUM_EXT("SLIM_0_TX Channels", msm_enum[2], msm_slim_0_tx_ch_get, msm_slim_0_tx_ch_put), SOC_ENUM_EXT("Internal BTSCO SampleRate", msm_btsco_enum[0], msm_btsco_rate_get, msm_btsco_rate_put), SOC_ENUM_EXT("AUX PCM SampleRate", msm_auxpcm_enum[0], msm_auxpcm_rate_get, msm_auxpcm_rate_put), SOC_ENUM_EXT("Stereo Selection", elite_msm_enum[0], elite_stereo_voice_get, elite_stereo_voice_put), }; static int msm_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_dai *codec_dai = rtd->codec_dai; struct snd_soc_dai *cpu_dai = rtd->cpu_dai; int ret = 0; unsigned int rx_ch[SLIM_MAX_RX_PORTS], tx_ch[SLIM_MAX_TX_PORTS]; unsigned int rx_ch_cnt = 0, tx_ch_cnt = 0; if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { pr_debug("%s: %s rx_dai_id = %d num_ch = %d\n", __func__, codec_dai->name, codec_dai->id, msm_slim_0_rx_ch); ret = snd_soc_dai_get_channel_map(codec_dai, &tx_ch_cnt, tx_ch, &rx_ch_cnt , rx_ch); if (ret < 0) { pr_err("%s: failed to get codec chan map\n", __func__); goto end; } ret = snd_soc_dai_set_channel_map(cpu_dai, 0, 0, msm_slim_0_rx_ch, rx_ch); if (ret < 0) { pr_err("%s: failed to set cpu chan map\n", __func__); goto end; } ret = snd_soc_dai_set_channel_map(codec_dai, 0, 0, msm_slim_0_rx_ch, rx_ch); if (ret < 0) { pr_err("%s: failed to set codec channel map\n", __func__); goto end; } } else { pr_debug("%s: %s tx_dai_id = %d num_ch = %d\n", __func__, codec_dai->name, codec_dai->id, msm_slim_0_tx_ch); ret = snd_soc_dai_get_channel_map(codec_dai, &tx_ch_cnt, tx_ch, &rx_ch_cnt , rx_ch); if (ret < 0) { pr_err("%s: failed to get codec chan map\n", __func__); goto end; } ret = snd_soc_dai_set_channel_map(cpu_dai, msm_slim_0_tx_ch, tx_ch, 0 , 0); if (ret < 0) { pr_err("%s: failed to set cpu chan map\n", __func__); goto end; } ret = snd_soc_dai_set_channel_map(codec_dai, msm_slim_0_tx_ch, tx_ch, 0, 0); if (ret < 0) { pr_err("%s: failed to set codec channel map\n", __func__); goto end; } } end: return ret; } static int msm_slimbus_2_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_dai *codec_dai = rtd->codec_dai; struct snd_soc_dai *cpu_dai = rtd->cpu_dai; int ret = 0; unsigned int rx_ch[SLIM_MAX_RX_PORTS], tx_ch[SLIM_MAX_TX_PORTS]; unsigned int rx_ch_cnt = 0, tx_ch_cnt = 0; unsigned int num_tx_ch = 0; unsigned int num_rx_ch = 0; if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { num_rx_ch = params_channels(params); pr_debug("%s: %s rx_dai_id = %d num_ch = %d\n", __func__, codec_dai->name, codec_dai->id, num_rx_ch); ret = snd_soc_dai_get_channel_map(codec_dai, &tx_ch_cnt, tx_ch, &rx_ch_cnt , rx_ch); if (ret < 0) { pr_err("%s: failed to get codec chan map\n", __func__); goto end; } ret = snd_soc_dai_set_channel_map(cpu_dai, 0, 0, num_rx_ch, rx_ch); if (ret < 0) { pr_err("%s: failed to set cpu chan map\n", __func__); goto end; } ret = snd_soc_dai_set_channel_map(codec_dai, 0, 0, num_rx_ch, rx_ch); if (ret < 0) { pr_err("%s: failed to set codec channel map\n", __func__); goto end; } } else { num_tx_ch = params_channels(params); pr_debug("%s: %s tx_dai_id = %d num_ch = %d\n", __func__, codec_dai->name, codec_dai->id, num_tx_ch); ret = snd_soc_dai_get_channel_map(codec_dai, &tx_ch_cnt, tx_ch, &rx_ch_cnt , rx_ch); if (ret < 0) { pr_err("%s: failed to get codec chan map\n", __func__); goto end; } ret = snd_soc_dai_set_channel_map(cpu_dai, num_tx_ch, tx_ch, 0 , 0); if (ret < 0) { pr_err("%s: failed to set cpu chan map\n", __func__); goto end; } ret = snd_soc_dai_set_channel_map(codec_dai, num_tx_ch, tx_ch, 0, 0); if (ret < 0) { pr_err("%s: failed to set codec channel map\n", __func__); goto end; } } end: return ret; } static int msm_audrx_init(struct snd_soc_pcm_runtime *rtd) { int err; struct snd_soc_codec *codec = rtd->codec; struct snd_soc_dapm_context *dapm = &codec->dapm; struct snd_soc_dai *cpu_dai = rtd->cpu_dai; pr_debug("%s(), dev_name: %s\n", __func__, dev_name(cpu_dai->dev)); snd_soc_dapm_new_controls(dapm, msm_dapm_widgets, ARRAY_SIZE(msm_dapm_widgets)); snd_soc_dapm_new_controls(dapm, elite_dapm_widgets, ARRAY_SIZE(elite_dapm_widgets)); snd_soc_dapm_add_routes(dapm, common_audio_map, ARRAY_SIZE(common_audio_map)); pr_debug("%s(), %s\n", __func__, codec->name); if (!strncmp(codec->name, "tabla1x_codec", 13)) snd_soc_dapm_add_routes(dapm, tabla_1_x_audio_map, ARRAY_SIZE(tabla_1_x_audio_map)); else snd_soc_dapm_add_routes(dapm, tabla_2_x_audio_map, ARRAY_SIZE(tabla_2_x_audio_map)); snd_soc_dapm_enable_pin(dapm, "Ext Spk Bottom Pos"); snd_soc_dapm_enable_pin(dapm, "Ext Spk Bottom Neg"); snd_soc_dapm_enable_pin(dapm, "Ext Spk Top Pos"); snd_soc_dapm_enable_pin(dapm, "Ext Spk Top Neg"); snd_soc_dapm_enable_pin(dapm, "Dock Spk Pos"); snd_soc_dapm_enable_pin(dapm, "Dock Spk Neg"); snd_soc_dapm_sync(dapm); err = snd_soc_jack_new(codec, "Headset Jack", (SND_JACK_HEADSET | SND_JACK_OC_HPHL | SND_JACK_OC_HPHR | SND_JACK_UNSUPPORTED), &hs_jack); if (err) { pr_err("failed to create new jack\n"); return err; } err = snd_soc_jack_new(codec, "Button Jack", TABLA_JACK_BUTTON_MASK, &button_jack); if (err) { pr_err("failed to create new jack\n"); return err; } codec_clk = clk_get(cpu_dai->dev, "osr_clk"); return err; } static int msm_slim_0_rx_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd, struct snd_pcm_hw_params *params) { struct snd_interval *rate = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE); struct snd_interval *channels = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS); pr_debug("%s()\n", __func__); rate->min = rate->max = 48000; channels->min = channels->max = msm_slim_0_rx_ch; return 0; } static int msm_slim_0_tx_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd, struct snd_pcm_hw_params *params) { struct snd_interval *rate = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE); struct snd_interval *channels = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS); pr_debug("%s()\n", __func__); rate->min = rate->max = 48000; channels->min = channels->max = msm_slim_0_tx_ch; return 0; } static int msm_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd, struct snd_pcm_hw_params *params) { struct snd_interval *rate = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE); pr_debug("%s()\n", __func__); rate->min = rate->max = 48000; return 0; } static int msm_hdmi_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd, struct snd_pcm_hw_params *params) { struct snd_interval *rate = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE); struct snd_interval *channels = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS); pr_debug("%s channels->min %u channels->max %u ()\n", __func__, channels->min, channels->max); rate->min = rate->max = 48000; return 0; } static int msm_btsco_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd, struct snd_pcm_hw_params *params) { struct snd_interval *rate = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE); struct snd_interval *channels = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS); rate->min = rate->max = msm_btsco_rate; channels->min = channels->max = msm_btsco_ch; return 0; } static int msm_auxpcm_be_params_fixup(struct snd_soc_pcm_runtime *rtd, struct snd_pcm_hw_params *params) { struct snd_interval *rate = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE); struct snd_interval *channels = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS); rate->min = rate->max = msm_auxpcm_rate; channels->min = channels->max = 1; return 0; } static int msm_aux_pcm_get_gpios(void) { int ret = 0; pr_debug("%s\n", __func__); ret = gpio_request(GPIO_AUX_PCM_DOUT, "AUX PCM DOUT"); if (ret < 0) { pr_err("%s: Failed to request gpio(%d): AUX PCM DOUT", __func__, GPIO_AUX_PCM_DOUT); goto fail_dout; } ret = gpio_request(GPIO_AUX_PCM_DIN, "AUX PCM DIN"); if (ret < 0) { pr_err("%s: Failed to request gpio(%d): AUX PCM DIN", __func__, GPIO_AUX_PCM_DIN); goto fail_din; } ret = gpio_request(GPIO_AUX_PCM_SYNC, "AUX PCM SYNC"); if (ret < 0) { pr_err("%s: Failed to request gpio(%d): AUX PCM SYNC", __func__, GPIO_AUX_PCM_SYNC); goto fail_sync; } ret = gpio_request(GPIO_AUX_PCM_CLK, "AUX PCM CLK"); if (ret < 0) { pr_err("%s: Failed to request gpio(%d): AUX PCM CLK", __func__, GPIO_AUX_PCM_CLK); goto fail_clk; } return 0; fail_clk: gpio_free(GPIO_AUX_PCM_SYNC); fail_sync: gpio_free(GPIO_AUX_PCM_DIN); fail_din: gpio_free(GPIO_AUX_PCM_DOUT); fail_dout: return ret; } static int msm_aux_pcm_free_gpios(void) { gpio_free(GPIO_AUX_PCM_DIN); gpio_free(GPIO_AUX_PCM_DOUT); gpio_free(GPIO_AUX_PCM_SYNC); gpio_free(GPIO_AUX_PCM_CLK); return 0; } static int msm_startup(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *rtd = substream->private_data; pr_debug("%s(): dai_link_str_name = %s cpu_dai = %s codec_dai = %s\n", __func__, rtd->dai_link->stream_name, rtd->dai_link->cpu_dai_name, rtd->dai_link->codec_dai_name); return 0; } static int msm_auxpcm_startup(struct snd_pcm_substream *substream) { int ret = 0; pr_debug("%s(): substream = %s\n", __func__, substream->name); ret = msm_aux_pcm_get_gpios(); if (ret < 0) { pr_err("%s: Aux PCM GPIO request failed\n", __func__); return -EINVAL; } return 0; } static void msm_auxpcm_shutdown(struct snd_pcm_substream *substream) { pr_debug("%s(): substream = %s\n", __func__, substream->name); msm_aux_pcm_free_gpios(); } static void msm_shutdown(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *rtd = substream->private_data; pr_debug("%s(): dai_link str_name = %s cpu_dai = %s codec_dai = %s\n", __func__, rtd->dai_link->stream_name, rtd->dai_link->cpu_dai_name, rtd->dai_link->codec_dai_name); } static struct snd_soc_ops msm_be_ops = { .startup = msm_startup, .hw_params = msm_hw_params, .shutdown = msm_shutdown, }; static struct snd_soc_ops msm_auxpcm_be_ops = { .startup = msm_auxpcm_startup, .shutdown = msm_auxpcm_shutdown, }; static struct snd_soc_ops msm_slimbus_2_be_ops = { .startup = msm_startup, .hw_params = msm_slimbus_2_hw_params, .shutdown = msm_shutdown, }; static struct snd_soc_dai_link msm_dai_common[] = { { .name = "MSM8960 Media1", .stream_name = "MultiMedia1", .cpu_dai_name = "MultiMedia1", .platform_name = "msm-pcm-dsp", .dynamic = 1, .codec_dai_name = "snd-soc-dummy-dai", .codec_name = "snd-soc-dummy", .trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .ignore_suspend = 1, .ignore_pmdown_time = 1, .be_id = MSM_FRONTEND_DAI_MULTIMEDIA1 }, { .name = "MSM8960 Media2", .stream_name = "MultiMedia2", .cpu_dai_name = "MultiMedia2", .platform_name = "msm-multi-ch-pcm-dsp", .dynamic = 1, .codec_dai_name = "snd-soc-dummy-dai", .codec_name = "snd-soc-dummy", .trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .ignore_suspend = 1, .ignore_pmdown_time = 1, .be_id = MSM_FRONTEND_DAI_MULTIMEDIA2, }, { .name = "Circuit-Switch Voice", .stream_name = "CS-Voice", .cpu_dai_name = "CS-VOICE", .platform_name = "msm-pcm-voice", .dynamic = 1, .codec_dai_name = "snd-soc-dummy-dai", .codec_name = "snd-soc-dummy", .trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .no_host_mode = SND_SOC_DAI_LINK_NO_HOST, .ignore_suspend = 1, .ignore_pmdown_time = 1, .be_id = MSM_FRONTEND_DAI_CS_VOICE, }, { .name = "MSM VoIP", .stream_name = "VoIP", .cpu_dai_name = "VoIP", .platform_name = "msm-voip-dsp", .dynamic = 1, .trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .codec_dai_name = "snd-soc-dummy-dai", .codec_name = "snd-soc-dummy", .ignore_suspend = 1, .ignore_pmdown_time = 1, .be_id = MSM_FRONTEND_DAI_VOIP, }, { .name = "MSM8960 LPA", .stream_name = "LPA", .cpu_dai_name = "MultiMedia3", .platform_name = "msm-pcm-lpa", .dynamic = 1, .trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .codec_dai_name = "snd-soc-dummy-dai", .codec_name = "snd-soc-dummy", .ignore_suspend = 1, .ignore_pmdown_time = 1, .be_id = MSM_FRONTEND_DAI_MULTIMEDIA3, }, { .name = "SLIMBUS_0 Hostless", .stream_name = "SLIMBUS_0 Hostless", .cpu_dai_name = "SLIMBUS0_HOSTLESS", .platform_name = "msm-pcm-hostless", .dynamic = 1, .trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .no_host_mode = SND_SOC_DAI_LINK_NO_HOST, .ignore_suspend = 1, .ignore_pmdown_time = 1, .codec_dai_name = "snd-soc-dummy-dai", .codec_name = "snd-soc-dummy", }, { .name = "INT_FM Hostless", .stream_name = "INT_FM Hostless", .cpu_dai_name = "INT_FM_HOSTLESS", .platform_name = "msm-pcm-hostless", .dynamic = 1, .trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .no_host_mode = SND_SOC_DAI_LINK_NO_HOST, .ignore_suspend = 1, .ignore_pmdown_time = 1, .codec_dai_name = "snd-soc-dummy-dai", .codec_name = "snd-soc-dummy", }, { .name = "MSM AFE-PCM RX", .stream_name = "AFE-PROXY RX", .cpu_dai_name = "msm-dai-q6.241", .codec_name = "msm-stub-codec.1", .codec_dai_name = "msm-stub-rx", .platform_name = "msm-pcm-afe", .ignore_suspend = 1, .ignore_pmdown_time = 1, }, { .name = "MSM AFE-PCM TX", .stream_name = "AFE-PROXY TX", .cpu_dai_name = "msm-dai-q6.240", .codec_name = "msm-stub-codec.1", .codec_dai_name = "msm-stub-tx", .platform_name = "msm-pcm-afe", .ignore_suspend = 1, }, { .name = "MSM8960 Compr", .stream_name = "COMPR", .cpu_dai_name = "MultiMedia4", .platform_name = "msm-compr-dsp", .dynamic = 1, .trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .codec_dai_name = "snd-soc-dummy-dai", .codec_name = "snd-soc-dummy", .ignore_suspend = 1, .ignore_pmdown_time = 1, .be_id = MSM_FRONTEND_DAI_MULTIMEDIA4, }, { .name = "AUXPCM Hostless", .stream_name = "AUXPCM Hostless", .cpu_dai_name = "AUXPCM_HOSTLESS", .platform_name = "msm-pcm-hostless", .dynamic = 1, .trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .no_host_mode = SND_SOC_DAI_LINK_NO_HOST, .ignore_suspend = 1, .ignore_pmdown_time = 1, .codec_dai_name = "snd-soc-dummy-dai", .codec_name = "snd-soc-dummy", }, { .name = "HDMI_RX_HOSTLESS", .stream_name = "HDMI_RX_HOSTLESS", .cpu_dai_name = "HDMI_HOSTLESS", .platform_name = "msm-pcm-hostless", .dynamic = 1, .trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .no_host_mode = SND_SOC_DAI_LINK_NO_HOST, .ignore_suspend = 1, .ignore_pmdown_time = 1, .codec_dai_name = "snd-soc-dummy-dai", .codec_name = "snd-soc-dummy", }, { .name = "VoLTE", .stream_name = "VoLTE", .cpu_dai_name = "VoLTE", .platform_name = "msm-pcm-voice", .dynamic = 1, .trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .no_host_mode = SND_SOC_DAI_LINK_NO_HOST, .ignore_suspend = 1, .ignore_pmdown_time = 1, .codec_dai_name = "snd-soc-dummy-dai", .codec_name = "snd-soc-dummy", .be_id = MSM_FRONTEND_DAI_VOLTE, }, { .name = "Voice2", .stream_name = "Voice2", .cpu_dai_name = "Voice2", .platform_name = "msm-pcm-voice", .dynamic = 1, .trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .no_host_mode = SND_SOC_DAI_LINK_NO_HOST, .ignore_suspend = 1, .ignore_pmdown_time = 1, .codec_dai_name = "snd-soc-dummy-dai", .codec_name = "snd-soc-dummy", .be_id = MSM_FRONTEND_DAI_VOICE2, }, { .name = "MSM8960 LowLatency", .stream_name = "MultiMedia5", .cpu_dai_name = "MultiMedia5", .platform_name = "msm-lowlatency-pcm-dsp", .dynamic = 1, .codec_dai_name = "snd-soc-dummy-dai", .codec_name = "snd-soc-dummy", .trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .ignore_suspend = 1, /* this dainlink has playback support */ .ignore_pmdown_time = 1, .be_id = MSM_FRONTEND_DAI_MULTIMEDIA5, }, { .name = LPASS_BE_INT_BT_SCO_RX, .stream_name = "Internal BT-SCO Playback", .cpu_dai_name = "msm-dai-q6.12288", .platform_name = "msm-pcm-routing", .codec_name = "msm-stub-codec.1", .codec_dai_name = "msm-stub-rx", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_INT_BT_SCO_RX, .be_hw_params_fixup = msm_btsco_be_hw_params_fixup, .ignore_pmdown_time = 1, }, { .name = LPASS_BE_INT_BT_SCO_TX, .stream_name = "Internal BT-SCO Capture", .cpu_dai_name = "msm-dai-q6.12289", .platform_name = "msm-pcm-routing", .codec_name = "msm-stub-codec.1", .codec_dai_name = "msm-stub-tx", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_INT_BT_SCO_TX, .be_hw_params_fixup = msm_btsco_be_hw_params_fixup, }, { .name = LPASS_BE_INT_FM_RX, .stream_name = "Internal FM Playback", .cpu_dai_name = "msm-dai-q6.12292", .platform_name = "msm-pcm-routing", .codec_name = "msm-stub-codec.1", .codec_dai_name = "msm-stub-rx", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_INT_FM_RX, .be_hw_params_fixup = msm_be_hw_params_fixup, .ignore_pmdown_time = 1, }, { .name = LPASS_BE_INT_FM_TX, .stream_name = "Internal FM Capture", .cpu_dai_name = "msm-dai-q6.12293", .platform_name = "msm-pcm-routing", .codec_name = "msm-stub-codec.1", .codec_dai_name = "msm-stub-tx", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_INT_FM_TX, .be_hw_params_fixup = msm_be_hw_params_fixup, }, { .name = LPASS_BE_HDMI, .stream_name = "HDMI Playback", .cpu_dai_name = "msm-dai-q6-hdmi.8", .platform_name = "msm-pcm-routing", .codec_name = "msm-stub-codec.1", .codec_dai_name = "msm-stub-rx", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_HDMI_RX, .be_hw_params_fixup = msm_hdmi_be_hw_params_fixup, .ignore_pmdown_time = 1, }, { .name = LPASS_BE_AFE_PCM_RX, .stream_name = "AFE Playback", .cpu_dai_name = "msm-dai-q6.224", .platform_name = "msm-pcm-routing", .codec_name = "msm-stub-codec.1", .codec_dai_name = "msm-stub-rx", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_AFE_PCM_RX, .ignore_pmdown_time = 1, }, { .name = LPASS_BE_AFE_PCM_TX, .stream_name = "AFE Capture", .cpu_dai_name = "msm-dai-q6.225", .platform_name = "msm-pcm-routing", .codec_name = "msm-stub-codec.1", .codec_dai_name = "msm-stub-tx", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_AFE_PCM_TX, }, { .name = LPASS_BE_AUXPCM_RX, .stream_name = "AUX PCM Playback", .cpu_dai_name = "msm-dai-q6.2", .platform_name = "msm-pcm-routing", .codec_name = "msm-stub-codec.1", .codec_dai_name = "msm-stub-rx", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_AUXPCM_RX, .be_hw_params_fixup = msm_auxpcm_be_params_fixup, .ops = &msm_auxpcm_be_ops, .ignore_pmdown_time = 1, }, { .name = LPASS_BE_AUXPCM_TX, .stream_name = "AUX PCM Capture", .cpu_dai_name = "msm-dai-q6.3", .platform_name = "msm-pcm-routing", .codec_name = "msm-stub-codec.1", .codec_dai_name = "msm-stub-tx", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_AUXPCM_TX, .be_hw_params_fixup = msm_auxpcm_be_params_fixup, }, { .name = LPASS_BE_VOICE_PLAYBACK_TX, .stream_name = "Voice Farend Playback", .cpu_dai_name = "msm-dai-q6.32773", .platform_name = "msm-pcm-routing", .codec_name = "msm-stub-codec.1", .codec_dai_name = "msm-stub-rx", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_VOICE_PLAYBACK_TX, .be_hw_params_fixup = msm_be_hw_params_fixup, }, { .name = LPASS_BE_INCALL_RECORD_TX, .stream_name = "Voice Uplink Capture", .cpu_dai_name = "msm-dai-q6.32772", .platform_name = "msm-pcm-routing", .codec_name = "msm-stub-codec.1", .codec_dai_name = "msm-stub-tx", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_INCALL_RECORD_TX, .be_hw_params_fixup = msm_be_hw_params_fixup, }, { .name = LPASS_BE_INCALL_RECORD_RX, .stream_name = "Voice Downlink Capture", .cpu_dai_name = "msm-dai-q6.32771", .platform_name = "msm-pcm-routing", .codec_name = "msm-stub-codec.1", .codec_dai_name = "msm-stub-tx", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_INCALL_RECORD_RX, .be_hw_params_fixup = msm_be_hw_params_fixup, .ignore_pmdown_time = 1, }, { .name = "MSM8960 Media6", .stream_name = "MultiMedia6", .cpu_dai_name = "MultiMedia6", .platform_name = "msm-multi-ch-pcm-dsp", .dynamic = 1, .trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .codec_dai_name = "snd-soc-dummy-dai", .codec_name = "snd-soc-dummy", .ignore_suspend = 1, .ignore_pmdown_time = 1, .be_id = MSM_FRONTEND_DAI_MULTIMEDIA6 }, { .name = "MSM8960 Compr2", .stream_name = "COMPR2", .cpu_dai_name = "MultiMedia7", .platform_name = "msm-compr-dsp", .dynamic = 1, .trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .codec_dai_name = "snd-soc-dummy-dai", .codec_name = "snd-soc-dummy", .ignore_suspend = 1, .ignore_pmdown_time = 1, .be_id = MSM_FRONTEND_DAI_MULTIMEDIA7, }, { .name = "MSM8960 Compr3", .stream_name = "COMPR3", .cpu_dai_name = "MultiMedia8", .platform_name = "msm-compr-dsp", .dynamic = 1, .trigger = {SND_SOC_DPCM_TRIGGER_POST, SND_SOC_DPCM_TRIGGER_POST}, .codec_dai_name = "snd-soc-dummy-dai", .codec_name = "snd-soc-dummy", .ignore_suspend = 1, .ignore_pmdown_time = 1, .be_id = MSM_FRONTEND_DAI_MULTIMEDIA8, }, }; static struct snd_soc_dai_link msm_dai_delta_tabla1x[] = { { .name = LPASS_BE_SLIMBUS_0_RX, .stream_name = "Slimbus Playback", .cpu_dai_name = "msm-dai-q6.16384", .platform_name = "msm-pcm-routing", .codec_name = "tabla1x_codec", .codec_dai_name = "tabla_rx1", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_SLIMBUS_0_RX, .init = &msm_audrx_init, .be_hw_params_fixup = msm_slim_0_rx_be_hw_params_fixup, .ops = &msm_be_ops, .ignore_pmdown_time = 1, }, { .name = LPASS_BE_SLIMBUS_0_TX, .stream_name = "Slimbus Capture", .cpu_dai_name = "msm-dai-q6.16385", .platform_name = "msm-pcm-routing", .codec_name = "tabla1x_codec", .codec_dai_name = "tabla_tx1", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_SLIMBUS_0_TX, .be_hw_params_fixup = msm_slim_0_tx_be_hw_params_fixup, .ops = &msm_be_ops, }, { .name = "SLIMBUS_2 Hostless Capture", .stream_name = "SLIMBUS_2 Hostless Capture", .cpu_dai_name = "msm-dai-q6.16389", .platform_name = "msm-pcm-hostless", .codec_name = "tabla1x_codec", .codec_dai_name = "tabla_tx2", .ignore_suspend = 1, .no_host_mode = SND_SOC_DAI_LINK_NO_HOST, .ops = &msm_slimbus_2_be_ops, }, { .name = "SLIMBUS_2 Hostless Playback", .stream_name = "SLIMBUS_2 Hostless Playback", .cpu_dai_name = "msm-dai-q6.16388", .platform_name = "msm-pcm-hostless", .codec_name = "tabla1x_codec", .codec_dai_name = "tabla_rx3", .ignore_suspend = 1, .no_host_mode = SND_SOC_DAI_LINK_NO_HOST, .ops = &msm_slimbus_2_be_ops, }, }; static struct snd_soc_dai_link msm_dai_delta_tabla2x[] = { { .name = LPASS_BE_SLIMBUS_0_RX, .stream_name = "Slimbus Playback", .cpu_dai_name = "msm-dai-q6.16384", .platform_name = "msm-pcm-routing", .codec_name = "tabla_codec", .codec_dai_name = "tabla_rx1", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_SLIMBUS_0_RX, .init = &msm_audrx_init, .be_hw_params_fixup = msm_slim_0_rx_be_hw_params_fixup, .ops = &msm_be_ops, .ignore_pmdown_time = 1, }, { .name = LPASS_BE_SLIMBUS_0_TX, .stream_name = "Slimbus Capture", .cpu_dai_name = "msm-dai-q6.16385", .platform_name = "msm-pcm-routing", .codec_name = "tabla_codec", .codec_dai_name = "tabla_tx1", .no_pcm = 1, .be_id = MSM_BACKEND_DAI_SLIMBUS_0_TX, .be_hw_params_fixup = msm_slim_0_tx_be_hw_params_fixup, .ops = &msm_be_ops, }, { .name = "SLIMBUS_2 Hostless Capture", .stream_name = "SLIMBUS_2 Hostless Capture", .cpu_dai_name = "msm-dai-q6.16389", .platform_name = "msm-pcm-hostless", .codec_name = "tabla_codec", .codec_dai_name = "tabla_tx2", .ignore_suspend = 1, .no_host_mode = SND_SOC_DAI_LINK_NO_HOST, .ops = &msm_slimbus_2_be_ops, }, { .name = "SLIMBUS_2 Hostless Playback", .stream_name = "SLIMBUS_2 Hostless Playback", .cpu_dai_name = "msm-dai-q6.16388", .platform_name = "msm-pcm-hostless", .codec_name = "tabla_codec", .codec_dai_name = "tabla_rx3", .ignore_suspend = 1, .no_host_mode = SND_SOC_DAI_LINK_NO_HOST, .ops = &msm_slimbus_2_be_ops, }, }; static struct snd_soc_dai_link msm_tabla1x_dai[ ARRAY_SIZE(msm_dai_common) + ARRAY_SIZE(msm_dai_delta_tabla1x)]; static struct snd_soc_dai_link msm_dai[ ARRAY_SIZE(msm_dai_common) + ARRAY_SIZE(msm_dai_delta_tabla2x)]; static struct snd_soc_card snd_soc_tabla1x_card_msm = { .name = "msm-tabla1x-snd-card", .dai_link = msm_tabla1x_dai, .num_links = ARRAY_SIZE(msm_tabla1x_dai), .controls = tabla_msm_controls, .num_controls = ARRAY_SIZE(tabla_msm_controls), }; static struct snd_soc_card snd_soc_card_msm = { .name = "msm-snd-card", .dai_link = msm_dai, .num_links = ARRAY_SIZE(msm_dai), .controls = tabla_msm_controls, .num_controls = ARRAY_SIZE(tabla_msm_controls), }; static struct platform_device *msm_snd_device; static struct platform_device *msm_snd_tabla1x_device; static int __init elite_audio_init(void) { int ret; if (!cpu_is_msm8960()) { pr_err("%s: Not the right machine type\n", __func__); return -ENODEV; } pr_debug("%s", __func__); msm_snd_device = platform_device_alloc("soc-audio", 0); if (!msm_snd_device) { pr_err("Platform device allocation failed\n"); return -ENOMEM; } memcpy(msm_dai, msm_dai_common, sizeof(msm_dai_common)); memcpy(msm_dai + ARRAY_SIZE(msm_dai_common), msm_dai_delta_tabla2x, sizeof(msm_dai_delta_tabla2x)); platform_set_drvdata(msm_snd_device, &snd_soc_card_msm); ret = platform_device_add(msm_snd_device); if (ret) { platform_device_put(msm_snd_device); return ret; } msm_snd_tabla1x_device = platform_device_alloc("soc-audio", 1); if (!msm_snd_tabla1x_device) { pr_err("Platform device allocation failed\n"); return -ENOMEM; } memcpy(msm_tabla1x_dai, msm_dai_common, sizeof(msm_dai_common)); memcpy(msm_tabla1x_dai + ARRAY_SIZE(msm_dai_common), msm_dai_delta_tabla1x, sizeof(msm_dai_delta_tabla1x)); platform_set_drvdata(msm_snd_tabla1x_device, &snd_soc_tabla1x_card_msm); ret = platform_device_add(msm_snd_tabla1x_device); if (ret) { platform_device_put(msm_snd_tabla1x_device); return ret; } mutex_init(&audio_notifier_lock); pr_debug("%s: register cable detect func for dock", __func__); ret = cable_detect_register_notifier(&audio_dock_notifier); mutex_init(&cdc_mclk_mutex); return ret; } late_initcall(elite_audio_init); static void __exit elite_audio_exit(void) { if (!cpu_is_msm8960()) { pr_err("%s: Not the right machine type\n", __func__); return; } pr_debug("%s", __func__); platform_device_unregister(msm_snd_device); platform_device_unregister(msm_snd_tabla1x_device); mutex_destroy(&audio_notifier_lock); mutex_destroy(&cdc_mclk_mutex); } module_exit(elite_audio_exit); MODULE_DESCRIPTION("ALSA Platform Elite"); MODULE_LICENSE("GPL v2");
kbc-developers/android_kernel_htc_msm8960
arch/arm/mach-msm/htc/elite/board-elite-audio.c
C
gpl-2.0
49,618
<?php /** * This file is part of the ramsey/uuid library * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> * @license http://opensource.org/licenses/MIT MIT * @link https://benramsey.com/projects/ramsey-uuid/ Documentation * @link https://packagist.org/packages/ramsey/uuid Packagist * @link https://github.com/ramsey/uuid GitHub */ namespace Ramsey\Uuid\Provider\Node; use Ramsey\Uuid\Provider\NodeProviderInterface; /** * FallbackNodeProvider attempts to gain the system host ID from an array of * providers, falling back to the next in line in the event a host ID can not be * obtained */ class FallbackNodeProvider implements NodeProviderInterface { /** * @var NodeProviderInterface[] */ private $nodeProviders; /** * Constructs a `FallbackNodeProvider` using an array of node providers * * @param NodeProviderInterface[] $providers Array of node providers */ public function __construct(array $providers) { $this->nodeProviders = $providers; } /** * Returns the system node ID by iterating over an array of node providers * and returning the first non-empty value found * * @return string System node ID as a hexadecimal string * @throws \Exception */ public function getNode() { foreach ($this->nodeProviders as $provider) { if ($node = $provider->getNode()) { return $node; } } return null; } }
matrix-msu/kora
vendor/ramsey/uuid/src/Provider/Node/FallbackNodeProvider.php
PHP
gpl-2.0
1,632
## # This file is part of WhatWeb and may be subject to # redistribution and commercial restrictions. Please see the WhatWeb # web site for more information on licensing and terms of use. # http://www.morningstarsecurity.com/research/whatweb ## Plugin.define "SQLiteManager" do author "Brendan Coles <bcoles@gmail.com>" # 2012-01-14 version "0.1" description "SQLiteManager - Web-based SQLite administration - Homepage: http://www.sqlitemanager.org" # Google results as at 2012-01-14 # # 33 for intitle:"SQLite version" "Welcome to SQLiteManager version" # 26 for inurl:"main.php?dbsel=" # Dorks # dorks [ 'intitle:"SQLite version" "Welcome to SQLiteManager version"' ] # Matches # matches [ # HTML Comments { :text=>'<!-- SQLiteFunctionProperties.class.php : propView() -->' }, { :text=>'<!-- common.lib.php : displayMenuTitle() -->' }, # Form { :text=>'<td style="white-space: nowrap"> <form name="database" action="main.php" enctype="multipart/form-data" method="POST" onSubmit="checkPath();" target="main">' }, # h2 class="sqlmVersion" { :text=>'<h2 class="sqlmVersion">Database : <a href="main.php?dbsel=' }, # Title # SQLite Version Detection { :string=>/<title>(SQLite version [\d\.\s-]+)(undefined)?<\/title>/ }, # h2 class="sqlmVersion" # Version Detection { :version=>/<h2 class="sqlmVersion">Welcome to <a href="http:\/\/www\.sqlitemanager\.org" target="_blank">SQLiteManager<\/a> version ([^\s^>]+)<\/h2>/ }, # h4 class="serverInfo" # SQLite Version Detection { :string=>/<h4 class="serverInfo">(SQLite version [\d\.\s-]+)(undefined)? \/ PHP version 5.2.17<\/h4>/ }, # h4 class="serverInfo" # SQLite Version Detection { :string=>/<h4 class="serverInfo">SQLite version [\d\.\s-]+(undefined)? \/ (PHP version [^\s^<]+)<\/h4>/, :offset=>1 }, ] end
tempbottle/WhatWeb
plugins/SQLiteManager.rb
Ruby
gpl-2.0
1,772
/* * Common code for the NVMe target. * Copyright (c) 2015-2016 HGST, a Western Digital Company. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #include <linux/random.h> #include <linux/rculist.h> #include "nvmet.h" static struct nvmet_fabrics_ops *nvmet_transports[NVMF_TRTYPE_MAX]; static DEFINE_IDA(cntlid_ida); /* * This read/write semaphore is used to synchronize access to configuration * information on a target system that will result in discovery log page * information change for at least one host. * The full list of resources to protected by this semaphore is: * * - subsystems list * - per-subsystem allowed hosts list * - allow_any_host subsystem attribute * - nvmet_genctr * - the nvmet_transports array * * When updating any of those lists/structures write lock should be obtained, * while when reading (popolating discovery log page or checking host-subsystem * link) read lock is obtained to allow concurrent reads. */ DECLARE_RWSEM(nvmet_config_sem); static struct nvmet_subsys *nvmet_find_get_subsys(struct nvmet_port *port, const char *subsysnqn); u16 nvmet_copy_to_sgl(struct nvmet_req *req, off_t off, const void *buf, size_t len) { if (sg_pcopy_from_buffer(req->sg, req->sg_cnt, buf, len, off) != len) return NVME_SC_SGL_INVALID_DATA | NVME_SC_DNR; return 0; } u16 nvmet_copy_from_sgl(struct nvmet_req *req, off_t off, void *buf, size_t len) { if (sg_pcopy_to_buffer(req->sg, req->sg_cnt, buf, len, off) != len) return NVME_SC_SGL_INVALID_DATA | NVME_SC_DNR; return 0; } static u32 nvmet_async_event_result(struct nvmet_async_event *aen) { return aen->event_type | (aen->event_info << 8) | (aen->log_page << 16); } static void nvmet_async_events_free(struct nvmet_ctrl *ctrl) { struct nvmet_req *req; while (1) { mutex_lock(&ctrl->lock); if (!ctrl->nr_async_event_cmds) { mutex_unlock(&ctrl->lock); return; } req = ctrl->async_event_cmds[--ctrl->nr_async_event_cmds]; mutex_unlock(&ctrl->lock); nvmet_req_complete(req, NVME_SC_INTERNAL | NVME_SC_DNR); } } static void nvmet_async_event_work(struct work_struct *work) { struct nvmet_ctrl *ctrl = container_of(work, struct nvmet_ctrl, async_event_work); struct nvmet_async_event *aen; struct nvmet_req *req; while (1) { mutex_lock(&ctrl->lock); aen = list_first_entry_or_null(&ctrl->async_events, struct nvmet_async_event, entry); if (!aen || !ctrl->nr_async_event_cmds) { mutex_unlock(&ctrl->lock); return; } req = ctrl->async_event_cmds[--ctrl->nr_async_event_cmds]; nvmet_set_result(req, nvmet_async_event_result(aen)); list_del(&aen->entry); kfree(aen); mutex_unlock(&ctrl->lock); nvmet_req_complete(req, 0); } } static void nvmet_add_async_event(struct nvmet_ctrl *ctrl, u8 event_type, u8 event_info, u8 log_page) { struct nvmet_async_event *aen; aen = kmalloc(sizeof(*aen), GFP_KERNEL); if (!aen) return; aen->event_type = event_type; aen->event_info = event_info; aen->log_page = log_page; mutex_lock(&ctrl->lock); list_add_tail(&aen->entry, &ctrl->async_events); mutex_unlock(&ctrl->lock); schedule_work(&ctrl->async_event_work); } int nvmet_register_transport(struct nvmet_fabrics_ops *ops) { int ret = 0; down_write(&nvmet_config_sem); if (nvmet_transports[ops->type]) ret = -EINVAL; else nvmet_transports[ops->type] = ops; up_write(&nvmet_config_sem); return ret; } EXPORT_SYMBOL_GPL(nvmet_register_transport); void nvmet_unregister_transport(struct nvmet_fabrics_ops *ops) { down_write(&nvmet_config_sem); nvmet_transports[ops->type] = NULL; up_write(&nvmet_config_sem); } EXPORT_SYMBOL_GPL(nvmet_unregister_transport); int nvmet_enable_port(struct nvmet_port *port) { struct nvmet_fabrics_ops *ops; int ret; lockdep_assert_held(&nvmet_config_sem); ops = nvmet_transports[port->disc_addr.trtype]; if (!ops) { up_write(&nvmet_config_sem); request_module("nvmet-transport-%d", port->disc_addr.trtype); down_write(&nvmet_config_sem); ops = nvmet_transports[port->disc_addr.trtype]; if (!ops) { pr_err("transport type %d not supported\n", port->disc_addr.trtype); return -EINVAL; } } if (!try_module_get(ops->owner)) return -EINVAL; ret = ops->add_port(port); if (ret) { module_put(ops->owner); return ret; } port->enabled = true; return 0; } void nvmet_disable_port(struct nvmet_port *port) { struct nvmet_fabrics_ops *ops; lockdep_assert_held(&nvmet_config_sem); port->enabled = false; ops = nvmet_transports[port->disc_addr.trtype]; ops->remove_port(port); module_put(ops->owner); } static void nvmet_keep_alive_timer(struct work_struct *work) { struct nvmet_ctrl *ctrl = container_of(to_delayed_work(work), struct nvmet_ctrl, ka_work); pr_err("ctrl %d keep-alive timer (%d seconds) expired!\n", ctrl->cntlid, ctrl->kato); nvmet_ctrl_fatal_error(ctrl); } static void nvmet_start_keep_alive_timer(struct nvmet_ctrl *ctrl) { pr_debug("ctrl %d start keep-alive timer for %d secs\n", ctrl->cntlid, ctrl->kato); INIT_DELAYED_WORK(&ctrl->ka_work, nvmet_keep_alive_timer); schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ); } static void nvmet_stop_keep_alive_timer(struct nvmet_ctrl *ctrl) { pr_debug("ctrl %d stop keep-alive\n", ctrl->cntlid); cancel_delayed_work_sync(&ctrl->ka_work); } static struct nvmet_ns *__nvmet_find_namespace(struct nvmet_ctrl *ctrl, __le32 nsid) { struct nvmet_ns *ns; list_for_each_entry_rcu(ns, &ctrl->subsys->namespaces, dev_link) { if (ns->nsid == le32_to_cpu(nsid)) return ns; } return NULL; } struct nvmet_ns *nvmet_find_namespace(struct nvmet_ctrl *ctrl, __le32 nsid) { struct nvmet_ns *ns; rcu_read_lock(); ns = __nvmet_find_namespace(ctrl, nsid); if (ns) percpu_ref_get(&ns->ref); rcu_read_unlock(); return ns; } static void nvmet_destroy_namespace(struct percpu_ref *ref) { struct nvmet_ns *ns = container_of(ref, struct nvmet_ns, ref); complete(&ns->disable_done); } void nvmet_put_namespace(struct nvmet_ns *ns) { percpu_ref_put(&ns->ref); } int nvmet_ns_enable(struct nvmet_ns *ns) { struct nvmet_subsys *subsys = ns->subsys; struct nvmet_ctrl *ctrl; int ret = 0; mutex_lock(&subsys->lock); if (ns->enabled) goto out_unlock; ns->bdev = blkdev_get_by_path(ns->device_path, FMODE_READ | FMODE_WRITE, NULL); if (IS_ERR(ns->bdev)) { pr_err("failed to open block device %s: (%ld)\n", ns->device_path, PTR_ERR(ns->bdev)); ret = PTR_ERR(ns->bdev); ns->bdev = NULL; goto out_unlock; } ns->size = i_size_read(ns->bdev->bd_inode); ns->blksize_shift = blksize_bits(bdev_logical_block_size(ns->bdev)); ret = percpu_ref_init(&ns->ref, nvmet_destroy_namespace, 0, GFP_KERNEL); if (ret) goto out_blkdev_put; if (ns->nsid > subsys->max_nsid) subsys->max_nsid = ns->nsid; /* * The namespaces list needs to be sorted to simplify the implementation * of the Identify Namepace List subcommand. */ if (list_empty(&subsys->namespaces)) { list_add_tail_rcu(&ns->dev_link, &subsys->namespaces); } else { struct nvmet_ns *old; list_for_each_entry_rcu(old, &subsys->namespaces, dev_link) { BUG_ON(ns->nsid == old->nsid); if (ns->nsid < old->nsid) break; } list_add_tail_rcu(&ns->dev_link, &old->dev_link); } list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry) nvmet_add_async_event(ctrl, NVME_AER_TYPE_NOTICE, 0, 0); ns->enabled = true; ret = 0; out_unlock: mutex_unlock(&subsys->lock); return ret; out_blkdev_put: blkdev_put(ns->bdev, FMODE_WRITE|FMODE_READ); ns->bdev = NULL; goto out_unlock; } void nvmet_ns_disable(struct nvmet_ns *ns) { struct nvmet_subsys *subsys = ns->subsys; struct nvmet_ctrl *ctrl; mutex_lock(&subsys->lock); if (!ns->enabled) goto out_unlock; ns->enabled = false; list_del_rcu(&ns->dev_link); mutex_unlock(&subsys->lock); /* * Now that we removed the namespaces from the lookup list, we * can kill the per_cpu ref and wait for any remaining references * to be dropped, as well as a RCU grace period for anyone only * using the namepace under rcu_read_lock(). Note that we can't * use call_rcu here as we need to ensure the namespaces have * been fully destroyed before unloading the module. */ percpu_ref_kill(&ns->ref); synchronize_rcu(); wait_for_completion(&ns->disable_done); percpu_ref_exit(&ns->ref); mutex_lock(&subsys->lock); list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry) nvmet_add_async_event(ctrl, NVME_AER_TYPE_NOTICE, 0, 0); if (ns->bdev) blkdev_put(ns->bdev, FMODE_WRITE|FMODE_READ); out_unlock: mutex_unlock(&subsys->lock); } void nvmet_ns_free(struct nvmet_ns *ns) { nvmet_ns_disable(ns); kfree(ns->device_path); kfree(ns); } struct nvmet_ns *nvmet_ns_alloc(struct nvmet_subsys *subsys, u32 nsid) { struct nvmet_ns *ns; ns = kzalloc(sizeof(*ns), GFP_KERNEL); if (!ns) return NULL; INIT_LIST_HEAD(&ns->dev_link); init_completion(&ns->disable_done); ns->nsid = nsid; ns->subsys = subsys; uuid_gen(&ns->uuid); return ns; } static void __nvmet_req_complete(struct nvmet_req *req, u16 status) { if (status) nvmet_set_status(req, status); if (req->sq->size) req->sq->sqhd = (req->sq->sqhd + 1) % req->sq->size; req->rsp->sq_head = cpu_to_le16(req->sq->sqhd); req->rsp->sq_id = cpu_to_le16(req->sq->qid); req->rsp->command_id = req->cmd->common.command_id; if (req->ns) nvmet_put_namespace(req->ns); req->ops->queue_response(req); } void nvmet_req_complete(struct nvmet_req *req, u16 status) { __nvmet_req_complete(req, status); percpu_ref_put(&req->sq->ref); } EXPORT_SYMBOL_GPL(nvmet_req_complete); void nvmet_cq_setup(struct nvmet_ctrl *ctrl, struct nvmet_cq *cq, u16 qid, u16 size) { cq->qid = qid; cq->size = size; ctrl->cqs[qid] = cq; } void nvmet_sq_setup(struct nvmet_ctrl *ctrl, struct nvmet_sq *sq, u16 qid, u16 size) { sq->sqhd = 0; sq->qid = qid; sq->size = size; ctrl->sqs[qid] = sq; } static void nvmet_confirm_sq(struct percpu_ref *ref) { struct nvmet_sq *sq = container_of(ref, struct nvmet_sq, ref); complete(&sq->confirm_done); } void nvmet_sq_destroy(struct nvmet_sq *sq) { /* * If this is the admin queue, complete all AERs so that our * queue doesn't have outstanding requests on it. */ if (sq->ctrl && sq->ctrl->sqs && sq->ctrl->sqs[0] == sq) nvmet_async_events_free(sq->ctrl); percpu_ref_kill_and_confirm(&sq->ref, nvmet_confirm_sq); wait_for_completion(&sq->confirm_done); wait_for_completion(&sq->free_done); percpu_ref_exit(&sq->ref); if (sq->ctrl) { nvmet_ctrl_put(sq->ctrl); sq->ctrl = NULL; /* allows reusing the queue later */ } } EXPORT_SYMBOL_GPL(nvmet_sq_destroy); static void nvmet_sq_free(struct percpu_ref *ref) { struct nvmet_sq *sq = container_of(ref, struct nvmet_sq, ref); complete(&sq->free_done); } int nvmet_sq_init(struct nvmet_sq *sq) { int ret; ret = percpu_ref_init(&sq->ref, nvmet_sq_free, 0, GFP_KERNEL); if (ret) { pr_err("percpu_ref init failed!\n"); return ret; } init_completion(&sq->free_done); init_completion(&sq->confirm_done); return 0; } EXPORT_SYMBOL_GPL(nvmet_sq_init); bool nvmet_req_init(struct nvmet_req *req, struct nvmet_cq *cq, struct nvmet_sq *sq, struct nvmet_fabrics_ops *ops) { u8 flags = req->cmd->common.flags; u16 status; req->cq = cq; req->sq = sq; req->ops = ops; req->sg = NULL; req->sg_cnt = 0; req->rsp->status = 0; /* no support for fused commands yet */ if (unlikely(flags & (NVME_CMD_FUSE_FIRST | NVME_CMD_FUSE_SECOND))) { status = NVME_SC_INVALID_FIELD | NVME_SC_DNR; goto fail; } /* either variant of SGLs is fine, as we don't support metadata */ if (unlikely((flags & NVME_CMD_SGL_ALL) != NVME_CMD_SGL_METABUF && (flags & NVME_CMD_SGL_ALL) != NVME_CMD_SGL_METASEG)) { status = NVME_SC_INVALID_FIELD | NVME_SC_DNR; goto fail; } if (unlikely(!req->sq->ctrl)) /* will return an error for any Non-connect command: */ status = nvmet_parse_connect_cmd(req); else if (likely(req->sq->qid != 0)) status = nvmet_parse_io_cmd(req); else if (req->cmd->common.opcode == nvme_fabrics_command) status = nvmet_parse_fabrics_cmd(req); else if (req->sq->ctrl->subsys->type == NVME_NQN_DISC) status = nvmet_parse_discovery_cmd(req); else status = nvmet_parse_admin_cmd(req); if (status) goto fail; if (unlikely(!percpu_ref_tryget_live(&sq->ref))) { status = NVME_SC_INVALID_FIELD | NVME_SC_DNR; goto fail; } return true; fail: __nvmet_req_complete(req, status); return false; } EXPORT_SYMBOL_GPL(nvmet_req_init); void nvmet_req_uninit(struct nvmet_req *req) { percpu_ref_put(&req->sq->ref); } EXPORT_SYMBOL_GPL(nvmet_req_uninit); static inline bool nvmet_cc_en(u32 cc) { return (cc >> NVME_CC_EN_SHIFT) & 0x1; } static inline u8 nvmet_cc_css(u32 cc) { return (cc >> NVME_CC_CSS_SHIFT) & 0x7; } static inline u8 nvmet_cc_mps(u32 cc) { return (cc >> NVME_CC_MPS_SHIFT) & 0xf; } static inline u8 nvmet_cc_ams(u32 cc) { return (cc >> NVME_CC_AMS_SHIFT) & 0x7; } static inline u8 nvmet_cc_shn(u32 cc) { return (cc >> NVME_CC_SHN_SHIFT) & 0x3; } static inline u8 nvmet_cc_iosqes(u32 cc) { return (cc >> NVME_CC_IOSQES_SHIFT) & 0xf; } static inline u8 nvmet_cc_iocqes(u32 cc) { return (cc >> NVME_CC_IOCQES_SHIFT) & 0xf; } static void nvmet_start_ctrl(struct nvmet_ctrl *ctrl) { lockdep_assert_held(&ctrl->lock); if (nvmet_cc_iosqes(ctrl->cc) != NVME_NVM_IOSQES || nvmet_cc_iocqes(ctrl->cc) != NVME_NVM_IOCQES || nvmet_cc_mps(ctrl->cc) != 0 || nvmet_cc_ams(ctrl->cc) != 0 || nvmet_cc_css(ctrl->cc) != 0) { ctrl->csts = NVME_CSTS_CFS; return; } ctrl->csts = NVME_CSTS_RDY; } static void nvmet_clear_ctrl(struct nvmet_ctrl *ctrl) { lockdep_assert_held(&ctrl->lock); /* XXX: tear down queues? */ ctrl->csts &= ~NVME_CSTS_RDY; ctrl->cc = 0; } void nvmet_update_cc(struct nvmet_ctrl *ctrl, u32 new) { u32 old; mutex_lock(&ctrl->lock); old = ctrl->cc; ctrl->cc = new; if (nvmet_cc_en(new) && !nvmet_cc_en(old)) nvmet_start_ctrl(ctrl); if (!nvmet_cc_en(new) && nvmet_cc_en(old)) nvmet_clear_ctrl(ctrl); if (nvmet_cc_shn(new) && !nvmet_cc_shn(old)) { nvmet_clear_ctrl(ctrl); ctrl->csts |= NVME_CSTS_SHST_CMPLT; } if (!nvmet_cc_shn(new) && nvmet_cc_shn(old)) ctrl->csts &= ~NVME_CSTS_SHST_CMPLT; mutex_unlock(&ctrl->lock); } static void nvmet_init_cap(struct nvmet_ctrl *ctrl) { /* command sets supported: NVMe command set: */ ctrl->cap = (1ULL << 37); /* CC.EN timeout in 500msec units: */ ctrl->cap |= (15ULL << 24); /* maximum queue entries supported: */ ctrl->cap |= NVMET_QUEUE_SIZE - 1; } u16 nvmet_ctrl_find_get(const char *subsysnqn, const char *hostnqn, u16 cntlid, struct nvmet_req *req, struct nvmet_ctrl **ret) { struct nvmet_subsys *subsys; struct nvmet_ctrl *ctrl; u16 status = 0; subsys = nvmet_find_get_subsys(req->port, subsysnqn); if (!subsys) { pr_warn("connect request for invalid subsystem %s!\n", subsysnqn); req->rsp->result.u32 = IPO_IATTR_CONNECT_DATA(subsysnqn); return NVME_SC_CONNECT_INVALID_PARAM | NVME_SC_DNR; } mutex_lock(&subsys->lock); list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry) { if (ctrl->cntlid == cntlid) { if (strncmp(hostnqn, ctrl->hostnqn, NVMF_NQN_SIZE)) { pr_warn("hostnqn mismatch.\n"); continue; } if (!kref_get_unless_zero(&ctrl->ref)) continue; *ret = ctrl; goto out; } } pr_warn("could not find controller %d for subsys %s / host %s\n", cntlid, subsysnqn, hostnqn); req->rsp->result.u32 = IPO_IATTR_CONNECT_DATA(cntlid); status = NVME_SC_CONNECT_INVALID_PARAM | NVME_SC_DNR; out: mutex_unlock(&subsys->lock); nvmet_subsys_put(subsys); return status; } u16 nvmet_check_ctrl_status(struct nvmet_req *req, struct nvme_command *cmd) { if (unlikely(!(req->sq->ctrl->cc & NVME_CC_ENABLE))) { pr_err("got io cmd %d while CC.EN == 0 on qid = %d\n", cmd->common.opcode, req->sq->qid); return NVME_SC_CMD_SEQ_ERROR | NVME_SC_DNR; } if (unlikely(!(req->sq->ctrl->csts & NVME_CSTS_RDY))) { pr_err("got io cmd %d while CSTS.RDY == 0 on qid = %d\n", cmd->common.opcode, req->sq->qid); req->ns = NULL; return NVME_SC_CMD_SEQ_ERROR | NVME_SC_DNR; } return 0; } static bool __nvmet_host_allowed(struct nvmet_subsys *subsys, const char *hostnqn) { struct nvmet_host_link *p; if (subsys->allow_any_host) return true; list_for_each_entry(p, &subsys->hosts, entry) { if (!strcmp(nvmet_host_name(p->host), hostnqn)) return true; } return false; } static bool nvmet_host_discovery_allowed(struct nvmet_req *req, const char *hostnqn) { struct nvmet_subsys_link *s; list_for_each_entry(s, &req->port->subsystems, entry) { if (__nvmet_host_allowed(s->subsys, hostnqn)) return true; } return false; } bool nvmet_host_allowed(struct nvmet_req *req, struct nvmet_subsys *subsys, const char *hostnqn) { lockdep_assert_held(&nvmet_config_sem); if (subsys->type == NVME_NQN_DISC) return nvmet_host_discovery_allowed(req, hostnqn); else return __nvmet_host_allowed(subsys, hostnqn); } u16 nvmet_alloc_ctrl(const char *subsysnqn, const char *hostnqn, struct nvmet_req *req, u32 kato, struct nvmet_ctrl **ctrlp) { struct nvmet_subsys *subsys; struct nvmet_ctrl *ctrl; int ret; u16 status; status = NVME_SC_CONNECT_INVALID_PARAM | NVME_SC_DNR; subsys = nvmet_find_get_subsys(req->port, subsysnqn); if (!subsys) { pr_warn("connect request for invalid subsystem %s!\n", subsysnqn); req->rsp->result.u32 = IPO_IATTR_CONNECT_DATA(subsysnqn); goto out; } status = NVME_SC_CONNECT_INVALID_PARAM | NVME_SC_DNR; down_read(&nvmet_config_sem); if (!nvmet_host_allowed(req, subsys, hostnqn)) { pr_info("connect by host %s for subsystem %s not allowed\n", hostnqn, subsysnqn); req->rsp->result.u32 = IPO_IATTR_CONNECT_DATA(hostnqn); up_read(&nvmet_config_sem); status = NVME_SC_CONNECT_INVALID_HOST | NVME_SC_DNR; goto out_put_subsystem; } up_read(&nvmet_config_sem); status = NVME_SC_INTERNAL; ctrl = kzalloc(sizeof(*ctrl), GFP_KERNEL); if (!ctrl) goto out_put_subsystem; mutex_init(&ctrl->lock); nvmet_init_cap(ctrl); INIT_WORK(&ctrl->async_event_work, nvmet_async_event_work); INIT_LIST_HEAD(&ctrl->async_events); memcpy(ctrl->subsysnqn, subsysnqn, NVMF_NQN_SIZE); memcpy(ctrl->hostnqn, hostnqn, NVMF_NQN_SIZE); kref_init(&ctrl->ref); ctrl->subsys = subsys; ctrl->cqs = kcalloc(subsys->max_qid + 1, sizeof(struct nvmet_cq *), GFP_KERNEL); if (!ctrl->cqs) goto out_free_ctrl; ctrl->sqs = kcalloc(subsys->max_qid + 1, sizeof(struct nvmet_sq *), GFP_KERNEL); if (!ctrl->sqs) goto out_free_cqs; ret = ida_simple_get(&cntlid_ida, NVME_CNTLID_MIN, NVME_CNTLID_MAX, GFP_KERNEL); if (ret < 0) { status = NVME_SC_CONNECT_CTRL_BUSY | NVME_SC_DNR; goto out_free_sqs; } ctrl->cntlid = ret; ctrl->ops = req->ops; if (ctrl->subsys->type == NVME_NQN_DISC) { /* Don't accept keep-alive timeout for discovery controllers */ if (kato) { status = NVME_SC_INVALID_FIELD | NVME_SC_DNR; goto out_free_sqs; } /* * Discovery controllers use some arbitrary high value in order * to cleanup stale discovery sessions * * From the latest base diff RC: * "The Keep Alive command is not supported by * Discovery controllers. A transport may specify a * fixed Discovery controller activity timeout value * (e.g., 2 minutes). If no commands are received * by a Discovery controller within that time * period, the controller may perform the * actions for Keep Alive Timer expiration". */ ctrl->kato = NVMET_DISC_KATO; } else { /* keep-alive timeout in seconds */ ctrl->kato = DIV_ROUND_UP(kato, 1000); } nvmet_start_keep_alive_timer(ctrl); mutex_lock(&subsys->lock); list_add_tail(&ctrl->subsys_entry, &subsys->ctrls); mutex_unlock(&subsys->lock); *ctrlp = ctrl; return 0; out_free_sqs: kfree(ctrl->sqs); out_free_cqs: kfree(ctrl->cqs); out_free_ctrl: kfree(ctrl); out_put_subsystem: nvmet_subsys_put(subsys); out: return status; } static void nvmet_ctrl_free(struct kref *ref) { struct nvmet_ctrl *ctrl = container_of(ref, struct nvmet_ctrl, ref); struct nvmet_subsys *subsys = ctrl->subsys; nvmet_stop_keep_alive_timer(ctrl); mutex_lock(&subsys->lock); list_del(&ctrl->subsys_entry); mutex_unlock(&subsys->lock); flush_work(&ctrl->async_event_work); cancel_work_sync(&ctrl->fatal_err_work); ida_simple_remove(&cntlid_ida, ctrl->cntlid); nvmet_subsys_put(subsys); kfree(ctrl->sqs); kfree(ctrl->cqs); kfree(ctrl); } void nvmet_ctrl_put(struct nvmet_ctrl *ctrl) { kref_put(&ctrl->ref, nvmet_ctrl_free); } static void nvmet_fatal_error_handler(struct work_struct *work) { struct nvmet_ctrl *ctrl = container_of(work, struct nvmet_ctrl, fatal_err_work); pr_err("ctrl %d fatal error occurred!\n", ctrl->cntlid); ctrl->ops->delete_ctrl(ctrl); } void nvmet_ctrl_fatal_error(struct nvmet_ctrl *ctrl) { mutex_lock(&ctrl->lock); if (!(ctrl->csts & NVME_CSTS_CFS)) { ctrl->csts |= NVME_CSTS_CFS; INIT_WORK(&ctrl->fatal_err_work, nvmet_fatal_error_handler); schedule_work(&ctrl->fatal_err_work); } mutex_unlock(&ctrl->lock); } EXPORT_SYMBOL_GPL(nvmet_ctrl_fatal_error); static struct nvmet_subsys *nvmet_find_get_subsys(struct nvmet_port *port, const char *subsysnqn) { struct nvmet_subsys_link *p; if (!port) return NULL; if (!strncmp(NVME_DISC_SUBSYS_NAME, subsysnqn, NVMF_NQN_SIZE)) { if (!kref_get_unless_zero(&nvmet_disc_subsys->ref)) return NULL; return nvmet_disc_subsys; } down_read(&nvmet_config_sem); list_for_each_entry(p, &port->subsystems, entry) { if (!strncmp(p->subsys->subsysnqn, subsysnqn, NVMF_NQN_SIZE)) { if (!kref_get_unless_zero(&p->subsys->ref)) break; up_read(&nvmet_config_sem); return p->subsys; } } up_read(&nvmet_config_sem); return NULL; } struct nvmet_subsys *nvmet_subsys_alloc(const char *subsysnqn, enum nvme_subsys_type type) { struct nvmet_subsys *subsys; subsys = kzalloc(sizeof(*subsys), GFP_KERNEL); if (!subsys) return NULL; subsys->ver = NVME_VS(1, 3, 0); /* NVMe 1.3.0 */ /* generate a random serial number as our controllers are ephemeral: */ get_random_bytes(&subsys->serial, sizeof(subsys->serial)); switch (type) { case NVME_NQN_NVME: subsys->max_qid = NVMET_NR_QUEUES; break; case NVME_NQN_DISC: subsys->max_qid = 0; break; default: pr_err("%s: Unknown Subsystem type - %d\n", __func__, type); kfree(subsys); return NULL; } subsys->type = type; subsys->subsysnqn = kstrndup(subsysnqn, NVMF_NQN_SIZE, GFP_KERNEL); if (!subsys->subsysnqn) { kfree(subsys); return NULL; } kref_init(&subsys->ref); mutex_init(&subsys->lock); INIT_LIST_HEAD(&subsys->namespaces); INIT_LIST_HEAD(&subsys->ctrls); INIT_LIST_HEAD(&subsys->hosts); return subsys; } static void nvmet_subsys_free(struct kref *ref) { struct nvmet_subsys *subsys = container_of(ref, struct nvmet_subsys, ref); WARN_ON_ONCE(!list_empty(&subsys->namespaces)); kfree(subsys->subsysnqn); kfree(subsys); } void nvmet_subsys_del_ctrls(struct nvmet_subsys *subsys) { struct nvmet_ctrl *ctrl; mutex_lock(&subsys->lock); list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry) ctrl->ops->delete_ctrl(ctrl); mutex_unlock(&subsys->lock); } void nvmet_subsys_put(struct nvmet_subsys *subsys) { kref_put(&subsys->ref, nvmet_subsys_free); } static int __init nvmet_init(void) { int error; error = nvmet_init_discovery(); if (error) goto out; error = nvmet_init_configfs(); if (error) goto out_exit_discovery; return 0; out_exit_discovery: nvmet_exit_discovery(); out: return error; } static void __exit nvmet_exit(void) { nvmet_exit_configfs(); nvmet_exit_discovery(); ida_destroy(&cntlid_ida); BUILD_BUG_ON(sizeof(struct nvmf_disc_rsp_page_entry) != 1024); BUILD_BUG_ON(sizeof(struct nvmf_disc_rsp_page_hdr) != 1024); } module_init(nvmet_init); module_exit(nvmet_exit); MODULE_LICENSE("GPL v2");
paulluo/linux
drivers/nvme/target/core.c
C
gpl-2.0
24,383
/* Copyright (C) 2008 Rodolfo Giometti <giometti@linux.it> * Copyright (C) 2008 Eurotech S.p.A. <info@eurotech.it> * Based on a previous work by Copyright (C) 2008 Texas Instruments, Inc. * * Copyright (c) 2011, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/module.h> #include <linux/param.h> #include <linux/jiffies.h> #include <linux/workqueue.h> #include <linux/delay.h> #include <linux/platform_device.h> #include <linux/power_supply.h> #include <linux/idr.h> #include <linux/i2c.h> #include <linux/slab.h> #include <asm/unaligned.h> #include <linux/time.h> #include <linux/mfd/pmic8058.h> #include <linux/regulator/pmic8058-regulator.h> #include <linux/gpio.h> #include <linux/regulator/consumer.h> #include <linux/regulator/machine.h> #include <linux/err.h> #include <linux/qpnp-charger.h> #include <linux/i2c/bq27520.h> /* use the same platform data as bq27520 */ #include <linux/of_gpio.h> //sjc0623 add #ifdef CONFIG_MACH_MSM8974_14001 /*OPPO 2013-09-22 liaofuchun add for bq27541 encryption*/ #include <linux/random.h> #include <linux/rtc.h> extern char *BQ27541_HMACSHA1_authenticate(char *Message,char *Key,char *result); #endif //CONFIG_MACH_MSM8974_14001 #ifdef CONFIG_OPPO_MSM_14021 /* OPPO 2014-06-23 sjc Add begin for 14021 */ static int mcu_en_gpio = 0; void mcu_en_gpio_set(int value) { if (value) { if (gpio_is_valid(mcu_en_gpio)) gpio_set_value(mcu_en_gpio, 0);///1); } else { if (gpio_is_valid(mcu_en_gpio)) { gpio_set_value(mcu_en_gpio, 1); usleep_range(10000, 10000); gpio_set_value(mcu_en_gpio, 0); } } } #else void mcu_en_gpio_set(int value) { return; } #endif //CONFIG_OPPO_MSM_14021 extern int load_soc(void);//sjc1121 extern void backup_soc_ex(int soc); /* yangfangbiao@oneplus.cn, 2015/01/19 Add for sync with android 4.4 */ /* OPPO 2013-12-20 liaofuchun add for fastchg firmware update */ #ifdef CONFIG_PIC1503_FASTCG extern unsigned char Pic16F_firmware_data[]; extern int pic_fw_ver_count; extern int pic_need_to_up_fw; extern int pic_have_updated; extern int pic16f_fw_update(bool pull96); #endif /* OPPO 2013-12-20 liaofuchun add end */ #define DRIVER_VERSION "1.1.0" /* Bq27541 standard data commands */ #define BQ27541_REG_CNTL 0x00 #define BQ27541_REG_AR 0x02 #define BQ27541_REG_ARTTE 0x04 #define BQ27541_REG_TEMP 0x06 #define BQ27541_REG_VOLT 0x08 #define BQ27541_REG_FLAGS 0x0A #define BQ27541_REG_NAC 0x0C #define BQ27541_REG_FAC 0x0e #define BQ27541_REG_RM 0x10 #define BQ27541_REG_FCC 0x12 #define BQ27541_REG_AI 0x14 #define BQ27541_REG_TTE 0x16 #define BQ27541_REG_TTF 0x18 #define BQ27541_REG_SI 0x1a #define BQ27541_REG_STTE 0x1c #define BQ27541_REG_MLI 0x1e #define BQ27541_REG_MLTTE 0x20 #define BQ27541_REG_AE 0x22 #define BQ27541_REG_AP 0x24 #define BQ27541_REG_TTECP 0x26 #define BQ27541_REG_SOH 0x28 #define BQ27541_REG_SOC 0x2c #define BQ27541_REG_NIC 0x2e #define BQ27541_REG_ICR 0x30 #define BQ27541_REG_LOGIDX 0x32 #define BQ27541_REG_LOGBUF 0x34 #define BQ27541_FLAG_DSC BIT(0) #define BQ27541_FLAG_FC BIT(9) #define BQ27541_CS_DLOGEN BIT(15) #define BQ27541_CS_SS BIT(13) /* Control subcommands */ #define BQ27541_SUBCMD_CTNL_STATUS 0x0000 #define BQ27541_SUBCMD_DEVCIE_TYPE 0x0001 #define BQ27541_SUBCMD_FW_VER 0x0002 #define BQ27541_SUBCMD_HW_VER 0x0003 #define BQ27541_SUBCMD_DF_CSUM 0x0004 #define BQ27541_SUBCMD_PREV_MACW 0x0007 #define BQ27541_SUBCMD_CHEM_ID 0x0008 #define BQ27541_SUBCMD_BD_OFFSET 0x0009 #define BQ27541_SUBCMD_INT_OFFSET 0x000a #define BQ27541_SUBCMD_CC_VER 0x000b #define BQ27541_SUBCMD_OCV 0x000c #define BQ27541_SUBCMD_BAT_INS 0x000d #define BQ27541_SUBCMD_BAT_REM 0x000e #define BQ27541_SUBCMD_SET_HIB 0x0011 #define BQ27541_SUBCMD_CLR_HIB 0x0012 #define BQ27541_SUBCMD_SET_SLP 0x0013 #define BQ27541_SUBCMD_CLR_SLP 0x0014 #define BQ27541_SUBCMD_FCT_RES 0x0015 #define BQ27541_SUBCMD_ENABLE_DLOG 0x0018 #define BQ27541_SUBCMD_DISABLE_DLOG 0x0019 #define BQ27541_SUBCMD_SEALED 0x0020 #define BQ27541_SUBCMD_ENABLE_IT 0x0021 #define BQ27541_SUBCMD_DISABLE_IT 0x0023 #define BQ27541_SUBCMD_CAL_MODE 0x0040 #define BQ27541_SUBCMD_RESET 0x0041 #define ZERO_DEGREE_CELSIUS_IN_TENTH_KELVIN (-2731) #define BQ27541_INIT_DELAY ((HZ)*1) /* OPPO 2013-08-24 wangjc Add begin for filter soc. */ #ifdef CONFIG_MACH_MSM8974_14001 #define CAPACITY_SALTATE_COUNTER 4 #define CAPACITY_SALTATE_COUNTER_NOT_CHARGING 13//40sec #ifdef CONFIG_MACH_MSM8974_14001 /* yangfangbiao@oneplus.cn, 2015/01/06 Add for sync with KK charge standard */ #define CAPACITY_SALTATE_COUNTER_60 20//40 1min #define CAPACITY_SALTATE_COUNTER_95 50//60 2.5min #define CAPACITY_SALTATE_COUNTER_FULL 100//120 5min #define CAPACITY_SALTATE_COUNTER_CHARGING_TERM 20//30 1min #endif /*CONFIG_MACH_MSM8974_14001*/ #define SOC_SHUTDOWN_VALID_LIMITS 20 /* yangfangbiao@oneplus.cn, 2015/01/06 Add for sync with KK charge standard */ #define TEN_MINUTES 600 #endif /* OPPO 2013-08-24 wangjc Add end */ /* If the system has several batteries we need a different name for each * of them... */ static DEFINE_IDR(battery_id); static DEFINE_MUTEX(battery_mutex); struct bq27541_device_info; struct bq27541_access_methods { int (*read)(u8 reg, int *rt_value, int b_single, struct bq27541_device_info *di); }; struct bq27541_device_info { struct device *dev; int id; struct bq27541_access_methods *bus; struct i2c_client *client; struct work_struct counter; /* 300ms delay is needed after bq27541 is powered up * and before any successful I2C transaction */ struct delayed_work hw_config; /* OPPO 2013-08-24 wangjc Add begin for filter soc. */ #ifdef CONFIG_MACH_MSM8974_14001 int cc_pre; int fcc_pre; int soc_pre; int temp_pre; int batt_vol_pre; int current_pre; int saltate_counter; int report_count; bool is_authenticated; //wangjc add for authentication bool fast_chg_started; bool fast_switch_to_normal; bool fast_normal_to_warm; //lfc add for fastchg over temp int battery_type; //lfc add for battery type struct power_supply *batt_psy; int irq; struct work_struct fastcg_work; bool alow_reading; struct timer_list watchdog; struct wake_lock fastchg_wake_lock; bool fast_chg_allow; bool fast_low_temp_full; /* jingchun.wang@Onlinerd.Driver, 2014/02/12 Add for retry when config fail */ int retry_count; /* jingchun.wang@Onlinerd.Driver, 2014/02/27 Add for get right soc when sleep long time */ unsigned long rtc_resume_time; unsigned long rtc_suspend_time; atomic_t suspended; #endif bool fast_chg_ing; /* OPPO 2013-08-24 wangjc Add end */ }; static int coulomb_counter; static spinlock_t lock; /* protect access to coulomb_counter */ static struct bq27541_device_info *bq27541_di; static int bq27541_i2c_txsubcmd(u8 reg, unsigned short subcmd, struct bq27541_device_info *di); static int bq27541_read(u8 reg, int *rt_value, int b_single, struct bq27541_device_info *di) { return di->bus->read(reg, rt_value, b_single, di); } /* * Return the battery temperature in tenths of degree Celsius * Or < 0 if something fails. */ static int bq27541_battery_temperature(struct bq27541_device_info *di) { int ret; int temp = 0; static int count = 0; #ifdef CONFIG_MACH_MSM8974_14001 /* jingchun.wang@Onlinerd.Driver, 2014/02/27 Add for get right soc when sleep long time */ if(atomic_read(&di->suspended) == 1) { return di->temp_pre + ZERO_DEGREE_CELSIUS_IN_TENTH_KELVIN; } #endif /*CONFIG_MACH_MSM8974_14001*/ if(di->alow_reading == true) { ret = bq27541_read(BQ27541_REG_TEMP, &temp, 0, di); #ifdef CONFIG_MACH_MSM8974_14001 /* jingchun.wang@Onlinerd.Driver, 2014/01/08 Add for don't report battery not connect when reading error once. */ if (ret) { count++; dev_err(di->dev, "error reading temperature\n"); if(count > 1) { count = 0; /* jingchun.wang@Onlinerd.Driver, 2014/01/22 Add for it report bad status when plug out battery */ di->temp_pre = -400 - ZERO_DEGREE_CELSIUS_IN_TENTH_KELVIN; return -400; } else { return di->temp_pre + ZERO_DEGREE_CELSIUS_IN_TENTH_KELVIN; } } count = 0; #endif /*CONFIG_MACH_MSM8974_14001*/ } else { return di->temp_pre + ZERO_DEGREE_CELSIUS_IN_TENTH_KELVIN; } di->temp_pre = temp; return temp + ZERO_DEGREE_CELSIUS_IN_TENTH_KELVIN; } /* OPPO 2013-08-24 wangjc Add begin for add adc interface. */ #ifdef CONFIG_MACH_MSM8974_14001 #define BQ27541_REG_CC 0x2a static int bq27541_battery_cc(struct bq27541_device_info *di)/* yangfangbiao@oneplus.cn, 2015/02/13 Add cc interface */ { int ret; int cc = 0; if (atomic_read(&di->suspended) == 1) return di->cc_pre; if (di->alow_reading == true) { ret = bq27541_read(BQ27541_REG_CC, &cc, 0, di); if (ret) { dev_err(di->dev, "error reading cc.\n"); return ret; } } else { return di->cc_pre; } di->cc_pre = cc; return cc; } static int bq27541_battery_fcc(struct bq27541_device_info *di)//sjc20150105 { int ret; int fcc = 0; if (di->alow_reading == true) { ret = bq27541_read(BQ27541_REG_FCC, &fcc, 0, di); if (ret) { dev_err(di->dev, "error reading fcc.\n"); return ret; } } return fcc; } static int bq27541_remaining_capacity(struct bq27541_device_info *di) { int ret; int cap = 0; if(di->alow_reading == true) { ret = bq27541_read(BQ27541_REG_RM, &cap, 0, di); if (ret) { dev_err(di->dev, "error reading capacity.\n"); return ret; } } return cap; } static int bq27541_battery_voltage(struct bq27541_device_info *di); extern int get_charging_status(void); extern int fuelgauge_battery_temp_region_get(void); static int bq27541_soc_calibrate(struct bq27541_device_info *di, int soc) { union power_supply_propval ret = {0,}; unsigned int soc_calib; int counter_temp = 0; static int charging_status = 0;//sjc1121 static int charging_status_pre = 0; /* yangfangbiao@oneplus.cn, 2015/01/06 Modify for sync with KK charge standard */ int soc_load;//sjc1121 int soc_temp; if(!di->batt_psy){ di->batt_psy = power_supply_get_by_name("battery"); //get the soc before reboot soc_load = load_soc(); if (soc_load == -1) { //get last soc error di->soc_pre = soc; } else if(abs(soc - soc_load) > SOC_SHUTDOWN_VALID_LIMITS) { //the battery maybe changed di->soc_pre = soc; } else { //compare the soc and the last soc if(soc_load > soc) { di->soc_pre = soc_load -1; } else { di->soc_pre = soc_load; } } #ifdef CONFIG_MACH_MSM8974_14001 /* yangfangbiao@oneplus.cn, 2015/02/3 Modify for V2.4 charge standard */ if (!di->batt_psy) { return di->soc_pre; } #endif /*CONFIG_MACH_MSM8974_14001*/ //store the soc when boot first time backup_soc_ex(di->soc_pre); } soc_temp = di->soc_pre; if(di->batt_psy){ ret.intval = get_charging_status();//sjc20150104 if(ret.intval == POWER_SUPPLY_STATUS_CHARGING || ret.intval == POWER_SUPPLY_STATUS_FULL) { // is charging charging_status = 1; } else { charging_status = 0; } if (charging_status ^ charging_status_pre) { charging_status_pre = charging_status; di->saltate_counter = 0; } if (charging_status) { // is charging /* yangfangbiao@oneplus.cn, 2015/01/06 Modify begin for sync with KK charge standard */ if (ret.intval == POWER_SUPPLY_STATUS_FULL) { soc_calib = di->soc_pre; if (di->soc_pre < 100 && (fuelgauge_battery_temp_region_get() == CV_BATTERY_TEMP_REGION__LITTLE_COOL || fuelgauge_battery_temp_region_get() == CV_BATTERY_TEMP_REGION__NORMAL)) {//sjc20150104 if (di->saltate_counter < CAPACITY_SALTATE_COUNTER_CHARGING_TERM) { di->saltate_counter++; } else { soc_calib = di->soc_pre + 1; di->saltate_counter = 0; } } } else { /* yangfangbiao@oneplus.cn, 2015/01/06 Modify end for sync with KK charge standard */ if(abs(soc - di->soc_pre) > 0) { di->saltate_counter++; if(di->saltate_counter < CAPACITY_SALTATE_COUNTER) return di->soc_pre; else di->saltate_counter = 0; } else di->saltate_counter = 0; if(soc > di->soc_pre) { soc_calib = di->soc_pre + 1; } else if(soc < (di->soc_pre - 2)) { /* jingchun.wang@Onlinerd.Driver, 2013/04/14 Add for allow soc fail when charging. */ soc_calib = di->soc_pre - 1; } else { soc_calib = di->soc_pre; } /* jingchun.wang@Onlinerd.Driver, 2013/12/12 Add for set capacity to 100 when full in normal temp */ if(ret.intval == POWER_SUPPLY_STATUS_FULL) { if(soc > 94) { soc_calib = 100; } } } } else { // not charging if ((abs(soc - di->soc_pre) > 0) || (di->batt_vol_pre <= 3300 * 1000 && di->batt_vol_pre > 2500 * 1000)) {//sjc1118 add for batt_vol is too low but soc is not jumping di->saltate_counter++; if(di->soc_pre == 100) { counter_temp = CAPACITY_SALTATE_COUNTER_FULL;//t>=5min } else if (di->soc_pre > 95) { counter_temp = CAPACITY_SALTATE_COUNTER_95;///t>=2.5min } else if (di->soc_pre > 60) { counter_temp = CAPACITY_SALTATE_COUNTER_60;//t>=1min } else { counter_temp = CAPACITY_SALTATE_COUNTER_NOT_CHARGING;//t>=40sec } /* sjc1020, when batt_vol is too low(and soc is jumping), decrease faster to avoid dead battery shutdown */ if (di->batt_vol_pre <= 3300 * 1000 && di->batt_vol_pre > 2500 * 1000 && di->soc_pre <= 10) { if (bq27541_battery_voltage(di) <= 3300 * 1000 && bq27541_battery_voltage(di) > 2500 * 1000) {//check again counter_temp = CAPACITY_SALTATE_COUNTER - 1;//about 9s } } if(di->saltate_counter < counter_temp) return di->soc_pre; else di->saltate_counter = 0; } else di->saltate_counter = 0; if(soc < di->soc_pre) soc_calib = di->soc_pre - 1; else if (di->batt_vol_pre <= 3300 * 1000 && di->batt_vol_pre > 2500 * 1000 && di->soc_pre > 0)//sjc1118 add for batt_vol is too low but soc is not jumping soc_calib = di->soc_pre - 1; else soc_calib = di->soc_pre; } } else { soc_calib = soc; } if(soc_calib > 100) soc_calib = 100; di->soc_pre = soc_calib; if(soc_temp != soc_calib) { //store when soc changed backup_soc_ex(soc_calib); pr_info("soc:%d, soc_calib:%d\n", soc, soc_calib); } return soc_calib; } static int bq27541_battery_soc(struct bq27541_device_info *di, bool raw) { int ret; int soc = 0; #ifdef CONFIG_MACH_MSM8974_14001 /* jingchun.wang@Onlinerd.Driver, 2014/02/27 Add for get right soc when sleep long time */ if(atomic_read(&di->suspended) == 1) { return di->soc_pre; } #endif /*CONFIG_MACH_MSM8974_14001*/ if(di->alow_reading == true) { ret = bq27541_read(BQ27541_REG_SOC, &soc, 0, di); if (ret) { dev_err(di->dev, "error reading soc.ret:%d\n",ret); goto read_soc_err; } } else { if(di->soc_pre) return di->soc_pre; else return 0; } if (raw == true) { if(soc > 90) { soc += 2; } if(soc <= di->soc_pre) { di->soc_pre = soc; } } soc = bq27541_soc_calibrate(di,soc); return soc; read_soc_err: if(di->soc_pre) return di->soc_pre; else return 0; } static int bq27541_average_current(struct bq27541_device_info *di) { int ret; int curr = 0; #ifdef CONFIG_MACH_MSM8974_14001 /* jingchun.wang@Onlinerd.Driver, 2014/02/27 Add for get right soc when sleep long time */ if(atomic_read(&di->suspended) == 1) { return -di->current_pre; } #endif /*CONFIG_MACH_MSM8974_14001*/ if(di->alow_reading == true) { ret = bq27541_read(BQ27541_REG_AI, &curr, 0, di); if (ret) { dev_err(di->dev, "error reading current.\n"); return ret; } } else { return -di->current_pre; } // negative current if(curr&0x8000) curr = -((~(curr-1))&0xFFFF); di->current_pre = curr; return -curr; } #endif /* OPPO 2013-08-24 wangjc Add end */ /* * Return the battery Voltage in milivolts * Or < 0 if something fails. */ static int bq27541_battery_voltage(struct bq27541_device_info *di) { int ret; int volt = 0; #ifdef CONFIG_MACH_MSM8974_14001 /* jingchun.wang@Onlinerd.Driver, 2014/02/27 Add for get right soc when sleep long time */ if(atomic_read(&di->suspended) == 1) { return di->batt_vol_pre; } #endif /*CONFIG_MACH_MSM8974_14001*/ if(di->alow_reading == true) { ret = bq27541_read(BQ27541_REG_VOLT, &volt, 0, di); if (ret) { dev_err(di->dev, "error reading voltage,ret:%d\n",ret); return ret; } } else { return di->batt_vol_pre; } di->batt_vol_pre = volt * 1000; return volt * 1000; } static void bq27541_cntl_cmd(struct bq27541_device_info *di, int subcmd) { bq27541_i2c_txsubcmd(BQ27541_REG_CNTL, subcmd, di); } /* * i2c specific code */ static int bq27541_i2c_txsubcmd(u8 reg, unsigned short subcmd, struct bq27541_device_info *di) { struct i2c_msg msg; unsigned char data[3]; int ret; if (!di->client) return -ENODEV; memset(data, 0, sizeof(data)); data[0] = reg; data[1] = subcmd & 0x00FF; data[2] = (subcmd & 0xFF00) >> 8; msg.addr = di->client->addr; msg.flags = 0; msg.len = 3; msg.buf = data; ret = i2c_transfer(di->client->adapter, &msg, 1); if (ret < 0) return -EIO; return 0; } static int bq27541_chip_config(struct bq27541_device_info *di) { int flags = 0, ret = 0; bq27541_cntl_cmd(di, BQ27541_SUBCMD_CTNL_STATUS); udelay(66); ret = bq27541_read(BQ27541_REG_CNTL, &flags, 0, di); if (ret < 0) { dev_err(di->dev, "error reading register %02x ret = %d\n", BQ27541_REG_CNTL, ret); return ret; } udelay(66); bq27541_cntl_cmd(di, BQ27541_SUBCMD_ENABLE_IT); udelay(66); if (!(flags & BQ27541_CS_DLOGEN)) { bq27541_cntl_cmd(di, BQ27541_SUBCMD_ENABLE_DLOG); udelay(66); } return 0; } static void bq27541_coulomb_counter_work(struct work_struct *work) { int value = 0, temp = 0, index = 0, ret = 0; struct bq27541_device_info *di; unsigned long flags; int count = 0; di = container_of(work, struct bq27541_device_info, counter); /* retrieve 30 values from FIFO of coulomb data logging buffer * and average over time */ do { ret = bq27541_read(BQ27541_REG_LOGBUF, &temp, 0, di); if (ret < 0) break; if (temp != 0x7FFF) { ++count; value += temp; } /* delay 66uS, waiting time between continuous reading * results */ udelay(66); ret = bq27541_read(BQ27541_REG_LOGIDX, &index, 0, di); if (ret < 0) break; udelay(66); } while (index != 0 || temp != 0x7FFF); if (ret < 0) { dev_err(di->dev, "Error reading datalog register\n"); return; } if (count) { spin_lock_irqsave(&lock, flags); coulomb_counter = value/count; spin_unlock_irqrestore(&lock, flags); } } static int bq27541_get_battery_mvolts(void) { return bq27541_battery_voltage(bq27541_di); } static int bq27541_get_battery_temperature(void) { return bq27541_battery_temperature(bq27541_di); } static int bq27541_is_battery_present(void) { return 1; } static int bq27541_is_battery_temp_within_range(void) { return 1; } static int bq27541_is_battery_id_valid(void) { return 1; } /* OPPO 2013-08-24 wangjc Add begin for add adc interface. */ #ifdef CONFIG_MACH_MSM8974_14001 static int bq27541_get_batt_cc(void)/* yangfangbiao@oneplus.cn, 2015/02/13 Add cc interface */ { return bq27541_battery_cc(bq27541_di); } static int bq27541_get_batt_fcc(void)//sjc20150105 { return bq27541_battery_fcc(bq27541_di); } static int bq27541_get_batt_remaining_capacity(void) { return bq27541_remaining_capacity(bq27541_di); } static int bq27541_get_battery_soc(void) { return bq27541_battery_soc(bq27541_di, false); } static int bq27541_get_average_current(void) { return bq27541_average_current(bq27541_di); } //wangjc add for authentication static int bq27541_is_battery_authenticated(void) { if(bq27541_di) { return bq27541_di->is_authenticated; } return false; } static int bq27541_fast_chg_started(void) { if(bq27541_di) { return bq27541_di->fast_chg_started; } return false; } static int bq27541_fast_switch_to_normal(void) { if(bq27541_di) { //pr_err("%s fast_switch_to_normal:%d\n",__func__,bq27541_di->fast_switch_to_normal); return bq27541_di->fast_switch_to_normal; } return false; } static int bq27541_set_switch_to_noraml_false(void) { if(bq27541_di) { bq27541_di->fast_switch_to_normal = false; } return 0; } static int bq27541_get_fast_low_temp_full(void) { if(bq27541_di) { return bq27541_di->fast_low_temp_full; } return false; } static int bq27541_set_fast_low_temp_full_false(void) { if(bq27541_di) { return bq27541_di->fast_low_temp_full = false; } return 0; } #endif /* OPPO 2013-08-24 wangjc Add end */ /* OPPO 2013-12-12 liaofuchun add for set/get fastchg allow begin*/ static int bq27541_fast_normal_to_warm(void) { if(bq27541_di) { //pr_err("%s fast_switch_to_normal:%d\n",__func__,bq27541_di->fast_switch_to_normal); return bq27541_di->fast_normal_to_warm; } return 0; } static int bq27541_set_fast_normal_to_warm_false(void) { if(bq27541_di) { bq27541_di->fast_normal_to_warm = false; } return 0; } static int bq27541_set_fast_chg_allow(int enable) { if(bq27541_di) { bq27541_di->fast_chg_allow = enable; } return 0; } static int bq27541_get_fast_chg_allow(void) { if(bq27541_di) { return bq27541_di->fast_chg_allow; } return 0; } static int bq27541_get_fast_chg_ing(void) { if(bq27541_di) { return bq27541_di->fast_chg_ing; } return 0; } /* OPPO 2013-12-12 liaofuchun add for set/get fastchg allow end */ static struct qpnp_battery_gauge bq27541_batt_gauge = { .get_battery_mvolts = bq27541_get_battery_mvolts, .get_battery_temperature = bq27541_get_battery_temperature, .is_battery_present = bq27541_is_battery_present, .is_battery_temp_within_range = bq27541_is_battery_temp_within_range, .is_battery_id_valid = bq27541_is_battery_id_valid, /* OPPO 2013-09-30 wangjc Add begin for add new interface */ #ifdef CONFIG_MACH_MSM8974_14001 .get_batt_cc = bq27541_get_batt_cc, /* yangfangbiao@oneplus.cn, 2015/02/13 Add cc interface */ .get_batt_fcc = bq27541_get_batt_fcc, /* yangfangbiao@oneplus.cn, 2015/01/06 Add for sync with KK charge standard */ .get_batt_remaining_capacity = bq27541_get_batt_remaining_capacity, .get_battery_soc = bq27541_get_battery_soc, .get_average_current = bq27541_get_average_current, //wangjc add for authentication .is_battery_authenticated = bq27541_is_battery_authenticated, .fast_chg_started = bq27541_fast_chg_started, .fast_switch_to_normal = bq27541_fast_switch_to_normal, .set_switch_to_noraml_false = bq27541_set_switch_to_noraml_false, .set_fast_chg_allow = bq27541_set_fast_chg_allow, .get_fast_chg_allow = bq27541_get_fast_chg_allow, .fast_normal_to_warm = bq27541_fast_normal_to_warm, .set_normal_to_warm_false = bq27541_set_fast_normal_to_warm_false, .get_fast_chg_ing = bq27541_get_fast_chg_ing, .get_fast_low_temp_full = bq27541_get_fast_low_temp_full, .set_low_temp_full_false = bq27541_set_fast_low_temp_full_false, #endif /* OPPO 2013-09-30 wangjc Add end */ }; static bool bq27541_authenticate(struct i2c_client *client); static int bq27541_batt_type_detect(struct i2c_client *client); static void bq27541_hw_config(struct work_struct *work) { int ret = 0, flags = 0, type = 0, fw_ver = 0; struct bq27541_device_info *di; di = container_of(work, struct bq27541_device_info, hw_config.work); ret = bq27541_chip_config(di); if (ret) { dev_err(di->dev, "Failed to config Bq27541\n"); #ifdef CONFIG_MACH_MSM8974_14001 /* jingchun.wang@Onlinerd.Driver, 2014/02/12 Add for retry when config fail */ di->retry_count--; if(di->retry_count > 0) { schedule_delayed_work(&di->hw_config, HZ); } #endif /*CONFIG_MACH_MSM8974_14001*/ return; } qpnp_battery_gauge_register(&bq27541_batt_gauge); bq27541_cntl_cmd(di, BQ27541_SUBCMD_CTNL_STATUS); udelay(66); bq27541_read(BQ27541_REG_CNTL, &flags, 0, di); bq27541_cntl_cmd(di, BQ27541_SUBCMD_DEVCIE_TYPE); udelay(66); bq27541_read(BQ27541_REG_CNTL, &type, 0, di); bq27541_cntl_cmd(di, BQ27541_SUBCMD_FW_VER); udelay(66); bq27541_read(BQ27541_REG_CNTL, &fw_ver, 0, di); #ifdef CONFIG_MACH_MSM8974_14001 /*OPPO 2013-09-18 liaofuchun add begin for check authenticate data*/ di->is_authenticated = bq27541_authenticate(di->client); di->battery_type = bq27541_batt_type_detect(di->client); #endif //CONFIG_MACH_MSM8974_14001 dev_info(di->dev, "DEVICE_TYPE is 0x%02X, FIRMWARE_VERSION is 0x%02X\n", type, fw_ver); dev_info(di->dev, "Complete bq27541 configuration 0x%02X\n", flags); } static int bq27541_read_i2c(u8 reg, int *rt_value, int b_single, struct bq27541_device_info *di) { struct i2c_client *client = di->client; /* OPPO 2013-12-09 wangjc Modify begin for use standard i2c interface */ #ifndef CONFIG_MACH_MSM8974_14001 struct i2c_msg msg[1]; #else struct i2c_msg msg[2]; #endif /* OPPO 2013-12-09 wangjc Modify end */ unsigned char data[2]; int err; if (!client->adapter) return -ENODEV; /* OPPO 2013-09-30 wangjc Add begin for eliminate conflict */ #ifdef CONFIG_MACH_MSM8974_14001 mutex_lock(&battery_mutex); #endif /* OPPO 2013-09-30 wangjc Add end */ /* OPPO 2013-12-09 wangjc Modify begin for use standard i2c interface */ #ifndef CONFIG_MACH_MSM8974_14001 msg->addr = client->addr; msg->flags = 0; msg->len = 1; msg->buf = data; data[0] = reg; err = i2c_transfer(client->adapter, msg, 1); if (err >= 0) { if (!b_single) msg->len = 2; else msg->len = 1; msg->flags = I2C_M_RD; err = i2c_transfer(client->adapter, msg, 1); if (err >= 0) { if (!b_single) *rt_value = get_unaligned_le16(data); else *rt_value = data[0]; mutex_unlock(&battery_mutex); return 0; } } #else /* Write register */ msg[0].addr = client->addr; msg[0].flags = 0; msg[0].len = 1; msg[0].buf = data; data[0] = reg; /* Read data */ msg[1].addr = client->addr; msg[1].flags = I2C_M_RD; if (!b_single) msg[1].len = 2; else msg[1].len = 1; msg[1].buf = data; err = i2c_transfer(client->adapter, msg, 2); if (err >= 0) { if (!b_single) *rt_value = get_unaligned_le16(data); else *rt_value = data[0]; mutex_unlock(&battery_mutex); return 0; } #endif /* OPPO 2013-12-09 wangjc Modify end */ /* OPPO 2013-09-30 wangjc Add begin for eliminate conflict */ #ifdef CONFIG_MACH_MSM8974_14001 mutex_unlock(&battery_mutex); #endif /* OPPO 2013-09-30 wangjc Add end */ return err; } #ifdef CONFIG_BQ27541_TEST_ENABLE static int reg; static int subcmd; static ssize_t bq27541_read_stdcmd(struct device *dev, struct device_attribute *attr, char *buf) { int ret; int temp = 0; struct platform_device *client; struct bq27541_device_info *di; client = to_platform_device(dev); di = platform_get_drvdata(client); if (reg <= BQ27541_REG_ICR && reg > 0x00) { ret = bq27541_read(reg, &temp, 0, di); if (ret) ret = snprintf(buf, PAGE_SIZE, "Read Error!\n"); else ret = snprintf(buf, PAGE_SIZE, "0x%02x\n", temp); } else ret = snprintf(buf, PAGE_SIZE, "Register Error!\n"); return ret; } static ssize_t bq27541_write_stdcmd(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { ssize_t ret = strnlen(buf, PAGE_SIZE); int cmd; sscanf(buf, "%x", &cmd); reg = cmd; return ret; } static ssize_t bq27541_read_subcmd(struct device *dev, struct device_attribute *attr, char *buf) { int ret; int temp = 0; struct platform_device *client; struct bq27541_device_info *di; client = to_platform_device(dev); di = platform_get_drvdata(client); if (subcmd == BQ27541_SUBCMD_DEVCIE_TYPE || subcmd == BQ27541_SUBCMD_FW_VER || subcmd == BQ27541_SUBCMD_HW_VER || subcmd == BQ27541_SUBCMD_CHEM_ID) { bq27541_cntl_cmd(di, subcmd); /* Retrieve Chip status */ udelay(66); ret = bq27541_read(BQ27541_REG_CNTL, &temp, 0, di); if (ret) ret = snprintf(buf, PAGE_SIZE, "Read Error!\n"); else ret = snprintf(buf, PAGE_SIZE, "0x%02x\n", temp); } else ret = snprintf(buf, PAGE_SIZE, "Register Error!\n"); return ret; } static ssize_t bq27541_write_subcmd(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { ssize_t ret = strnlen(buf, PAGE_SIZE); int cmd; sscanf(buf, "%x", &cmd); subcmd = cmd; return ret; } static DEVICE_ATTR(std_cmd, S_IRUGO|S_IWUGO, bq27541_read_stdcmd, bq27541_write_stdcmd); static DEVICE_ATTR(sub_cmd, S_IRUGO|S_IWUGO, bq27541_read_subcmd, bq27541_write_subcmd); static struct attribute *fs_attrs[] = { &dev_attr_std_cmd.attr, &dev_attr_sub_cmd.attr, NULL, }; static struct attribute_group fs_attr_group = { .attrs = fs_attrs, }; static struct platform_device this_device = { .name = "bq27541-test", .id = -1, .dev.platform_data = NULL, }; #endif #ifdef CONFIG_MACH_MSM8974_14001 /*OPPO 2013-09-18 liaofuchun add begin for bq27541 authenticate */ #define BLOCKDATACTRL 0X61 #define DATAFLASHBLOCK 0X3F #define AUTHENDATA 0X40 #define AUTHENCHECKSUM 0X54 #define MESSAGE_LEN 20 #define KEY_LEN 16 /* OPPO 2014-02-25 sjc Modify begin for FIND7OP not use authenticate */ #if defined (CONFIG_MACH_MSM8974_14001) || defined (CONFIG_OPPO_MSM_14021) static bool bq27541_authenticate(struct i2c_client *client) { return true; } #else static bool bq27541_authenticate(struct i2c_client *client) { char recv_buf[MESSAGE_LEN]={0x0}; char send_buf[MESSAGE_LEN]={0x0}; char result[MESSAGE_LEN]={0x0}; char Key[KEY_LEN]={0x77,0x30,0xa1,0x28,0x0a,0xa1,0x13,0x20,0xef,0xcd,0xab,0x89,0x67,0x45,0x23,0x01}; char checksum_buf[1] ={0x0}; char authen_cmd_buf[1] = {0x00}; int i,rc; pr_info("%s Enter\n",__func__); // step 0: produce 20 bytes random data and checksum get_random_bytes(send_buf,20); for(i = 0;i < 20;i++){ checksum_buf[0] = checksum_buf[0] + send_buf[i]; } checksum_buf[0] = 0xff - (checksum_buf[0]&0xff); /* step 1: unseal mode->write 0x01 to blockdatactrl authen_cmd_buf[0] = 0x01; rc = i2c_smbus_write_i2c_block_data(client,BLOCKDATACTRL,1,&authen_cmd_buf[0]); } */ // step 1: seal mode->write 0x00 to dataflashblock rc = i2c_smbus_write_i2c_block_data(client,DATAFLASHBLOCK,1,&authen_cmd_buf[0]); if( rc < 0 ){ pr_info("%s i2c write error\n",__func__); return false; } // step 2: write 20 bytes to authendata_reg i2c_smbus_write_i2c_block_data(client,AUTHENDATA,MESSAGE_LEN,&send_buf[0]); msleep(1); // step 3: write checksum to authenchecksum_reg for compute i2c_smbus_write_i2c_block_data(client,AUTHENCHECKSUM,1,&checksum_buf[0]); msleep(50); // step 4: read authendata i2c_smbus_read_i2c_block_data(client,AUTHENDATA,MESSAGE_LEN,&recv_buf[0]); // step 5: phone do hmac(sha1-generic) algorithm BQ27541_HMACSHA1_authenticate(send_buf,Key,result); // step 6: compare recv_buf from bq27541 and result by phone rc = strncmp(recv_buf,result,MESSAGE_LEN); if(rc == 0){ pr_info("bq27541_authenticate success\n"); return true; } pr_info("bq27541_authenticate error,dump buf:\n"); for(i = 0;i < 20;i++){ pr_info("send_buf[%d]:0x%x,recv_buf[%d]:0x%x ?= result[%d]:0x%x\n",i,send_buf[i],i,recv_buf[i],i,result[i]); } return false; } #endif //CONFIG_MACH_MSM8974_14001 /* OPPO 2014-02-25 sjc Modify end */ #endif //CONFIG_MACH_MSM8974_14001 #ifdef CONFIG_MACH_MSM8974_14001 //Fuchun.Liao@EXP.Driver,2014/01/10 add for check battery type #define BATTERY_2700MA 0 #define BATTERY_3000MA 1 #define TYPE_INFO_LEN 8 #if defined (CONFIG_MACH_MSM8974_14001) || defined (CONFIG_OPPO_MSM_14021) static int bq27541_batt_type_detect(struct i2c_client *client) { return BATTERY_3000MA; } #else //defined (CONFIG_MACH_MSM8974_14001) || defined (CONFIG_OPPO_MSM_14021) /* jingchun.wang@Onlinerd.Driver, 2014/03/10 Modify for 14001 */ static int bq27541_batt_type_detect(struct i2c_client *client) { char blockA_cmd_buf[1] = {0x01}; char rc = 0; char recv_buf[TYPE_INFO_LEN] = {0x0}; int i = 0; rc = i2c_smbus_write_i2c_block_data(client,DATAFLASHBLOCK,1,&blockA_cmd_buf[0]); if( rc < 0 ){ pr_info("%s i2c write error\n",__func__); return 0; } msleep(30); //it is needed i2c_smbus_read_i2c_block_data(client,AUTHENDATA,TYPE_INFO_LEN,&recv_buf[0]); if((recv_buf[0] == 0x01) && (recv_buf[1] == 0x09) && (recv_buf[2] == 0x08) && (recv_buf[3] == 0x06)) rc = BATTERY_2700MA; else if((recv_buf[0] == 0x02) && (recv_buf[1] == 0x00) && (recv_buf[2] == 0x01) && (recv_buf[3] == 0x03)) rc = BATTERY_3000MA; else { for(i = 0;i < TYPE_INFO_LEN;i++) pr_info("%s error,recv_buf[%d]:0x%x\n",__func__,i,recv_buf[i]); rc = BATTERY_2700MA; } pr_info("%s battery_type:%d\n",__func__,rc); return rc; } #endif //defined (CONFIG_MACH_MSM8974_14001) || defined (CONFIG_OPPO_MSM_14021) #endif //CONFIG_MACH_MSM8974_14001 /* OPPO 2013-12-12 liaofuchun add for fastchg */ #ifdef CONFIG_PIC1503_FASTCG #define AP_TX_EN GPIO_CFG(0, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA) #define AP_TX_DIS GPIO_CFG(0, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA) static irqreturn_t irq_rx_handler(int irq, void *dev_id) { struct bq27541_device_info *di = dev_id; //pr_info("%s\n", __func__); schedule_work(&di->fastcg_work); return IRQ_HANDLED; } #define AP_SWITCH_USB GPIO_CFG(96, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA) static void fastcg_work_func(struct work_struct *work) { int data = 0; int i; int bit = 0; int retval = 0; int ret_info = 0; static int fw_ver_info = 0; int volt = 0; int temp = 0; int soc = 0; int current_now = 0; int remain_cap = 0; static bool isnot_power_on = 0; free_irq(bq27541_di->irq, bq27541_di); for(i = 0; i < 7; i++) { gpio_set_value(0, 0); gpio_tlmm_config(AP_TX_EN, GPIO_CFG_ENABLE); usleep_range(1000,1000); gpio_set_value(0, 1); gpio_tlmm_config(AP_TX_DIS, GPIO_CFG_ENABLE); usleep_range(19000,19000); bit = gpio_get_value(1); data |= bit<<(6-i); if((i == 2) && (data != 0x50) && (!fw_ver_info)){ //data recvd not start from "101" pr_err("%s data err:%d\n",__func__,data); if(bq27541_di->fast_chg_started == true) { bq27541_di->alow_reading = true; bq27541_di->fast_chg_started = false; bq27541_di->fast_chg_allow = false; bq27541_di->fast_switch_to_normal = false; bq27541_di->fast_normal_to_warm = false; bq27541_di->fast_chg_ing = false; gpio_set_value(96, 0); mcu_en_gpio_set(1);//sjc0623 add retval = gpio_tlmm_config(AP_SWITCH_USB, GPIO_CFG_ENABLE); if (retval) { pr_err("%s switch usb error %d\n", __func__, retval); } power_supply_changed(bq27541_di->batt_psy); } goto out; } } pr_err("%s recv data:0x%x\n", __func__, data); //lfc add for power_supply_changed NULL pointer when batt_psy unregistered if(bq27541_di->batt_psy == NULL){ msleep(2); gpio_tlmm_config(GPIO_CFG(1,0,GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA),1); gpio_direction_output(1, 0); retval = request_irq(bq27541_di->irq, irq_rx_handler, IRQF_TRIGGER_RISING, "mcu_data", bq27541_di); //0X01:rising edge,0x02:falling edge if(retval < 0) pr_err("%s request ap rx irq failed.\n", __func__); return ; } if(data == 0x52) { //request fast charging wake_lock(&bq27541_di->fastchg_wake_lock); pic_need_to_up_fw = 0; fw_ver_info = 0; bq27541_di->alow_reading = false; bq27541_di->fast_chg_started = true; bq27541_di->fast_chg_allow = false; bq27541_di->fast_normal_to_warm = false; mod_timer(&bq27541_di->watchdog, jiffies + msecs_to_jiffies(10000)); if(!isnot_power_on){ isnot_power_on = 1; ret_info = 0x1; } else { ret_info = 0x2; } } else if(data == 0x54) { //fast charge stopped bq27541_di->alow_reading = true; bq27541_di->fast_chg_started = false; bq27541_di->fast_chg_allow = false; bq27541_di->fast_switch_to_normal = false; bq27541_di->fast_normal_to_warm = false; bq27541_di->fast_chg_ing = false; //switch off fast chg pr_info("%s fastchg stop unexpectly,switch off fastchg\n", __func__); gpio_set_value(96, 0); mcu_en_gpio_set(1);//sjc0623 add retval = gpio_tlmm_config(AP_SWITCH_USB, GPIO_CFG_ENABLE); if (retval) { pr_err("%s switch usb error %d\n", __func__, retval); } del_timer(&bq27541_di->watchdog); ret_info = 0x2; } else if(data == 0x58) { //tell ap can read i2c bq27541_di->alow_reading = true; //reading bq27541_di->fast_chg_ing = true; volt = bq27541_get_battery_mvolts(); temp = bq27541_get_battery_temperature(); remain_cap = bq27541_get_batt_remaining_capacity(); soc = bq27541_get_battery_soc(); current_now = bq27541_get_average_current(); pr_err("%s volt:%d,temp:%d,remain_cap:%d,soc:%d,current:%d\n",__func__,volt,temp, remain_cap,soc,current_now); //don't read bq27541_di->alow_reading = false; mod_timer(&bq27541_di->watchdog, jiffies + msecs_to_jiffies(10000)); ret_info = 0x2; } else if(data == 0x5a){ //fastchg full,vbatt > 4350 #if 0 //lfc modify for it(set fast_switch_to_normal ture) is earlier than usb_plugged_out irq(set it false) bq27541_di->fast_switch_to_normal = true; bq27541_di->alow_reading = true; bq27541_di->fast_chg_started = false; bq27541_di->fast_chg_allow = false; #endif //switch off fast chg pr_info("%s fastchg full,switch off fastchg,set GPIO96 0\n", __func__); gpio_set_value(96, 0); mcu_en_gpio_set(1);//sjc0623 add retval = gpio_tlmm_config(AP_SWITCH_USB, GPIO_CFG_ENABLE); if (retval) { pr_err("%s switch usb error %d\n", __func__, retval); } del_timer(&bq27541_di->watchdog); ret_info = 0x2; } else if(data == 0x53){ if (bq27541_di->battery_type == BATTERY_3000MA){ //13097 ATL battery //if temp:10~20 decigec,vddmax = 4250mv //switch off fast chg pr_info("%s fastchg low temp full,switch off fastchg,set GPIO96 0\n", __func__); gpio_set_value(96, 0); mcu_en_gpio_set(1);//sjc0623 add retval = gpio_tlmm_config(AP_SWITCH_USB, GPIO_CFG_ENABLE); if (retval) { pr_err("%s switch usb error %d\n", __func__, retval); } } del_timer(&bq27541_di->watchdog); ret_info = 0x2; } else if(data == 0x59){ //usb bad connected,stop fastchg #if 0 //lfc modify for it(set fast_switch_to_normal ture) is earlier than usb_plugged_out irq(set it false) bq27541_di->alow_reading = true; bq27541_di->fast_chg_started = false; bq27541_di->fast_chg_allow = false; bq27541_di->fast_switch_to_normal = true; #endif //switch off fast chg pr_info("%s usb bad connect,switch off fastchg\n", __func__); gpio_set_value(96, 0); mcu_en_gpio_set(1);//sjc0623 add retval = gpio_tlmm_config(AP_SWITCH_USB, GPIO_CFG_ENABLE); if (retval) { pr_err("%s switch usb error %d\n", __func__, retval); } del_timer(&bq27541_di->watchdog); ret_info = 0x2; } else if(data == 0x5c){ //fastchg temp over 45 or under 20 pr_info("%s fastchg temp > 45 or < 20,switch off fastchg,set GPIO96 0\n", __func__); gpio_set_value(96, 0); mcu_en_gpio_set(1);//sjc0623 add retval = gpio_tlmm_config(AP_SWITCH_USB, GPIO_CFG_ENABLE); if (retval) { pr_err("%s switch usb error %d\n", __func__, retval); } del_timer(&bq27541_di->watchdog); ret_info = 0x2; } else if(data == 0x56){ //ready to get fw_ver fw_ver_info = 1; ret_info = 0x2; } else if(fw_ver_info){ //get fw_ver //fw in local is large than mcu1503_fw_ver if((!pic_have_updated) && (Pic16F_firmware_data[pic_fw_ver_count - 4] > data)){ ret_info = 0x2; pic_need_to_up_fw = 1; //need to update fw }else{ ret_info = 0x1; pic_need_to_up_fw = 0; //fw is already new,needn't to up } pr_info("local_fw:0x%x,need_to_up_fw:%d\n",Pic16F_firmware_data[pic_fw_ver_count - 4],pic_need_to_up_fw); fw_ver_info = 0; } else { gpio_set_value(96, 0); mcu_en_gpio_set(1);//sjc0623 add retval = gpio_tlmm_config(AP_SWITCH_USB, GPIO_CFG_ENABLE); if (retval) { pr_err("%s data err(101xxxx) switch usb error %d\n", __func__, retval); goto out; //avoid i2c conflict } msleep(500); //avoid i2c conflict //data err bq27541_di->alow_reading = true; bq27541_di->fast_chg_started = false; bq27541_di->fast_chg_allow = false; bq27541_di->fast_switch_to_normal = false; bq27541_di->fast_normal_to_warm = false; bq27541_di->fast_chg_ing = false; //data err pr_info("%s data err(101xxxx),switch off fastchg\n", __func__); power_supply_changed(bq27541_di->batt_psy); goto out; } msleep(2); gpio_tlmm_config(GPIO_CFG(1,0,GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA),1); gpio_direction_output(1, 0); for(i = 0; i < 3; i++) { if(i == 0){ //tell mcu1503 battery_type gpio_set_value(1, ret_info >> 1); } else if(i == 1){ gpio_set_value(1, ret_info & 0x1); } else { gpio_set_value(1,bq27541_di->battery_type); } gpio_set_value(0, 0); gpio_tlmm_config(AP_TX_EN, GPIO_CFG_ENABLE); usleep_range(1000,1000); gpio_set_value(0, 1); gpio_tlmm_config(AP_TX_DIS, GPIO_CFG_ENABLE); usleep_range(19000,19000); } out: gpio_tlmm_config(GPIO_CFG(1,0,GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA),1); gpio_direction_input(1); //lfc add for it is faster than usb_plugged_out irq to send 0x5a(fast_chg full and usb bad connected) to AP if(data == 0x5a || data == 0x59){ usleep_range(180000,180000); bq27541_di->fast_switch_to_normal = true; bq27541_di->alow_reading = true; bq27541_di->fast_chg_started = false; bq27541_di->fast_chg_allow = false; bq27541_di->fast_chg_ing = false; } //fastchg temp over( > 45 or < 20) //lfc add to set fastchg vddmax = 4250mv during 10 ~ 20 decigec for ATL 3000mAH battery if(data == 0x53){ if(bq27541_di->battery_type == BATTERY_3000MA){ //13097 ATL battery usleep_range(180000,180000); bq27541_di->fast_low_temp_full = true; bq27541_di->alow_reading = true; bq27541_di->fast_chg_started = false; bq27541_di->fast_chg_allow = false; bq27541_di->fast_chg_ing = false; } } //lfc add to set fastchg vddmax = 4250mv end if(data == 0x5c){ usleep_range(180000,180000); bq27541_di->fast_normal_to_warm = true; bq27541_di->alow_reading = true; bq27541_di->fast_chg_started = false; bq27541_di->fast_chg_allow = false; bq27541_di->fast_chg_ing = false; } if(pic_need_to_up_fw){ msleep(500); del_timer(&bq27541_di->watchdog); pic16f_fw_update(false); pic_need_to_up_fw = 0; mod_timer(&bq27541_di->watchdog, jiffies + msecs_to_jiffies(10000)); } retval = request_irq(bq27541_di->irq, irq_rx_handler, IRQF_TRIGGER_RISING, "mcu_data", bq27541_di); //0X01:rising edge,0x02:falling edge if(retval < 0) { pr_err("%s request ap rx irq failed.\n", __func__); } if((data == 0x52) || (data == 0x58)){ power_supply_changed(bq27541_di->batt_psy); } if(data == 0x53){ if(bq27541_di->battery_type == BATTERY_3000MA){ power_supply_changed(bq27541_di->batt_psy); wake_unlock(&bq27541_di->fastchg_wake_lock); } } if((data == 0x54) || (data == 0x5a) || (data == 0x59) || (data == 0x5c)){ power_supply_changed(bq27541_di->batt_psy); wake_unlock(&bq27541_di->fastchg_wake_lock); } } void di_watchdog(unsigned long data) { struct bq27541_device_info *di = (struct bq27541_device_info *)data; int ret = 0; pr_err("di_watchdog can't receive mcu data\n"); di->alow_reading = true; di->fast_chg_started = false; di->fast_switch_to_normal = false; di->fast_low_temp_full = false; di->fast_chg_allow = false; di->fast_normal_to_warm = false; di->fast_chg_ing = false; //switch off fast chg pr_info("%s switch off fastchg\n", __func__); gpio_set_value(96, 0); mcu_en_gpio_set(1);//sjc0623 add ret = gpio_tlmm_config(AP_SWITCH_USB, GPIO_CFG_ENABLE); if (ret) { pr_info("%s switch usb error %d\n", __func__, ret); } wake_unlock(&bq27541_di->fastchg_wake_lock); } #endif /* OPPO 2013-12-12 liaofuchun add for fastchg */ #define MAX_RETRY_COUNT 5 static int bq27541_battery_probe(struct i2c_client *client, const struct i2c_device_id *id) { char *name; struct bq27541_device_info *di; struct bq27541_access_methods *bus; int num; int retval = 0; #ifdef CONFIG_OPPO_MSM_14021 /* OPPO 2014-06-23 sjc Add begin for 14021 */ struct device_node *dev_node = client->dev.of_node; int ret; if (dev_node) { mcu_en_gpio = of_get_named_gpio(dev_node, "microchip,mcu-en-gpio", 0); } else { mcu_en_gpio = 0; printk(KERN_ERR "%s: mcu_en_gpio failed\n", __func__); } if (gpio_is_valid(mcu_en_gpio)) { ret = gpio_request(mcu_en_gpio, "mcu_en_gpio"); if (ret) { printk(KERN_ERR "%s: gpio_request failed for %d ret=%d\n", __func__, mcu_en_gpio, ret); } else { gpio_set_value(mcu_en_gpio, 0); } } #endif //CONFIG_OPPO_MSM_14021 pr_info("%s\n", __func__); if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) return -ENODEV; /* Get new ID for the new battery device */ retval = idr_pre_get(&battery_id, GFP_KERNEL); if (retval == 0) return -ENOMEM; mutex_lock(&battery_mutex); retval = idr_get_new(&battery_id, client, &num); mutex_unlock(&battery_mutex); if (retval < 0) return retval; name = kasprintf(GFP_KERNEL, "%s-%d", id->name, num); if (!name) { dev_err(&client->dev, "failed to allocate device name\n"); retval = -ENOMEM; goto batt_failed_1; } di = kzalloc(sizeof(*di), GFP_KERNEL); if (!di) { dev_err(&client->dev, "failed to allocate device info data\n"); retval = -ENOMEM; goto batt_failed_2; } di->id = num; bus = kzalloc(sizeof(*bus), GFP_KERNEL); if (!bus) { dev_err(&client->dev, "failed to allocate access method " "data\n"); retval = -ENOMEM; goto batt_failed_3; } i2c_set_clientdata(client, di); di->dev = &client->dev; bus->read = &bq27541_read_i2c; di->bus = bus; di->client = client; /* OPPO 2013-08-19 wangjc Add begin for error temp */ #ifdef CONFIG_MACH_MSM8974_14001 di->temp_pre = 0; #endif /* OPPO 2013-08-19 wangjc Add end */ di->alow_reading = true; di->fast_chg_ing = false; di->fast_low_temp_full = false; #ifdef CONFIG_MACH_MSM8974_14001 /* jingchun.wang@Onlinerd.Driver, 2014/02/12 Add for retry when config fail */ di->retry_count = MAX_RETRY_COUNT; atomic_set(&di->suspended, 0); #endif /*CONFIG_MACH_MSM8974_14001*/ #ifdef CONFIG_BQ27541_TEST_ENABLE platform_set_drvdata(&this_device, di); retval = platform_device_register(&this_device); if (!retval) { retval = sysfs_create_group(&this_device.dev.kobj, &fs_attr_group); if (retval) goto batt_failed_4; } else goto batt_failed_4; #endif if (retval) { dev_err(&client->dev, "failed to setup bq27541\n"); goto batt_failed_4; } if (retval) { dev_err(&client->dev, "failed to powerup bq27541\n"); goto batt_failed_4; } spin_lock_init(&lock); bq27541_di = di; INIT_WORK(&di->counter, bq27541_coulomb_counter_work); INIT_DELAYED_WORK(&di->hw_config, bq27541_hw_config); schedule_delayed_work(&di->hw_config, 0); /* OPPO 2013-12-22 wangjc add for fastchg*/ #ifdef CONFIG_PIC1503_FASTCG init_timer(&di->watchdog); di->watchdog.data = (unsigned long)di; di->watchdog.function = di_watchdog; wake_lock_init(&di->fastchg_wake_lock, WAKE_LOCK_SUSPEND, "fastcg_wake_lock"); INIT_WORK(&di->fastcg_work,fastcg_work_func); gpio_request(1, "mcu_clk"); gpio_tlmm_config(GPIO_CFG(1,0,GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA),1); gpio_direction_input(1); di->irq = gpio_to_irq(1); retval = request_irq(di->irq, irq_rx_handler, IRQF_TRIGGER_RISING, "mcu_data", di); //0X01:rising edge,0x02:falling edge if(retval < 0) { pr_err("%s request ap rx irq failed.\n", __func__); } #endif /* OPPO 2013-12-22 wangjc add end*/ return 0; batt_failed_4: kfree(bus); batt_failed_3: kfree(di); batt_failed_2: kfree(name); batt_failed_1: mutex_lock(&battery_mutex); idr_remove(&battery_id, num); mutex_unlock(&battery_mutex); return retval; } static int bq27541_battery_remove(struct i2c_client *client) { struct bq27541_device_info *di = i2c_get_clientdata(client); #ifdef CONFIG_OPPO_MSM_14021 /* OPPO 2014-06-23 sjc Add begin for 14021 */ if (gpio_is_valid(mcu_en_gpio))//sjc0623 add gpio_free(mcu_en_gpio); #endif qpnp_battery_gauge_unregister(&bq27541_batt_gauge); bq27541_cntl_cmd(di, BQ27541_SUBCMD_DISABLE_DLOG); udelay(66); bq27541_cntl_cmd(di, BQ27541_SUBCMD_DISABLE_IT); cancel_delayed_work_sync(&di->hw_config); kfree(di->bus); mutex_lock(&battery_mutex); idr_remove(&battery_id, di->id); mutex_unlock(&battery_mutex); kfree(di); return 0; } static int bq27541_battery_suspend(struct i2c_client *client, pm_message_t message) { struct bq27541_device_info *di = i2c_get_clientdata(client); atomic_set(&di->suspended, 1); return 0; } /*1 minute*/ #define RESUME_TIME 1*60 static int bq27541_battery_resume(struct i2c_client *client) { struct bq27541_device_info *di = i2c_get_clientdata(client); atomic_set(&di->suspended, 0); bq27541_battery_soc(bq27541_di, true); return 0; } static const struct of_device_id bq27541_match[] = { { .compatible = "ti,bq27541-battery" }, { }, }; static const struct i2c_device_id bq27541_id[] = { { "bq27541-battery", 1 }, {}, }; MODULE_DEVICE_TABLE(i2c, BQ27541_id); static struct i2c_driver bq27541_battery_driver = { .driver = { .name = "bq27541-battery", .owner = THIS_MODULE, .of_match_table = bq27541_match, }, .probe = bq27541_battery_probe, .remove = bq27541_battery_remove, .suspend = bq27541_battery_suspend , .resume = bq27541_battery_resume, .id_table = bq27541_id, }; static int __init bq27541_battery_init(void) { int ret; ret = i2c_add_driver(&bq27541_battery_driver); if (ret) printk(KERN_ERR "Unable to register BQ27541 driver\n"); return ret; } module_init(bq27541_battery_init); static void __exit bq27541_battery_exit(void) { i2c_del_driver(&bq27541_battery_driver); } module_exit(bq27541_battery_exit); MODULE_LICENSE("GPL v2"); MODULE_AUTHOR("Qualcomm Innovation Center, Inc."); MODULE_DESCRIPTION("BQ27541 battery monitor driver");
atila1974/AK-OnePlusOne-CAF
drivers/power/bq27541_fuelgauger.c
C
gpl-2.0
50,014
/* * linux/fs/inode.c * * (C) 1997 Linus Torvalds */ #include <linux/fs.h> #include <linux/mm.h> #include <linux/dcache.h> #include <linux/init.h> #include <linux/quotaops.h> #include <linux/slab.h> #include <linux/writeback.h> #include <linux/module.h> #include <linux/backing-dev.h> #include <linux/wait.h> #include <linux/rwsem.h> #include <linux/hash.h> #include <linux/swap.h> #include <linux/security.h> #include <linux/pagemap.h> #include <linux/cdev.h> #include <linux/bootmem.h> #include <linux/inotify.h> #include <linux/fsnotify.h> #include <linux/mount.h> #include <linux/async.h> #include <linux/posix_acl.h> /* * This is needed for the following functions: * - inode_has_buffers * - invalidate_inode_buffers * - invalidate_bdev * * FIXME: remove all knowledge of the buffer layer from this file */ #include <linux/buffer_head.h> /* * New inode.c implementation. * * This implementation has the basic premise of trying * to be extremely low-overhead and SMP-safe, yet be * simple enough to be "obviously correct". * * Famous last words. */ /* inode dynamic allocation 1999, Andrea Arcangeli <andrea@suse.de> */ /* #define INODE_PARANOIA 1 */ /* #define INODE_DEBUG 1 */ /* * Inode lookup is no longer as critical as it used to be: * most of the lookups are going to be through the dcache. */ #define I_HASHBITS i_hash_shift #define I_HASHMASK i_hash_mask static unsigned int i_hash_mask __read_mostly; static unsigned int i_hash_shift __read_mostly; /* * Each inode can be on two separate lists. One is * the hash list of the inode, used for lookups. The * other linked list is the "type" list: * "in_use" - valid inode, i_count > 0, i_nlink > 0 * "dirty" - as "in_use" but also dirty * "unused" - valid inode, i_count = 0 * * A "dirty" list is maintained for each super block, * allowing for low-overhead inode sync() operations. */ LIST_HEAD(inode_in_use); LIST_HEAD(inode_unused); static struct hlist_head *inode_hashtable __read_mostly; /* * A simple spinlock to protect the list manipulations. * * NOTE! You also have to own the lock if you change * the i_state of an inode while it is in use.. */ DEFINE_SPINLOCK(inode_lock); /* * iprune_sem provides exclusion between the kswapd or try_to_free_pages * icache shrinking path, and the umount path. Without this exclusion, * by the time prune_icache calls iput for the inode whose pages it has * been invalidating, or by the time it calls clear_inode & destroy_inode * from its final dispose_list, the struct super_block they refer to * (for inode->i_sb->s_op) may already have been freed and reused. * * We make this an rwsem because the fastpath is icache shrinking. In * some cases a filesystem may be doing a significant amount of work in * its inode reclaim code, so this should improve parallelism. */ static DECLARE_RWSEM(iprune_sem); /* * Statistics gathering.. */ struct inodes_stat_t inodes_stat; static struct kmem_cache *inode_cachep __read_mostly; static void wake_up_inode(struct inode *inode) { /* * Prevent speculative execution through spin_unlock(&inode_lock); */ smp_mb(); wake_up_bit(&inode->i_state, __I_LOCK); } /** * inode_init_always - perform inode structure intialisation * @sb: superblock inode belongs to * @inode: inode to initialise * * These are initializations that need to be done on every inode * allocation as the fields are not initialised by slab allocation. */ int inode_init_always(struct super_block *sb, struct inode *inode) { static const struct address_space_operations empty_aops; static const struct inode_operations empty_iops; static const struct file_operations empty_fops; struct address_space *const mapping = &inode->i_data; inode->i_sb = sb; inode->i_blkbits = sb->s_blocksize_bits; inode->i_flags = 0; atomic_set(&inode->i_count, 1); inode->i_op = &empty_iops; inode->i_fop = &empty_fops; inode->i_nlink = 1; inode->i_uid = 0; inode->i_gid = 0; atomic_set(&inode->i_writecount, 0); inode->i_size = 0; inode->i_blocks = 0; inode->i_bytes = 0; inode->i_generation = 0; #ifdef CONFIG_QUOTA memset(&inode->i_dquot, 0, sizeof(inode->i_dquot)); #endif inode->i_pipe = NULL; inode->i_bdev = NULL; inode->i_cdev = NULL; inode->i_rdev = 0; inode->dirtied_when = 0; if (security_inode_alloc(inode)) goto out; spin_lock_init(&inode->i_lock); lockdep_set_class(&inode->i_lock, &sb->s_type->i_lock_key); mutex_init(&inode->i_mutex); lockdep_set_class(&inode->i_mutex, &sb->s_type->i_mutex_key); init_rwsem(&inode->i_alloc_sem); lockdep_set_class(&inode->i_alloc_sem, &sb->s_type->i_alloc_sem_key); mapping->a_ops = &empty_aops; mapping->host = inode; mapping->flags = 0; mapping_set_gfp_mask(mapping, GFP_HIGHUSER_MOVABLE); mapping->assoc_mapping = NULL; mapping->backing_dev_info = &default_backing_dev_info; mapping->writeback_index = 0; /* * If the block_device provides a backing_dev_info for client * inodes then use that. Otherwise the inode share the bdev's * backing_dev_info. */ if (sb->s_bdev) { struct backing_dev_info *bdi; bdi = sb->s_bdev->bd_inode->i_mapping->backing_dev_info; mapping->backing_dev_info = bdi; } inode->i_private = NULL; inode->i_mapping = mapping; #ifdef CONFIG_FS_POSIX_ACL inode->i_acl = inode->i_default_acl = ACL_NOT_CACHED; #endif #ifdef CONFIG_FSNOTIFY inode->i_fsnotify_mask = 0; #endif return 0; out: return -ENOMEM; } EXPORT_SYMBOL(inode_init_always); static struct inode *alloc_inode(struct super_block *sb) { struct inode *inode; if (sb->s_op->alloc_inode) inode = sb->s_op->alloc_inode(sb); else inode = kmem_cache_alloc(inode_cachep, GFP_KERNEL); if (!inode) return NULL; if (unlikely(inode_init_always(sb, inode))) { if (inode->i_sb->s_op->destroy_inode) inode->i_sb->s_op->destroy_inode(inode); else kmem_cache_free(inode_cachep, inode); return NULL; } return inode; } void __destroy_inode(struct inode *inode) { BUG_ON(inode_has_buffers(inode)); security_inode_free(inode); fsnotify_inode_delete(inode); #ifdef CONFIG_FS_POSIX_ACL if (inode->i_acl && inode->i_acl != ACL_NOT_CACHED) posix_acl_release(inode->i_acl); if (inode->i_default_acl && inode->i_default_acl != ACL_NOT_CACHED) posix_acl_release(inode->i_default_acl); #endif } EXPORT_SYMBOL(__destroy_inode); void destroy_inode(struct inode *inode) { __destroy_inode(inode); if (inode->i_sb->s_op->destroy_inode) inode->i_sb->s_op->destroy_inode(inode); else kmem_cache_free(inode_cachep, (inode)); } /* * These are initializations that only need to be done * once, because the fields are idempotent across use * of the inode, so let the slab aware of that. */ void inode_init_once(struct inode *inode) { memset(inode, 0, sizeof(*inode)); INIT_HLIST_NODE(&inode->i_hash); INIT_LIST_HEAD(&inode->i_dentry); INIT_LIST_HEAD(&inode->i_devices); INIT_RADIX_TREE(&inode->i_data.page_tree, GFP_ATOMIC); spin_lock_init(&inode->i_data.tree_lock); spin_lock_init(&inode->i_data.i_mmap_lock); INIT_LIST_HEAD(&inode->i_data.private_list); spin_lock_init(&inode->i_data.private_lock); INIT_RAW_PRIO_TREE_ROOT(&inode->i_data.i_mmap); INIT_LIST_HEAD(&inode->i_data.i_mmap_nonlinear); i_size_ordered_init(inode); #ifdef CONFIG_INOTIFY INIT_LIST_HEAD(&inode->inotify_watches); mutex_init(&inode->inotify_mutex); #endif #ifdef CONFIG_FSNOTIFY INIT_HLIST_HEAD(&inode->i_fsnotify_mark_entries); #endif } EXPORT_SYMBOL(inode_init_once); static void init_once(void *foo) { struct inode *inode = (struct inode *) foo; inode_init_once(inode); } /* * inode_lock must be held */ void __iget(struct inode *inode) { if (atomic_read(&inode->i_count)) { atomic_inc(&inode->i_count); return; } atomic_inc(&inode->i_count); if (!(inode->i_state & (I_DIRTY|I_SYNC))) list_move(&inode->i_list, &inode_in_use); inodes_stat.nr_unused--; } /** * clear_inode - clear an inode * @inode: inode to clear * * This is called by the filesystem to tell us * that the inode is no longer useful. We just * terminate it with extreme prejudice. */ void clear_inode(struct inode *inode) { might_sleep(); invalidate_inode_buffers(inode); BUG_ON(inode->i_data.nrpages); BUG_ON(!(inode->i_state & I_FREEING)); BUG_ON(inode->i_state & I_CLEAR); inode_sync_wait(inode); vfs_dq_drop(inode); if (inode->i_sb->s_op->clear_inode) inode->i_sb->s_op->clear_inode(inode); if (S_ISBLK(inode->i_mode) && inode->i_bdev) bd_forget(inode); if (S_ISCHR(inode->i_mode) && inode->i_cdev) cd_forget(inode); inode->i_state = I_CLEAR; } EXPORT_SYMBOL(clear_inode); /* * dispose_list - dispose of the contents of a local list * @head: the head of the list to free * * Dispose-list gets a local list with local inodes in it, so it doesn't * need to worry about list corruption and SMP locks. */ static void dispose_list(struct list_head *head) { int nr_disposed = 0; while (!list_empty(head)) { struct inode *inode; inode = list_first_entry(head, struct inode, i_list); list_del(&inode->i_list); if (inode->i_data.nrpages) truncate_inode_pages(&inode->i_data, 0); clear_inode(inode); spin_lock(&inode_lock); hlist_del_init(&inode->i_hash); list_del_init(&inode->i_sb_list); spin_unlock(&inode_lock); wake_up_inode(inode); destroy_inode(inode); nr_disposed++; } spin_lock(&inode_lock); inodes_stat.nr_inodes -= nr_disposed; spin_unlock(&inode_lock); } /* * Invalidate all inodes for a device. */ static int invalidate_list(struct list_head *head, struct list_head *dispose) { struct list_head *next; int busy = 0, count = 0; next = head->next; for (;;) { struct list_head *tmp = next; struct inode *inode; /* * We can reschedule here without worrying about the list's * consistency because the per-sb list of inodes must not * change during umount anymore, and because iprune_sem keeps * shrink_icache_memory() away. */ cond_resched_lock(&inode_lock); next = next->next; if (tmp == head) break; inode = list_entry(tmp, struct inode, i_sb_list); if (inode->i_state & I_NEW) continue; invalidate_inode_buffers(inode); if (!atomic_read(&inode->i_count)) { list_move(&inode->i_list, dispose); WARN_ON(inode->i_state & I_NEW); inode->i_state |= I_FREEING; count++; continue; } busy = 1; } /* only unused inodes may be cached with i_count zero */ inodes_stat.nr_unused -= count; return busy; } /** * invalidate_inodes - discard the inodes on a device * @sb: superblock * * Discard all of the inodes for a given superblock. If the discard * fails because there are busy inodes then a non zero value is returned. * If the discard is successful all the inodes have been discarded. */ int invalidate_inodes(struct super_block *sb) { int busy; LIST_HEAD(throw_away); down_write(&iprune_sem); spin_lock(&inode_lock); inotify_unmount_inodes(&sb->s_inodes); fsnotify_unmount_inodes(&sb->s_inodes); busy = invalidate_list(&sb->s_inodes, &throw_away); spin_unlock(&inode_lock); dispose_list(&throw_away); up_write(&iprune_sem); return busy; } EXPORT_SYMBOL(invalidate_inodes); static int can_unuse(struct inode *inode) { if (inode->i_state) return 0; if (inode_has_buffers(inode)) return 0; if (atomic_read(&inode->i_count)) return 0; if (inode->i_data.nrpages) return 0; return 1; } /* * Scan `goal' inodes on the unused list for freeable ones. They are moved to * a temporary list and then are freed outside inode_lock by dispose_list(). * * Any inodes which are pinned purely because of attached pagecache have their * pagecache removed. We expect the final iput() on that inode to add it to * the front of the inode_unused list. So look for it there and if the * inode is still freeable, proceed. The right inode is found 99.9% of the * time in testing on a 4-way. * * If the inode has metadata buffers attached to mapping->private_list then * try to remove them. */ static void prune_icache(int nr_to_scan) { LIST_HEAD(freeable); int nr_pruned = 0; int nr_scanned; unsigned long reap = 0; down_read(&iprune_sem); spin_lock(&inode_lock); for (nr_scanned = 0; nr_scanned < nr_to_scan; nr_scanned++) { struct inode *inode; if (list_empty(&inode_unused)) break; inode = list_entry(inode_unused.prev, struct inode, i_list); if (inode->i_state || atomic_read(&inode->i_count)) { list_move(&inode->i_list, &inode_unused); continue; } if (inode_has_buffers(inode) || inode->i_data.nrpages) { __iget(inode); spin_unlock(&inode_lock); if (remove_inode_buffers(inode)) reap += invalidate_mapping_pages(&inode->i_data, 0, -1); iput(inode); spin_lock(&inode_lock); if (inode != list_entry(inode_unused.next, struct inode, i_list)) continue; /* wrong inode or list_empty */ if (!can_unuse(inode)) continue; } list_move(&inode->i_list, &freeable); WARN_ON(inode->i_state & I_NEW); inode->i_state |= I_FREEING; nr_pruned++; } inodes_stat.nr_unused -= nr_pruned; if (current_is_kswapd()) __count_vm_events(KSWAPD_INODESTEAL, reap); else __count_vm_events(PGINODESTEAL, reap); spin_unlock(&inode_lock); dispose_list(&freeable); up_read(&iprune_sem); } /* * shrink_icache_memory() will attempt to reclaim some unused inodes. Here, * "unused" means that no dentries are referring to the inodes: the files are * not open and the dcache references to those inodes have already been * reclaimed. * * This function is passed the number of inodes to scan, and it returns the * total number of remaining possibly-reclaimable inodes. */ static int shrink_icache_memory(int nr, gfp_t gfp_mask) { if (nr) { /* * Nasty deadlock avoidance. We may hold various FS locks, * and we don't want to recurse into the FS that called us * in clear_inode() and friends.. */ if (!(gfp_mask & __GFP_FS)) return -1; prune_icache(nr); } return (inodes_stat.nr_unused / 100) * sysctl_vfs_cache_pressure; } static struct shrinker icache_shrinker = { .shrink = shrink_icache_memory, .seeks = DEFAULT_SEEKS, }; static void __wait_on_freeing_inode(struct inode *inode); /* * Called with the inode lock held. * NOTE: we are not increasing the inode-refcount, you must call __iget() * by hand after calling find_inode now! This simplifies iunique and won't * add any additional branch in the common code. */ static struct inode *find_inode(struct super_block *sb, struct hlist_head *head, int (*test)(struct inode *, void *), void *data) { struct hlist_node *node; struct inode *inode = NULL; repeat: hlist_for_each_entry(inode, node, head, i_hash) { if (inode->i_sb != sb) continue; if (!test(inode, data)) continue; if (inode->i_state & (I_FREEING|I_CLEAR|I_WILL_FREE)) { __wait_on_freeing_inode(inode); goto repeat; } break; } return node ? inode : NULL; } /* * find_inode_fast is the fast path version of find_inode, see the comment at * iget_locked for details. */ static struct inode *find_inode_fast(struct super_block *sb, struct hlist_head *head, unsigned long ino) { struct hlist_node *node; struct inode *inode = NULL; repeat: hlist_for_each_entry(inode, node, head, i_hash) { if (inode->i_ino != ino) continue; if (inode->i_sb != sb) continue; if (inode->i_state & (I_FREEING|I_CLEAR|I_WILL_FREE)) { __wait_on_freeing_inode(inode); goto repeat; } break; } return node ? inode : NULL; } static unsigned long hash(struct super_block *sb, unsigned long hashval) { unsigned long tmp; tmp = (hashval * (unsigned long)sb) ^ (GOLDEN_RATIO_PRIME + hashval) / L1_CACHE_BYTES; tmp = tmp ^ ((tmp ^ GOLDEN_RATIO_PRIME) >> I_HASHBITS); return tmp & I_HASHMASK; } static inline void __inode_add_to_lists(struct super_block *sb, struct hlist_head *head, struct inode *inode) { inodes_stat.nr_inodes++; list_add(&inode->i_list, &inode_in_use); list_add(&inode->i_sb_list, &sb->s_inodes); if (head) hlist_add_head(&inode->i_hash, head); } /** * inode_add_to_lists - add a new inode to relevant lists * @sb: superblock inode belongs to * @inode: inode to mark in use * * When an inode is allocated it needs to be accounted for, added to the in use * list, the owning superblock and the inode hash. This needs to be done under * the inode_lock, so export a function to do this rather than the inode lock * itself. We calculate the hash list to add to here so it is all internal * which requires the caller to have already set up the inode number in the * inode to add. */ void inode_add_to_lists(struct super_block *sb, struct inode *inode) { struct hlist_head *head = inode_hashtable + hash(sb, inode->i_ino); spin_lock(&inode_lock); __inode_add_to_lists(sb, head, inode); spin_unlock(&inode_lock); } EXPORT_SYMBOL_GPL(inode_add_to_lists); /** * new_inode - obtain an inode * @sb: superblock * * Allocates a new inode for given superblock. The default gfp_mask * for allocations related to inode->i_mapping is GFP_HIGHUSER_MOVABLE. * If HIGHMEM pages are unsuitable or it is known that pages allocated * for the page cache are not reclaimable or migratable, * mapping_set_gfp_mask() must be called with suitable flags on the * newly created inode's mapping * */ struct inode *new_inode(struct super_block *sb) { /* * On a 32bit, non LFS stat() call, glibc will generate an EOVERFLOW * error if st_ino won't fit in target struct field. Use 32bit counter * here to attempt to avoid that. */ static unsigned int last_ino; struct inode *inode; spin_lock_prefetch(&inode_lock); inode = alloc_inode(sb); if (inode) { spin_lock(&inode_lock); __inode_add_to_lists(sb, NULL, inode); inode->i_ino = ++last_ino; inode->i_state = 0; spin_unlock(&inode_lock); } return inode; } EXPORT_SYMBOL(new_inode); void unlock_new_inode(struct inode *inode) { #ifdef CONFIG_DEBUG_LOCK_ALLOC if (inode->i_mode & S_IFDIR) { struct file_system_type *type = inode->i_sb->s_type; /* Set new key only if filesystem hasn't already changed it */ if (!lockdep_match_class(&inode->i_mutex, &type->i_mutex_key)) { /* * ensure nobody is actually holding i_mutex */ mutex_destroy(&inode->i_mutex); mutex_init(&inode->i_mutex); lockdep_set_class(&inode->i_mutex, &type->i_mutex_dir_key); } } #endif /* * This is special! We do not need the spinlock when clearing I_LOCK, * because we're guaranteed that nobody else tries to do anything about * the state of the inode when it is locked, as we just created it (so * there can be no old holders that haven't tested I_LOCK). * However we must emit the memory barrier so that other CPUs reliably * see the clearing of I_LOCK after the other inode initialisation has * completed. */ smp_mb(); WARN_ON((inode->i_state & (I_LOCK|I_NEW)) != (I_LOCK|I_NEW)); inode->i_state &= ~(I_LOCK|I_NEW); wake_up_inode(inode); } EXPORT_SYMBOL(unlock_new_inode); /* * This is called without the inode lock held.. Be careful. * * We no longer cache the sb_flags in i_flags - see fs.h * -- rmk@arm.uk.linux.org */ static struct inode *get_new_inode(struct super_block *sb, struct hlist_head *head, int (*test)(struct inode *, void *), int (*set)(struct inode *, void *), void *data) { struct inode *inode; inode = alloc_inode(sb); if (inode) { struct inode *old; spin_lock(&inode_lock); /* We released the lock, so.. */ old = find_inode(sb, head, test, data); if (!old) { if (set(inode, data)) goto set_failed; __inode_add_to_lists(sb, head, inode); inode->i_state = I_LOCK|I_NEW; spin_unlock(&inode_lock); /* Return the locked inode with I_NEW set, the * caller is responsible for filling in the contents */ return inode; } /* * Uhhuh, somebody else created the same inode under * us. Use the old inode instead of the one we just * allocated. */ __iget(old); spin_unlock(&inode_lock); destroy_inode(inode); inode = old; wait_on_inode(inode); } return inode; set_failed: spin_unlock(&inode_lock); destroy_inode(inode); return NULL; } /* * get_new_inode_fast is the fast path version of get_new_inode, see the * comment at iget_locked for details. */ static struct inode *get_new_inode_fast(struct super_block *sb, struct hlist_head *head, unsigned long ino) { struct inode *inode; inode = alloc_inode(sb); if (inode) { struct inode *old; spin_lock(&inode_lock); /* We released the lock, so.. */ old = find_inode_fast(sb, head, ino); if (!old) { inode->i_ino = ino; __inode_add_to_lists(sb, head, inode); inode->i_state = I_LOCK|I_NEW; spin_unlock(&inode_lock); /* Return the locked inode with I_NEW set, the * caller is responsible for filling in the contents */ return inode; } /* * Uhhuh, somebody else created the same inode under * us. Use the old inode instead of the one we just * allocated. */ __iget(old); spin_unlock(&inode_lock); destroy_inode(inode); inode = old; wait_on_inode(inode); } return inode; } /** * iunique - get a unique inode number * @sb: superblock * @max_reserved: highest reserved inode number * * Obtain an inode number that is unique on the system for a given * superblock. This is used by file systems that have no natural * permanent inode numbering system. An inode number is returned that * is higher than the reserved limit but unique. * * BUGS: * With a large number of inodes live on the file system this function * currently becomes quite slow. */ ino_t iunique(struct super_block *sb, ino_t max_reserved) { /* * On a 32bit, non LFS stat() call, glibc will generate an EOVERFLOW * error if st_ino won't fit in target struct field. Use 32bit counter * here to attempt to avoid that. */ static unsigned int counter; struct inode *inode; struct hlist_head *head; ino_t res; spin_lock(&inode_lock); do { if (counter <= max_reserved) counter = max_reserved + 1; res = counter++; head = inode_hashtable + hash(sb, res); inode = find_inode_fast(sb, head, res); } while (inode != NULL); spin_unlock(&inode_lock); return res; } EXPORT_SYMBOL(iunique); struct inode *igrab(struct inode *inode) { spin_lock(&inode_lock); if (!(inode->i_state & (I_FREEING|I_CLEAR|I_WILL_FREE))) __iget(inode); else /* * Handle the case where s_op->clear_inode is not been * called yet, and somebody is calling igrab * while the inode is getting freed. */ inode = NULL; spin_unlock(&inode_lock); return inode; } EXPORT_SYMBOL(igrab); /** * ifind - internal function, you want ilookup5() or iget5(). * @sb: super block of file system to search * @head: the head of the list to search * @test: callback used for comparisons between inodes * @data: opaque data pointer to pass to @test * @wait: if true wait for the inode to be unlocked, if false do not * * ifind() searches for the inode specified by @data in the inode * cache. This is a generalized version of ifind_fast() for file systems where * the inode number is not sufficient for unique identification of an inode. * * If the inode is in the cache, the inode is returned with an incremented * reference count. * * Otherwise NULL is returned. * * Note, @test is called with the inode_lock held, so can't sleep. */ static struct inode *ifind(struct super_block *sb, struct hlist_head *head, int (*test)(struct inode *, void *), void *data, const int wait) { struct inode *inode; spin_lock(&inode_lock); inode = find_inode(sb, head, test, data); if (inode) { __iget(inode); spin_unlock(&inode_lock); if (likely(wait)) wait_on_inode(inode); return inode; } spin_unlock(&inode_lock); return NULL; } /** * ifind_fast - internal function, you want ilookup() or iget(). * @sb: super block of file system to search * @head: head of the list to search * @ino: inode number to search for * * ifind_fast() searches for the inode @ino in the inode cache. This is for * file systems where the inode number is sufficient for unique identification * of an inode. * * If the inode is in the cache, the inode is returned with an incremented * reference count. * * Otherwise NULL is returned. */ static struct inode *ifind_fast(struct super_block *sb, struct hlist_head *head, unsigned long ino) { struct inode *inode; spin_lock(&inode_lock); inode = find_inode_fast(sb, head, ino); if (inode) { __iget(inode); spin_unlock(&inode_lock); wait_on_inode(inode); return inode; } spin_unlock(&inode_lock); return NULL; } /** * ilookup5_nowait - search for an inode in the inode cache * @sb: super block of file system to search * @hashval: hash value (usually inode number) to search for * @test: callback used for comparisons between inodes * @data: opaque data pointer to pass to @test * * ilookup5() uses ifind() to search for the inode specified by @hashval and * @data in the inode cache. This is a generalized version of ilookup() for * file systems where the inode number is not sufficient for unique * identification of an inode. * * If the inode is in the cache, the inode is returned with an incremented * reference count. Note, the inode lock is not waited upon so you have to be * very careful what you do with the returned inode. You probably should be * using ilookup5() instead. * * Otherwise NULL is returned. * * Note, @test is called with the inode_lock held, so can't sleep. */ struct inode *ilookup5_nowait(struct super_block *sb, unsigned long hashval, int (*test)(struct inode *, void *), void *data) { struct hlist_head *head = inode_hashtable + hash(sb, hashval); return ifind(sb, head, test, data, 0); } EXPORT_SYMBOL(ilookup5_nowait); /** * ilookup5 - search for an inode in the inode cache * @sb: super block of file system to search * @hashval: hash value (usually inode number) to search for * @test: callback used for comparisons between inodes * @data: opaque data pointer to pass to @test * * ilookup5() uses ifind() to search for the inode specified by @hashval and * @data in the inode cache. This is a generalized version of ilookup() for * file systems where the inode number is not sufficient for unique * identification of an inode. * * If the inode is in the cache, the inode lock is waited upon and the inode is * returned with an incremented reference count. * * Otherwise NULL is returned. * * Note, @test is called with the inode_lock held, so can't sleep. */ struct inode *ilookup5(struct super_block *sb, unsigned long hashval, int (*test)(struct inode *, void *), void *data) { struct hlist_head *head = inode_hashtable + hash(sb, hashval); return ifind(sb, head, test, data, 1); } EXPORT_SYMBOL(ilookup5); /** * ilookup - search for an inode in the inode cache * @sb: super block of file system to search * @ino: inode number to search for * * ilookup() uses ifind_fast() to search for the inode @ino in the inode cache. * This is for file systems where the inode number is sufficient for unique * identification of an inode. * * If the inode is in the cache, the inode is returned with an incremented * reference count. * * Otherwise NULL is returned. */ struct inode *ilookup(struct super_block *sb, unsigned long ino) { struct hlist_head *head = inode_hashtable + hash(sb, ino); return ifind_fast(sb, head, ino); } EXPORT_SYMBOL(ilookup); /** * iget5_locked - obtain an inode from a mounted file system * @sb: super block of file system * @hashval: hash value (usually inode number) to get * @test: callback used for comparisons between inodes * @set: callback used to initialize a new struct inode * @data: opaque data pointer to pass to @test and @set * * iget5_locked() uses ifind() to search for the inode specified by @hashval * and @data in the inode cache and if present it is returned with an increased * reference count. This is a generalized version of iget_locked() for file * systems where the inode number is not sufficient for unique identification * of an inode. * * If the inode is not in cache, get_new_inode() is called to allocate a new * inode and this is returned locked, hashed, and with the I_NEW flag set. The * file system gets to fill it in before unlocking it via unlock_new_inode(). * * Note both @test and @set are called with the inode_lock held, so can't sleep. */ struct inode *iget5_locked(struct super_block *sb, unsigned long hashval, int (*test)(struct inode *, void *), int (*set)(struct inode *, void *), void *data) { struct hlist_head *head = inode_hashtable + hash(sb, hashval); struct inode *inode; inode = ifind(sb, head, test, data, 1); if (inode) return inode; /* * get_new_inode() will do the right thing, re-trying the search * in case it had to block at any point. */ return get_new_inode(sb, head, test, set, data); } EXPORT_SYMBOL(iget5_locked); /** * iget_locked - obtain an inode from a mounted file system * @sb: super block of file system * @ino: inode number to get * * iget_locked() uses ifind_fast() to search for the inode specified by @ino in * the inode cache and if present it is returned with an increased reference * count. This is for file systems where the inode number is sufficient for * unique identification of an inode. * * If the inode is not in cache, get_new_inode_fast() is called to allocate a * new inode and this is returned locked, hashed, and with the I_NEW flag set. * The file system gets to fill it in before unlocking it via * unlock_new_inode(). */ struct inode *iget_locked(struct super_block *sb, unsigned long ino) { struct hlist_head *head = inode_hashtable + hash(sb, ino); struct inode *inode; inode = ifind_fast(sb, head, ino); if (inode) return inode; /* * get_new_inode_fast() will do the right thing, re-trying the search * in case it had to block at any point. */ return get_new_inode_fast(sb, head, ino); } EXPORT_SYMBOL(iget_locked); int insert_inode_locked(struct inode *inode) { struct super_block *sb = inode->i_sb; ino_t ino = inode->i_ino; struct hlist_head *head = inode_hashtable + hash(sb, ino); inode->i_state |= I_LOCK|I_NEW; while (1) { struct hlist_node *node; struct inode *old = NULL; spin_lock(&inode_lock); hlist_for_each_entry(old, node, head, i_hash) { if (old->i_ino != ino) continue; if (old->i_sb != sb) continue; if (old->i_state & (I_FREEING|I_CLEAR|I_WILL_FREE)) continue; break; } if (likely(!node)) { hlist_add_head(&inode->i_hash, head); spin_unlock(&inode_lock); return 0; } __iget(old); spin_unlock(&inode_lock); wait_on_inode(old); if (unlikely(!hlist_unhashed(&old->i_hash))) { iput(old); return -EBUSY; } iput(old); } } EXPORT_SYMBOL(insert_inode_locked); int insert_inode_locked4(struct inode *inode, unsigned long hashval, int (*test)(struct inode *, void *), void *data) { struct super_block *sb = inode->i_sb; struct hlist_head *head = inode_hashtable + hash(sb, hashval); inode->i_state |= I_LOCK|I_NEW; while (1) { struct hlist_node *node; struct inode *old = NULL; spin_lock(&inode_lock); hlist_for_each_entry(old, node, head, i_hash) { if (old->i_sb != sb) continue; if (!test(old, data)) continue; if (old->i_state & (I_FREEING|I_CLEAR|I_WILL_FREE)) continue; break; } if (likely(!node)) { hlist_add_head(&inode->i_hash, head); spin_unlock(&inode_lock); return 0; } __iget(old); spin_unlock(&inode_lock); wait_on_inode(old); if (unlikely(!hlist_unhashed(&old->i_hash))) { iput(old); return -EBUSY; } iput(old); } } EXPORT_SYMBOL(insert_inode_locked4); /** * __insert_inode_hash - hash an inode * @inode: unhashed inode * @hashval: unsigned long value used to locate this object in the * inode_hashtable. * * Add an inode to the inode hash for this superblock. */ void __insert_inode_hash(struct inode *inode, unsigned long hashval) { struct hlist_head *head = inode_hashtable + hash(inode->i_sb, hashval); spin_lock(&inode_lock); hlist_add_head(&inode->i_hash, head); spin_unlock(&inode_lock); } EXPORT_SYMBOL(__insert_inode_hash); /** * remove_inode_hash - remove an inode from the hash * @inode: inode to unhash * * Remove an inode from the superblock. */ void remove_inode_hash(struct inode *inode) { spin_lock(&inode_lock); hlist_del_init(&inode->i_hash); spin_unlock(&inode_lock); } EXPORT_SYMBOL(remove_inode_hash); /* * Tell the filesystem that this inode is no longer of any interest and should * be completely destroyed. * * We leave the inode in the inode hash table until *after* the filesystem's * ->delete_inode completes. This ensures that an iget (such as nfsd might * instigate) will always find up-to-date information either in the hash or on * disk. * * I_FREEING is set so that no-one will take a new reference to the inode while * it is being deleted. */ void generic_delete_inode(struct inode *inode) { const struct super_operations *op = inode->i_sb->s_op; list_del_init(&inode->i_list); list_del_init(&inode->i_sb_list); WARN_ON(inode->i_state & I_NEW); inode->i_state |= I_FREEING; inodes_stat.nr_inodes--; spin_unlock(&inode_lock); security_inode_delete(inode); if (op->delete_inode) { void (*delete)(struct inode *) = op->delete_inode; if (!is_bad_inode(inode)) vfs_dq_init(inode); /* Filesystems implementing their own * s_op->delete_inode are required to call * truncate_inode_pages and clear_inode() * internally */ delete(inode); } else { truncate_inode_pages(&inode->i_data, 0); clear_inode(inode); } spin_lock(&inode_lock); hlist_del_init(&inode->i_hash); spin_unlock(&inode_lock); wake_up_inode(inode); BUG_ON(inode->i_state != I_CLEAR); destroy_inode(inode); } EXPORT_SYMBOL(generic_delete_inode); /** * generic_detach_inode - remove inode from inode lists * @inode: inode to remove * * Remove inode from inode lists, write it if it's dirty. This is just an * internal VFS helper exported for hugetlbfs. Do not use! * * Returns 1 if inode should be completely destroyed. */ int generic_detach_inode(struct inode *inode) { struct super_block *sb = inode->i_sb; if (!hlist_unhashed(&inode->i_hash)) { if (!(inode->i_state & (I_DIRTY|I_SYNC))) list_move(&inode->i_list, &inode_unused); inodes_stat.nr_unused++; if (sb->s_flags & MS_ACTIVE) { spin_unlock(&inode_lock); return 0; } WARN_ON(inode->i_state & I_NEW); inode->i_state |= I_WILL_FREE; spin_unlock(&inode_lock); write_inode_now(inode, 1); spin_lock(&inode_lock); WARN_ON(inode->i_state & I_NEW); inode->i_state &= ~I_WILL_FREE; inodes_stat.nr_unused--; hlist_del_init(&inode->i_hash); } list_del_init(&inode->i_list); list_del_init(&inode->i_sb_list); WARN_ON(inode->i_state & I_NEW); inode->i_state |= I_FREEING; inodes_stat.nr_inodes--; spin_unlock(&inode_lock); return 1; } EXPORT_SYMBOL_GPL(generic_detach_inode); static void generic_forget_inode(struct inode *inode) { if (!generic_detach_inode(inode)) return; if (inode->i_data.nrpages) truncate_inode_pages(&inode->i_data, 0); clear_inode(inode); wake_up_inode(inode); destroy_inode(inode); } /* * Normal UNIX filesystem behaviour: delete the * inode when the usage count drops to zero, and * i_nlink is zero. */ void generic_drop_inode(struct inode *inode) { if (!inode->i_nlink) generic_delete_inode(inode); else generic_forget_inode(inode); } EXPORT_SYMBOL_GPL(generic_drop_inode); /* * Called when we're dropping the last reference * to an inode. * * Call the FS "drop()" function, defaulting to * the legacy UNIX filesystem behaviour.. * * NOTE! NOTE! NOTE! We're called with the inode lock * held, and the drop function is supposed to release * the lock! */ static inline void iput_final(struct inode *inode) { const struct super_operations *op = inode->i_sb->s_op; void (*drop)(struct inode *) = generic_drop_inode; if (op && op->drop_inode) drop = op->drop_inode; drop(inode); } /** * iput - put an inode * @inode: inode to put * * Puts an inode, dropping its usage count. If the inode use count hits * zero, the inode is then freed and may also be destroyed. * * Consequently, iput() can sleep. */ void iput(struct inode *inode) { if (inode) { BUG_ON(inode->i_state == I_CLEAR); if (atomic_dec_and_lock(&inode->i_count, &inode_lock)) iput_final(inode); } } EXPORT_SYMBOL(iput); /** * bmap - find a block number in a file * @inode: inode of file * @block: block to find * * Returns the block number on the device holding the inode that * is the disk block number for the block of the file requested. * That is, asked for block 4 of inode 1 the function will return the * disk block relative to the disk start that holds that block of the * file. */ sector_t bmap(struct inode *inode, sector_t block) { sector_t res = 0; if (inode->i_mapping->a_ops->bmap) res = inode->i_mapping->a_ops->bmap(inode->i_mapping, block); return res; } EXPORT_SYMBOL(bmap); /* * With relative atime, only update atime if the previous atime is * earlier than either the ctime or mtime or if at least a day has * passed since the last atime update. */ static int relatime_need_update(struct vfsmount *mnt, struct inode *inode, struct timespec now) { if (!(mnt->mnt_flags & MNT_RELATIME)) return 1; /* * Is mtime younger than atime? If yes, update atime: */ if (timespec_compare(&inode->i_mtime, &inode->i_atime) >= 0) return 1; /* * Is ctime younger than atime? If yes, update atime: */ if (timespec_compare(&inode->i_ctime, &inode->i_atime) >= 0) return 1; /* * Is the previous atime value older than a day? If yes, * update atime: */ if ((long)(now.tv_sec - inode->i_atime.tv_sec) >= 24*60*60) return 1; /* * Good, we can skip the atime update: */ return 0; } /** * touch_atime - update the access time * @mnt: mount the inode is accessed on * @dentry: dentry accessed * * Update the accessed time on an inode and mark it for writeback. * This function automatically handles read only file systems and media, * as well as the "noatime" flag and inode specific "noatime" markers. */ void touch_atime(struct vfsmount *mnt, struct dentry *dentry) { struct inode *inode = dentry->d_inode; struct timespec now; if (inode->i_flags & S_NOATIME) return; if (IS_NOATIME(inode)) return; if ((inode->i_sb->s_flags & MS_NODIRATIME) && S_ISDIR(inode->i_mode)) return; if (mnt->mnt_flags & MNT_NOATIME) return; if ((mnt->mnt_flags & MNT_NODIRATIME) && S_ISDIR(inode->i_mode)) return; now = current_fs_time(inode->i_sb); if (!relatime_need_update(mnt, inode, now)) return; if (timespec_equal(&inode->i_atime, &now)) return; if (mnt_want_write(mnt)) return; inode->i_atime = now; mark_inode_dirty_sync(inode); mnt_drop_write(mnt); } EXPORT_SYMBOL(touch_atime); /** * file_update_time - update mtime and ctime time * @file: file accessed * * Update the mtime and ctime members of an inode and mark the inode * for writeback. Note that this function is meant exclusively for * usage in the file write path of filesystems, and filesystems may * choose to explicitly ignore update via this function with the * S_NOCMTIME inode flag, e.g. for network filesystem where these * timestamps are handled by the server. */ void file_update_time(struct file *file) { struct inode *inode = file->f_path.dentry->d_inode; struct timespec now; enum { S_MTIME = 1, S_CTIME = 2, S_VERSION = 4 } sync_it = 0; /* First try to exhaust all avenues to not sync */ if (IS_NOCMTIME(inode)) return; now = current_fs_time(inode->i_sb); if (!timespec_equal(&inode->i_mtime, &now)) sync_it = S_MTIME; if (!timespec_equal(&inode->i_ctime, &now)) sync_it |= S_CTIME; if (IS_I_VERSION(inode)) sync_it |= S_VERSION; if (!sync_it) return; /* Finally allowed to write? Takes lock. */ if (mnt_want_write_file(file)) return; /* Only change inode inside the lock region */ if (sync_it & S_VERSION) inode_inc_iversion(inode); if (sync_it & S_CTIME) inode->i_ctime = now; if (sync_it & S_MTIME) inode->i_mtime = now; mark_inode_dirty_sync(inode); mnt_drop_write(file->f_path.mnt); } EXPORT_SYMBOL(file_update_time); int inode_needs_sync(struct inode *inode) { if (IS_SYNC(inode)) return 1; if (S_ISDIR(inode->i_mode) && IS_DIRSYNC(inode)) return 1; return 0; } EXPORT_SYMBOL(inode_needs_sync); int inode_wait(void *word) { schedule(); return 0; } EXPORT_SYMBOL(inode_wait); /* * If we try to find an inode in the inode hash while it is being * deleted, we have to wait until the filesystem completes its * deletion before reporting that it isn't found. This function waits * until the deletion _might_ have completed. Callers are responsible * to recheck inode state. * * It doesn't matter if I_LOCK is not set initially, a call to * wake_up_inode() after removing from the hash list will DTRT. * * This is called with inode_lock held. */ static void __wait_on_freeing_inode(struct inode *inode) { wait_queue_head_t *wq; DEFINE_WAIT_BIT(wait, &inode->i_state, __I_LOCK); wq = bit_waitqueue(&inode->i_state, __I_LOCK); prepare_to_wait(wq, &wait.wait, TASK_UNINTERRUPTIBLE); spin_unlock(&inode_lock); schedule(); finish_wait(wq, &wait.wait); spin_lock(&inode_lock); } static __initdata unsigned long ihash_entries; static int __init set_ihash_entries(char *str) { if (!str) return 0; ihash_entries = simple_strtoul(str, &str, 0); return 1; } __setup("ihash_entries=", set_ihash_entries); /* * Initialize the waitqueues and inode hash table. */ void __init inode_init_early(void) { int loop; /* If hashes are distributed across NUMA nodes, defer * hash allocation until vmalloc space is available. */ if (hashdist) return; inode_hashtable = alloc_large_system_hash("Inode-cache", sizeof(struct hlist_head), ihash_entries, 14, HASH_EARLY, &i_hash_shift, &i_hash_mask, 0); for (loop = 0; loop < (1 << i_hash_shift); loop++) INIT_HLIST_HEAD(&inode_hashtable[loop]); } void __init inode_init(void) { int loop; /* inode slab cache */ inode_cachep = kmem_cache_create("inode_cache", sizeof(struct inode), 0, (SLAB_RECLAIM_ACCOUNT|SLAB_PANIC| SLAB_MEM_SPREAD), init_once); register_shrinker(&icache_shrinker); /* Hash may have been set up in inode_init_early */ if (!hashdist) return; inode_hashtable = alloc_large_system_hash("Inode-cache", sizeof(struct hlist_head), ihash_entries, 14, 0, &i_hash_shift, &i_hash_mask, 0); for (loop = 0; loop < (1 << i_hash_shift); loop++) INIT_HLIST_HEAD(&inode_hashtable[loop]); } void init_special_inode(struct inode *inode, umode_t mode, dev_t rdev) { inode->i_mode = mode; if (S_ISCHR(mode)) { inode->i_fop = &def_chr_fops; inode->i_rdev = rdev; } else if (S_ISBLK(mode)) { inode->i_fop = &def_blk_fops; inode->i_rdev = rdev; } else if (S_ISFIFO(mode)) inode->i_fop = &def_fifo_fops; else if (S_ISSOCK(mode)) inode->i_fop = &bad_sock_fops; else printk(KERN_DEBUG "init_special_inode: bogus i_mode (%o) for" " inode %s:%lu\n", mode, inode->i_sb->s_id, inode->i_ino); } EXPORT_SYMBOL(init_special_inode);
liquidware/liquidware_beagleboard_android_kernel
fs/inode.c
C
gpl-2.0
43,307
/* * drivers/i2c/busses/i2c-tegra.c * * Copyright (C) 2010 Google, Inc. * Author: Colin Cross <ccross@android.com> * * Copyright (C) 2010-2012 NVIDIA Corporation * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ /*#define DEBUG 1*/ /*#define VERBOSE_DEBUG 1*/ #include <linux/kernel.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/clk.h> #include <linux/err.h> #include <linux/i2c.h> #include <linux/io.h> #include <linux/interrupt.h> #include <linux/delay.h> #include <linux/slab.h> #include <linux/i2c-tegra.h> #include <linux/of_i2c.h> #include <linux/spinlock.h> #include <asm/unaligned.h> #include <mach/clk.h> #include <mach/pinmux.h> #define TEGRA_I2C_TIMEOUT (msecs_to_jiffies(1000)) #define TEGRA_I2C_RETRIES 3 #define BYTES_PER_FIFO_WORD 4 #define I2C_UNKNOWN_RETRY_TIME 500 #define I2C_CNFG 0x000 #define I2C_CNFG_DEBOUNCE_CNT_SHIFT 12 #define I2C_CNFG_PACKET_MODE_EN (1<<10) #define I2C_CNFG_NEW_MASTER_FSM (1<<11) #define I2C_STATUS 0x01C #define I2C_STATUS_BUSY (1<<8) #define I2C_SL_CNFG 0x020 #define I2C_SL_CNFG_NACK (1<<1) #define I2C_SL_CNFG_NEWSL (1<<2) #define I2C_SL_ADDR1 0x02c #define I2C_SL_ADDR2 0x030 #define I2C_TX_FIFO 0x050 #define I2C_RX_FIFO 0x054 #define I2C_PACKET_TRANSFER_STATUS 0x058 #define I2C_FIFO_CONTROL 0x05c #define I2C_FIFO_CONTROL_TX_FLUSH (1<<1) #define I2C_FIFO_CONTROL_RX_FLUSH (1<<0) #define I2C_FIFO_CONTROL_TX_TRIG_SHIFT 5 #define I2C_FIFO_CONTROL_RX_TRIG_SHIFT 2 #define I2C_FIFO_STATUS 0x060 #define I2C_FIFO_STATUS_TX_MASK 0xF0 #define I2C_FIFO_STATUS_TX_SHIFT 4 #define I2C_FIFO_STATUS_RX_MASK 0x0F #define I2C_FIFO_STATUS_RX_SHIFT 0 #define I2C_INT_MASK 0x064 #define I2C_INT_STATUS 0x068 #define I2C_INT_PACKET_XFER_COMPLETE (1<<7) #define I2C_INT_ALL_PACKETS_XFER_COMPLETE (1<<6) #define I2C_INT_TX_FIFO_OVERFLOW (1<<5) #define I2C_INT_RX_FIFO_UNDERFLOW (1<<4) #define I2C_INT_NO_ACK (1<<3) #define I2C_INT_ARBITRATION_LOST (1<<2) #define I2C_INT_TX_FIFO_DATA_REQ (1<<1) #define I2C_INT_RX_FIFO_DATA_REQ (1<<0) #define I2C_CLK_DIVISOR 0x06c #define DVC_CTRL_REG1 0x000 #define DVC_CTRL_REG1_INTR_EN (1<<10) #define DVC_CTRL_REG2 0x004 #define DVC_CTRL_REG3 0x008 #define DVC_CTRL_REG3_SW_PROG (1<<26) #define DVC_CTRL_REG3_I2C_DONE_INTR_EN (1<<30) #define DVC_STATUS 0x00c #define DVC_STATUS_I2C_DONE_INTR (1<<30) #define I2C_ERR_NONE 0x00 #define I2C_ERR_NO_ACK 0x01 #define I2C_ERR_ARBITRATION_LOST 0x02 #define I2C_ERR_UNKNOWN_INTERRUPT 0x04 #define I2C_ERR_UNEXPECTED_STATUS 0x08 #define PACKET_HEADER0_HEADER_SIZE_SHIFT 28 #define PACKET_HEADER0_PACKET_ID_SHIFT 16 #define PACKET_HEADER0_CONT_ID_SHIFT 12 #define PACKET_HEADER0_PROTOCOL_I2C (1<<4) #define I2C_HEADER_HIGHSPEED_MODE (1<<22) #define I2C_HEADER_CONT_ON_NAK (1<<21) #define I2C_HEADER_SEND_START_BYTE (1<<20) #define I2C_HEADER_READ (1<<19) #define I2C_HEADER_10BIT_ADDR (1<<18) #define I2C_HEADER_IE_ENABLE (1<<17) #define I2C_HEADER_REPEAT_START (1<<16) #define I2C_HEADER_CONTINUE_XFER (1<<15) #define I2C_HEADER_MASTER_ADDR_SHIFT 12 #define I2C_HEADER_SLAVE_ADDR_SHIFT 1 #define SL_ADDR1(addr) (addr & 0xff) #define SL_ADDR2(addr) ((addr >> 8) & 0xff) /* * msg_end_type: The bus control which need to be send at end of transfer. * @MSG_END_STOP: Send stop pulse at end of transfer. * @MSG_END_REPEAT_START: Send repeat start at end of transfer. * @MSG_END_CONTINUE: The following on message is coming and so do not send * stop or repeat start. */ enum msg_end_type { MSG_END_STOP, MSG_END_REPEAT_START, MSG_END_CONTINUE, }; struct tegra_i2c_dev; struct tegra_i2c_bus { struct tegra_i2c_dev *dev; const struct tegra_pingroup_config *mux; int mux_len; unsigned long bus_clk_rate; struct i2c_adapter adapter; int scl_gpio; int sda_gpio; }; /** * struct tegra_i2c_dev - per device i2c context * @dev: device reference for power management * @adapter: core i2c layer adapter information * @clk: clock reference for i2c controller * @i2c_clk: clock reference for i2c bus * @base: ioremapped registers cookie * @cont_id: i2c controller id, used for for packet header * @irq: irq number of transfer complete interrupt * @is_dvc: identifies the DVC i2c controller, has a different register layout * @msg_complete: transfer completion notifier * @msg_err: error code for completed message * @msg_buf: pointer to current message data * @msg_buf_remaining: size of unsent data in the message buffer * @msg_read: identifies read transfers * @bus_clk_rate: current i2c bus clock rate * @is_suspended: prevents i2c controller accesses after suspend is called */ struct tegra_i2c_dev { struct device *dev; struct clk *div_clk; struct clk *fast_clk; struct rt_mutex dev_lock; spinlock_t fifo_lock; void __iomem *base; int cont_id; int irq; bool irq_disabled; int is_dvc; struct completion msg_complete; int msg_err; u8 *msg_buf; u32 packet_header; u32 payload_size; u32 io_header; size_t msg_buf_remaining; int msg_read; struct i2c_msg *msgs; int msg_add; int msgs_num; bool is_suspended; int bus_count; const struct tegra_pingroup_config *last_mux; int last_mux_len; unsigned long last_bus_clk_rate; u16 slave_addr; bool is_clkon_always; bool is_high_speed_enable; u16 hs_master_code; int (*arb_recovery)(int scl_gpio, int sda_gpio); struct tegra_i2c_bus busses[1]; }; static void dvc_writel(struct tegra_i2c_dev *i2c_dev, u32 val, unsigned long reg) { writel(val, i2c_dev->base + reg); } static u32 dvc_readl(struct tegra_i2c_dev *i2c_dev, unsigned long reg) { return readl(i2c_dev->base + reg); } static void dvc_i2c_mask_irq(struct tegra_i2c_dev *i2c_dev, u32 mask) { u32 int_mask = dvc_readl(i2c_dev, DVC_CTRL_REG3); int_mask &= ~mask; dvc_writel(i2c_dev, int_mask, DVC_CTRL_REG3); } static void dvc_i2c_unmask_irq(struct tegra_i2c_dev *i2c_dev, u32 mask) { u32 int_mask = dvc_readl(i2c_dev, DVC_CTRL_REG3); int_mask |= mask; dvc_writel(i2c_dev, int_mask, DVC_CTRL_REG3); } /* * i2c_writel and i2c_readl will offset the register if necessary to talk * to the I2C block inside the DVC block */ static unsigned long tegra_i2c_reg_addr(struct tegra_i2c_dev *i2c_dev, unsigned long reg) { if (i2c_dev->is_dvc) reg += (reg >= I2C_TX_FIFO) ? 0x10 : 0x40; return reg; } static void i2c_writel(struct tegra_i2c_dev *i2c_dev, u32 val, unsigned long reg) { writel(val, i2c_dev->base + tegra_i2c_reg_addr(i2c_dev, reg)); /* Read back register to make sure that register writes completed */ if (reg != I2C_TX_FIFO) readl(i2c_dev->base + tegra_i2c_reg_addr(i2c_dev, reg)); } static u32 i2c_readl(struct tegra_i2c_dev *i2c_dev, unsigned long reg) { return readl(i2c_dev->base + tegra_i2c_reg_addr(i2c_dev, reg)); } static void i2c_writesl(struct tegra_i2c_dev *i2c_dev, void *data, unsigned long reg, int len) { writesl(i2c_dev->base + tegra_i2c_reg_addr(i2c_dev, reg), data, len); } static void i2c_readsl(struct tegra_i2c_dev *i2c_dev, void *data, unsigned long reg, int len) { readsl(i2c_dev->base + tegra_i2c_reg_addr(i2c_dev, reg), data, len); } static void tegra_i2c_mask_irq(struct tegra_i2c_dev *i2c_dev, u32 mask) { u32 int_mask = i2c_readl(i2c_dev, I2C_INT_MASK); int_mask &= ~mask; i2c_writel(i2c_dev, int_mask, I2C_INT_MASK); } static void tegra_i2c_unmask_irq(struct tegra_i2c_dev *i2c_dev, u32 mask) { u32 int_mask = i2c_readl(i2c_dev, I2C_INT_MASK); int_mask |= mask; i2c_writel(i2c_dev, int_mask, I2C_INT_MASK); } static int tegra_i2c_flush_fifos(struct tegra_i2c_dev *i2c_dev) { unsigned long timeout = jiffies + HZ; u32 val = i2c_readl(i2c_dev, I2C_FIFO_CONTROL); val |= I2C_FIFO_CONTROL_TX_FLUSH | I2C_FIFO_CONTROL_RX_FLUSH; i2c_writel(i2c_dev, val, I2C_FIFO_CONTROL); while (i2c_readl(i2c_dev, I2C_FIFO_CONTROL) & (I2C_FIFO_CONTROL_TX_FLUSH | I2C_FIFO_CONTROL_RX_FLUSH)) { if (time_after(jiffies, timeout)) { dev_warn(i2c_dev->dev, "timeout waiting for fifo flush\n"); return -ETIMEDOUT; } msleep(1); } return 0; } static int tegra_i2c_empty_rx_fifo(struct tegra_i2c_dev *i2c_dev) { u32 val; int rx_fifo_avail; u8 *buf = i2c_dev->msg_buf; size_t buf_remaining = i2c_dev->msg_buf_remaining; int words_to_transfer; val = i2c_readl(i2c_dev, I2C_FIFO_STATUS); rx_fifo_avail = (val & I2C_FIFO_STATUS_RX_MASK) >> I2C_FIFO_STATUS_RX_SHIFT; /* Rounds down to not include partial word at the end of buf */ words_to_transfer = buf_remaining / BYTES_PER_FIFO_WORD; if (words_to_transfer > rx_fifo_avail) words_to_transfer = rx_fifo_avail; i2c_readsl(i2c_dev, buf, I2C_RX_FIFO, words_to_transfer); buf += words_to_transfer * BYTES_PER_FIFO_WORD; buf_remaining -= words_to_transfer * BYTES_PER_FIFO_WORD; rx_fifo_avail -= words_to_transfer; /* * If there is a partial word at the end of buf, handle it manually to * prevent overwriting past the end of buf */ if (rx_fifo_avail > 0 && buf_remaining > 0) { BUG_ON(buf_remaining > 3); val = i2c_readl(i2c_dev, I2C_RX_FIFO); memcpy(buf, &val, buf_remaining); buf_remaining = 0; rx_fifo_avail--; } BUG_ON(rx_fifo_avail > 0 && buf_remaining > 0); i2c_dev->msg_buf_remaining = buf_remaining; i2c_dev->msg_buf = buf; return 0; } static int tegra_i2c_fill_tx_fifo(struct tegra_i2c_dev *i2c_dev) { u32 val; int tx_fifo_avail; u8 *buf; size_t buf_remaining; int words_to_transfer; unsigned long flags; spin_lock_irqsave(&i2c_dev->fifo_lock, flags); if (!i2c_dev->msg_buf_remaining) { spin_unlock_irqrestore(&i2c_dev->fifo_lock, flags); return 0; } buf = i2c_dev->msg_buf; buf_remaining = i2c_dev->msg_buf_remaining; val = i2c_readl(i2c_dev, I2C_FIFO_STATUS); tx_fifo_avail = (val & I2C_FIFO_STATUS_TX_MASK) >> I2C_FIFO_STATUS_TX_SHIFT; /* Rounds down to not include partial word at the end of buf */ words_to_transfer = buf_remaining / BYTES_PER_FIFO_WORD; /* It's very common to have < 4 bytes, so optimize that case. */ if (words_to_transfer) { if (words_to_transfer > tx_fifo_avail) words_to_transfer = tx_fifo_avail; /* * Update state before writing to FIFO. If this casues us * to finish writing all bytes (AKA buf_remaining goes to 0) we * have a potential for an interrupt (PACKET_XFER_COMPLETE is * not maskable). We need to make sure that the isr sees * buf_remaining as 0 and doesn't call us back re-entrantly. */ buf_remaining -= words_to_transfer * BYTES_PER_FIFO_WORD; tx_fifo_avail -= words_to_transfer; i2c_dev->msg_buf_remaining = buf_remaining; i2c_dev->msg_buf = buf + words_to_transfer * BYTES_PER_FIFO_WORD; barrier(); i2c_writesl(i2c_dev, buf, I2C_TX_FIFO, words_to_transfer); buf += words_to_transfer * BYTES_PER_FIFO_WORD; } /* * If there is a partial word at the end of buf, handle it manually to * prevent reading past the end of buf, which could cross a page * boundary and fault. */ if (tx_fifo_avail > 0 && buf_remaining > 0) { if (buf_remaining > 3) { dev_err(i2c_dev->dev, "Remaining buffer more than 3 %d\n", buf_remaining); BUG(); } memcpy(&val, buf, buf_remaining); /* Again update before writing to FIFO to make sure isr sees. */ i2c_dev->msg_buf_remaining = 0; i2c_dev->msg_buf = NULL; barrier(); i2c_writel(i2c_dev, val, I2C_TX_FIFO); } spin_unlock_irqrestore(&i2c_dev->fifo_lock, flags); return 0; } /* * One of the Tegra I2C blocks is inside the DVC (Digital Voltage Controller) * block. This block is identical to the rest of the I2C blocks, except that * it only supports master mode, it has registers moved around, and it needs * some extra init to get it into I2C mode. The register moves are handled * by i2c_readl and i2c_writel */ static void tegra_dvc_init(struct tegra_i2c_dev *i2c_dev) { u32 val = 0; val = dvc_readl(i2c_dev, DVC_CTRL_REG3); val |= DVC_CTRL_REG3_SW_PROG; dvc_writel(i2c_dev, val, DVC_CTRL_REG3); val = dvc_readl(i2c_dev, DVC_CTRL_REG1); val |= DVC_CTRL_REG1_INTR_EN; dvc_writel(i2c_dev, val, DVC_CTRL_REG1); } static void tegra_i2c_slave_init(struct tegra_i2c_dev *i2c_dev) { u32 val = I2C_SL_CNFG_NEWSL | I2C_SL_CNFG_NACK; i2c_writel(i2c_dev, val, I2C_SL_CNFG); if (i2c_dev->slave_addr) { u16 addr = i2c_dev->slave_addr; i2c_writel(i2c_dev, SL_ADDR1(addr), I2C_SL_ADDR1); i2c_writel(i2c_dev, SL_ADDR2(addr), I2C_SL_ADDR2); } } static inline int tegra_i2c_clock_enable(struct tegra_i2c_dev *i2c_dev) { int ret; ret = clk_enable(i2c_dev->fast_clk); if (ret < 0) { dev_err(i2c_dev->dev, "Error in enabling fast clock err %d\n", ret); return ret; } ret = clk_enable(i2c_dev->div_clk); if (ret < 0) { dev_err(i2c_dev->dev, "Error in enabling div clock err %d\n", ret); clk_disable(i2c_dev->fast_clk); } return ret; } static inline void tegra_i2c_clock_disable(struct tegra_i2c_dev *i2c_dev) { clk_disable(i2c_dev->div_clk); clk_disable(i2c_dev->fast_clk); } static int tegra_i2c_init(struct tegra_i2c_dev *i2c_dev) { u32 val; int err = 0; tegra_i2c_clock_enable(i2c_dev); /* Interrupt generated before sending stop signal so * wait for some time so that stop signal can be send proerly */ mdelay(1); tegra_periph_reset_assert(i2c_dev->div_clk); udelay(2); tegra_periph_reset_deassert(i2c_dev->div_clk); if (i2c_dev->is_dvc) tegra_dvc_init(i2c_dev); val = I2C_CNFG_NEW_MASTER_FSM | I2C_CNFG_PACKET_MODE_EN | (0x2 << I2C_CNFG_DEBOUNCE_CNT_SHIFT); i2c_writel(i2c_dev, val, I2C_CNFG); i2c_writel(i2c_dev, 0, I2C_INT_MASK); clk_set_rate(i2c_dev->div_clk, i2c_dev->last_bus_clk_rate * 8); i2c_writel(i2c_dev, 0x3, I2C_CLK_DIVISOR); if (!i2c_dev->is_dvc) { u32 sl_cfg = i2c_readl(i2c_dev, I2C_SL_CNFG); sl_cfg |= I2C_SL_CNFG_NACK | I2C_SL_CNFG_NEWSL; i2c_writel(i2c_dev, sl_cfg, I2C_SL_CNFG); i2c_writel(i2c_dev, 0xfc, I2C_SL_ADDR1); i2c_writel(i2c_dev, 0x00, I2C_SL_ADDR2); } val = 7 << I2C_FIFO_CONTROL_TX_TRIG_SHIFT | 0 << I2C_FIFO_CONTROL_RX_TRIG_SHIFT; i2c_writel(i2c_dev, val, I2C_FIFO_CONTROL); if (!i2c_dev->is_dvc) tegra_i2c_slave_init(i2c_dev); if (tegra_i2c_flush_fifos(i2c_dev)) err = -ETIMEDOUT; tegra_i2c_clock_disable(i2c_dev); if (i2c_dev->irq_disabled) { i2c_dev->irq_disabled = 0; enable_irq(i2c_dev->irq); } return err; } static irqreturn_t tegra_i2c_isr(int irq, void *dev_id) { u32 status; const u32 status_err = I2C_INT_NO_ACK | I2C_INT_ARBITRATION_LOST | I2C_INT_TX_FIFO_OVERFLOW; struct tegra_i2c_dev *i2c_dev = dev_id; int times = 0; status = i2c_readl(i2c_dev, I2C_INT_STATUS); if (status == 0) { printk(KERN_INFO "[I2C]Unknown interrupt happen\n"); //Read I2C INT STATUS repetitiously for timing issue while(status == 0 && times < I2C_UNKNOWN_RETRY_TIME){ status = i2c_readl(i2c_dev, I2C_INT_STATUS); times++; if(times == (I2C_UNKNOWN_RETRY_TIME -1) ){ dev_warn(i2c_dev->dev, "unknown interrupt Add 0x%02x\n",i2c_dev->msg_add); i2c_dev->msg_err |= I2C_ERR_UNKNOWN_INTERRUPT; goto err; } } printk(KERN_INFO "[I2C]Retry unknown interrupt success\n"); } if (unlikely(status & status_err)) { dev_warn(i2c_dev->dev, "I2c error status 0x%08x\n", status); if (status & I2C_INT_NO_ACK) { i2c_dev->msg_err |= I2C_ERR_NO_ACK; dev_warn(i2c_dev->dev, "no acknowledge from address" " 0x%x\n", i2c_dev->msg_add); dev_warn(i2c_dev->dev, "Packet status 0x%08x\n", i2c_readl(i2c_dev, I2C_PACKET_TRANSFER_STATUS)); } if (status & I2C_INT_ARBITRATION_LOST) { i2c_dev->msg_err |= I2C_ERR_ARBITRATION_LOST; dev_warn(i2c_dev->dev, "arbitration lost during " " communicate to add 0x%x\n", i2c_dev->msg_add); dev_warn(i2c_dev->dev, "Packet status 0x%08x\n", i2c_readl(i2c_dev, I2C_PACKET_TRANSFER_STATUS)); } if (status & I2C_INT_TX_FIFO_OVERFLOW) { i2c_dev->msg_err |= I2C_INT_TX_FIFO_OVERFLOW; dev_warn(i2c_dev->dev, "Tx fifo overflow during " " communicate to add 0x%x\n", i2c_dev->msg_add); dev_warn(i2c_dev->dev, "Packet status 0x%08x\n", i2c_readl(i2c_dev, I2C_PACKET_TRANSFER_STATUS)); } goto err; } if (unlikely((i2c_readl(i2c_dev, I2C_STATUS) & I2C_STATUS_BUSY) && (status == I2C_INT_TX_FIFO_DATA_REQ) && i2c_dev->msg_read && i2c_dev->msg_buf_remaining)) { dev_warn(i2c_dev->dev, "unexpected status\n"); i2c_dev->msg_err |= I2C_ERR_UNEXPECTED_STATUS; if (!i2c_dev->irq_disabled) { disable_irq_nosync(i2c_dev->irq); i2c_dev->irq_disabled = 1; } goto err; } if (i2c_dev->msg_read && (status & I2C_INT_RX_FIFO_DATA_REQ)) { if (i2c_dev->msg_buf_remaining) tegra_i2c_empty_rx_fifo(i2c_dev); else BUG(); } if (!i2c_dev->msg_read && (status & I2C_INT_TX_FIFO_DATA_REQ)) { if (i2c_dev->msg_buf_remaining) tegra_i2c_fill_tx_fifo(i2c_dev); else tegra_i2c_mask_irq(i2c_dev, I2C_INT_TX_FIFO_DATA_REQ); } i2c_writel(i2c_dev, status, I2C_INT_STATUS); if (i2c_dev->is_dvc) dvc_writel(i2c_dev, DVC_STATUS_I2C_DONE_INTR, DVC_STATUS); if (status & I2C_INT_PACKET_XFER_COMPLETE) { BUG_ON(i2c_dev->msg_buf_remaining); complete(&i2c_dev->msg_complete); } return IRQ_HANDLED; err: dev_dbg(i2c_dev->dev, "reg: 0x%08x 0x%08x 0x%08x 0x%08x\n", i2c_readl(i2c_dev, I2C_CNFG), i2c_readl(i2c_dev, I2C_STATUS), i2c_readl(i2c_dev, I2C_INT_STATUS), i2c_readl(i2c_dev, I2C_PACKET_TRANSFER_STATUS)); dev_dbg(i2c_dev->dev, "packet: 0x%08x %u 0x%08x\n", i2c_dev->packet_header, i2c_dev->payload_size, i2c_dev->io_header); if (i2c_dev->msgs) { struct i2c_msg *msgs = i2c_dev->msgs; int i; for (i = 0; i < i2c_dev->msgs_num; i++) dev_dbg(i2c_dev->dev, "msgs[%d] %c, addr=0x%04x, len=%d\n", i, (msgs[i].flags & I2C_M_RD) ? 'R' : 'W', msgs[i].addr, msgs[i].len); } /* An error occurred, mask all interrupts */ tegra_i2c_mask_irq(i2c_dev, I2C_INT_NO_ACK | I2C_INT_ARBITRATION_LOST | I2C_INT_PACKET_XFER_COMPLETE | I2C_INT_TX_FIFO_DATA_REQ | I2C_INT_RX_FIFO_DATA_REQ | I2C_INT_TX_FIFO_OVERFLOW); i2c_writel(i2c_dev, status, I2C_INT_STATUS); /* An error occured, mask dvc interrupt */ if (i2c_dev->is_dvc) dvc_i2c_mask_irq(i2c_dev, DVC_CTRL_REG3_I2C_DONE_INTR_EN); if (i2c_dev->is_dvc) dvc_writel(i2c_dev, DVC_STATUS_I2C_DONE_INTR, DVC_STATUS); complete(&i2c_dev->msg_complete); return IRQ_HANDLED; } static int tegra_i2c_xfer_msg(struct tegra_i2c_bus *i2c_bus, struct i2c_msg *msg, enum msg_end_type end_state) { struct tegra_i2c_dev *i2c_dev = i2c_bus->dev; u32 int_mask; int ret; int arb_stat; if (msg->len == 0) return -EINVAL; tegra_i2c_flush_fifos(i2c_dev); /* Toggle the direction flag if rev dir is selected */ if (msg->flags & I2C_M_REV_DIR_ADDR) msg->flags ^= I2C_M_RD; i2c_dev->msg_buf = msg->buf; i2c_dev->msg_buf_remaining = msg->len; i2c_dev->msg_err = I2C_ERR_NONE; i2c_dev->msg_read = (msg->flags & I2C_M_RD); INIT_COMPLETION(i2c_dev->msg_complete); i2c_dev->msg_add = msg->addr; i2c_dev->packet_header = (0 << PACKET_HEADER0_HEADER_SIZE_SHIFT) | PACKET_HEADER0_PROTOCOL_I2C | (i2c_dev->cont_id << PACKET_HEADER0_CONT_ID_SHIFT) | (1 << PACKET_HEADER0_PACKET_ID_SHIFT); i2c_writel(i2c_dev, i2c_dev->packet_header, I2C_TX_FIFO); i2c_dev->payload_size = msg->len - 1; i2c_writel(i2c_dev, i2c_dev->payload_size, I2C_TX_FIFO); i2c_dev->io_header = I2C_HEADER_IE_ENABLE; if (end_state == MSG_END_CONTINUE) i2c_dev->io_header |= I2C_HEADER_CONTINUE_XFER; else if (end_state == MSG_END_REPEAT_START) i2c_dev->io_header |= I2C_HEADER_REPEAT_START; if (msg->flags & I2C_M_TEN) { i2c_dev->io_header |= msg->addr; i2c_dev->io_header |= I2C_HEADER_10BIT_ADDR; } else { i2c_dev->io_header |= (msg->addr << I2C_HEADER_SLAVE_ADDR_SHIFT); } if (msg->flags & I2C_M_IGNORE_NAK) i2c_dev->io_header |= I2C_HEADER_CONT_ON_NAK; if (msg->flags & I2C_M_RD) i2c_dev->io_header |= I2C_HEADER_READ; if (i2c_dev->is_high_speed_enable) { i2c_dev->io_header |= I2C_HEADER_HIGHSPEED_MODE; i2c_dev->io_header |= ((i2c_dev->hs_master_code & 0x7) << I2C_HEADER_MASTER_ADDR_SHIFT); } i2c_writel(i2c_dev, i2c_dev->io_header, I2C_TX_FIFO); if (!(msg->flags & I2C_M_RD)) tegra_i2c_fill_tx_fifo(i2c_dev); if (i2c_dev->is_dvc) dvc_i2c_unmask_irq(i2c_dev, DVC_CTRL_REG3_I2C_DONE_INTR_EN); int_mask = I2C_INT_NO_ACK | I2C_INT_ARBITRATION_LOST | I2C_INT_TX_FIFO_OVERFLOW; if (msg->flags & I2C_M_RD) int_mask |= I2C_INT_RX_FIFO_DATA_REQ; else if (i2c_dev->msg_buf_remaining) int_mask |= I2C_INT_TX_FIFO_DATA_REQ; tegra_i2c_unmask_irq(i2c_dev, int_mask); dev_dbg(i2c_dev->dev, "unmasked irq: %02x\n", i2c_readl(i2c_dev, I2C_INT_MASK)); ret = wait_for_completion_timeout(&i2c_dev->msg_complete, TEGRA_I2C_TIMEOUT); tegra_i2c_mask_irq(i2c_dev, int_mask); if (i2c_dev->is_dvc) dvc_i2c_mask_irq(i2c_dev, DVC_CTRL_REG3_I2C_DONE_INTR_EN); /* Restore the message flag */ if (msg->flags & I2C_M_REV_DIR_ADDR) msg->flags ^= I2C_M_RD; if (WARN_ON(ret == 0)) { dev_err(i2c_dev->dev, "i2c transfer timed out, addr 0x%04x, data 0x%02x\n", msg->addr, msg->buf[0]); tegra_i2c_init(i2c_dev); return -ETIMEDOUT; } dev_dbg(i2c_dev->dev, "transfer complete: %d %d %d\n", ret, completion_done(&i2c_dev->msg_complete), i2c_dev->msg_err); if (likely(i2c_dev->msg_err == I2C_ERR_NONE)) return 0; /* Arbitration Lost occurs, Start recovery */ if (i2c_dev->msg_err == I2C_ERR_ARBITRATION_LOST) { if (i2c_dev->arb_recovery) { arb_stat = i2c_dev->arb_recovery(i2c_bus->scl_gpio, i2c_bus->sda_gpio); if (!arb_stat) return -EAGAIN; } } /* * NACK interrupt is generated before the I2C controller generates the * STOP condition on the bus. So wait for 2 clock periods before resetting * the controller so that STOP condition has been delivered properly. */ if (i2c_dev->msg_err == I2C_ERR_NO_ACK) udelay(DIV_ROUND_UP(2 * 1000000, i2c_dev->last_bus_clk_rate)); tegra_i2c_init(i2c_dev); if (i2c_dev->msg_err == I2C_ERR_NO_ACK) { if (msg->flags & I2C_M_IGNORE_NAK) return 0; return -EREMOTEIO; } if (i2c_dev->msg_err & I2C_ERR_UNEXPECTED_STATUS) return -EAGAIN; return -EIO; } bool tegra_i2c_is_ready(struct i2c_adapter *adap) { struct tegra_i2c_bus *i2c_bus = i2c_get_adapdata(adap); struct tegra_i2c_dev *i2c_dev = i2c_bus->dev; return !(i2c_dev->is_suspended); } EXPORT_SYMBOL(tegra_i2c_is_ready); static int tegra_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg msgs[], int num) { struct tegra_i2c_bus *i2c_bus = i2c_get_adapdata(adap); struct tegra_i2c_dev *i2c_dev = i2c_bus->dev; int i; int ret = 0; rt_mutex_lock(&i2c_dev->dev_lock); if (i2c_dev->is_suspended) { rt_mutex_unlock(&i2c_dev->dev_lock); return -EBUSY; } if (i2c_dev->last_mux != i2c_bus->mux) { tegra_pinmux_set_safe_pinmux_table(i2c_dev->last_mux, i2c_dev->last_mux_len); tegra_pinmux_config_pinmux_table(i2c_bus->mux, i2c_bus->mux_len); i2c_dev->last_mux = i2c_bus->mux; i2c_dev->last_mux_len = i2c_bus->mux_len; } if (i2c_dev->last_bus_clk_rate != i2c_bus->bus_clk_rate) { clk_set_rate(i2c_dev->div_clk, i2c_bus->bus_clk_rate * 8); i2c_dev->last_bus_clk_rate = i2c_bus->bus_clk_rate; } i2c_dev->msgs = msgs; i2c_dev->msgs_num = num; tegra_i2c_clock_enable(i2c_dev); for (i = 0; i < num; i++) { enum msg_end_type end_type = MSG_END_STOP; if (i < (num - 1)) { if (msgs[i + 1].flags & I2C_M_NOSTART) end_type = MSG_END_CONTINUE; else end_type = MSG_END_REPEAT_START; } ret = tegra_i2c_xfer_msg(i2c_bus, &msgs[i], end_type); if (ret) break; } tegra_i2c_clock_disable(i2c_dev); rt_mutex_unlock(&i2c_dev->dev_lock); i2c_dev->msgs = NULL; i2c_dev->msgs_num = 0; return ret ?: i; } static u32 tegra_i2c_func(struct i2c_adapter *adap) { return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL | I2C_FUNC_10BIT_ADDR | I2C_FUNC_PROTOCOL_MANGLING; } static const struct i2c_algorithm tegra_i2c_algo = { .master_xfer = tegra_i2c_xfer, .functionality = tegra_i2c_func, }; static int __devinit tegra_i2c_probe(struct platform_device *pdev) { struct tegra_i2c_dev *i2c_dev; struct tegra_i2c_platform_data *plat = pdev->dev.platform_data; struct resource *res; struct clk *div_clk; struct clk *fast_clk = NULL; const unsigned int *prop; void *base; int irq; int nbus; int i = 0; int ret = 0; if (!plat) { dev_err(&pdev->dev, "no platform data?\n"); return -ENODEV; } if (plat->bus_count <= 0 || plat->adapter_nr < 0) { dev_err(&pdev->dev, "invalid platform data?\n"); return -ENODEV; } WARN_ON(plat->bus_count > TEGRA_I2C_MAX_BUS); nbus = min(TEGRA_I2C_MAX_BUS, plat->bus_count); res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) { dev_err(&pdev->dev, "no mem resource\n"); return -EINVAL; } base = devm_request_and_ioremap(&pdev->dev, res); if (!base) { dev_err(&pdev->dev, "Cannot request/ioremap I2C registers\n"); return -EADDRNOTAVAIL; } res = platform_get_resource(pdev, IORESOURCE_IRQ, 0); if (!res) { dev_err(&pdev->dev, "no irq resource\n"); return -EINVAL; } irq = res->start; div_clk = devm_clk_get(&pdev->dev, "i2c-div"); if (IS_ERR(div_clk)) { dev_err(&pdev->dev, "missing controller clock"); return PTR_ERR(div_clk); } fast_clk = devm_clk_get(&pdev->dev, "i2c-fast"); if (IS_ERR(fast_clk)) { dev_err(&pdev->dev, "missing controller fast clock"); return PTR_ERR(fast_clk); } i2c_dev = devm_kzalloc(&pdev->dev, sizeof(struct tegra_i2c_dev) + (nbus-1) * sizeof(struct tegra_i2c_bus), GFP_KERNEL); if (!i2c_dev) { dev_err(&pdev->dev, "Could not allocate struct tegra_i2c_dev"); return -ENOMEM; } i2c_dev->base = base; i2c_dev->div_clk = div_clk; i2c_dev->fast_clk = fast_clk; i2c_dev->irq = irq; i2c_dev->cont_id = pdev->id; i2c_dev->dev = &pdev->dev; i2c_dev->is_clkon_always = plat->is_clkon_always; i2c_dev->last_bus_clk_rate = 100000; /* default clock rate */ if (plat) { i2c_dev->last_bus_clk_rate = plat->bus_clk_rate[0]; } else if (i2c_dev->dev->of_node) { /* if there is a device tree node ... */ /* TODO: DAN: this doesn't work for DT */ prop = of_get_property(i2c_dev->dev->of_node, "clock-frequency", NULL); if (prop) i2c_dev->last_bus_clk_rate = be32_to_cpup(prop); } i2c_dev->is_high_speed_enable = plat->is_high_speed_enable; i2c_dev->last_bus_clk_rate = plat->bus_clk_rate[0] ?: 100000; i2c_dev->msgs = NULL; i2c_dev->msgs_num = 0; rt_mutex_init(&i2c_dev->dev_lock); spin_lock_init(&i2c_dev->fifo_lock); i2c_dev->slave_addr = plat->slave_addr; i2c_dev->hs_master_code = plat->hs_master_code; i2c_dev->is_dvc = plat->is_dvc; i2c_dev->arb_recovery = plat->arb_recovery; init_completion(&i2c_dev->msg_complete); platform_set_drvdata(pdev, i2c_dev); if (i2c_dev->is_clkon_always) tegra_i2c_clock_enable(i2c_dev); ret = tegra_i2c_init(i2c_dev); if (ret) { dev_err(&pdev->dev, "Failed to initialize i2c controller"); return ret; } ret = devm_request_irq(&pdev->dev, i2c_dev->irq, tegra_i2c_isr, IRQF_NO_SUSPEND, pdev->name, i2c_dev); if (ret) { dev_err(&pdev->dev, "Failed to request irq %i\n", i2c_dev->irq); return ret; } for (i = 0; i < nbus; i++) { struct tegra_i2c_bus *i2c_bus = &i2c_dev->busses[i]; i2c_bus->dev = i2c_dev; i2c_bus->mux = plat->bus_mux[i]; i2c_bus->mux_len = plat->bus_mux_len[i]; i2c_bus->bus_clk_rate = plat->bus_clk_rate[i] ?: 100000; i2c_bus->scl_gpio = plat->scl_gpio[i]; i2c_bus->sda_gpio = plat->sda_gpio[i]; i2c_bus->adapter.dev.of_node = pdev->dev.of_node; i2c_bus->adapter.algo = &tegra_i2c_algo; i2c_set_adapdata(&i2c_bus->adapter, i2c_bus); i2c_bus->adapter.owner = THIS_MODULE; i2c_bus->adapter.class = I2C_CLASS_HWMON; strlcpy(i2c_bus->adapter.name, "Tegra I2C adapter", sizeof(i2c_bus->adapter.name)); i2c_bus->adapter.dev.parent = &pdev->dev; i2c_bus->adapter.nr = plat->adapter_nr + i; if (plat->retries) i2c_bus->adapter.retries = plat->retries; else i2c_bus->adapter.retries = TEGRA_I2C_RETRIES; if (plat->timeout) i2c_bus->adapter.timeout = plat->timeout; ret = i2c_add_numbered_adapter(&i2c_bus->adapter); if (ret) { dev_err(&pdev->dev, "Failed to add I2C adapter\n"); goto err_del_bus; } of_i2c_register_devices(&i2c_bus->adapter); i2c_dev->bus_count++; } return 0; err_del_bus: while (i2c_dev->bus_count--) i2c_del_adapter(&i2c_dev->busses[i2c_dev->bus_count].adapter); return ret; } static int __devexit tegra_i2c_remove(struct platform_device *pdev) { struct tegra_i2c_dev *i2c_dev = platform_get_drvdata(pdev); while (i2c_dev->bus_count--) i2c_del_adapter(&i2c_dev->busses[i2c_dev->bus_count].adapter); if (i2c_dev->is_clkon_always) tegra_i2c_clock_disable(i2c_dev); return 0; } #ifdef CONFIG_PM static int tegra_i2c_suspend_noirq(struct device *dev) { struct platform_device *pdev = to_platform_device(dev); struct tegra_i2c_dev *i2c_dev = platform_get_drvdata(pdev); rt_mutex_lock(&i2c_dev->dev_lock); i2c_dev->is_suspended = true; if (i2c_dev->is_clkon_always) tegra_i2c_clock_disable(i2c_dev); rt_mutex_unlock(&i2c_dev->dev_lock); return 0; } static int tegra_i2c_resume_noirq(struct device *dev) { struct platform_device *pdev = to_platform_device(dev); struct tegra_i2c_dev *i2c_dev = platform_get_drvdata(pdev); int ret; rt_mutex_lock(&i2c_dev->dev_lock); if (i2c_dev->is_clkon_always) tegra_i2c_clock_enable(i2c_dev); ret = tegra_i2c_init(i2c_dev); if (ret) { rt_mutex_unlock(&i2c_dev->dev_lock); return ret; } i2c_dev->is_suspended = false; rt_mutex_unlock(&i2c_dev->dev_lock); return 0; } static const struct dev_pm_ops tegra_i2c_pm = { .suspend_noirq = tegra_i2c_suspend_noirq, .resume_noirq = tegra_i2c_resume_noirq, }; #define TEGRA_I2C_PM (&tegra_i2c_pm) #else #define TEGRA_I2C_PM NULL #endif #if defined(CONFIG_OF) /* Match table for of_platform binding */ static const struct of_device_id tegra_i2c_of_match[] __devinitconst = { { .compatible = "nvidia,tegra20-i2c", }, {}, }; MODULE_DEVICE_TABLE(of, tegra_i2c_of_match); #endif static struct platform_driver tegra_i2c_driver = { .probe = tegra_i2c_probe, .remove = __devexit_p(tegra_i2c_remove), .driver = { .name = "tegra-i2c", .owner = THIS_MODULE, .of_match_table = of_match_ptr(tegra_i2c_of_match), .pm = TEGRA_I2C_PM, }, }; static int __init tegra_i2c_init_driver(void) { return platform_driver_register(&tegra_i2c_driver); } static void __exit tegra_i2c_exit_driver(void) { platform_driver_unregister(&tegra_i2c_driver); } subsys_initcall(tegra_i2c_init_driver); module_exit(tegra_i2c_exit_driver); MODULE_DESCRIPTION("nVidia Tegra2 I2C Bus Controller driver"); MODULE_AUTHOR("Colin Cross"); MODULE_LICENSE("GPL v2");
aureljared/pulsar
drivers/i2c/busses/i2c-tegra.c
C
gpl-2.0
31,045
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_25) on Wed Jul 23 10:47:42 EDT 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Deprecated List</title> <meta name="date" content="2014-07-23"> <link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Deprecated List"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li><a href="overview-tree.html">Tree</a></li> <li class="navBarCell1Rev">Deprecated</li> <li><a href="index-files/index-1.html">Index</a></li> <li><a href="help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="index.html?deprecated-list.html" target="_top">Frames</a></li> <li><a href="deprecated-list.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Deprecated API" class="title">Deprecated API</h1> <h2 title="Contents">Contents</h2> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li><a href="overview-tree.html">Tree</a></li> <li class="navBarCell1Rev">Deprecated</li> <li><a href="index-files/index-1.html">Index</a></li> <li><a href="help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="index.html?deprecated-list.html" target="_top">Frames</a></li> <li><a href="deprecated-list.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
cosimoiaia/pyAiml-2.0
doc/program-ab-reference-doc/deprecated-list.html
HTML
gpl-2.0
3,477
/* * Copyright (C) 2008 The Android Open Source Project * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <pthread.h> struct user_desc { unsigned int entry_number; unsigned long base_addr; unsigned int limit; unsigned int seg_32bit:1; unsigned int contents:2; unsigned int read_exec_only:1; unsigned int limit_in_pages:1; unsigned int seg_not_present:1; unsigned int useable:1; unsigned int empty:25; }; extern int __set_thread_area(struct user_desc *u_info); /* the following can't be const, since the first call will * update the 'entry_number' field */ static struct user_desc _tls_desc = { -1, 0, 0x1000, 1, 0, 0, 1, 0, 1, 0 }; static pthread_mutex_t _tls_desc_lock = PTHREAD_MUTEX_INITIALIZER; struct _thread_area_head { void *self; }; /* we implement thread local storage through the gs: segment descriptor * we create a segment descriptor for the tls */ int __set_tls(void *ptr) { int rc, segment; pthread_mutex_lock(&_tls_desc_lock); _tls_desc.base_addr = (unsigned long)ptr; /* We also need to write the location of the tls to ptr[0] */ ((struct _thread_area_head *)ptr)->self = ptr; rc = __set_thread_area( &_tls_desc ); if (rc != 0) { /* could not set thread local area */ pthread_mutex_unlock(&_tls_desc_lock); return -1; } /* this weird computation comes from GLibc */ segment = _tls_desc.entry_number*8 + 3; asm __volatile__ ( " movw %w0, %%gs" :: "q"(segment) ); pthread_mutex_unlock(&_tls_desc_lock); return 0; }
infraredbg/Lenovo_A820_kernel_kk
bionic/libc/arch-x86/bionic/__set_tls.c
C
gpl-2.0
2,960