code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
/* * Copyright (C) 2008 Apple Inc. All Rights Reserved. * Copyright (C) 2011 Google 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: * 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 APPLE INC. ``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 APPLE INC. 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. */ importScript("BreakpointsSidebarPane.js"); importScript("CallStackSidebarPane.js"); importScript("FilePathScoreFunction.js"); importScript("FilteredItemSelectionDialog.js"); importScript("UISourceCodeFrame.js"); importScript("JavaScriptSourceFrame.js"); importScript("NavigatorOverlayController.js"); importScript("NavigatorView.js"); importScript("RevisionHistoryView.js"); importScript("ScopeChainSidebarPane.js"); importScript("ScriptsNavigator.js"); importScript("ScriptsSearchScope.js"); importScript("StyleSheetOutlineDialog.js"); importScript("TabbedEditorContainer.js"); importScript("WatchExpressionsSidebarPane.js"); importScript("WorkersSidebarPane.js"); /** * @constructor * @implements {WebInspector.TabbedEditorContainerDelegate} * @implements {WebInspector.ContextMenu.Provider} * @extends {WebInspector.Panel} * @param {WebInspector.Workspace=} workspaceForTest */ WebInspector.ScriptsPanel = function(workspaceForTest) { WebInspector.Panel.call(this, "scripts"); this.registerRequiredCSS("scriptsPanel.css"); this.registerRequiredCSS("textPrompt.css"); // Watch Expressions autocomplete. WebInspector.settings.navigatorWasOnceHidden = WebInspector.settings.createSetting("navigatorWasOnceHidden", false); WebInspector.settings.debuggerSidebarHidden = WebInspector.settings.createSetting("debuggerSidebarHidden", false); this._workspace = workspaceForTest || WebInspector.workspace; function viewGetter() { return this.visibleView; } WebInspector.GoToLineDialog.install(this, viewGetter.bind(this)); var helpSection = WebInspector.shortcutsScreen.section(WebInspector.UIString("Sources Panel")); this.debugToolbar = this._createDebugToolbar(); const initialDebugSidebarWidth = 225; const minimumDebugSidebarWidthPercent = 0.5; this.createSidebarView(this.element, WebInspector.SidebarView.SidebarPosition.End, initialDebugSidebarWidth); this.splitView.element.id = "scripts-split-view"; this.splitView.setSidebarElementConstraints(Preferences.minScriptsSidebarWidth); this.splitView.setMainElementConstraints(minimumDebugSidebarWidthPercent); // Create scripts navigator const initialNavigatorWidth = 225; const minimumViewsContainerWidthPercent = 0.5; this.editorView = new WebInspector.SidebarView(WebInspector.SidebarView.SidebarPosition.Start, "scriptsPanelNavigatorSidebarWidth", initialNavigatorWidth); this.editorView.element.tabIndex = 0; this.editorView.setSidebarElementConstraints(Preferences.minScriptsSidebarWidth); this.editorView.setMainElementConstraints(minimumViewsContainerWidthPercent); this.editorView.show(this.splitView.mainElement); this._navigator = new WebInspector.ScriptsNavigator(); this._navigator.view.show(this.editorView.sidebarElement); var tabbedEditorPlaceholderText = WebInspector.isMac() ? WebInspector.UIString("Hit Cmd+O to open a file") : WebInspector.UIString("Hit Ctrl+O to open a file"); this._editorContentsElement = this.editorView.mainElement.createChild("div", "fill"); this._editorFooterElement = this.editorView.mainElement.createChild("div", "inspector-footer status-bar hidden"); this._editorContainer = new WebInspector.TabbedEditorContainer(this, "previouslyViewedFiles", tabbedEditorPlaceholderText); this._editorContainer.show(this._editorContentsElement); this._navigatorController = new WebInspector.NavigatorOverlayController(this.editorView, this._navigator.view, this._editorContainer.view); this._navigator.addEventListener(WebInspector.ScriptsNavigator.Events.ScriptSelected, this._scriptSelected, this); this._navigator.addEventListener(WebInspector.ScriptsNavigator.Events.ItemSearchStarted, this._itemSearchStarted, this); this._navigator.addEventListener(WebInspector.ScriptsNavigator.Events.ItemCreationRequested, this._itemCreationRequested, this); this._navigator.addEventListener(WebInspector.ScriptsNavigator.Events.ItemRenamingRequested, this._itemRenamingRequested, this); this._editorContainer.addEventListener(WebInspector.TabbedEditorContainer.Events.EditorSelected, this._editorSelected, this); this._editorContainer.addEventListener(WebInspector.TabbedEditorContainer.Events.EditorClosed, this._editorClosed, this); this._debugSidebarResizeWidgetElement = this.splitView.mainElement.createChild("div", "resizer-widget"); this._debugSidebarResizeWidgetElement.id = "scripts-debug-sidebar-resizer-widget"; this.splitView.installResizer(this._debugSidebarResizeWidgetElement); this.sidebarPanes = {}; this.sidebarPanes.watchExpressions = new WebInspector.WatchExpressionsSidebarPane(); this.sidebarPanes.callstack = new WebInspector.CallStackSidebarPane(); this.sidebarPanes.callstack.addEventListener(WebInspector.CallStackSidebarPane.Events.CallFrameSelected, this._callFrameSelectedInSidebar.bind(this)); this.sidebarPanes.scopechain = new WebInspector.ScopeChainSidebarPane(); this.sidebarPanes.jsBreakpoints = new WebInspector.JavaScriptBreakpointsSidebarPane(WebInspector.breakpointManager, this._showSourceLocation.bind(this)); this.sidebarPanes.domBreakpoints = WebInspector.domBreakpointsSidebarPane.createProxy(this); this.sidebarPanes.xhrBreakpoints = new WebInspector.XHRBreakpointsSidebarPane(); this.sidebarPanes.eventListenerBreakpoints = new WebInspector.EventListenerBreakpointsSidebarPane(); if (Capabilities.canInspectWorkers && !WebInspector.WorkerManager.isWorkerFrontend()) { WorkerAgent.enable(); this.sidebarPanes.workerList = new WebInspector.WorkersSidebarPane(WebInspector.workerManager); } this.sidebarPanes.callstack.registerShortcuts(this.registerShortcuts.bind(this)); this.registerShortcuts(WebInspector.ScriptsPanelDescriptor.ShortcutKeys.GoToMember, this._showOutlineDialog.bind(this)); this.registerShortcuts(WebInspector.ScriptsPanelDescriptor.ShortcutKeys.ToggleBreakpoint, this._toggleBreakpoint.bind(this)); this._pauseOnExceptionButton = new WebInspector.StatusBarButton("", "scripts-pause-on-exceptions-status-bar-item", 3); this._pauseOnExceptionButton.addEventListener("click", this._togglePauseOnExceptions, this); this._toggleFormatSourceButton = new WebInspector.StatusBarButton(WebInspector.UIString("Pretty print"), "scripts-toggle-pretty-print-status-bar-item"); this._toggleFormatSourceButton.toggled = false; this._toggleFormatSourceButton.addEventListener("click", this._toggleFormatSource, this); this._scriptViewStatusBarItemsContainer = document.createElement("div"); this._scriptViewStatusBarItemsContainer.className = "inline-block"; this._scriptViewStatusBarTextContainer = document.createElement("div"); this._scriptViewStatusBarTextContainer.className = "inline-block"; this._installDebuggerSidebarController(); WebInspector.dockController.addEventListener(WebInspector.DockController.Events.DockSideChanged, this._dockSideChanged.bind(this)); WebInspector.settings.splitVerticallyWhenDockedToRight.addChangeListener(this._dockSideChanged.bind(this)); this._dockSideChanged(); /** @type {!Map.<!WebInspector.UISourceCode, !WebInspector.SourceFrame>} */ this._sourceFramesByUISourceCode = new Map(); this._updateDebuggerButtons(); this._pauseOnExceptionStateChanged(); if (WebInspector.debuggerModel.isPaused()) this._debuggerPaused(); WebInspector.settings.pauseOnExceptionStateString.addChangeListener(this._pauseOnExceptionStateChanged, this); WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.DebuggerWasEnabled, this._debuggerWasEnabled, this); WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.DebuggerWasDisabled, this._debuggerWasDisabled, this); WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.DebuggerPaused, this._debuggerPaused, this); WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.DebuggerResumed, this._debuggerResumed, this); WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.CallFrameSelected, this._callFrameSelected, this); WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.ConsoleCommandEvaluatedInSelectedCallFrame, this._consoleCommandEvaluatedInSelectedCallFrame, this); WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.BreakpointsActiveStateChanged, this._breakpointsActiveStateChanged, this); WebInspector.startBatchUpdate(); this._workspace.uiSourceCodes().forEach(this._addUISourceCode.bind(this)); WebInspector.endBatchUpdate(); this._workspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeAdded, this._uiSourceCodeAdded, this); this._workspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeRemoved, this._uiSourceCodeRemoved, this); this._workspace.addEventListener(WebInspector.Workspace.Events.ProjectWillReset, this._projectWillReset.bind(this), this); WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.GlobalObjectCleared, this._debuggerReset, this); WebInspector.advancedSearchController.registerSearchScope(new WebInspector.ScriptsSearchScope(this._workspace)); this._boundOnKeyUp = this._onKeyUp.bind(this); this._boundOnKeyDown = this._onKeyDown.bind(this); } WebInspector.ScriptsPanel.prototype = { get statusBarItems() { return [this._pauseOnExceptionButton.element, this._toggleFormatSourceButton.element, this._scriptViewStatusBarItemsContainer]; }, /** * @return {?Element} */ statusBarText: function() { return this._scriptViewStatusBarTextContainer; }, defaultFocusedElement: function() { return this._editorContainer.view.defaultFocusedElement() || this._navigator.view.defaultFocusedElement(); }, get paused() { return this._paused; }, wasShown: function() { WebInspector.Panel.prototype.wasShown.call(this); this._navigatorController.wasShown(); this.element.addEventListener("keydown", this._boundOnKeyDown, false); this.element.addEventListener("keyup", this._boundOnKeyUp, false); }, willHide: function() { this.element.removeEventListener("keydown", this._boundOnKeyDown, false); this.element.removeEventListener("keyup", this._boundOnKeyUp, false); WebInspector.Panel.prototype.willHide.call(this); WebInspector.closeViewInDrawer(); }, /** * @param {WebInspector.Event} event */ _uiSourceCodeAdded: function(event) { var uiSourceCode = /** @type {WebInspector.UISourceCode} */ (event.data); this._addUISourceCode(uiSourceCode); }, /** * @param {WebInspector.UISourceCode} uiSourceCode */ _addUISourceCode: function(uiSourceCode) { if (this._toggleFormatSourceButton.toggled) uiSourceCode.setFormatted(true); if (uiSourceCode.project().isServiceProject()) return; this._navigator.addUISourceCode(uiSourceCode); this._editorContainer.addUISourceCode(uiSourceCode); // Replace debugger script-based uiSourceCode with a network-based one. var currentUISourceCode = this._currentUISourceCode; if (currentUISourceCode && currentUISourceCode.project().isServiceProject() && currentUISourceCode !== uiSourceCode && currentUISourceCode.url === uiSourceCode.url) { this._showFile(uiSourceCode); this._editorContainer.removeUISourceCode(currentUISourceCode); } }, _uiSourceCodeRemoved: function(event) { var uiSourceCode = /** @type {WebInspector.UISourceCode} */ (event.data); this._removeUISourceCodes([uiSourceCode]); }, /** * @param {Array.<WebInspector.UISourceCode>} uiSourceCodes */ _removeUISourceCodes: function(uiSourceCodes) { for (var i = 0; i < uiSourceCodes.length; ++i) { this._navigator.removeUISourceCode(uiSourceCodes[i]); this._removeSourceFrame(uiSourceCodes[i]); } this._editorContainer.removeUISourceCodes(uiSourceCodes); }, _consoleCommandEvaluatedInSelectedCallFrame: function(event) { this.sidebarPanes.scopechain.update(WebInspector.debuggerModel.selectedCallFrame()); }, _debuggerPaused: function() { var details = WebInspector.debuggerModel.debuggerPausedDetails(); this._paused = true; this._waitingToPause = false; this._stepping = false; this._updateDebuggerButtons(); WebInspector.inspectorView.setCurrentPanel(this); this.sidebarPanes.callstack.update(details.callFrames); if (details.reason === WebInspector.DebuggerModel.BreakReason.DOM) { WebInspector.domBreakpointsSidebarPane.highlightBreakpoint(details.auxData); function didCreateBreakpointHitStatusMessage(element) { this.sidebarPanes.callstack.setStatus(element); } WebInspector.domBreakpointsSidebarPane.createBreakpointHitStatusMessage(details.auxData, didCreateBreakpointHitStatusMessage.bind(this)); } else if (details.reason === WebInspector.DebuggerModel.BreakReason.EventListener) { var eventName = details.auxData.eventName; this.sidebarPanes.eventListenerBreakpoints.highlightBreakpoint(details.auxData.eventName); var eventNameForUI = WebInspector.EventListenerBreakpointsSidebarPane.eventNameForUI(eventName, details.auxData); this.sidebarPanes.callstack.setStatus(WebInspector.UIString("Paused on a \"%s\" Event Listener.", eventNameForUI)); } else if (details.reason === WebInspector.DebuggerModel.BreakReason.XHR) { this.sidebarPanes.xhrBreakpoints.highlightBreakpoint(details.auxData["breakpointURL"]); this.sidebarPanes.callstack.setStatus(WebInspector.UIString("Paused on a XMLHttpRequest.")); } else if (details.reason === WebInspector.DebuggerModel.BreakReason.Exception) this.sidebarPanes.callstack.setStatus(WebInspector.UIString("Paused on exception: '%s'.", details.auxData.description)); else if (details.reason === WebInspector.DebuggerModel.BreakReason.Assert) this.sidebarPanes.callstack.setStatus(WebInspector.UIString("Paused on assertion.")); else if (details.reason === WebInspector.DebuggerModel.BreakReason.CSPViolation) this.sidebarPanes.callstack.setStatus(WebInspector.UIString("Paused on a script blocked due to Content Security Policy directive: \"%s\".", details.auxData["directiveText"])); else if (details.reason === WebInspector.DebuggerModel.BreakReason.DebugCommand) this.sidebarPanes.callstack.setStatus(WebInspector.UIString("Paused on a debugged function")); else { function didGetUILocation(uiLocation) { var breakpoint = WebInspector.breakpointManager.findBreakpoint(uiLocation.uiSourceCode, uiLocation.lineNumber); if (!breakpoint) return; this.sidebarPanes.jsBreakpoints.highlightBreakpoint(breakpoint); this.sidebarPanes.callstack.setStatus(WebInspector.UIString("Paused on a JavaScript breakpoint.")); } if (details.callFrames.length) details.callFrames[0].createLiveLocation(didGetUILocation.bind(this)); else console.warn("ScriptsPanel paused, but callFrames.length is zero."); // TODO remove this once we understand this case better } this._enableDebuggerSidebar(true); this._toggleDebuggerSidebarButton.setEnabled(false); window.focus(); InspectorFrontendHost.bringToFront(); }, _debuggerResumed: function() { this._paused = false; this._waitingToPause = false; this._stepping = false; this._clearInterface(); this._toggleDebuggerSidebarButton.setEnabled(true); }, _debuggerWasEnabled: function() { this._updateDebuggerButtons(); }, _debuggerWasDisabled: function() { this._debuggerReset(); }, _debuggerReset: function() { this._debuggerResumed(); this.sidebarPanes.watchExpressions.reset(); delete this._skipExecutionLineRevealing; }, _projectWillReset: function(event) { var project = event.data; var uiSourceCodes = project.uiSourceCodes(); this._removeUISourceCodes(uiSourceCodes); if (project.type() === WebInspector.projectTypes.Network) this._editorContainer.reset(); }, get visibleView() { return this._editorContainer.visibleView; }, _updateScriptViewStatusBarItems: function() { this._scriptViewStatusBarItemsContainer.removeChildren(); this._scriptViewStatusBarTextContainer.removeChildren(); var sourceFrame = this.visibleView; if (sourceFrame) { var statusBarItems = sourceFrame.statusBarItems() || []; for (var i = 0; i < statusBarItems.length; ++i) this._scriptViewStatusBarItemsContainer.appendChild(statusBarItems[i]); var statusBarText = sourceFrame.statusBarText(); if (statusBarText) this._scriptViewStatusBarTextContainer.appendChild(statusBarText); } }, /** * @param {Element} anchor */ canShowAnchorLocation: function(anchor) { if (WebInspector.debuggerModel.debuggerEnabled() && anchor.uiSourceCode) return true; var uiSourceCode = WebInspector.workspace.uiSourceCodeForURL(anchor.href); if (uiSourceCode) { anchor.uiSourceCode = uiSourceCode; return true; } return false; }, /** * @param {Element} anchor */ showAnchorLocation: function(anchor) { this._showSourceLocation(anchor.uiSourceCode, anchor.lineNumber, anchor.columnNumber); }, /** * @param {WebInspector.UISourceCode} uiSourceCode * @param {number=} lineNumber * @param {number=} columnNumber */ showUISourceCode: function(uiSourceCode, lineNumber, columnNumber) { this._showSourceLocation(uiSourceCode, lineNumber, columnNumber); }, /** * @return {?WebInspector.UISourceCode} */ currentUISourceCode: function() { return this._currentUISourceCode; }, /** * @param {WebInspector.UILocation} uiLocation */ showUILocation: function(uiLocation) { this._showSourceLocation(uiLocation.uiSourceCode, uiLocation.lineNumber, uiLocation.columnNumber); }, /** * @param {WebInspector.UISourceCode} uiSourceCode * @param {number=} lineNumber * @param {number=} columnNumber */ _showSourceLocation: function(uiSourceCode, lineNumber, columnNumber) { var sourceFrame = this._showFile(uiSourceCode); if (typeof lineNumber === "number") sourceFrame.highlightPosition(lineNumber, columnNumber); sourceFrame.focus(); WebInspector.notifications.dispatchEventToListeners(WebInspector.UserMetrics.UserAction, { action: WebInspector.UserMetrics.UserActionNames.OpenSourceLink, url: uiSourceCode.originURL(), lineNumber: lineNumber }); }, /** * @param {WebInspector.UISourceCode} uiSourceCode * @return {WebInspector.SourceFrame} */ _showFile: function(uiSourceCode) { var sourceFrame = this._getOrCreateSourceFrame(uiSourceCode); if (this._currentUISourceCode === uiSourceCode) return sourceFrame; this._currentUISourceCode = uiSourceCode; if (!uiSourceCode.project().isServiceProject()) this._navigator.revealUISourceCode(uiSourceCode, true); this._editorContainer.showFile(uiSourceCode); this._updateScriptViewStatusBarItems(); if (this._currentUISourceCode.project().type() === WebInspector.projectTypes.Snippets) this._runSnippetButton.element.removeStyleClass("hidden"); else this._runSnippetButton.element.addStyleClass("hidden"); return sourceFrame; }, /** * @param {WebInspector.UISourceCode} uiSourceCode * @return {WebInspector.SourceFrame} */ _createSourceFrame: function(uiSourceCode) { var sourceFrame; switch (uiSourceCode.contentType()) { case WebInspector.resourceTypes.Script: sourceFrame = new WebInspector.JavaScriptSourceFrame(this, uiSourceCode); break; case WebInspector.resourceTypes.Document: sourceFrame = new WebInspector.JavaScriptSourceFrame(this, uiSourceCode); break; case WebInspector.resourceTypes.Stylesheet: default: sourceFrame = new WebInspector.UISourceCodeFrame(uiSourceCode); break; } this._sourceFramesByUISourceCode.put(uiSourceCode, sourceFrame); return sourceFrame; }, /** * @param {WebInspector.UISourceCode} uiSourceCode * @return {WebInspector.SourceFrame} */ _getOrCreateSourceFrame: function(uiSourceCode) { return this._sourceFramesByUISourceCode.get(uiSourceCode) || this._createSourceFrame(uiSourceCode); }, /** * @param {WebInspector.UISourceCode} uiSourceCode * @return {WebInspector.SourceFrame} */ viewForFile: function(uiSourceCode) { return this._getOrCreateSourceFrame(uiSourceCode); }, /** * @param {WebInspector.UISourceCode} uiSourceCode */ _removeSourceFrame: function(uiSourceCode) { var sourceFrame = this._sourceFramesByUISourceCode.get(uiSourceCode); if (!sourceFrame) return; this._sourceFramesByUISourceCode.remove(uiSourceCode); sourceFrame.dispose(); }, _clearCurrentExecutionLine: function() { if (this._executionSourceFrame) this._executionSourceFrame.clearExecutionLine(); delete this._executionSourceFrame; }, _setExecutionLine: function(uiLocation) { var callFrame = WebInspector.debuggerModel.selectedCallFrame() var sourceFrame = this._getOrCreateSourceFrame(uiLocation.uiSourceCode); sourceFrame.setExecutionLine(uiLocation.lineNumber, callFrame); this._executionSourceFrame = sourceFrame; }, _executionLineChanged: function(uiLocation) { this._clearCurrentExecutionLine(); this._setExecutionLine(uiLocation); var uiSourceCode = uiLocation.uiSourceCode; var scriptFile = this._currentUISourceCode ? this._currentUISourceCode.scriptFile() : null; if (this._skipExecutionLineRevealing) return; this._skipExecutionLineRevealing = true; var sourceFrame = this._showFile(uiSourceCode); sourceFrame.revealLine(uiLocation.lineNumber); if (sourceFrame.canEditSource()) sourceFrame.setSelection(WebInspector.TextRange.createFromLocation(uiLocation.lineNumber, 0)); sourceFrame.focus(); }, _callFrameSelected: function(event) { var callFrame = event.data; if (!callFrame) return; this.sidebarPanes.scopechain.update(callFrame); this.sidebarPanes.watchExpressions.refreshExpressions(); this.sidebarPanes.callstack.setSelectedCallFrame(callFrame); callFrame.createLiveLocation(this._executionLineChanged.bind(this)); }, _editorClosed: function(event) { this._navigatorController.hideNavigatorOverlay(); var uiSourceCode = /** @type {WebInspector.UISourceCode} */ (event.data); if (this._currentUISourceCode === uiSourceCode) delete this._currentUISourceCode; // ScriptsNavigator does not need to update on EditorClosed. this._updateScriptViewStatusBarItems(); WebInspector.searchController.resetSearch(); }, _editorSelected: function(event) { var uiSourceCode = /** @type {WebInspector.UISourceCode} */ (event.data); var sourceFrame = this._showFile(uiSourceCode); this._navigatorController.hideNavigatorOverlay(); if (!this._navigatorController.isNavigatorPinned()) sourceFrame.focus(); WebInspector.searchController.resetSearch(); }, _scriptSelected: function(event) { var uiSourceCode = /** @type {WebInspector.UISourceCode} */ (event.data.uiSourceCode); var sourceFrame = this._showFile(uiSourceCode); this._navigatorController.hideNavigatorOverlay(); if (sourceFrame && (!this._navigatorController.isNavigatorPinned() || event.data.focusSource)) sourceFrame.focus(); }, _itemSearchStarted: function(event) { var searchText = /** @type {string} */ (event.data); WebInspector.OpenResourceDialog.show(this, this.editorView.mainElement, searchText); }, _pauseOnExceptionStateChanged: function() { var pauseOnExceptionsState = WebInspector.settings.pauseOnExceptionStateString.get(); switch (pauseOnExceptionsState) { case WebInspector.DebuggerModel.PauseOnExceptionsState.DontPauseOnExceptions: this._pauseOnExceptionButton.title = WebInspector.UIString("Don't pause on exceptions.\nClick to Pause on all exceptions."); break; case WebInspector.DebuggerModel.PauseOnExceptionsState.PauseOnAllExceptions: this._pauseOnExceptionButton.title = WebInspector.UIString("Pause on all exceptions.\nClick to Pause on uncaught exceptions."); break; case WebInspector.DebuggerModel.PauseOnExceptionsState.PauseOnUncaughtExceptions: this._pauseOnExceptionButton.title = WebInspector.UIString("Pause on uncaught exceptions.\nClick to Not pause on exceptions."); break; } this._pauseOnExceptionButton.state = pauseOnExceptionsState; }, _updateDebuggerButtons: function() { if (WebInspector.debuggerModel.debuggerEnabled()) { this._pauseOnExceptionButton.visible = true; } else { this._pauseOnExceptionButton.visible = false; } if (this._paused) { this._updateButtonTitle(this._pauseButton, WebInspector.UIString("Resume script execution (%s).")) this._pauseButton.state = true; this._pauseButton.setLongClickOptionsEnabled((function() { return [ this._longResumeButton ] }).bind(this)); this._pauseButton.setEnabled(true); this._stepOverButton.setEnabled(true); this._stepIntoButton.setEnabled(true); this._stepOutButton.setEnabled(true); this.debuggerStatusElement.textContent = WebInspector.UIString("Paused"); } else { this._updateButtonTitle(this._pauseButton, WebInspector.UIString("Pause script execution (%s).")) this._pauseButton.state = false; this._pauseButton.setLongClickOptionsEnabled(null); this._pauseButton.setEnabled(!this._waitingToPause); this._stepOverButton.setEnabled(false); this._stepIntoButton.setEnabled(false); this._stepOutButton.setEnabled(false); if (this._waitingToPause) this.debuggerStatusElement.textContent = WebInspector.UIString("Pausing"); else if (this._stepping) this.debuggerStatusElement.textContent = WebInspector.UIString("Stepping"); else this.debuggerStatusElement.textContent = ""; } }, _clearInterface: function() { this.sidebarPanes.callstack.update(null); this.sidebarPanes.scopechain.update(null); this.sidebarPanes.jsBreakpoints.clearBreakpointHighlight(); WebInspector.domBreakpointsSidebarPane.clearBreakpointHighlight(); this.sidebarPanes.eventListenerBreakpoints.clearBreakpointHighlight(); this.sidebarPanes.xhrBreakpoints.clearBreakpointHighlight(); this._clearCurrentExecutionLine(); this._updateDebuggerButtons(); }, _togglePauseOnExceptions: function() { var nextStateMap = {}; var stateEnum = WebInspector.DebuggerModel.PauseOnExceptionsState; nextStateMap[stateEnum.DontPauseOnExceptions] = stateEnum.PauseOnAllExceptions; nextStateMap[stateEnum.PauseOnAllExceptions] = stateEnum.PauseOnUncaughtExceptions; nextStateMap[stateEnum.PauseOnUncaughtExceptions] = stateEnum.DontPauseOnExceptions; WebInspector.settings.pauseOnExceptionStateString.set(nextStateMap[this._pauseOnExceptionButton.state]); }, /** * @param {Event=} event * @return {boolean} */ _runSnippet: function(event) { if (this._currentUISourceCode.project().type() !== WebInspector.projectTypes.Snippets) return false; WebInspector.scriptSnippetModel.evaluateScriptSnippet(this._currentUISourceCode); return true; }, /** * @param {Event=} event * @return {boolean} */ _togglePause: function(event) { if (this._paused) { delete this._skipExecutionLineRevealing; this._paused = false; this._waitingToPause = false; DebuggerAgent.resume(); } else { this._stepping = false; this._waitingToPause = true; // Make sure pauses didn't stick skipped. DebuggerAgent.setSkipAllPauses(false); DebuggerAgent.pause(); } this._clearInterface(); return true; }, /** * @param {WebInspector.Event=} event * @return {boolean} */ _longResume: function(event) { if (!this._paused) return true; this._paused = false; this._waitingToPause = false; DebuggerAgent.setSkipAllPauses(true, true); setTimeout(DebuggerAgent.setSkipAllPauses.bind(DebuggerAgent, false), 500); DebuggerAgent.resume(); this._clearInterface(); return true; }, /** * @param {Event=} event * @return {boolean} */ _stepOverClicked: function(event) { if (!this._paused) return true; delete this._skipExecutionLineRevealing; this._paused = false; this._stepping = true; this._clearInterface(); DebuggerAgent.stepOver(); return true; }, /** * @param {Event=} event * @return {boolean} */ _stepIntoClicked: function(event) { if (!this._paused) return true; delete this._skipExecutionLineRevealing; this._paused = false; this._stepping = true; this._clearInterface(); DebuggerAgent.stepInto(); return true; }, /** * @param {Event=} event * @return {boolean} */ _stepIntoSelectionClicked: function(event) { if (!this._paused) return true; if (this._executionSourceFrame) { var stepIntoMarkup = this._executionSourceFrame.stepIntoMarkup(); if (stepIntoMarkup) stepIntoMarkup.iterateSelection(event.shiftKey); } return true; }, doStepIntoSelection: function(rawLocation) { if (!this._paused) return; delete this._skipExecutionLineRevealing; this._paused = false; this._stepping = true; this._clearInterface(); WebInspector.debuggerModel.stepIntoSelection(rawLocation); }, /** * @param {Event=} event * @return {boolean} */ _stepOutClicked: function(event) { if (!this._paused) return true; delete this._skipExecutionLineRevealing; this._paused = false; this._stepping = true; this._clearInterface(); DebuggerAgent.stepOut(); return true; }, /** * @param {WebInspector.Event} event */ _callFrameSelectedInSidebar: function(event) { var callFrame = /** @type {WebInspector.DebuggerModel.CallFrame} */ (event.data); delete this._skipExecutionLineRevealing; WebInspector.debuggerModel.setSelectedCallFrame(callFrame); }, continueToLocation: function(rawLocation) { if (!this._paused) return; delete this._skipExecutionLineRevealing; this._paused = false; this._stepping = true; this._clearInterface(); WebInspector.debuggerModel.continueToLocation(rawLocation); }, _toggleBreakpointsClicked: function(event) { WebInspector.debuggerModel.setBreakpointsActive(!WebInspector.debuggerModel.breakpointsActive()); }, _breakpointsActiveStateChanged: function(event) { var active = event.data; this._toggleBreakpointsButton.toggled = !active; if (active) { this._toggleBreakpointsButton.title = WebInspector.UIString("Deactivate breakpoints."); WebInspector.inspectorView.element.removeStyleClass("breakpoints-deactivated"); this.sidebarPanes.jsBreakpoints.listElement.removeStyleClass("breakpoints-list-deactivated"); } else { this._toggleBreakpointsButton.title = WebInspector.UIString("Activate breakpoints."); WebInspector.inspectorView.element.addStyleClass("breakpoints-deactivated"); this.sidebarPanes.jsBreakpoints.listElement.addStyleClass("breakpoints-list-deactivated"); } }, _createDebugToolbar: function() { var debugToolbar = document.createElement("div"); debugToolbar.className = "status-bar"; debugToolbar.id = "scripts-debug-toolbar"; var title, handler; var platformSpecificModifier = WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta; // Run snippet. title = WebInspector.UIString("Run snippet (%s)."); handler = this._runSnippet.bind(this); this._runSnippetButton = this._createButtonAndRegisterShortcuts("scripts-run-snippet", title, handler, WebInspector.ScriptsPanelDescriptor.ShortcutKeys.RunSnippet); debugToolbar.appendChild(this._runSnippetButton.element); this._runSnippetButton.element.addStyleClass("hidden"); // Continue. handler = this._togglePause.bind(this); this._pauseButton = this._createButtonAndRegisterShortcuts("scripts-pause", "", handler, WebInspector.ScriptsPanelDescriptor.ShortcutKeys.PauseContinue); debugToolbar.appendChild(this._pauseButton.element); // Long resume. title = WebInspector.UIString("Resume with all pauses blocked for 500 ms"); this._longResumeButton = new WebInspector.StatusBarButton(title, "scripts-long-resume"); this._longResumeButton.addEventListener("click", this._longResume.bind(this), this); // Step over. title = WebInspector.UIString("Step over next function call (%s)."); handler = this._stepOverClicked.bind(this); this._stepOverButton = this._createButtonAndRegisterShortcuts("scripts-step-over", title, handler, WebInspector.ScriptsPanelDescriptor.ShortcutKeys.StepOver); debugToolbar.appendChild(this._stepOverButton.element); // Step into. title = WebInspector.UIString("Step into next function call (%s)."); handler = this._stepIntoClicked.bind(this); this._stepIntoButton = this._createButtonAndRegisterShortcuts("scripts-step-into", title, handler, WebInspector.ScriptsPanelDescriptor.ShortcutKeys.StepInto); debugToolbar.appendChild(this._stepIntoButton.element); // Step into selection (keyboard shortcut only). this.registerShortcuts(WebInspector.ScriptsPanelDescriptor.ShortcutKeys.StepIntoSelection, this._stepIntoSelectionClicked.bind(this)) // Step out. title = WebInspector.UIString("Step out of current function (%s)."); handler = this._stepOutClicked.bind(this); this._stepOutButton = this._createButtonAndRegisterShortcuts("scripts-step-out", title, handler, WebInspector.ScriptsPanelDescriptor.ShortcutKeys.StepOut); debugToolbar.appendChild(this._stepOutButton.element); this._toggleBreakpointsButton = new WebInspector.StatusBarButton(WebInspector.UIString("Deactivate breakpoints."), "scripts-toggle-breakpoints"); this._toggleBreakpointsButton.toggled = false; this._toggleBreakpointsButton.addEventListener("click", this._toggleBreakpointsClicked, this); debugToolbar.appendChild(this._toggleBreakpointsButton.element); this.debuggerStatusElement = document.createElement("div"); this.debuggerStatusElement.id = "scripts-debugger-status"; debugToolbar.appendChild(this.debuggerStatusElement); return debugToolbar; }, /** * @param {WebInspector.StatusBarButton} button * @param {string} buttonTitle */ _updateButtonTitle: function(button, buttonTitle) { var hasShortcuts = button.shortcuts && button.shortcuts.length; if (hasShortcuts) button.title = String.vsprintf(buttonTitle, [button.shortcuts[0].name]); else button.title = buttonTitle; }, /** * @param {string} buttonId * @param {string} buttonTitle * @param {function(Event=):boolean} handler * @param {!Array.<!WebInspector.KeyboardShortcut.Descriptor>} shortcuts * @return {WebInspector.StatusBarButton} */ _createButtonAndRegisterShortcuts: function(buttonId, buttonTitle, handler, shortcuts) { var button = new WebInspector.StatusBarButton(buttonTitle, buttonId); button.element.addEventListener("click", handler, false); button.shortcuts = shortcuts; this._updateButtonTitle(button, buttonTitle); this.registerShortcuts(shortcuts, handler); return button; }, searchCanceled: function() { if (this._searchView) this._searchView.searchCanceled(); delete this._searchView; delete this._searchQuery; }, /** * @param {string} query * @param {boolean} shouldJump */ performSearch: function(query, shouldJump) { WebInspector.searchController.updateSearchMatchesCount(0, this); if (!this.visibleView) return; this._searchView = this.visibleView; this._searchQuery = query; function finishedCallback(view, searchMatches) { if (!searchMatches) return; WebInspector.searchController.updateSearchMatchesCount(searchMatches, this); } function currentMatchChanged(currentMatchIndex) { WebInspector.searchController.updateCurrentMatchIndex(currentMatchIndex, this); } this._searchView.performSearch(query, shouldJump, finishedCallback.bind(this), currentMatchChanged.bind(this)); }, /** * @return {number} */ minimalSearchQuerySize: function() { return 0; }, jumpToNextSearchResult: function() { if (!this._searchView) return; if (this._searchView !== this.visibleView) { this.performSearch(this._searchQuery, true); return; } this._searchView.jumpToNextSearchResult(); return true; }, jumpToPreviousSearchResult: function() { if (!this._searchView) return; if (this._searchView !== this.visibleView) { this.performSearch(this._searchQuery, true); if (this._searchView) this._searchView.jumpToLastSearchResult(); return; } this._searchView.jumpToPreviousSearchResult(); }, /** * @return {boolean} */ canSearchAndReplace: function() { var view = /** @type {WebInspector.SourceFrame} */ (this.visibleView); return !!view && view.canEditSource(); }, /** * @param {string} text */ replaceSelectionWith: function(text) { var view = /** @type {WebInspector.SourceFrame} */ (this.visibleView); view.replaceSearchMatchWith(text); }, /** * @param {string} query * @param {string} text */ replaceAllWith: function(query, text) { var view = /** @type {WebInspector.SourceFrame} */ (this.visibleView); view.replaceAllWith(query, text); }, _onKeyDown: function(event) { if (event.keyCode !== WebInspector.KeyboardShortcut.Keys.CtrlOrMeta.code) return; if (!this._paused || !this._executionSourceFrame) return; var stepIntoMarkup = this._executionSourceFrame.stepIntoMarkup(); if (stepIntoMarkup) stepIntoMarkup.startIteratingSelection(); }, _onKeyUp: function(event) { if (event.keyCode !== WebInspector.KeyboardShortcut.Keys.CtrlOrMeta.code) return; if (!this._paused || !this._executionSourceFrame) return; var stepIntoMarkup = this._executionSourceFrame.stepIntoMarkup(); if (!stepIntoMarkup) return; var currentPosition = stepIntoMarkup.getSelectedItemIndex(); if (typeof currentPosition === "undefined") { stepIntoMarkup.stopIteratingSelection(); } else { var rawLocation = stepIntoMarkup.getRawPosition(currentPosition); this.doStepIntoSelection(rawLocation); } }, _toggleFormatSource: function() { delete this._skipExecutionLineRevealing; this._toggleFormatSourceButton.toggled = !this._toggleFormatSourceButton.toggled; var uiSourceCodes = this._workspace.uiSourceCodes(); for (var i = 0; i < uiSourceCodes.length; ++i) uiSourceCodes[i].setFormatted(this._toggleFormatSourceButton.toggled); var currentFile = this._editorContainer.currentFile(); WebInspector.notifications.dispatchEventToListeners(WebInspector.UserMetrics.UserAction, { action: WebInspector.UserMetrics.UserActionNames.TogglePrettyPrint, enabled: this._toggleFormatSourceButton.toggled, url: currentFile ? currentFile.originURL() : null }); }, addToWatch: function(expression) { this.sidebarPanes.watchExpressions.addExpression(expression); }, /** * @return {boolean} */ _toggleBreakpoint: function() { var sourceFrame = this.visibleView; if (!sourceFrame) return false; if (sourceFrame instanceof WebInspector.JavaScriptSourceFrame) { var javaScriptSourceFrame = /** @type {WebInspector.JavaScriptSourceFrame} */ (sourceFrame); javaScriptSourceFrame.toggleBreakpointOnCurrentLine(); return true; } return false; }, /** * @param {Event=} event * @return {boolean} */ _showOutlineDialog: function(event) { var uiSourceCode = this._editorContainer.currentFile(); if (!uiSourceCode) return false; switch (uiSourceCode.contentType()) { case WebInspector.resourceTypes.Document: case WebInspector.resourceTypes.Script: WebInspector.JavaScriptOutlineDialog.show(this.visibleView, uiSourceCode); return true; case WebInspector.resourceTypes.Stylesheet: WebInspector.StyleSheetOutlineDialog.show(this.visibleView, uiSourceCode); return true; } return false; }, _installDebuggerSidebarController: function() { this._toggleDebuggerSidebarButton = new WebInspector.StatusBarButton("", "right-sidebar-show-hide-button scripts-debugger-show-hide-button", 3); this._toggleDebuggerSidebarButton.addEventListener("click", clickHandler, this); this.editorView.element.appendChild(this._toggleDebuggerSidebarButton.element); this._enableDebuggerSidebar(!WebInspector.settings.debuggerSidebarHidden.get()); function clickHandler() { this._enableDebuggerSidebar(this._toggleDebuggerSidebarButton.state === "left"); } }, /** * @param {boolean} show */ _enableDebuggerSidebar: function(show) { this._toggleDebuggerSidebarButton.state = show ? "right" : "left"; this._toggleDebuggerSidebarButton.title = show ? WebInspector.UIString("Hide debugger") : WebInspector.UIString("Show debugger"); if (show) this.splitView.showSidebarElement(); else this.splitView.hideSidebarElement(); this._debugSidebarResizeWidgetElement.enableStyleClass("hidden", !show); WebInspector.settings.debuggerSidebarHidden.set(!show); }, /** * @param {WebInspector.Event} event */ _itemCreationRequested: function(event) { var project = event.data.project; var path = event.data.path; var filePath; var shouldHideNavigator; var uiSourceCode; project.createFile(path, null, fileCreated.bind(this)); /** * @param {?string} path */ function fileCreated(path) { if (!path) return; filePath = path; uiSourceCode = project.uiSourceCode(filePath); this._showSourceLocation(uiSourceCode); shouldHideNavigator = !this._navigatorController.isNavigatorPinned(); if (this._navigatorController.isNavigatorHidden()) this._navigatorController.showNavigatorOverlay(); this._navigator.rename(uiSourceCode, callback.bind(this)); } /** * @param {boolean} committed */ function callback(committed) { if (shouldHideNavigator) this._navigatorController.hideNavigatorOverlay(); if (!committed) { project.deleteFile(uiSourceCode); return; } this._showSourceLocation(uiSourceCode); } }, /** * @param {WebInspector.Event} event */ _itemRenamingRequested: function(event) { var uiSourceCode = /** @type {WebInspector.UISourceCode} */ (event.data); var shouldHideNavigator = !this._navigatorController.isNavigatorPinned(); if (this._navigatorController.isNavigatorHidden()) this._navigatorController.showNavigatorOverlay(); this._navigator.rename(uiSourceCode, callback.bind(this)); /** * @param {boolean} committed */ function callback(committed) { if (shouldHideNavigator && committed) { this._navigatorController.hideNavigatorOverlay(); this._showSourceLocation(uiSourceCode); } } }, /** * @param {WebInspector.UISourceCode} uiSourceCode */ _showLocalHistory: function(uiSourceCode) { WebInspector.RevisionHistoryView.showHistory(uiSourceCode); }, /** * @param {WebInspector.ContextMenu} contextMenu * @param {Object} target */ appendApplicableItems: function(event, contextMenu, target) { this._appendUISourceCodeItems(contextMenu, target); this._appendFunctionItems(contextMenu, target); }, /** * @param {WebInspector.UISourceCode} uiSourceCode */ _mapFileSystemToNetwork: function(uiSourceCode) { WebInspector.SelectUISourceCodeForProjectTypeDialog.show(uiSourceCode.name(), WebInspector.projectTypes.Network, mapFileSystemToNetwork.bind(this), this.editorView.mainElement) /** * @param {WebInspector.UISourceCode} networkUISourceCode */ function mapFileSystemToNetwork(networkUISourceCode) { this._workspace.addMapping(networkUISourceCode, uiSourceCode, WebInspector.fileSystemWorkspaceProvider); } }, /** * @param {WebInspector.UISourceCode} uiSourceCode */ _removeNetworkMapping: function(uiSourceCode) { if (confirm(WebInspector.UIString("Are you sure you want to remove network mapping?"))) this._workspace.removeMapping(uiSourceCode); }, /** * @param {WebInspector.UISourceCode} networkUISourceCode */ _mapNetworkToFileSystem: function(networkUISourceCode) { WebInspector.SelectUISourceCodeForProjectTypeDialog.show(networkUISourceCode.name(), WebInspector.projectTypes.FileSystem, mapNetworkToFileSystem.bind(this), this.editorView.mainElement) /** * @param {WebInspector.UISourceCode} uiSourceCode */ function mapNetworkToFileSystem(uiSourceCode) { this._workspace.addMapping(networkUISourceCode, uiSourceCode, WebInspector.fileSystemWorkspaceProvider); } }, /** * @param {WebInspector.ContextMenu} contextMenu * @param {WebInspector.UISourceCode} uiSourceCode */ _appendUISourceCodeMappingItems: function(contextMenu, uiSourceCode) { if (uiSourceCode.project().type() === WebInspector.projectTypes.FileSystem) { var hasMappings = !!uiSourceCode.url; if (!hasMappings) contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Map to network resource\u2026" : "Map to Network Resource\u2026"), this._mapFileSystemToNetwork.bind(this, uiSourceCode)); else contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Remove network mapping" : "Remove Network Mapping"), this._removeNetworkMapping.bind(this, uiSourceCode)); } if (uiSourceCode.project().type() === WebInspector.projectTypes.Network) { /** * @param {WebInspector.Project} project */ function filterProject(project) { return project.type() === WebInspector.projectTypes.FileSystem; } if (!this._workspace.projects().filter(filterProject).length) return; if (this._workspace.uiSourceCodeForURL(uiSourceCode.url) === uiSourceCode) contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Map to file system resource\u2026" : "Map to File System Resource\u2026"), this._mapNetworkToFileSystem.bind(this, uiSourceCode)); } }, /** * @param {WebInspector.ContextMenu} contextMenu * @param {Object} target */ _appendUISourceCodeItems: function(contextMenu, target) { if (!(target instanceof WebInspector.UISourceCode)) return; var uiSourceCode = /** @type {WebInspector.UISourceCode} */ (target); contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Local modifications\u2026" : "Local Modifications\u2026"), this._showLocalHistory.bind(this, uiSourceCode)); if (WebInspector.isolatedFileSystemManager.supportsFileSystems()) this._appendUISourceCodeMappingItems(contextMenu, uiSourceCode); }, /** * @param {WebInspector.ContextMenu} contextMenu * @param {Object} target */ _appendFunctionItems: function(contextMenu, target) { if (!(target instanceof WebInspector.RemoteObject)) return; var remoteObject = /** @type {WebInspector.RemoteObject} */ (target); if (remoteObject.type !== "function") return; function didGetDetails(error, response) { if (error) { console.error(error); return; } WebInspector.inspectorView.setCurrentPanel(this); var uiLocation = WebInspector.debuggerModel.rawLocationToUILocation(response.location); this._showSourceLocation(uiLocation.uiSourceCode, uiLocation.lineNumber, uiLocation.columnNumber); } function revealFunction() { DebuggerAgent.getFunctionDetails(remoteObject.objectId, didGetDetails.bind(this)); } contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Show function definition" : "Show Function Definition"), revealFunction.bind(this)); }, showGoToSourceDialog: function() { var uiSourceCodes = this._editorContainer.historyUISourceCodes(); /** @type {!Map.<WebInspector.UISourceCode, number>} */ var defaultScores = new Map(); for (var i = 1; i < uiSourceCodes.length; ++i) // Skip current element defaultScores.put(uiSourceCodes[i], uiSourceCodes.length - i); WebInspector.OpenResourceDialog.show(this, this.editorView.mainElement, undefined, defaultScores); }, _dockSideChanged: function() { var dockSide = WebInspector.dockController.dockSide(); var vertically = dockSide === WebInspector.DockController.State.DockedToRight && WebInspector.settings.splitVerticallyWhenDockedToRight.get(); this._splitVertically(vertically); }, /** * @param {boolean} vertically */ _splitVertically: function(vertically) { if (this.sidebarPaneView && vertically === !this.splitView.isVertical()) return; if (this.sidebarPaneView) this.sidebarPaneView.detach(); this.splitView.setVertical(!vertically); if (!vertically) { this.sidebarPaneView = new WebInspector.SidebarPaneStack(); for (var pane in this.sidebarPanes) this.sidebarPaneView.addPane(this.sidebarPanes[pane]); this.sidebarElement.appendChild(this.debugToolbar); } else { this._enableDebuggerSidebar(true); this.sidebarPaneView = new WebInspector.SplitView(true, this.name + "PanelSplitSidebarRatio", 0.5); var group1 = new WebInspector.SidebarPaneStack(); group1.show(this.sidebarPaneView.firstElement()); group1.element.id = "scripts-sidebar-stack-pane"; group1.addPane(this.sidebarPanes.callstack); group1.addPane(this.sidebarPanes.jsBreakpoints); group1.addPane(this.sidebarPanes.domBreakpoints); group1.addPane(this.sidebarPanes.xhrBreakpoints); group1.addPane(this.sidebarPanes.eventListenerBreakpoints); if (this.sidebarPanes.workerList) group1.addPane(this.sidebarPanes.workerList); var group2 = new WebInspector.SidebarTabbedPane(); group2.show(this.sidebarPaneView.secondElement()); group2.addPane(this.sidebarPanes.scopechain); group2.addPane(this.sidebarPanes.watchExpressions); this.sidebarPaneView.firstElement().appendChild(this.debugToolbar); } this.sidebarPaneView.element.id = "scripts-debug-sidebar-contents"; this.sidebarPaneView.show(this.splitView.sidebarElement); this.sidebarPanes.scopechain.expand(); this.sidebarPanes.jsBreakpoints.expand(); this.sidebarPanes.callstack.expand(); if (WebInspector.settings.watchExpressions.get().length > 0) this.sidebarPanes.watchExpressions.expand(); }, /** * @return {boolean} */ canSetFooterElement: function() { return true; }, /** * @param {Element?} element */ setFooterElement: function(element) { if (element) { this._editorFooterElement.removeStyleClass("hidden"); this._editorFooterElement.appendChild(element); this._editorContentsElement.style.bottom = this._editorFooterElement.offsetHeight + "px"; } else { this._editorFooterElement.addStyleClass("hidden"); this._editorFooterElement.removeChildren(); this._editorContentsElement.style.bottom = 0; } this.doResize(); }, __proto__: WebInspector.Panel.prototype }
WAPMADRID/server
wapmadrid/node_modules/grunt-node-inspector/node_modules/node-inspector/front-end/ScriptsPanel.js
JavaScript
gpl-2.0
57,906
<?php namespace GuzzleHttp\Tests\Psr7; use GuzzleHttp\Psr7; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Uri; /** * @covers GuzzleHttp\Psr7\Request */ class RequestTest extends \PHPUnit_Framework_TestCase { public function testRequestUriMayBeString() { $r = new Request('GET', '/'); $this->assertEquals('/', (string) $r->getUri()); } public function testRequestUriMayBeUri() { $uri = new Uri('/'); $r = new Request('GET', $uri); $this->assertSame($uri, $r->getUri()); } /** * @expectedException \InvalidArgumentException */ public function testValidateRequestUri() { new Request('GET', '///'); } public function testCanConstructWithBody() { $r = new Request('GET', '/', [], 'baz'); $this->assertInstanceOf('Psr\Http\Message\StreamInterface', $r->getBody()); $this->assertEquals('baz', (string) $r->getBody()); } public function testNullBody() { $r = new Request('GET', '/', [], null); $this->assertInstanceOf('Psr\Http\Message\StreamInterface', $r->getBody()); $this->assertSame('', (string) $r->getBody()); } public function testFalseyBody() { $r = new Request('GET', '/', [], '0'); $this->assertInstanceOf('Psr\Http\Message\StreamInterface', $r->getBody()); $this->assertSame('0', (string) $r->getBody()); } public function testConstructorDoesNotReadStreamBody() { $streamIsRead = false; $body = Psr7\FnStream::decorate(Psr7\stream_for(''), [ '__toString' => function () use (&$streamIsRead) { $streamIsRead = true; return ''; } ]); $r = new Request('GET', '/', [], $body); $this->assertFalse($streamIsRead); $this->assertSame($body, $r->getBody()); } public function testCapitalizesMethod() { $r = new Request('get', '/'); $this->assertEquals('GET', $r->getMethod()); } public function testCapitalizesWithMethod() { $r = new Request('GET', '/'); $this->assertEquals('PUT', $r->withMethod('put')->getMethod()); } public function testWithUri() { $r1 = new Request('GET', '/'); $u1 = $r1->getUri(); $u2 = new Uri('http://www.example.com'); $r2 = $r1->withUri($u2); $this->assertNotSame($r1, $r2); $this->assertSame($u2, $r2->getUri()); $this->assertSame($u1, $r1->getUri()); } public function testSameInstanceWhenSameUri() { $r1 = new Request('GET', 'http://foo.com'); $r2 = $r1->withUri($r1->getUri()); $this->assertSame($r1, $r2); } public function testWithRequestTarget() { $r1 = new Request('GET', '/'); $r2 = $r1->withRequestTarget('*'); $this->assertEquals('*', $r2->getRequestTarget()); $this->assertEquals('/', $r1->getRequestTarget()); } /** * @expectedException \InvalidArgumentException */ public function testRequestTargetDoesNotAllowSpaces() { $r1 = new Request('GET', '/'); $r1->withRequestTarget('/foo bar'); } public function testRequestTargetDefaultsToSlash() { $r1 = new Request('GET', ''); $this->assertEquals('/', $r1->getRequestTarget()); $r2 = new Request('GET', '*'); $this->assertEquals('*', $r2->getRequestTarget()); $r3 = new Request('GET', 'http://foo.com/bar baz/'); $this->assertEquals('/bar%20baz/', $r3->getRequestTarget()); } public function testBuildsRequestTarget() { $r1 = new Request('GET', 'http://foo.com/baz?bar=bam'); $this->assertEquals('/baz?bar=bam', $r1->getRequestTarget()); } public function testBuildsRequestTargetWithFalseyQuery() { $r1 = new Request('GET', 'http://foo.com/baz?0'); $this->assertEquals('/baz?0', $r1->getRequestTarget()); } public function testHostIsAddedFirst() { $r = new Request('GET', 'http://foo.com/baz?bar=bam', ['Foo' => 'Bar']); $this->assertEquals([ 'Host' => ['foo.com'], 'Foo' => ['Bar'] ], $r->getHeaders()); } public function testCanGetHeaderAsCsv() { $r = new Request('GET', 'http://foo.com/baz?bar=bam', [ 'Foo' => ['a', 'b', 'c'] ]); $this->assertEquals('a, b, c', $r->getHeaderLine('Foo')); $this->assertEquals('', $r->getHeaderLine('Bar')); } public function testHostIsNotOverwrittenWhenPreservingHost() { $r = new Request('GET', 'http://foo.com/baz?bar=bam', ['Host' => 'a.com']); $this->assertEquals(['Host' => ['a.com']], $r->getHeaders()); $r2 = $r->withUri(new Uri('http://www.foo.com/bar'), true); $this->assertEquals('a.com', $r2->getHeaderLine('Host')); } public function testOverridesHostWithUri() { $r = new Request('GET', 'http://foo.com/baz?bar=bam'); $this->assertEquals(['Host' => ['foo.com']], $r->getHeaders()); $r2 = $r->withUri(new Uri('http://www.baz.com/bar')); $this->assertEquals('www.baz.com', $r2->getHeaderLine('Host')); } public function testAggregatesHeaders() { $r = new Request('GET', '', [ 'ZOO' => 'zoobar', 'zoo' => ['foobar', 'zoobar'] ]); $this->assertEquals(['ZOO' => ['zoobar', 'foobar', 'zoobar']], $r->getHeaders()); $this->assertEquals('zoobar, foobar, zoobar', $r->getHeaderLine('zoo')); } public function testAddsPortToHeader() { $r = new Request('GET', 'http://foo.com:8124/bar'); $this->assertEquals('foo.com:8124', $r->getHeaderLine('host')); } public function testAddsPortToHeaderAndReplacePreviousPort() { $r = new Request('GET', 'http://foo.com:8124/bar'); $r = $r->withUri(new Uri('http://foo.com:8125/bar')); $this->assertEquals('foo.com:8125', $r->getHeaderLine('host')); } }
yeqingwen/Yii2_PHP7_Redis
yii2/vendor/guzzlehttp/psr7/tests/RequestTest.php
PHP
apache-2.0
6,062
/******************************************************************* * This file is part of the Emulex Linux Device Driver for * * Fibre Channel Host Bus Adapters. * * Copyright (C) 2017-2019 Broadcom. All Rights Reserved. The term * * “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. * * Copyright (C) 2004-2016 Emulex. All rights reserved. * * EMULEX and SLI are trademarks of Emulex. * * www.broadcom.com * * Portions Copyright (C) 2004-2005 Christoph Hellwig * * * * This program is free software; you can redistribute it and/or * * modify it under the terms of version 2 of the GNU General * * Public License as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful. * * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE * * DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD * * TO BE LEGALLY INVALID. See the GNU General Public License for * * more details, a copy of which can be found in the file COPYING * * included with this package. * ********************************************************************/ #define LPFC_NVME_DEFAULT_SEGS (64 + 1) /* 256K IOs */ #define LPFC_NVME_ERSP_LEN 0x20 #define LPFC_NVME_WAIT_TMO 10 #define LPFC_NVME_EXPEDITE_XRICNT 8 #define LPFC_NVME_FB_SHIFT 9 #define LPFC_NVME_MAX_FB (1 << 20) /* 1M */ #define LPFC_MAX_NVME_INFO_TMP_LEN 100 #define LPFC_NVME_INFO_MORE_STR "\nCould be more info...\n" #define lpfc_ndlp_get_nrport(ndlp) \ ((!ndlp->nrport || (ndlp->upcall_flags & NLP_WAIT_FOR_UNREG)) \ ? NULL : ndlp->nrport) struct lpfc_nvme_qhandle { uint32_t index; /* WQ index to use */ uint32_t qidx; /* queue index passed to create */ uint32_t cpu_id; /* current cpu id at time of create */ }; /* Declare nvme-based local and remote port definitions. */ struct lpfc_nvme_lport { struct lpfc_vport *vport; struct completion *lport_unreg_cmp; /* Add stats counters here */ atomic_t fc4NvmeLsRequests; atomic_t fc4NvmeLsCmpls; atomic_t xmt_fcp_noxri; atomic_t xmt_fcp_bad_ndlp; atomic_t xmt_fcp_qdepth; atomic_t xmt_fcp_wqerr; atomic_t xmt_fcp_err; atomic_t xmt_fcp_abort; atomic_t xmt_ls_abort; atomic_t xmt_ls_err; atomic_t cmpl_fcp_xb; atomic_t cmpl_fcp_err; atomic_t cmpl_ls_xb; atomic_t cmpl_ls_err; }; struct lpfc_nvme_rport { struct lpfc_nvme_lport *lport; struct nvme_fc_remote_port *remoteport; struct lpfc_nodelist *ndlp; struct completion rport_unreg_done; }; struct lpfc_nvme_fcpreq_priv { struct lpfc_io_buf *nvme_buf; };
BPI-SINOVOIP/BPI-Mainline-kernel
linux-5.4/drivers/scsi/lpfc/lpfc_nvme.h
C
gpl-2.0
2,942
ccflags-y += -I$(srctree) obj-y += mt_storage_logger.o
zhengdejin/X1_Code
kernel-3.10/drivers/misc/mediatek/mt_logger/Makefile
Makefile
apache-2.0
58
// // push_app_define.h // my_push_server // // Created by luoning on 14-11-12. // Copyright (c) 2014年 luoning. All rights reserved. // #ifndef my_push_server_push_app_define_h #define my_push_server_push_app_define_h #endif
wendysuly/TeamTalk
server/src/push_server/push_app_define.h
C
apache-2.0
235
/* * Copyright 2013 Google Inc. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SkPdfFileAttachmentAnnotationDictionary_DEFINED #define SkPdfFileAttachmentAnnotationDictionary_DEFINED #include "SkPdfDictionary_autogen.h" // Additional entries specific to a file attachment annotation class SkPdfFileAttachmentAnnotationDictionary : public SkPdfDictionary { public: public: SkPdfFileAttachmentAnnotationDictionary* asFileAttachmentAnnotationDictionary() {return this;} const SkPdfFileAttachmentAnnotationDictionary* asFileAttachmentAnnotationDictionary() const {return this;} private: SkPdfALinkAnnotationDictionary* asALinkAnnotationDictionary() {return (SkPdfALinkAnnotationDictionary*)this;} const SkPdfALinkAnnotationDictionary* asALinkAnnotationDictionary() const {return (const SkPdfALinkAnnotationDictionary*)this;} SkPdfActionDictionary* asActionDictionary() {return (SkPdfActionDictionary*)this;} const SkPdfActionDictionary* asActionDictionary() const {return (const SkPdfActionDictionary*)this;} SkPdfAlternateImageDictionary* asAlternateImageDictionary() {return (SkPdfAlternateImageDictionary*)this;} const SkPdfAlternateImageDictionary* asAlternateImageDictionary() const {return (const SkPdfAlternateImageDictionary*)this;} SkPdfAnnotationActionsDictionary* asAnnotationActionsDictionary() {return (SkPdfAnnotationActionsDictionary*)this;} const SkPdfAnnotationActionsDictionary* asAnnotationActionsDictionary() const {return (const SkPdfAnnotationActionsDictionary*)this;} SkPdfAnnotationDictionary* asAnnotationDictionary() {return (SkPdfAnnotationDictionary*)this;} const SkPdfAnnotationDictionary* asAnnotationDictionary() const {return (const SkPdfAnnotationDictionary*)this;} SkPdfAppearanceCharacteristicsDictionary* asAppearanceCharacteristicsDictionary() {return (SkPdfAppearanceCharacteristicsDictionary*)this;} const SkPdfAppearanceCharacteristicsDictionary* asAppearanceCharacteristicsDictionary() const {return (const SkPdfAppearanceCharacteristicsDictionary*)this;} SkPdfAppearanceDictionary* asAppearanceDictionary() {return (SkPdfAppearanceDictionary*)this;} const SkPdfAppearanceDictionary* asAppearanceDictionary() const {return (const SkPdfAppearanceDictionary*)this;} SkPdfApplicationDataDictionary* asApplicationDataDictionary() {return (SkPdfApplicationDataDictionary*)this;} const SkPdfApplicationDataDictionary* asApplicationDataDictionary() const {return (const SkPdfApplicationDataDictionary*)this;} SkPdfArtifactsDictionary* asArtifactsDictionary() {return (SkPdfArtifactsDictionary*)this;} const SkPdfArtifactsDictionary* asArtifactsDictionary() const {return (const SkPdfArtifactsDictionary*)this;} SkPdfAttributeObjectDictionary* asAttributeObjectDictionary() {return (SkPdfAttributeObjectDictionary*)this;} const SkPdfAttributeObjectDictionary* asAttributeObjectDictionary() const {return (const SkPdfAttributeObjectDictionary*)this;} SkPdfBeadDictionary* asBeadDictionary() {return (SkPdfBeadDictionary*)this;} const SkPdfBeadDictionary* asBeadDictionary() const {return (const SkPdfBeadDictionary*)this;} SkPdfBlockLevelStructureElementsDictionary* asBlockLevelStructureElementsDictionary() {return (SkPdfBlockLevelStructureElementsDictionary*)this;} const SkPdfBlockLevelStructureElementsDictionary* asBlockLevelStructureElementsDictionary() const {return (const SkPdfBlockLevelStructureElementsDictionary*)this;} SkPdfBorderStyleDictionary* asBorderStyleDictionary() {return (SkPdfBorderStyleDictionary*)this;} const SkPdfBorderStyleDictionary* asBorderStyleDictionary() const {return (const SkPdfBorderStyleDictionary*)this;} SkPdfBoxColorInformationDictionary* asBoxColorInformationDictionary() {return (SkPdfBoxColorInformationDictionary*)this;} const SkPdfBoxColorInformationDictionary* asBoxColorInformationDictionary() const {return (const SkPdfBoxColorInformationDictionary*)this;} SkPdfBoxStyleDictionary* asBoxStyleDictionary() {return (SkPdfBoxStyleDictionary*)this;} const SkPdfBoxStyleDictionary* asBoxStyleDictionary() const {return (const SkPdfBoxStyleDictionary*)this;} SkPdfCIDFontDescriptorDictionary* asCIDFontDescriptorDictionary() {return (SkPdfCIDFontDescriptorDictionary*)this;} const SkPdfCIDFontDescriptorDictionary* asCIDFontDescriptorDictionary() const {return (const SkPdfCIDFontDescriptorDictionary*)this;} SkPdfCIDFontDictionary* asCIDFontDictionary() {return (SkPdfCIDFontDictionary*)this;} const SkPdfCIDFontDictionary* asCIDFontDictionary() const {return (const SkPdfCIDFontDictionary*)this;} SkPdfCIDSystemInfoDictionary* asCIDSystemInfoDictionary() {return (SkPdfCIDSystemInfoDictionary*)this;} const SkPdfCIDSystemInfoDictionary* asCIDSystemInfoDictionary() const {return (const SkPdfCIDSystemInfoDictionary*)this;} SkPdfCMapDictionary* asCMapDictionary() {return (SkPdfCMapDictionary*)this;} const SkPdfCMapDictionary* asCMapDictionary() const {return (const SkPdfCMapDictionary*)this;} SkPdfCalgrayColorSpaceDictionary* asCalgrayColorSpaceDictionary() {return (SkPdfCalgrayColorSpaceDictionary*)this;} const SkPdfCalgrayColorSpaceDictionary* asCalgrayColorSpaceDictionary() const {return (const SkPdfCalgrayColorSpaceDictionary*)this;} SkPdfCalrgbColorSpaceDictionary* asCalrgbColorSpaceDictionary() {return (SkPdfCalrgbColorSpaceDictionary*)this;} const SkPdfCalrgbColorSpaceDictionary* asCalrgbColorSpaceDictionary() const {return (const SkPdfCalrgbColorSpaceDictionary*)this;} SkPdfCatalogDictionary* asCatalogDictionary() {return (SkPdfCatalogDictionary*)this;} const SkPdfCatalogDictionary* asCatalogDictionary() const {return (const SkPdfCatalogDictionary*)this;} SkPdfCcittfaxdecodeFilterDictionary* asCcittfaxdecodeFilterDictionary() {return (SkPdfCcittfaxdecodeFilterDictionary*)this;} const SkPdfCcittfaxdecodeFilterDictionary* asCcittfaxdecodeFilterDictionary() const {return (const SkPdfCcittfaxdecodeFilterDictionary*)this;} SkPdfCheckboxFieldDictionary* asCheckboxFieldDictionary() {return (SkPdfCheckboxFieldDictionary*)this;} const SkPdfCheckboxFieldDictionary* asCheckboxFieldDictionary() const {return (const SkPdfCheckboxFieldDictionary*)this;} SkPdfChoiceFieldDictionary* asChoiceFieldDictionary() {return (SkPdfChoiceFieldDictionary*)this;} const SkPdfChoiceFieldDictionary* asChoiceFieldDictionary() const {return (const SkPdfChoiceFieldDictionary*)this;} SkPdfComponentsWithMetadataDictionary* asComponentsWithMetadataDictionary() {return (SkPdfComponentsWithMetadataDictionary*)this;} const SkPdfComponentsWithMetadataDictionary* asComponentsWithMetadataDictionary() const {return (const SkPdfComponentsWithMetadataDictionary*)this;} SkPdfDctdecodeFilterDictionary* asDctdecodeFilterDictionary() {return (SkPdfDctdecodeFilterDictionary*)this;} const SkPdfDctdecodeFilterDictionary* asDctdecodeFilterDictionary() const {return (const SkPdfDctdecodeFilterDictionary*)this;} SkPdfDeviceNColorSpaceDictionary* asDeviceNColorSpaceDictionary() {return (SkPdfDeviceNColorSpaceDictionary*)this;} const SkPdfDeviceNColorSpaceDictionary* asDeviceNColorSpaceDictionary() const {return (const SkPdfDeviceNColorSpaceDictionary*)this;} SkPdfDocumentCatalogActionsDictionary* asDocumentCatalogActionsDictionary() {return (SkPdfDocumentCatalogActionsDictionary*)this;} const SkPdfDocumentCatalogActionsDictionary* asDocumentCatalogActionsDictionary() const {return (const SkPdfDocumentCatalogActionsDictionary*)this;} SkPdfDocumentInformationDictionary* asDocumentInformationDictionary() {return (SkPdfDocumentInformationDictionary*)this;} const SkPdfDocumentInformationDictionary* asDocumentInformationDictionary() const {return (const SkPdfDocumentInformationDictionary*)this;} SkPdfEmbeddedFileParameterDictionary* asEmbeddedFileParameterDictionary() {return (SkPdfEmbeddedFileParameterDictionary*)this;} const SkPdfEmbeddedFileParameterDictionary* asEmbeddedFileParameterDictionary() const {return (const SkPdfEmbeddedFileParameterDictionary*)this;} SkPdfEmbeddedFileStreamDictionary* asEmbeddedFileStreamDictionary() {return (SkPdfEmbeddedFileStreamDictionary*)this;} const SkPdfEmbeddedFileStreamDictionary* asEmbeddedFileStreamDictionary() const {return (const SkPdfEmbeddedFileStreamDictionary*)this;} SkPdfEmbeddedFontStreamDictionary* asEmbeddedFontStreamDictionary() {return (SkPdfEmbeddedFontStreamDictionary*)this;} const SkPdfEmbeddedFontStreamDictionary* asEmbeddedFontStreamDictionary() const {return (const SkPdfEmbeddedFontStreamDictionary*)this;} SkPdfEncodingDictionary* asEncodingDictionary() {return (SkPdfEncodingDictionary*)this;} const SkPdfEncodingDictionary* asEncodingDictionary() const {return (const SkPdfEncodingDictionary*)this;} SkPdfEncryptedEmbeddedFileStreamDictionary* asEncryptedEmbeddedFileStreamDictionary() {return (SkPdfEncryptedEmbeddedFileStreamDictionary*)this;} const SkPdfEncryptedEmbeddedFileStreamDictionary* asEncryptedEmbeddedFileStreamDictionary() const {return (const SkPdfEncryptedEmbeddedFileStreamDictionary*)this;} SkPdfEncryptionCommonDictionary* asEncryptionCommonDictionary() {return (SkPdfEncryptionCommonDictionary*)this;} const SkPdfEncryptionCommonDictionary* asEncryptionCommonDictionary() const {return (const SkPdfEncryptionCommonDictionary*)this;} SkPdfFDFCatalogDictionary* asFDFCatalogDictionary() {return (SkPdfFDFCatalogDictionary*)this;} const SkPdfFDFCatalogDictionary* asFDFCatalogDictionary() const {return (const SkPdfFDFCatalogDictionary*)this;} SkPdfFDFDictionary* asFDFDictionary() {return (SkPdfFDFDictionary*)this;} const SkPdfFDFDictionary* asFDFDictionary() const {return (const SkPdfFDFDictionary*)this;} SkPdfFDFFieldDictionary* asFDFFieldDictionary() {return (SkPdfFDFFieldDictionary*)this;} const SkPdfFDFFieldDictionary* asFDFFieldDictionary() const {return (const SkPdfFDFFieldDictionary*)this;} SkPdfFDFFileAnnotationDictionary* asFDFFileAnnotationDictionary() {return (SkPdfFDFFileAnnotationDictionary*)this;} const SkPdfFDFFileAnnotationDictionary* asFDFFileAnnotationDictionary() const {return (const SkPdfFDFFileAnnotationDictionary*)this;} SkPdfFDFNamedPageReferenceDictionary* asFDFNamedPageReferenceDictionary() {return (SkPdfFDFNamedPageReferenceDictionary*)this;} const SkPdfFDFNamedPageReferenceDictionary* asFDFNamedPageReferenceDictionary() const {return (const SkPdfFDFNamedPageReferenceDictionary*)this;} SkPdfFDFPageDictionary* asFDFPageDictionary() {return (SkPdfFDFPageDictionary*)this;} const SkPdfFDFPageDictionary* asFDFPageDictionary() const {return (const SkPdfFDFPageDictionary*)this;} SkPdfFDFTemplateDictionary* asFDFTemplateDictionary() {return (SkPdfFDFTemplateDictionary*)this;} const SkPdfFDFTemplateDictionary* asFDFTemplateDictionary() const {return (const SkPdfFDFTemplateDictionary*)this;} SkPdfFDFTrailerDictionary* asFDFTrailerDictionary() {return (SkPdfFDFTrailerDictionary*)this;} const SkPdfFDFTrailerDictionary* asFDFTrailerDictionary() const {return (const SkPdfFDFTrailerDictionary*)this;} SkPdfFieldDictionary* asFieldDictionary() {return (SkPdfFieldDictionary*)this;} const SkPdfFieldDictionary* asFieldDictionary() const {return (const SkPdfFieldDictionary*)this;} SkPdfFileSpecificationDictionary* asFileSpecificationDictionary() {return (SkPdfFileSpecificationDictionary*)this;} const SkPdfFileSpecificationDictionary* asFileSpecificationDictionary() const {return (const SkPdfFileSpecificationDictionary*)this;} SkPdfFileTrailerDictionary* asFileTrailerDictionary() {return (SkPdfFileTrailerDictionary*)this;} const SkPdfFileTrailerDictionary* asFileTrailerDictionary() const {return (const SkPdfFileTrailerDictionary*)this;} SkPdfFontDescriptorDictionary* asFontDescriptorDictionary() {return (SkPdfFontDescriptorDictionary*)this;} const SkPdfFontDescriptorDictionary* asFontDescriptorDictionary() const {return (const SkPdfFontDescriptorDictionary*)this;} SkPdfFontDictionary* asFontDictionary() {return (SkPdfFontDictionary*)this;} const SkPdfFontDictionary* asFontDictionary() const {return (const SkPdfFontDictionary*)this;} SkPdfType0FontDictionary* asType0FontDictionary() {return (SkPdfType0FontDictionary*)this;} const SkPdfType0FontDictionary* asType0FontDictionary() const {return (const SkPdfType0FontDictionary*)this;} SkPdfType1FontDictionary* asType1FontDictionary() {return (SkPdfType1FontDictionary*)this;} const SkPdfType1FontDictionary* asType1FontDictionary() const {return (const SkPdfType1FontDictionary*)this;} SkPdfMultiMasterFontDictionary* asMultiMasterFontDictionary() {return (SkPdfMultiMasterFontDictionary*)this;} const SkPdfMultiMasterFontDictionary* asMultiMasterFontDictionary() const {return (const SkPdfMultiMasterFontDictionary*)this;} SkPdfTrueTypeFontDictionary* asTrueTypeFontDictionary() {return (SkPdfTrueTypeFontDictionary*)this;} const SkPdfTrueTypeFontDictionary* asTrueTypeFontDictionary() const {return (const SkPdfTrueTypeFontDictionary*)this;} SkPdfType3FontDictionary* asType3FontDictionary() {return (SkPdfType3FontDictionary*)this;} const SkPdfType3FontDictionary* asType3FontDictionary() const {return (const SkPdfType3FontDictionary*)this;} SkPdfFormFieldActionsDictionary* asFormFieldActionsDictionary() {return (SkPdfFormFieldActionsDictionary*)this;} const SkPdfFormFieldActionsDictionary* asFormFieldActionsDictionary() const {return (const SkPdfFormFieldActionsDictionary*)this;} SkPdfFreeTextAnnotationDictionary* asFreeTextAnnotationDictionary() {return (SkPdfFreeTextAnnotationDictionary*)this;} const SkPdfFreeTextAnnotationDictionary* asFreeTextAnnotationDictionary() const {return (const SkPdfFreeTextAnnotationDictionary*)this;} SkPdfFunctionCommonDictionary* asFunctionCommonDictionary() {return (SkPdfFunctionCommonDictionary*)this;} const SkPdfFunctionCommonDictionary* asFunctionCommonDictionary() const {return (const SkPdfFunctionCommonDictionary*)this;} SkPdfGoToActionDictionary* asGoToActionDictionary() {return (SkPdfGoToActionDictionary*)this;} const SkPdfGoToActionDictionary* asGoToActionDictionary() const {return (const SkPdfGoToActionDictionary*)this;} SkPdfGraphicsStateDictionary* asGraphicsStateDictionary() {return (SkPdfGraphicsStateDictionary*)this;} const SkPdfGraphicsStateDictionary* asGraphicsStateDictionary() const {return (const SkPdfGraphicsStateDictionary*)this;} SkPdfGroupAttributesDictionary* asGroupAttributesDictionary() {return (SkPdfGroupAttributesDictionary*)this;} const SkPdfGroupAttributesDictionary* asGroupAttributesDictionary() const {return (const SkPdfGroupAttributesDictionary*)this;} SkPdfHideActionDictionary* asHideActionDictionary() {return (SkPdfHideActionDictionary*)this;} const SkPdfHideActionDictionary* asHideActionDictionary() const {return (const SkPdfHideActionDictionary*)this;} SkPdfIccProfileStreamDictionary* asIccProfileStreamDictionary() {return (SkPdfIccProfileStreamDictionary*)this;} const SkPdfIccProfileStreamDictionary* asIccProfileStreamDictionary() const {return (const SkPdfIccProfileStreamDictionary*)this;} SkPdfIconFitDictionary* asIconFitDictionary() {return (SkPdfIconFitDictionary*)this;} const SkPdfIconFitDictionary* asIconFitDictionary() const {return (const SkPdfIconFitDictionary*)this;} SkPdfImportDataActionDictionary* asImportDataActionDictionary() {return (SkPdfImportDataActionDictionary*)this;} const SkPdfImportDataActionDictionary* asImportDataActionDictionary() const {return (const SkPdfImportDataActionDictionary*)this;} SkPdfInkAnnotationDictionary* asInkAnnotationDictionary() {return (SkPdfInkAnnotationDictionary*)this;} const SkPdfInkAnnotationDictionary* asInkAnnotationDictionary() const {return (const SkPdfInkAnnotationDictionary*)this;} SkPdfInlineLevelStructureElementsDictionary* asInlineLevelStructureElementsDictionary() {return (SkPdfInlineLevelStructureElementsDictionary*)this;} const SkPdfInlineLevelStructureElementsDictionary* asInlineLevelStructureElementsDictionary() const {return (const SkPdfInlineLevelStructureElementsDictionary*)this;} SkPdfInteractiveFormDictionary* asInteractiveFormDictionary() {return (SkPdfInteractiveFormDictionary*)this;} const SkPdfInteractiveFormDictionary* asInteractiveFormDictionary() const {return (const SkPdfInteractiveFormDictionary*)this;} SkPdfJavascriptActionDictionary* asJavascriptActionDictionary() {return (SkPdfJavascriptActionDictionary*)this;} const SkPdfJavascriptActionDictionary* asJavascriptActionDictionary() const {return (const SkPdfJavascriptActionDictionary*)this;} SkPdfJavascriptDictionary* asJavascriptDictionary() {return (SkPdfJavascriptDictionary*)this;} const SkPdfJavascriptDictionary* asJavascriptDictionary() const {return (const SkPdfJavascriptDictionary*)this;} SkPdfJbig2DecodeFilterDictionary* asJbig2DecodeFilterDictionary() {return (SkPdfJbig2DecodeFilterDictionary*)this;} const SkPdfJbig2DecodeFilterDictionary* asJbig2DecodeFilterDictionary() const {return (const SkPdfJbig2DecodeFilterDictionary*)this;} SkPdfLabColorSpaceDictionary* asLabColorSpaceDictionary() {return (SkPdfLabColorSpaceDictionary*)this;} const SkPdfLabColorSpaceDictionary* asLabColorSpaceDictionary() const {return (const SkPdfLabColorSpaceDictionary*)this;} SkPdfLaunchActionDictionary* asLaunchActionDictionary() {return (SkPdfLaunchActionDictionary*)this;} const SkPdfLaunchActionDictionary* asLaunchActionDictionary() const {return (const SkPdfLaunchActionDictionary*)this;} SkPdfLineAnnotationDictionary* asLineAnnotationDictionary() {return (SkPdfLineAnnotationDictionary*)this;} const SkPdfLineAnnotationDictionary* asLineAnnotationDictionary() const {return (const SkPdfLineAnnotationDictionary*)this;} SkPdfListAttributeDictionary* asListAttributeDictionary() {return (SkPdfListAttributeDictionary*)this;} const SkPdfListAttributeDictionary* asListAttributeDictionary() const {return (const SkPdfListAttributeDictionary*)this;} SkPdfLzwdecodeAndFlatedecodeFiltersDictionary* asLzwdecodeAndFlatedecodeFiltersDictionary() {return (SkPdfLzwdecodeAndFlatedecodeFiltersDictionary*)this;} const SkPdfLzwdecodeAndFlatedecodeFiltersDictionary* asLzwdecodeAndFlatedecodeFiltersDictionary() const {return (const SkPdfLzwdecodeAndFlatedecodeFiltersDictionary*)this;} SkPdfMacOsFileInformationDictionary* asMacOsFileInformationDictionary() {return (SkPdfMacOsFileInformationDictionary*)this;} const SkPdfMacOsFileInformationDictionary* asMacOsFileInformationDictionary() const {return (const SkPdfMacOsFileInformationDictionary*)this;} SkPdfMarkInformationDictionary* asMarkInformationDictionary() {return (SkPdfMarkInformationDictionary*)this;} const SkPdfMarkInformationDictionary* asMarkInformationDictionary() const {return (const SkPdfMarkInformationDictionary*)this;} SkPdfMarkedContentReferenceDictionary* asMarkedContentReferenceDictionary() {return (SkPdfMarkedContentReferenceDictionary*)this;} const SkPdfMarkedContentReferenceDictionary* asMarkedContentReferenceDictionary() const {return (const SkPdfMarkedContentReferenceDictionary*)this;} SkPdfMarkupAnnotationsDictionary* asMarkupAnnotationsDictionary() {return (SkPdfMarkupAnnotationsDictionary*)this;} const SkPdfMarkupAnnotationsDictionary* asMarkupAnnotationsDictionary() const {return (const SkPdfMarkupAnnotationsDictionary*)this;} SkPdfMetadataStreamDictionary* asMetadataStreamDictionary() {return (SkPdfMetadataStreamDictionary*)this;} const SkPdfMetadataStreamDictionary* asMetadataStreamDictionary() const {return (const SkPdfMetadataStreamDictionary*)this;} SkPdfMovieActionDictionary* asMovieActionDictionary() {return (SkPdfMovieActionDictionary*)this;} const SkPdfMovieActionDictionary* asMovieActionDictionary() const {return (const SkPdfMovieActionDictionary*)this;} SkPdfMovieActivationDictionary* asMovieActivationDictionary() {return (SkPdfMovieActivationDictionary*)this;} const SkPdfMovieActivationDictionary* asMovieActivationDictionary() const {return (const SkPdfMovieActivationDictionary*)this;} SkPdfMovieAnnotationDictionary* asMovieAnnotationDictionary() {return (SkPdfMovieAnnotationDictionary*)this;} const SkPdfMovieAnnotationDictionary* asMovieAnnotationDictionary() const {return (const SkPdfMovieAnnotationDictionary*)this;} SkPdfMovieDictionary* asMovieDictionary() {return (SkPdfMovieDictionary*)this;} const SkPdfMovieDictionary* asMovieDictionary() const {return (const SkPdfMovieDictionary*)this;} SkPdfNameDictionary* asNameDictionary() {return (SkPdfNameDictionary*)this;} const SkPdfNameDictionary* asNameDictionary() const {return (const SkPdfNameDictionary*)this;} SkPdfNameTreeNodeDictionary* asNameTreeNodeDictionary() {return (SkPdfNameTreeNodeDictionary*)this;} const SkPdfNameTreeNodeDictionary* asNameTreeNodeDictionary() const {return (const SkPdfNameTreeNodeDictionary*)this;} SkPdfNamedActionsDictionary* asNamedActionsDictionary() {return (SkPdfNamedActionsDictionary*)this;} const SkPdfNamedActionsDictionary* asNamedActionsDictionary() const {return (const SkPdfNamedActionsDictionary*)this;} SkPdfNumberTreeNodeDictionary* asNumberTreeNodeDictionary() {return (SkPdfNumberTreeNodeDictionary*)this;} const SkPdfNumberTreeNodeDictionary* asNumberTreeNodeDictionary() const {return (const SkPdfNumberTreeNodeDictionary*)this;} SkPdfObjectReferenceDictionary* asObjectReferenceDictionary() {return (SkPdfObjectReferenceDictionary*)this;} const SkPdfObjectReferenceDictionary* asObjectReferenceDictionary() const {return (const SkPdfObjectReferenceDictionary*)this;} SkPdfOpiVersionDictionary* asOpiVersionDictionary() {return (SkPdfOpiVersionDictionary*)this;} const SkPdfOpiVersionDictionary* asOpiVersionDictionary() const {return (const SkPdfOpiVersionDictionary*)this;} SkPdfOutlineDictionary* asOutlineDictionary() {return (SkPdfOutlineDictionary*)this;} const SkPdfOutlineDictionary* asOutlineDictionary() const {return (const SkPdfOutlineDictionary*)this;} SkPdfOutlineItemDictionary* asOutlineItemDictionary() {return (SkPdfOutlineItemDictionary*)this;} const SkPdfOutlineItemDictionary* asOutlineItemDictionary() const {return (const SkPdfOutlineItemDictionary*)this;} SkPdfPDF_XOutputIntentDictionary* asPDF_XOutputIntentDictionary() {return (SkPdfPDF_XOutputIntentDictionary*)this;} const SkPdfPDF_XOutputIntentDictionary* asPDF_XOutputIntentDictionary() const {return (const SkPdfPDF_XOutputIntentDictionary*)this;} SkPdfPSXobjectDictionary* asPSXobjectDictionary() {return (SkPdfPSXobjectDictionary*)this;} const SkPdfPSXobjectDictionary* asPSXobjectDictionary() const {return (const SkPdfPSXobjectDictionary*)this;} SkPdfPageLabelDictionary* asPageLabelDictionary() {return (SkPdfPageLabelDictionary*)this;} const SkPdfPageLabelDictionary* asPageLabelDictionary() const {return (const SkPdfPageLabelDictionary*)this;} SkPdfPageObjectActionsDictionary* asPageObjectActionsDictionary() {return (SkPdfPageObjectActionsDictionary*)this;} const SkPdfPageObjectActionsDictionary* asPageObjectActionsDictionary() const {return (const SkPdfPageObjectActionsDictionary*)this;} SkPdfPageObjectDictionary* asPageObjectDictionary() {return (SkPdfPageObjectDictionary*)this;} const SkPdfPageObjectDictionary* asPageObjectDictionary() const {return (const SkPdfPageObjectDictionary*)this;} SkPdfPagePieceDictionary* asPagePieceDictionary() {return (SkPdfPagePieceDictionary*)this;} const SkPdfPagePieceDictionary* asPagePieceDictionary() const {return (const SkPdfPagePieceDictionary*)this;} SkPdfPageTreeNodeDictionary* asPageTreeNodeDictionary() {return (SkPdfPageTreeNodeDictionary*)this;} const SkPdfPageTreeNodeDictionary* asPageTreeNodeDictionary() const {return (const SkPdfPageTreeNodeDictionary*)this;} SkPdfPopUpAnnotationDictionary* asPopUpAnnotationDictionary() {return (SkPdfPopUpAnnotationDictionary*)this;} const SkPdfPopUpAnnotationDictionary* asPopUpAnnotationDictionary() const {return (const SkPdfPopUpAnnotationDictionary*)this;} SkPdfPrinterMarkAnnotationDictionary* asPrinterMarkAnnotationDictionary() {return (SkPdfPrinterMarkAnnotationDictionary*)this;} const SkPdfPrinterMarkAnnotationDictionary* asPrinterMarkAnnotationDictionary() const {return (const SkPdfPrinterMarkAnnotationDictionary*)this;} SkPdfPrinterMarkFormDictionary* asPrinterMarkFormDictionary() {return (SkPdfPrinterMarkFormDictionary*)this;} const SkPdfPrinterMarkFormDictionary* asPrinterMarkFormDictionary() const {return (const SkPdfPrinterMarkFormDictionary*)this;} SkPdfRadioButtonFieldDictionary* asRadioButtonFieldDictionary() {return (SkPdfRadioButtonFieldDictionary*)this;} const SkPdfRadioButtonFieldDictionary* asRadioButtonFieldDictionary() const {return (const SkPdfRadioButtonFieldDictionary*)this;} SkPdfReferenceDictionary* asReferenceDictionary() {return (SkPdfReferenceDictionary*)this;} const SkPdfReferenceDictionary* asReferenceDictionary() const {return (const SkPdfReferenceDictionary*)this;} SkPdfRemoteGoToActionDictionary* asRemoteGoToActionDictionary() {return (SkPdfRemoteGoToActionDictionary*)this;} const SkPdfRemoteGoToActionDictionary* asRemoteGoToActionDictionary() const {return (const SkPdfRemoteGoToActionDictionary*)this;} SkPdfResetFormActionDictionary* asResetFormActionDictionary() {return (SkPdfResetFormActionDictionary*)this;} const SkPdfResetFormActionDictionary* asResetFormActionDictionary() const {return (const SkPdfResetFormActionDictionary*)this;} SkPdfResourceDictionary* asResourceDictionary() {return (SkPdfResourceDictionary*)this;} const SkPdfResourceDictionary* asResourceDictionary() const {return (const SkPdfResourceDictionary*)this;} SkPdfRubberStampAnnotationDictionary* asRubberStampAnnotationDictionary() {return (SkPdfRubberStampAnnotationDictionary*)this;} const SkPdfRubberStampAnnotationDictionary* asRubberStampAnnotationDictionary() const {return (const SkPdfRubberStampAnnotationDictionary*)this;} SkPdfSeparationDictionary* asSeparationDictionary() {return (SkPdfSeparationDictionary*)this;} const SkPdfSeparationDictionary* asSeparationDictionary() const {return (const SkPdfSeparationDictionary*)this;} SkPdfShadingDictionary* asShadingDictionary() {return (SkPdfShadingDictionary*)this;} const SkPdfShadingDictionary* asShadingDictionary() const {return (const SkPdfShadingDictionary*)this;} SkPdfType1ShadingDictionary* asType1ShadingDictionary() {return (SkPdfType1ShadingDictionary*)this;} const SkPdfType1ShadingDictionary* asType1ShadingDictionary() const {return (const SkPdfType1ShadingDictionary*)this;} SkPdfType2ShadingDictionary* asType2ShadingDictionary() {return (SkPdfType2ShadingDictionary*)this;} const SkPdfType2ShadingDictionary* asType2ShadingDictionary() const {return (const SkPdfType2ShadingDictionary*)this;} SkPdfType3ShadingDictionary* asType3ShadingDictionary() {return (SkPdfType3ShadingDictionary*)this;} const SkPdfType3ShadingDictionary* asType3ShadingDictionary() const {return (const SkPdfType3ShadingDictionary*)this;} SkPdfType4ShadingDictionary* asType4ShadingDictionary() {return (SkPdfType4ShadingDictionary*)this;} const SkPdfType4ShadingDictionary* asType4ShadingDictionary() const {return (const SkPdfType4ShadingDictionary*)this;} SkPdfType5ShadingDictionary* asType5ShadingDictionary() {return (SkPdfType5ShadingDictionary*)this;} const SkPdfType5ShadingDictionary* asType5ShadingDictionary() const {return (const SkPdfType5ShadingDictionary*)this;} SkPdfType6ShadingDictionary* asType6ShadingDictionary() {return (SkPdfType6ShadingDictionary*)this;} const SkPdfType6ShadingDictionary* asType6ShadingDictionary() const {return (const SkPdfType6ShadingDictionary*)this;} SkPdfSignatureDictionary* asSignatureDictionary() {return (SkPdfSignatureDictionary*)this;} const SkPdfSignatureDictionary* asSignatureDictionary() const {return (const SkPdfSignatureDictionary*)this;} SkPdfSoftMaskDictionary* asSoftMaskDictionary() {return (SkPdfSoftMaskDictionary*)this;} const SkPdfSoftMaskDictionary* asSoftMaskDictionary() const {return (const SkPdfSoftMaskDictionary*)this;} SkPdfSoundActionDictionary* asSoundActionDictionary() {return (SkPdfSoundActionDictionary*)this;} const SkPdfSoundActionDictionary* asSoundActionDictionary() const {return (const SkPdfSoundActionDictionary*)this;} SkPdfSoundAnnotationDictionary* asSoundAnnotationDictionary() {return (SkPdfSoundAnnotationDictionary*)this;} const SkPdfSoundAnnotationDictionary* asSoundAnnotationDictionary() const {return (const SkPdfSoundAnnotationDictionary*)this;} SkPdfSoundObjectDictionary* asSoundObjectDictionary() {return (SkPdfSoundObjectDictionary*)this;} const SkPdfSoundObjectDictionary* asSoundObjectDictionary() const {return (const SkPdfSoundObjectDictionary*)this;} SkPdfSourceInformationDictionary* asSourceInformationDictionary() {return (SkPdfSourceInformationDictionary*)this;} const SkPdfSourceInformationDictionary* asSourceInformationDictionary() const {return (const SkPdfSourceInformationDictionary*)this;} SkPdfSquareOrCircleAnnotation* asSquareOrCircleAnnotation() {return (SkPdfSquareOrCircleAnnotation*)this;} const SkPdfSquareOrCircleAnnotation* asSquareOrCircleAnnotation() const {return (const SkPdfSquareOrCircleAnnotation*)this;} SkPdfStandardSecurityHandlerDictionary* asStandardSecurityHandlerDictionary() {return (SkPdfStandardSecurityHandlerDictionary*)this;} const SkPdfStandardSecurityHandlerDictionary* asStandardSecurityHandlerDictionary() const {return (const SkPdfStandardSecurityHandlerDictionary*)this;} SkPdfStandardStructureDictionary* asStandardStructureDictionary() {return (SkPdfStandardStructureDictionary*)this;} const SkPdfStandardStructureDictionary* asStandardStructureDictionary() const {return (const SkPdfStandardStructureDictionary*)this;} SkPdfStreamCommonDictionary* asStreamCommonDictionary() {return (SkPdfStreamCommonDictionary*)this;} const SkPdfStreamCommonDictionary* asStreamCommonDictionary() const {return (const SkPdfStreamCommonDictionary*)this;} SkPdfStructureElementAccessDictionary* asStructureElementAccessDictionary() {return (SkPdfStructureElementAccessDictionary*)this;} const SkPdfStructureElementAccessDictionary* asStructureElementAccessDictionary() const {return (const SkPdfStructureElementAccessDictionary*)this;} SkPdfStructureElementDictionary* asStructureElementDictionary() {return (SkPdfStructureElementDictionary*)this;} const SkPdfStructureElementDictionary* asStructureElementDictionary() const {return (const SkPdfStructureElementDictionary*)this;} SkPdfStructureTreeRootDictionary* asStructureTreeRootDictionary() {return (SkPdfStructureTreeRootDictionary*)this;} const SkPdfStructureTreeRootDictionary* asStructureTreeRootDictionary() const {return (const SkPdfStructureTreeRootDictionary*)this;} SkPdfSubmitFormActionDictionary* asSubmitFormActionDictionary() {return (SkPdfSubmitFormActionDictionary*)this;} const SkPdfSubmitFormActionDictionary* asSubmitFormActionDictionary() const {return (const SkPdfSubmitFormActionDictionary*)this;} SkPdfTableAttributesDictionary* asTableAttributesDictionary() {return (SkPdfTableAttributesDictionary*)this;} const SkPdfTableAttributesDictionary* asTableAttributesDictionary() const {return (const SkPdfTableAttributesDictionary*)this;} SkPdfTextAnnotationDictionary* asTextAnnotationDictionary() {return (SkPdfTextAnnotationDictionary*)this;} const SkPdfTextAnnotationDictionary* asTextAnnotationDictionary() const {return (const SkPdfTextAnnotationDictionary*)this;} SkPdfTextFieldDictionary* asTextFieldDictionary() {return (SkPdfTextFieldDictionary*)this;} const SkPdfTextFieldDictionary* asTextFieldDictionary() const {return (const SkPdfTextFieldDictionary*)this;} SkPdfThreadActionDictionary* asThreadActionDictionary() {return (SkPdfThreadActionDictionary*)this;} const SkPdfThreadActionDictionary* asThreadActionDictionary() const {return (const SkPdfThreadActionDictionary*)this;} SkPdfThreadDictionary* asThreadDictionary() {return (SkPdfThreadDictionary*)this;} const SkPdfThreadDictionary* asThreadDictionary() const {return (const SkPdfThreadDictionary*)this;} SkPdfTransitionDictionary* asTransitionDictionary() {return (SkPdfTransitionDictionary*)this;} const SkPdfTransitionDictionary* asTransitionDictionary() const {return (const SkPdfTransitionDictionary*)this;} SkPdfTransparencyGroupDictionary* asTransparencyGroupDictionary() {return (SkPdfTransparencyGroupDictionary*)this;} const SkPdfTransparencyGroupDictionary* asTransparencyGroupDictionary() const {return (const SkPdfTransparencyGroupDictionary*)this;} SkPdfTrapNetworkAnnotationDictionary* asTrapNetworkAnnotationDictionary() {return (SkPdfTrapNetworkAnnotationDictionary*)this;} const SkPdfTrapNetworkAnnotationDictionary* asTrapNetworkAnnotationDictionary() const {return (const SkPdfTrapNetworkAnnotationDictionary*)this;} SkPdfTrapNetworkAppearanceStreamDictionary* asTrapNetworkAppearanceStreamDictionary() {return (SkPdfTrapNetworkAppearanceStreamDictionary*)this;} const SkPdfTrapNetworkAppearanceStreamDictionary* asTrapNetworkAppearanceStreamDictionary() const {return (const SkPdfTrapNetworkAppearanceStreamDictionary*)this;} SkPdfType0FunctionDictionary* asType0FunctionDictionary() {return (SkPdfType0FunctionDictionary*)this;} const SkPdfType0FunctionDictionary* asType0FunctionDictionary() const {return (const SkPdfType0FunctionDictionary*)this;} SkPdfType10HalftoneDictionary* asType10HalftoneDictionary() {return (SkPdfType10HalftoneDictionary*)this;} const SkPdfType10HalftoneDictionary* asType10HalftoneDictionary() const {return (const SkPdfType10HalftoneDictionary*)this;} SkPdfType16HalftoneDictionary* asType16HalftoneDictionary() {return (SkPdfType16HalftoneDictionary*)this;} const SkPdfType16HalftoneDictionary* asType16HalftoneDictionary() const {return (const SkPdfType16HalftoneDictionary*)this;} SkPdfType1HalftoneDictionary* asType1HalftoneDictionary() {return (SkPdfType1HalftoneDictionary*)this;} const SkPdfType1HalftoneDictionary* asType1HalftoneDictionary() const {return (const SkPdfType1HalftoneDictionary*)this;} SkPdfType1PatternDictionary* asType1PatternDictionary() {return (SkPdfType1PatternDictionary*)this;} const SkPdfType1PatternDictionary* asType1PatternDictionary() const {return (const SkPdfType1PatternDictionary*)this;} SkPdfType2FunctionDictionary* asType2FunctionDictionary() {return (SkPdfType2FunctionDictionary*)this;} const SkPdfType2FunctionDictionary* asType2FunctionDictionary() const {return (const SkPdfType2FunctionDictionary*)this;} SkPdfType2PatternDictionary* asType2PatternDictionary() {return (SkPdfType2PatternDictionary*)this;} const SkPdfType2PatternDictionary* asType2PatternDictionary() const {return (const SkPdfType2PatternDictionary*)this;} SkPdfType3FunctionDictionary* asType3FunctionDictionary() {return (SkPdfType3FunctionDictionary*)this;} const SkPdfType3FunctionDictionary* asType3FunctionDictionary() const {return (const SkPdfType3FunctionDictionary*)this;} SkPdfType5HalftoneDictionary* asType5HalftoneDictionary() {return (SkPdfType5HalftoneDictionary*)this;} const SkPdfType5HalftoneDictionary* asType5HalftoneDictionary() const {return (const SkPdfType5HalftoneDictionary*)this;} SkPdfType6HalftoneDictionary* asType6HalftoneDictionary() {return (SkPdfType6HalftoneDictionary*)this;} const SkPdfType6HalftoneDictionary* asType6HalftoneDictionary() const {return (const SkPdfType6HalftoneDictionary*)this;} SkPdfURIActionDictionary* asURIActionDictionary() {return (SkPdfURIActionDictionary*)this;} const SkPdfURIActionDictionary* asURIActionDictionary() const {return (const SkPdfURIActionDictionary*)this;} SkPdfURIDictionary* asURIDictionary() {return (SkPdfURIDictionary*)this;} const SkPdfURIDictionary* asURIDictionary() const {return (const SkPdfURIDictionary*)this;} SkPdfURLAliasDictionary* asURLAliasDictionary() {return (SkPdfURLAliasDictionary*)this;} const SkPdfURLAliasDictionary* asURLAliasDictionary() const {return (const SkPdfURLAliasDictionary*)this;} SkPdfVariableTextFieldDictionary* asVariableTextFieldDictionary() {return (SkPdfVariableTextFieldDictionary*)this;} const SkPdfVariableTextFieldDictionary* asVariableTextFieldDictionary() const {return (const SkPdfVariableTextFieldDictionary*)this;} SkPdfViewerPreferencesDictionary* asViewerPreferencesDictionary() {return (SkPdfViewerPreferencesDictionary*)this;} const SkPdfViewerPreferencesDictionary* asViewerPreferencesDictionary() const {return (const SkPdfViewerPreferencesDictionary*)this;} SkPdfWebCaptureCommandDictionary* asWebCaptureCommandDictionary() {return (SkPdfWebCaptureCommandDictionary*)this;} const SkPdfWebCaptureCommandDictionary* asWebCaptureCommandDictionary() const {return (const SkPdfWebCaptureCommandDictionary*)this;} SkPdfWebCaptureCommandSettingsDictionary* asWebCaptureCommandSettingsDictionary() {return (SkPdfWebCaptureCommandSettingsDictionary*)this;} const SkPdfWebCaptureCommandSettingsDictionary* asWebCaptureCommandSettingsDictionary() const {return (const SkPdfWebCaptureCommandSettingsDictionary*)this;} SkPdfWebCaptureDictionary* asWebCaptureDictionary() {return (SkPdfWebCaptureDictionary*)this;} const SkPdfWebCaptureDictionary* asWebCaptureDictionary() const {return (const SkPdfWebCaptureDictionary*)this;} SkPdfWebCaptureImageSetDictionary* asWebCaptureImageSetDictionary() {return (SkPdfWebCaptureImageSetDictionary*)this;} const SkPdfWebCaptureImageSetDictionary* asWebCaptureImageSetDictionary() const {return (const SkPdfWebCaptureImageSetDictionary*)this;} SkPdfWebCaptureInformationDictionary* asWebCaptureInformationDictionary() {return (SkPdfWebCaptureInformationDictionary*)this;} const SkPdfWebCaptureInformationDictionary* asWebCaptureInformationDictionary() const {return (const SkPdfWebCaptureInformationDictionary*)this;} SkPdfWebCapturePageSetDictionary* asWebCapturePageSetDictionary() {return (SkPdfWebCapturePageSetDictionary*)this;} const SkPdfWebCapturePageSetDictionary* asWebCapturePageSetDictionary() const {return (const SkPdfWebCapturePageSetDictionary*)this;} SkPdfWidgetAnnotationDictionary* asWidgetAnnotationDictionary() {return (SkPdfWidgetAnnotationDictionary*)this;} const SkPdfWidgetAnnotationDictionary* asWidgetAnnotationDictionary() const {return (const SkPdfWidgetAnnotationDictionary*)this;} SkPdfWindowsLaunchActionDictionary* asWindowsLaunchActionDictionary() {return (SkPdfWindowsLaunchActionDictionary*)this;} const SkPdfWindowsLaunchActionDictionary* asWindowsLaunchActionDictionary() const {return (const SkPdfWindowsLaunchActionDictionary*)this;} SkPdfXObjectDictionary* asXObjectDictionary() {return (SkPdfXObjectDictionary*)this;} const SkPdfXObjectDictionary* asXObjectDictionary() const {return (const SkPdfXObjectDictionary*)this;} SkPdfImageDictionary* asImageDictionary() {return (SkPdfImageDictionary*)this;} const SkPdfImageDictionary* asImageDictionary() const {return (const SkPdfImageDictionary*)this;} SkPdfSoftMaskImageDictionary* asSoftMaskImageDictionary() {return (SkPdfSoftMaskImageDictionary*)this;} const SkPdfSoftMaskImageDictionary* asSoftMaskImageDictionary() const {return (const SkPdfSoftMaskImageDictionary*)this;} SkPdfType1FormDictionary* asType1FormDictionary() {return (SkPdfType1FormDictionary*)this;} const SkPdfType1FormDictionary* asType1FormDictionary() const {return (const SkPdfType1FormDictionary*)this;} public: bool valid() const {return true;} SkString Subtype(SkPdfNativeDoc* doc); bool has_Subtype() const; SkPdfFileSpec FS(SkPdfNativeDoc* doc); bool has_FS() const; SkString Contents(SkPdfNativeDoc* doc); bool has_Contents() const; SkString Name(SkPdfNativeDoc* doc); bool has_Name() const; }; #endif // SkPdfFileAttachmentAnnotationDictionary_DEFINED
CTSRD-SOAAP/chromium-42.0.2311.135
third_party/skia/experimental/PdfViewer/pdfparser/native/pdfapi/SkPdfFileAttachmentAnnotationDictionary_autogen.h
C
bsd-3-clause
40,377
''' Tests for commands module Nick Mathewson ''' import unittest import os, tempfile, re from test.test_support import run_unittest, reap_children, import_module, \ check_warnings # Silence Py3k warning commands = import_module('commands', deprecated=True) # The module says: # "NB This only works (and is only relevant) for UNIX." # # Actually, getoutput should work on any platform with an os.popen, but # I'll take the comment as given, and skip this suite. if os.name != 'posix': raise unittest.SkipTest('Not posix; skipping test_commands') class CommandTests(unittest.TestCase): def test_getoutput(self): self.assertEqual(commands.getoutput('echo xyzzy'), 'xyzzy') self.assertEqual(commands.getstatusoutput('echo xyzzy'), (0, 'xyzzy')) # we use mkdtemp in the next line to create an empty directory # under our exclusive control; from that, we can invent a pathname # that we _know_ won't exist. This is guaranteed to fail. dir = None try: dir = tempfile.mkdtemp() name = os.path.join(dir, "foo") status, output = commands.getstatusoutput('cat ' + name) self.assertNotEqual(status, 0) finally: if dir is not None: os.rmdir(dir) def test_getstatus(self): # This pattern should match 'ls -ld /.' on any posix # system, however perversely configured. Even on systems # (e.g., Cygwin) where user and group names can have spaces: # drwxr-xr-x 15 Administ Domain U 4096 Aug 12 12:50 / # drwxr-xr-x 15 Joe User My Group 4096 Aug 12 12:50 / # Note that the first case above has a space in the group name # while the second one has a space in both names. # Special attributes supported: # + = has ACLs # @ = has Mac OS X extended attributes # . = has a SELinux security context pat = r'''d......... # It is a directory. [.+@]? # It may have special attributes. \s+\d+ # It has some number of links. [^/]* # Skip user, group, size, and date. /\. # and end with the name of the file. ''' with check_warnings((".*commands.getstatus.. is deprecated", DeprecationWarning)): self.assertTrue(re.match(pat, commands.getstatus("/."), re.VERBOSE)) def test_main(): run_unittest(CommandTests) reap_children() if __name__ == "__main__": test_main()
teeple/pns_server
work/install/Python-2.7.4/Lib/test/test_commands.py
Python
gpl-2.0
2,640
# SPDX-License-Identifier: GPL-2.0 mirror_install() { local from_dev=$1; shift local direction=$1; shift local to_dev=$1; shift local filter=$1; shift tc filter add dev $from_dev $direction \ pref 1000 $filter \ action mirred egress mirror dev $to_dev } mirror_uninstall() { local from_dev=$1; shift local direction=$1; shift tc filter del dev $swp1 $direction pref 1000 } mirror_test() { local vrf_name=$1; shift local sip=$1; shift local dip=$1; shift local dev=$1; shift local pref=$1; shift local expect=$1; shift local ping_timeout=$((PING_TIMEOUT * 5)) local t0=$(tc_rule_stats_get $dev $pref) ip vrf exec $vrf_name \ ${PING} ${sip:+-I $sip} $dip -c 10 -i 0.5 -w $ping_timeout \ &> /dev/null sleep 0.5 local t1=$(tc_rule_stats_get $dev $pref) local delta=$((t1 - t0)) # Tolerate a couple stray extra packets. ((expect <= delta && delta <= expect + 2)) check_err $? "Expected to capture $expect packets, got $delta." } do_test_span_dir_ips() { local expect=$1; shift local dev=$1; shift local direction=$1; shift local ip1=$1; shift local ip2=$1; shift icmp_capture_install $dev mirror_test v$h1 $ip1 $ip2 $dev 100 $expect mirror_test v$h2 $ip2 $ip1 $dev 100 $expect icmp_capture_uninstall $dev } quick_test_span_dir_ips() { do_test_span_dir_ips 10 "$@" } fail_test_span_dir_ips() { do_test_span_dir_ips 0 "$@" } test_span_dir_ips() { local dev=$1; shift local direction=$1; shift local forward_type=$1; shift local backward_type=$1; shift local ip1=$1; shift local ip2=$1; shift quick_test_span_dir_ips "$dev" "$direction" "$ip1" "$ip2" icmp_capture_install $dev "type $forward_type" mirror_test v$h1 $ip1 $ip2 $dev 100 10 icmp_capture_uninstall $dev icmp_capture_install $dev "type $backward_type" mirror_test v$h2 $ip2 $ip1 $dev 100 10 icmp_capture_uninstall $dev } fail_test_span_dir() { fail_test_span_dir_ips "$@" 192.0.2.1 192.0.2.2 } test_span_dir() { test_span_dir_ips "$@" 192.0.2.1 192.0.2.2 } do_test_span_vlan_dir_ips() { local expect=$1; shift local dev=$1; shift local vid=$1; shift local direction=$1; shift local ip1=$1; shift local ip2=$1; shift # Install the capture as skip_hw to avoid double-counting of packets. # The traffic is meant for local box anyway, so will be trapped to # kernel. vlan_capture_install $dev "skip_hw vlan_id $vid vlan_ethtype ip" mirror_test v$h1 $ip1 $ip2 $dev 100 $expect mirror_test v$h2 $ip2 $ip1 $dev 100 $expect vlan_capture_uninstall $dev } quick_test_span_vlan_dir_ips() { do_test_span_vlan_dir_ips 10 "$@" } fail_test_span_vlan_dir_ips() { do_test_span_vlan_dir_ips 0 "$@" } quick_test_span_vlan_dir() { quick_test_span_vlan_dir_ips "$@" 192.0.2.1 192.0.2.2 } fail_test_span_vlan_dir() { fail_test_span_vlan_dir_ips "$@" 192.0.2.1 192.0.2.2 }
Taeung/tip
tools/testing/selftests/net/forwarding/mirror_lib.sh
Shell
gpl-2.0
2,808
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * oci8 Result Class * * This class extends the parent result class: CI_DB_result * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_oci8_result extends CI_DB_result { var $stmt_id; var $curs_id; var $limit_used; /** * Number of rows in the result set. * * Oracle doesn't have a graceful way to retun the number of rows * so we have to use what amounts to a hack. * * * @access public * @return integer */ function num_rows() { $rowcount = count($this->result_array()); @ociexecute($this->stmt_id); if ($this->curs_id) { @ociexecute($this->curs_id); } return $rowcount; } // -------------------------------------------------------------------- /** * Number of fields in the result set * * @access public * @return integer */ function num_fields() { $count = @ocinumcols($this->stmt_id); // if we used a limit we subtract it if ($this->limit_used) { $count = $count - 1; } return $count; } // -------------------------------------------------------------------- /** * Fetch Field Names * * Generates an array of column names * * @access public * @return array */ function list_fields() { $field_names = array(); $fieldCount = $this->num_fields(); for ($c = 1; $c <= $fieldCount; $c++) { $field_names[] = ocicolumnname($this->stmt_id, $c); } return $field_names; } // -------------------------------------------------------------------- /** * Field data * * Generates an array of objects containing field meta-data * * @access public * @return array */ function field_data() { $retval = array(); $fieldCount = $this->num_fields(); for ($c = 1; $c <= $fieldCount; $c++) { $F = new stdClass(); $F->name = ocicolumnname($this->stmt_id, $c); $F->type = ocicolumntype($this->stmt_id, $c); $F->max_length = ocicolumnsize($this->stmt_id, $c); $retval[] = $F; } return $retval; } // -------------------------------------------------------------------- /** * Free the result * * @return null */ function free_result() { if (is_resource($this->result_id)) { ocifreestatement($this->result_id); $this->result_id = FALSE; } } // -------------------------------------------------------------------- /** * Result - associative array * * Returns the result set as an array * * @access private * @return array */ function _fetch_assoc(&$row) { $id = ($this->curs_id) ? $this->curs_id : $this->stmt_id; return ocifetchinto($id, $row, OCI_ASSOC + OCI_RETURN_NULLS); } // -------------------------------------------------------------------- /** * Result - object * * Returns the result set as an object * * @access private * @return object */ function _fetch_object() { $result = array(); // If PHP 5 is being used we can fetch an result object if (function_exists('oci_fetch_object')) { $id = ($this->curs_id) ? $this->curs_id : $this->stmt_id; return @oci_fetch_object($id); } // If PHP 4 is being used we have to build our own result foreach ($this->result_array() as $key => $val) { $obj = new stdClass(); if (is_array($val)) { foreach ($val as $k => $v) { $obj->$k = $v; } } else { $obj->$key = $val; } $result[] = $obj; } return $result; } // -------------------------------------------------------------------- /** * Query result. "array" version. * * @access public * @return array */ function result_array() { if (count($this->result_array) > 0) { return $this->result_array; } // oracle's fetch functions do not return arrays. // The information is returned in reference parameters $row = NULL; while ($this->_fetch_assoc($row)) { $this->result_array[] = $row; } return $this->result_array; } // -------------------------------------------------------------------- /** * Data Seek * * Moves the internal pointer to the desired offset. We call * this internally before fetching results to make sure the * result set starts at zero * * @access private * @return array */ function _data_seek($n = 0) { return FALSE; // Not needed } } /* End of file oci8_result.php */ /* Location: ./system/database/drivers/oci8/oci8_result.php */
zeshaq/zeteq-cms-basic
web/tiny_mce/plugins/jbimages/ci/system/database/drivers/oci8/oci8_result.php
PHP
mit
4,923
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @fileOverview Defines the {@link CKEDITOR.loader} objects, which is used to * load core scripts and their dependencies from _source. */ if ( typeof CKEDITOR == 'undefined' ) CKEDITOR = {}; if ( !CKEDITOR.loader ) { /** * Load core scripts and their dependencies from _source. * @namespace * @example */ CKEDITOR.loader = (function() { // Table of script names and their dependencies. var scripts = { 'core/_bootstrap' : [ 'core/config', 'core/ckeditor', 'core/plugins', 'core/scriptloader', 'core/tools', /* The following are entries that we want to force loading at the end to avoid dependence recursion */ 'core/dom/comment', 'core/dom/elementpath', 'core/dom/text', 'core/dom/rangelist' ], 'core/ckeditor' : [ 'core/ckeditor_basic', 'core/dom', 'core/dtd', 'core/dom/document', 'core/dom/element', 'core/editor', 'core/event', 'core/htmlparser', 'core/htmlparser/element', 'core/htmlparser/fragment', 'core/htmlparser/filter', 'core/htmlparser/basicwriter', 'core/tools' ], 'core/ckeditor_base' : [], 'core/ckeditor_basic' : [ 'core/editor_basic', 'core/env', 'core/event' ], 'core/command' : [], 'core/config' : [ 'core/ckeditor_base' ], 'core/dom' : [], 'core/dom/comment' : [ 'core/dom/node' ], 'core/dom/document' : [ 'core/dom', 'core/dom/domobject', 'core/dom/window' ], 'core/dom/documentfragment' : [ 'core/dom/element' ], 'core/dom/element' : [ 'core/dom', 'core/dom/document', 'core/dom/domobject', 'core/dom/node', 'core/dom/nodelist', 'core/tools' ], 'core/dom/elementpath' : [ 'core/dom/element' ], 'core/dom/event' : [], 'core/dom/node' : [ 'core/dom/domobject', 'core/tools' ], 'core/dom/nodelist' : [ 'core/dom/node' ], 'core/dom/domobject' : [ 'core/dom/event' ], 'core/dom/range' : [ 'core/dom/document', 'core/dom/documentfragment', 'core/dom/element', 'core/dom/walker' ], 'core/dom/rangelist' : [ 'core/dom/range' ], 'core/dom/text' : [ 'core/dom/node', 'core/dom/domobject' ], 'core/dom/walker' : [ 'core/dom/node' ], 'core/dom/window' : [ 'core/dom/domobject' ], 'core/dtd' : [ 'core/tools' ], 'core/editor' : [ 'core/command', 'core/config', 'core/editor_basic', 'core/focusmanager', 'core/lang', 'core/plugins', 'core/skins', 'core/themes', 'core/tools', 'core/ui' ], 'core/editor_basic' : [ 'core/event' ], 'core/env' : [], 'core/event' : [], 'core/focusmanager' : [], 'core/htmlparser' : [], 'core/htmlparser/comment' : [ 'core/htmlparser' ], 'core/htmlparser/element' : [ 'core/htmlparser', 'core/htmlparser/fragment' ], 'core/htmlparser/fragment' : [ 'core/htmlparser', 'core/htmlparser/comment', 'core/htmlparser/text', 'core/htmlparser/cdata' ], 'core/htmlparser/text' : [ 'core/htmlparser' ], 'core/htmlparser/cdata' : [ 'core/htmlparser' ], 'core/htmlparser/filter' : [ 'core/htmlparser' ], 'core/htmlparser/basicwriter': [ 'core/htmlparser' ], 'core/lang' : [], 'core/plugins' : [ 'core/resourcemanager' ], 'core/resourcemanager' : [ 'core/scriptloader', 'core/tools' ], 'core/scriptloader' : [ 'core/dom/element', 'core/env' ], 'core/skins' : [ 'core/scriptloader' ], 'core/themes' : [ 'core/resourcemanager' ], 'core/tools' : [ 'core/env' ], 'core/ui' : [] }; var basePath = (function() { // This is a copy of CKEDITOR.basePath, but requires the script having // "_source/core/loader.js". if ( CKEDITOR && CKEDITOR.basePath ) return CKEDITOR.basePath; // Find out the editor directory path, based on its <script> tag. var path = ''; var scripts = document.getElementsByTagName( 'script' ); for ( var i = 0 ; i < scripts.length ; i++ ) { var match = scripts[i].src.match( /(^|.*?[\\\/])(?:_source\/)?core\/loader.js(?:\?.*)?$/i ); if ( match ) { path = match[1]; break; } } // In IE (only) the script.src string is the raw valued entered in the // HTML. Other browsers return the full resolved URL instead. if ( path.indexOf('://') == -1 ) { // Absolute path. if ( path.indexOf( '/' ) === 0 ) path = location.href.match( /^.*?:\/\/[^\/]*/ )[0] + path; // Relative path. else path = location.href.match( /^[^\?]*\// )[0] + path; } return path; })(); var timestamp = 'D03G5XL'; var getUrl = function( resource ) { if ( CKEDITOR && CKEDITOR.getUrl ) return CKEDITOR.getUrl( resource ); return basePath + resource + ( resource.indexOf( '?' ) >= 0 ? '&' : '?' ) + 't=' + timestamp; }; var pendingLoad = []; /** @lends CKEDITOR.loader */ return { /** * The list of loaded scripts in their loading order. * @type Array * @example * // Alert the loaded script names. * alert( <b>CKEDITOR.loader.loadedScripts</b> ); */ loadedScripts : [], loadPending : function() { var scriptName = pendingLoad.shift(); if ( !scriptName ) return; var scriptSrc = getUrl( '_source/' + scriptName + '.js' ); var script = document.createElement( 'script' ); script.type = 'text/javascript'; script.src = scriptSrc; function onScriptLoaded() { // Append this script to the list of loaded scripts. CKEDITOR.loader.loadedScripts.push( scriptName ); // Load the next. CKEDITOR.loader.loadPending(); } // We must guarantee the execution order of the scripts, so we // need to load them one by one. (#4145) // The following if/else block has been taken from the scriptloader core code. if ( typeof(script.onreadystatechange) !== "undefined" ) { /** @ignore */ script.onreadystatechange = function() { if ( script.readyState == 'loaded' || script.readyState == 'complete' ) { script.onreadystatechange = null; onScriptLoaded(); } }; } else { /** @ignore */ script.onload = function() { // Some browsers, such as Safari, may call the onLoad function // immediately. Which will break the loading sequence. (#3661) setTimeout( function() { onScriptLoaded( scriptName ); }, 0 ); }; } document.body.appendChild( script ); }, /** * Loads a specific script, including its dependencies. This is not a * synchronous loading, which means that the code to be loaded will * not necessarily be available after this call. * @example * CKEDITOR.loader.load( 'core/dom/element' ); */ load : function( scriptName, defer ) { // Check if the script has already been loaded. if ( scriptName in this.loadedScripts ) return; // Get the script dependencies list. var dependencies = scripts[ scriptName ]; if ( !dependencies ) throw 'The script name"' + scriptName + '" is not defined.'; // Mark the script as loaded, even before really loading it, to // avoid cross references recursion. this.loadedScripts[ scriptName ] = true; // Load all dependencies first. for ( var i = 0 ; i < dependencies.length ; i++ ) this.load( dependencies[ i ], true ); var scriptSrc = getUrl( '_source/' + scriptName + '.js' ); // Append the <script> element to the DOM. // If the page is fully loaded, we can't use document.write // but if the script is run while the body is loading then it's safe to use it // Unfortunately, Firefox <3.6 doesn't support document.readyState, so it won't get this improvement if ( document.body && (!document.readyState || document.readyState == 'complete') ) { pendingLoad.push( scriptName ); if ( !defer ) this.loadPending(); } else { // Append this script to the list of loaded scripts. this.loadedScripts.push( scriptName ); document.write( '<script src="' + scriptSrc + '" type="text/javascript"><\/script>' ); } } }; })(); } // Check if any script has been defined for autoload. if ( CKEDITOR._autoLoad ) { CKEDITOR.loader.load( CKEDITOR._autoLoad ); delete CKEDITOR._autoLoad; }
geobretagne/popp
web/sites/all/libraries/ckeditor/_source/core/loader.js
JavaScript
gpl-3.0
8,215
/* * 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.spark.mllib.fpm; import java.io.File; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.apache.spark.SharedSparkSession; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.util.Utils; public class JavaFPGrowthSuite extends SharedSparkSession { @Test public void runFPGrowth() { @SuppressWarnings("unchecked") JavaRDD<List<String>> rdd = jsc.parallelize(Arrays.asList( Arrays.asList("r z h k p".split(" ")), Arrays.asList("z y x w v u t s".split(" ")), Arrays.asList("s x o n r".split(" ")), Arrays.asList("x z y m t s q e".split(" ")), Arrays.asList("z".split(" ")), Arrays.asList("x z y r q t p".split(" "))), 2); FPGrowthModel<String> model = new FPGrowth() .setMinSupport(0.5) .setNumPartitions(2) .run(rdd); List<FPGrowth.FreqItemset<String>> freqItemsets = model.freqItemsets().toJavaRDD().collect(); assertEquals(18, freqItemsets.size()); for (FPGrowth.FreqItemset<String> itemset : freqItemsets) { // Test return types. List<String> items = itemset.javaItems(); long freq = itemset.freq(); } } @Test public void runFPGrowthSaveLoad() { @SuppressWarnings("unchecked") JavaRDD<List<String>> rdd = jsc.parallelize(Arrays.asList( Arrays.asList("r z h k p".split(" ")), Arrays.asList("z y x w v u t s".split(" ")), Arrays.asList("s x o n r".split(" ")), Arrays.asList("x z y m t s q e".split(" ")), Arrays.asList("z".split(" ")), Arrays.asList("x z y r q t p".split(" "))), 2); FPGrowthModel<String> model = new FPGrowth() .setMinSupport(0.5) .setNumPartitions(2) .run(rdd); File tempDir = Utils.createTempDir( System.getProperty("java.io.tmpdir"), "JavaFPGrowthSuite"); String outputPath = tempDir.getPath(); try { model.save(spark.sparkContext(), outputPath); @SuppressWarnings("unchecked") FPGrowthModel<String> newModel = (FPGrowthModel<String>) FPGrowthModel.load(spark.sparkContext(), outputPath); List<FPGrowth.FreqItemset<String>> freqItemsets = newModel.freqItemsets().toJavaRDD() .collect(); assertEquals(18, freqItemsets.size()); for (FPGrowth.FreqItemset<String> itemset : freqItemsets) { // Test return types. List<String> items = itemset.javaItems(); long freq = itemset.freq(); } } finally { Utils.deleteRecursively(tempDir); } } }
ahnqirage/spark
mllib/src/test/java/org/apache/spark/mllib/fpm/JavaFPGrowthSuite.java
Java
apache-2.0
3,370
{% load i18n %} {% comment %}Translators: Django comment block for translators string's meaning unveiled {% endcomment %} {% trans "This literal should be included." %} {% trans "This literal should also be included wrapped or not wrapped depending on the use of the --no-wrap option." %} {% comment %}Some random comment Some random comment Translators: One-line translator comment #1 {% endcomment %} {% trans "Translatable literal #1a" %} {% comment %}Some random comment Some random comment Translators: Two-line translator comment #1 continued here. {% endcomment %} {% trans "Translatable literal #1b" %} {% comment %}Some random comment Translators: One-line translator comment #2 {% endcomment %} {% trans "Translatable literal #2a" %} {% comment %}Some random comment Translators: Two-line translator comment #2 continued here. {% endcomment %} {% trans "Translatable literal #2b" %} {% comment %} Translators: One-line translator comment #3 {% endcomment %} {% trans "Translatable literal #3a" %} {% comment %} Translators: Two-line translator comment #3 continued here. {% endcomment %} {% trans "Translatable literal #3b" %} {% comment %} Translators: One-line translator comment #4{% endcomment %} {% trans "Translatable literal #4a" %} {% comment %} Translators: Two-line translator comment #4 continued here.{% endcomment %} {% trans "Translatable literal #4b" %} {% comment %} Translators: One-line translator comment #5 -- with non ASCII characters: áéíóúö{% endcomment %} {% trans "Translatable literal #5a" %} {% comment %} Translators: Two-line translator comment #5 -- with non ASCII characters: áéíóúö continued here.{% endcomment %} {% trans "Translatable literal #6b" %} {% trans "Translatable literal #7a" context "Special trans context #1" %} {% trans "Translatable literal #7b" as var context "Special trans context #2" %} {% trans "Translatable literal #7c" context "Special trans context #3" as var %} {% trans "Translatable literal #7.1a" | upper context "context #7.1a" %} {% trans "Translatable literal #7.1b" |upper as var context "context #7.1b" %} {% trans "Translatable literal #7.1c"| upper context "context #7.1c" as var %} {% trans "Translatable literal #7.1d"|add:" foo" context "context #7.1d" %} {% trans "Translatable literal #7.1e"|add:' ûè本' as var context "context #7.1e" %} {% with foo=" foo" %} {% trans "Translatable literal #7.1f"|add:foo context "context #7.1f" as var %} {% endwith %} {% trans "Translatable literal #7.1g"|add:2 context "context #7.1g" as var %} {% trans "Translatable literal #7.1h" | add:"foo" | add:2 context "context #7.1h" as var %} <!-- Source file inside a msgid, should be left as-is. --> {% trans "#: templates/test.html.py" %} <!-- Deliberate duplicated string. --> {% trans "This literal should be included." %} {% blocktrans context "Special blocktrans context #1" %}Translatable literal #8a{% endblocktrans %} {% blocktrans count 2 context "Special blocktrans context #2" %}Translatable literal #8b-singular{% plural %}Translatable literal #8b-plural{% endblocktrans %} {% blocktrans context "Special blocktrans context #3" count 2 %}Translatable literal #8c-singular{% plural %}Translatable literal #8c-plural{% endblocktrans %} {% blocktrans with a=1 context "Special blocktrans context #4" %}Translatable literal #8d {{ a }}{% endblocktrans %} {% trans "Translatable literal with context wrapped in single quotes" context 'Context wrapped in single quotes' as var %} {% trans "Translatable literal with context wrapped in double quotes" context "Context wrapped in double quotes" as var %} {% blocktrans context 'Special blocktrans context wrapped in single quotes' %}Translatable literal with context wrapped in single quotes{% endblocktrans %} {% blocktrans context "Special blocktrans context wrapped in double quotes" %}Translatable literal with context wrapped in double quotes{% endblocktrans %} {# BasicExtractorTests.test_blocktrans_trimmed #} {% blocktrans %} Text with a few line breaks. {% endblocktrans %} {% blocktrans trimmed %} Again some text with a few line breaks, this time should be trimmed. {% endblocktrans %} {% trans "Get my line number" %} {% blocktrans trimmed count counter=mylist|length %} First `trans`, then `blocktrans` with a plural {% plural %} Plural for a `trans` and `blocktrans` collision case {% endblocktrans %} {% trans "Non-breaking space :" %}
camilonova/django
tests/i18n/commands/templates/test.html
HTML
bsd-3-clause
4,428
// Type definitions for babel-plugin-syntax-jsx 6.18 // Project: https://github.com/babel/babel/tree/master/packages/babel-plugin-syntax-jsx // Definitions by: Marvin Hagemeister <https://github.com/marvinhagemeister> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // NB: This export doesn't match the handbook example, where `jsx` is the default export. // But it does match the runtime behaviour (at least at the time of this writing). For some reason, // babel-plugin-syntax-jsx/lib/index.js has this line at the bottom: module.exports = exports["default"]; declare function jsx(): { manipulateOptions(opts: any, parserOpts: { plugins: string[] }): void; }; export default jsx;
borisyankov/DefinitelyTyped
types/babel-plugin-syntax-jsx/index.d.ts
TypeScript
mit
707
/* * Copyright (C) 2008 Matt Fleming <[email protected]> * Copyright (C) 2008 Paul Mundt <[email protected]> * * Code for replacing ftrace calls with jumps. * * Copyright (C) 2007-2008 Steven Rostedt <[email protected]> * * Thanks goes to Ingo Molnar, for suggesting the idea. * Mathieu Desnoyers, for suggesting postponing the modifications. * Arjan van de Ven, for keeping me straight, and explaining to me * the dangers of modifying code on the run. */ #include <linux/uaccess.h> #include <linux/ftrace.h> #include <linux/string.h> #include <linux/init.h> #include <linux/io.h> #include <linux/kernel.h> #include <asm/ftrace.h> #include <asm/cacheflush.h> #include <asm/unistd.h> #include <trace/syscall.h> #ifdef CONFIG_DYNAMIC_FTRACE static unsigned char ftrace_replaced_code[MCOUNT_INSN_SIZE]; static unsigned char ftrace_nop[4]; /* * If we're trying to nop out a call to a function, we instead * place a call to the address after the memory table. * * 8c011060 <a>: * 8c011060: 02 d1 mov.l 8c01106c <a+0xc>,r1 * 8c011062: 22 4f sts.l pr,@-r15 * 8c011064: 02 c7 mova 8c011070 <a+0x10>,r0 * 8c011066: 2b 41 jmp @r1 * 8c011068: 2a 40 lds r0,pr * 8c01106a: 09 00 nop * 8c01106c: 68 24 .word 0x2468 <--- ip * 8c01106e: 1d 8c .word 0x8c1d * 8c011070: 26 4f lds.l @r15+,pr <--- ip + MCOUNT_INSN_SIZE * * We write 0x8c011070 to 0x8c01106c so that on entry to a() we branch * past the _mcount call and continue executing code like normal. */ static unsigned char *ftrace_nop_replace(unsigned long ip) { __raw_writel(ip + MCOUNT_INSN_SIZE, ftrace_nop); return ftrace_nop; } static unsigned char *ftrace_call_replace(unsigned long ip, unsigned long addr) { /* Place the address in the memory table. */ __raw_writel(addr, ftrace_replaced_code); /* * No locking needed, this must be called via kstop_machine * which in essence is like running on a uniprocessor machine. */ return ftrace_replaced_code; } /* * Modifying code must take extra care. On an SMP machine, if * the code being modified is also being executed on another CPU * that CPU will have undefined results and possibly take a GPF. * We use kstop_machine to stop other CPUS from exectuing code. * But this does not stop NMIs from happening. We still need * to protect against that. We separate out the modification of * the code to take care of this. * * Two buffers are added: An IP buffer and a "code" buffer. * * 1) Put the instruction pointer into the IP buffer * and the new code into the "code" buffer. * 2) Wait for any running NMIs to finish and set a flag that says * we are modifying code, it is done in an atomic operation. * 3) Write the code * 4) clear the flag. * 5) Wait for any running NMIs to finish. * * If an NMI is executed, the first thing it does is to call * "ftrace_nmi_enter". This will check if the flag is set to write * and if it is, it will write what is in the IP and "code" buffers. * * The trick is, it does not matter if everyone is writing the same * content to the code location. Also, if a CPU is executing code * it is OK to write to that code location if the contents being written * are the same as what exists. */ #define MOD_CODE_WRITE_FLAG (1 << 31) /* set when NMI should do the write */ static atomic_t nmi_running = ATOMIC_INIT(0); static int mod_code_status; /* holds return value of text write */ static void *mod_code_ip; /* holds the IP to write to */ static void *mod_code_newcode; /* holds the text to write to the IP */ static unsigned nmi_wait_count; static atomic_t nmi_update_count = ATOMIC_INIT(0); int ftrace_arch_read_dyn_info(char *buf, int size) { int r; r = snprintf(buf, size, "%u %u", nmi_wait_count, atomic_read(&nmi_update_count)); return r; } static void clear_mod_flag(void) { int old = atomic_read(&nmi_running); for (;;) { int new = old & ~MOD_CODE_WRITE_FLAG; if (old == new) break; old = atomic_cmpxchg(&nmi_running, old, new); } } static void ftrace_mod_code(void) { /* * Yes, more than one CPU process can be writing to mod_code_status. * (and the code itself) * But if one were to fail, then they all should, and if one were * to succeed, then they all should. */ mod_code_status = probe_kernel_write(mod_code_ip, mod_code_newcode, MCOUNT_INSN_SIZE); /* if we fail, then kill any new writers */ if (mod_code_status) clear_mod_flag(); } void ftrace_nmi_enter(void) { if (atomic_inc_return(&nmi_running) & MOD_CODE_WRITE_FLAG) { smp_rmb(); ftrace_mod_code(); atomic_inc(&nmi_update_count); } /* Must have previous changes seen before executions */ smp_mb(); } void ftrace_nmi_exit(void) { /* Finish all executions before clearing nmi_running */ smp_mb(); atomic_dec(&nmi_running); } static void wait_for_nmi_and_set_mod_flag(void) { if (!atomic_cmpxchg(&nmi_running, 0, MOD_CODE_WRITE_FLAG)) return; do { cpu_relax(); } while (atomic_cmpxchg(&nmi_running, 0, MOD_CODE_WRITE_FLAG)); nmi_wait_count++; } static void wait_for_nmi(void) { if (!atomic_read(&nmi_running)) return; do { cpu_relax(); } while (atomic_read(&nmi_running)); nmi_wait_count++; } static int do_ftrace_mod_code(unsigned long ip, void *new_code) { mod_code_ip = (void *)ip; mod_code_newcode = new_code; /* The buffers need to be visible before we let NMIs write them */ smp_mb(); wait_for_nmi_and_set_mod_flag(); /* Make sure all running NMIs have finished before we write the code */ smp_mb(); ftrace_mod_code(); /* Make sure the write happens before clearing the bit */ smp_mb(); clear_mod_flag(); wait_for_nmi(); return mod_code_status; } static int ftrace_modify_code(unsigned long ip, unsigned char *old_code, unsigned char *new_code) { unsigned char replaced[MCOUNT_INSN_SIZE]; /* * Note: Due to modules and __init, code can * disappear and change, we need to protect against faulting * as well as code changing. We do this by using the * probe_kernel_* functions. * * No real locking needed, this code is run through * kstop_machine, or before SMP starts. */ /* read the text we want to modify */ if (probe_kernel_read(replaced, (void *)ip, MCOUNT_INSN_SIZE)) return -EFAULT; /* Make sure it is what we expect it to be */ if (memcmp(replaced, old_code, MCOUNT_INSN_SIZE) != 0) return -EINVAL; /* replace the text with the new text */ if (do_ftrace_mod_code(ip, new_code)) return -EPERM; flush_icache_range(ip, ip + MCOUNT_INSN_SIZE); return 0; } int ftrace_update_ftrace_func(ftrace_func_t func) { unsigned long ip = (unsigned long)(&ftrace_call) + MCOUNT_INSN_OFFSET; unsigned char old[MCOUNT_INSN_SIZE], *new; memcpy(old, (unsigned char *)ip, MCOUNT_INSN_SIZE); new = ftrace_call_replace(ip, (unsigned long)func); return ftrace_modify_code(ip, old, new); } int ftrace_make_nop(struct module *mod, struct dyn_ftrace *rec, unsigned long addr) { unsigned char *new, *old; unsigned long ip = rec->ip; old = ftrace_call_replace(ip, addr); new = ftrace_nop_replace(ip); return ftrace_modify_code(rec->ip, old, new); } int ftrace_make_call(struct dyn_ftrace *rec, unsigned long addr) { unsigned char *new, *old; unsigned long ip = rec->ip; old = ftrace_nop_replace(ip); new = ftrace_call_replace(ip, addr); return ftrace_modify_code(rec->ip, old, new); } int __init ftrace_dyn_arch_init(void *data) { /* The return code is retured via data */ __raw_writel(0, (unsigned long)data); return 0; } #endif /* CONFIG_DYNAMIC_FTRACE */ #ifdef CONFIG_FUNCTION_GRAPH_TRACER #ifdef CONFIG_DYNAMIC_FTRACE extern void ftrace_graph_call(void); static int ftrace_mod(unsigned long ip, unsigned long old_addr, unsigned long new_addr) { unsigned char code[MCOUNT_INSN_SIZE]; if (probe_kernel_read(code, (void *)ip, MCOUNT_INSN_SIZE)) return -EFAULT; if (old_addr != __raw_readl((unsigned long *)code)) return -EINVAL; __raw_writel(new_addr, ip); return 0; } int ftrace_enable_ftrace_graph_caller(void) { unsigned long ip, old_addr, new_addr; ip = (unsigned long)(&ftrace_graph_call) + GRAPH_INSN_OFFSET; old_addr = (unsigned long)(&skip_trace); new_addr = (unsigned long)(&ftrace_graph_caller); return ftrace_mod(ip, old_addr, new_addr); } int ftrace_disable_ftrace_graph_caller(void) { unsigned long ip, old_addr, new_addr; ip = (unsigned long)(&ftrace_graph_call) + GRAPH_INSN_OFFSET; old_addr = (unsigned long)(&ftrace_graph_caller); new_addr = (unsigned long)(&skip_trace); return ftrace_mod(ip, old_addr, new_addr); } #endif /* CONFIG_DYNAMIC_FTRACE */ /* * Hook the return address and push it in the stack of return addrs * in the current thread info. * * This is the main routine for the function graph tracer. The function * graph tracer essentially works like this: * * parent is the stack address containing self_addr's return address. * We pull the real return address out of parent and store it in * current's ret_stack. Then, we replace the return address on the stack * with the address of return_to_handler. self_addr is the function that * called mcount. * * When self_addr returns, it will jump to return_to_handler which calls * ftrace_return_to_handler. ftrace_return_to_handler will pull the real * return address off of current's ret_stack and jump to it. */ void prepare_ftrace_return(unsigned long *parent, unsigned long self_addr) { unsigned long old; int faulted, err; struct ftrace_graph_ent trace; unsigned long return_hooker = (unsigned long)&return_to_handler; if (unlikely(atomic_read(&current->tracing_graph_pause))) return; /* * Protect against fault, even if it shouldn't * happen. This tool is too much intrusive to * ignore such a protection. */ __asm__ __volatile__( "1: \n\t" "mov.l @%2, %0 \n\t" "2: \n\t" "mov.l %3, @%2 \n\t" "mov #0, %1 \n\t" "3: \n\t" ".section .fixup, \"ax\" \n\t" "4: \n\t" "mov.l 5f, %0 \n\t" "jmp @%0 \n\t" " mov #1, %1 \n\t" ".balign 4 \n\t" "5: .long 3b \n\t" ".previous \n\t" ".section __ex_table,\"a\" \n\t" ".long 1b, 4b \n\t" ".long 2b, 4b \n\t" ".previous \n\t" : "=&r" (old), "=r" (faulted) : "r" (parent), "r" (return_hooker) ); if (unlikely(faulted)) { ftrace_graph_stop(); WARN_ON(1); return; } err = ftrace_push_return_trace(old, self_addr, &trace.depth, 0); if (err == -EBUSY) { __raw_writel(old, parent); return; } trace.func = self_addr; /* Only trace if the calling function expects to */ if (!ftrace_graph_entry(&trace)) { current->curr_ret_stack--; __raw_writel(old, parent); } } #endif /* CONFIG_FUNCTION_GRAPH_TRACER */
talnoah/android_kernel_htc_dlx
virt/arch/sh/kernel/ftrace.c
C
gpl-2.0
10,865
/* YUI 3.15.0 (build 834026e) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('dd-drop', function (Y, NAME) { /** * Provides the ability to create a Drop Target. * @module dd * @submodule dd-drop */ /** * Provides the ability to create a Drop Target. * @class Drop * @extends Base * @constructor * @namespace DD */ var NODE = 'node', DDM = Y.DD.DDM, OFFSET_HEIGHT = 'offsetHeight', OFFSET_WIDTH = 'offsetWidth', /** * Fires when a drag element is over this target. * @event drop:over * @param {EventFacade} event An Event Facade object with the following specific property added: * <dl> * <dt>drop</dt><dd>The drop object at the time of the event.</dd> * <dt>drag</dt><dd>The drag object at the time of the event.</dd> * </dl> * @bubbles DDM * @type {CustomEvent} */ EV_DROP_OVER = 'drop:over', /** * Fires when a drag element enters this target. * @event drop:enter * @param {EventFacade} event An Event Facade object with the following specific property added: * <dl> * <dt>drop</dt><dd>The drop object at the time of the event.</dd> * <dt>drag</dt><dd>The drag object at the time of the event.</dd> * </dl> * @bubbles DDM * @type {CustomEvent} */ EV_DROP_ENTER = 'drop:enter', /** * Fires when a drag element exits this target. * @event drop:exit * @param {EventFacade} event An Event Facade object * @bubbles DDM * @type {CustomEvent} */ EV_DROP_EXIT = 'drop:exit', /** * Fires when a draggable node is dropped on this Drop Target. (Fired from dd-ddm-drop) * @event drop:hit * @param {EventFacade} event An Event Facade object with the following specific property added: * <dl> * <dt>drop</dt><dd>The best guess on what was dropped on.</dd> * <dt>drag</dt><dd>The drag object at the time of the event.</dd> * <dt>others</dt><dd>An array of all the other drop targets that was dropped on.</dd> * </dl> * @bubbles DDM * @type {CustomEvent} */ Drop = function() { this._lazyAddAttrs = false; Drop.superclass.constructor.apply(this, arguments); //DD init speed up. Y.on('domready', Y.bind(function() { Y.later(100, this, this._createShim); }, this)); DDM._regTarget(this); /* TODO if (Dom.getStyle(this.el, 'position') == 'fixed') { Event.on(window, 'scroll', function() { this.activateShim(); }, this, true); } */ }; Drop.NAME = 'drop'; Drop.ATTRS = { /** * Y.Node instance to use as the element to make a Drop Target * @attribute node * @type Node */ node: { setter: function(node) { var n = Y.one(node); if (!n) { Y.error('DD.Drop: Invalid Node Given: ' + node); } return n; } }, /** * Array of groups to add this drop into. * @attribute groups * @type Array */ groups: { value: ['default'], getter: function() { if (!this._groups) { this._groups = {}; return []; } return Y.Object.keys(this._groups); }, setter: function(g) { this._groups = Y.Array.hash(g); return g; } }, /** * CSS style padding to make the Drop Target bigger than the node. * @attribute padding * @type String */ padding: { value: '0', setter: function(p) { return DDM.cssSizestoObject(p); } }, /** * Set to lock this drop element. * @attribute lock * @type Boolean */ lock: { value: false, setter: function(lock) { if (lock) { this.get(NODE).addClass(DDM.CSS_PREFIX + '-drop-locked'); } else { this.get(NODE).removeClass(DDM.CSS_PREFIX + '-drop-locked'); } return lock; } }, /** * Controls the default bubble parent for this Drop instance. Default: Y.DD.DDM. Set to false to disable bubbling. * Use bubbleTargets in config. * @deprecated * @attribute bubbles * @type Object */ bubbles: { setter: function(t) { this.addTarget(t); return t; } }, /** * Use the Drop shim. Default: true * @deprecated * @attribute useShim * @type Boolean */ useShim: { value: true, setter: function(v) { Y.DD.DDM._noShim = !v; return v; } } }; Y.extend(Drop, Y.Base, { /** * The default bubbleTarget for this object. Default: Y.DD.DDM * @private * @property _bubbleTargets */ _bubbleTargets: Y.DD.DDM, /** * Add this Drop instance to a group, this should be used for on-the-fly group additions. * @method addToGroup * @param {String} g The group to add this Drop Instance to. * @chainable */ addToGroup: function(g) { this._groups[g] = true; return this; }, /** * Remove this Drop instance from a group, this should be used for on-the-fly group removals. * @method removeFromGroup * @param {String} g The group to remove this Drop Instance from. * @chainable */ removeFromGroup: function(g) { delete this._groups[g]; return this; }, /** * This method creates all the events for this Event Target and publishes them so we get Event Bubbling. * @private * @method _createEvents */ _createEvents: function() { var ev = [ EV_DROP_OVER, EV_DROP_ENTER, EV_DROP_EXIT, 'drop:hit' ]; Y.Array.each(ev, function(v) { this.publish(v, { type: v, emitFacade: true, preventable: false, bubbles: true, queuable: false, prefix: 'drop' }); }, this); }, /** * Flag for determining if the target is valid in this operation. * @private * @property _valid * @type Boolean */ _valid: null, /** * The groups this target belongs to. * @private * @property _groups * @type Array */ _groups: null, /** * Node reference to the targets shim * @property shim * @type {Object} */ shim: null, /** * A region object associated with this target, used for checking regions while dragging. * @property region * @type Object */ region: null, /** * This flag is tripped when a drag element is over this target. * @property overTarget * @type Boolean */ overTarget: null, /** * Check if this target is in one of the supplied groups. * @method inGroup * @param {Array} groups The groups to check against * @return Boolean */ inGroup: function(groups) { this._valid = false; var ret = false; Y.Array.each(groups, function(v) { if (this._groups[v]) { ret = true; this._valid = true; } }, this); return ret; }, /** * Private lifecycle method * @private * @method initializer */ initializer: function() { Y.later(100, this, this._createEvents); var node = this.get(NODE), id; if (!node.get('id')) { id = Y.stamp(node); node.set('id', id); } node.addClass(DDM.CSS_PREFIX + '-drop'); //Shouldn't have to do this.. this.set('groups', this.get('groups')); }, /** * Lifecycle destructor, unreg the drag from the DDM and remove listeners * @private * @method destructor */ destructor: function() { DDM._unregTarget(this); if (this.shim && (this.shim !== this.get(NODE))) { this.shim.detachAll(); this.shim.remove(); this.shim = null; } this.get(NODE).removeClass(DDM.CSS_PREFIX + '-drop'); this.detachAll(); }, /** * Removes classes from the target, resets some flags and sets the shims deactive position [-999, -999] * @private * @method _deactivateShim */ _deactivateShim: function() { if (!this.shim) { return false; } this.get(NODE).removeClass(DDM.CSS_PREFIX + '-drop-active-valid'); this.get(NODE).removeClass(DDM.CSS_PREFIX + '-drop-active-invalid'); this.get(NODE).removeClass(DDM.CSS_PREFIX + '-drop-over'); if (this.get('useShim')) { this.shim.setStyles({ top: '-999px', left: '-999px', zIndex: '1' }); } this.overTarget = false; }, /** * Activates the shim and adds some interaction CSS classes * @private * @method _activateShim */ _activateShim: function() { if (!DDM.activeDrag) { return false; //Nothing is dragging, no reason to activate. } if (this.get(NODE) === DDM.activeDrag.get(NODE)) { return false; } if (this.get('lock')) { return false; } var node = this.get(NODE); //TODO Visibility Check.. //if (this.inGroup(DDM.activeDrag.get('groups')) && this.get(NODE).isVisible()) { if (this.inGroup(DDM.activeDrag.get('groups'))) { node.removeClass(DDM.CSS_PREFIX + '-drop-active-invalid'); node.addClass(DDM.CSS_PREFIX + '-drop-active-valid'); DDM._addValid(this); this.overTarget = false; if (!this.get('useShim')) { this.shim = this.get(NODE); } this.sizeShim(); } else { DDM._removeValid(this); node.removeClass(DDM.CSS_PREFIX + '-drop-active-valid'); node.addClass(DDM.CSS_PREFIX + '-drop-active-invalid'); } }, /** * Positions and sizes the shim with the raw data from the node, * this can be used to programatically adjust the Targets shim for Animation.. * @method sizeShim */ sizeShim: function() { if (!DDM.activeDrag) { return false; //Nothing is dragging, no reason to activate. } if (this.get(NODE) === DDM.activeDrag.get(NODE)) { return false; } //if (this.get('lock') || !this.get('useShim')) { if (this.get('lock')) { return false; } if (!this.shim) { Y.later(100, this, this.sizeShim); return false; } var node = this.get(NODE), nh = node.get(OFFSET_HEIGHT), nw = node.get(OFFSET_WIDTH), xy = node.getXY(), p = this.get('padding'), dd, dH, dW; //Apply padding nw = nw + p.left + p.right; nh = nh + p.top + p.bottom; xy[0] = xy[0] - p.left; xy[1] = xy[1] - p.top; if (DDM.activeDrag.get('dragMode') === DDM.INTERSECT) { //Intersect Mode, make the shim bigger dd = DDM.activeDrag; dH = dd.get(NODE).get(OFFSET_HEIGHT); dW = dd.get(NODE).get(OFFSET_WIDTH); nh = (nh + dH); nw = (nw + dW); xy[0] = xy[0] - (dW - dd.deltaXY[0]); xy[1] = xy[1] - (dH - dd.deltaXY[1]); } if (this.get('useShim')) { //Set the style on the shim this.shim.setStyles({ height: nh + 'px', width: nw + 'px', top: xy[1] + 'px', left: xy[0] + 'px' }); } //Create the region to be used by intersect when a drag node is over us. this.region = { '0': xy[0], '1': xy[1], area: 0, top: xy[1], right: xy[0] + nw, bottom: xy[1] + nh, left: xy[0] }; }, /** * Creates the Target shim and adds it to the DDM's playground.. * @private * @method _createShim */ _createShim: function() { //No playground, defer if (!DDM._pg) { Y.later(10, this, this._createShim); return; } //Shim already here, cancel if (this.shim) { return; } var s = this.get('node'); if (this.get('useShim')) { s = Y.Node.create('<div id="' + this.get(NODE).get('id') + '_shim"></div>'); s.setStyles({ height: this.get(NODE).get(OFFSET_HEIGHT) + 'px', width: this.get(NODE).get(OFFSET_WIDTH) + 'px', backgroundColor: 'yellow', opacity: '.5', zIndex: '1', overflow: 'hidden', top: '-900px', left: '-900px', position: 'absolute' }); DDM._pg.appendChild(s); s.on('mouseover', Y.bind(this._handleOverEvent, this)); s.on('mouseout', Y.bind(this._handleOutEvent, this)); } this.shim = s; }, /** * This handles the over target call made from this object or from the DDM * @private * @method _handleOverTarget */ _handleTargetOver: function() { if (DDM.isOverTarget(this)) { this.get(NODE).addClass(DDM.CSS_PREFIX + '-drop-over'); DDM.activeDrop = this; DDM.otherDrops[this] = this; if (this.overTarget) { DDM.activeDrag.fire('drag:over', { drop: this, drag: DDM.activeDrag }); this.fire(EV_DROP_OVER, { drop: this, drag: DDM.activeDrag }); } else { //Prevent an enter before a start.. if (DDM.activeDrag.get('dragging')) { this.overTarget = true; this.fire(EV_DROP_ENTER, { drop: this, drag: DDM.activeDrag }); DDM.activeDrag.fire('drag:enter', { drop: this, drag: DDM.activeDrag }); DDM.activeDrag.get(NODE).addClass(DDM.CSS_PREFIX + '-drag-over'); //TODO - Is this needed?? //DDM._handleTargetOver(); } } } else { this._handleOut(); } }, /** * Handles the mouseover DOM event on the Target Shim * @private * @method _handleOverEvent */ _handleOverEvent: function() { this.shim.setStyle('zIndex', '999'); DDM._addActiveShim(this); }, /** * Handles the mouseout DOM event on the Target Shim * @private * @method _handleOutEvent */ _handleOutEvent: function() { this.shim.setStyle('zIndex', '1'); DDM._removeActiveShim(this); }, /** * Handles out of target calls/checks * @private * @method _handleOut */ _handleOut: function(force) { if (!DDM.isOverTarget(this) || force) { if (this.overTarget) { this.overTarget = false; if (!force) { DDM._removeActiveShim(this); } if (DDM.activeDrag) { this.get(NODE).removeClass(DDM.CSS_PREFIX + '-drop-over'); DDM.activeDrag.get(NODE).removeClass(DDM.CSS_PREFIX + '-drag-over'); this.fire(EV_DROP_EXIT, { drop: this, drag: DDM.activeDrag }); DDM.activeDrag.fire('drag:exit', { drop: this, drag: DDM.activeDrag }); delete DDM.otherDrops[this]; } } } } }); Y.DD.Drop = Drop; }, '3.15.0', {"requires": ["dd-drag", "dd-ddm-drop"]});
sameertechworks/wpmoodle
moodle/lib/yuilib/3.15.0/dd-drop/dd-drop.js
JavaScript
gpl-2.0
17,932
// cycle.js // 2011-08-24 /*jslint evil: true, regexp: true */ /*members $ref, apply, call, decycle, hasOwnProperty, length, prototype, push, retrocycle, stringify, test, toString */ var cycle = exports; cycle.decycle = function decycle(object) { 'use strict'; // Make a deep copy of an object or array, assuring that there is at most // one instance of each object or array in the resulting structure. The // duplicate references (which might be forming cycles) are replaced with // an object of the form // {$ref: PATH} // where the PATH is a JSONPath string that locates the first occurance. // So, // var a = []; // a[0] = a; // return JSON.stringify(JSON.decycle(a)); // produces the string '[{"$ref":"$"}]'. // JSONPath is used to locate the unique object. $ indicates the top level of // the object or array. [NUMBER] or [STRING] indicates a child member or // property. var objects = [], // Keep a reference to each unique object or array paths = []; // Keep the path to each unique object or array return (function derez(value, path) { // The derez recurses through the object, producing the deep copy. var i, // The loop counter name, // Property name nu; // The new object or array switch (typeof value) { case 'object': // typeof null === 'object', so get out if this value is not really an object. // Also get out if it is a weird builtin object. if (value === null || value instanceof Boolean || value instanceof Date || value instanceof Number || value instanceof RegExp || value instanceof String) { return value; } // If the value is an object or array, look to see if we have already // encountered it. If so, return a $ref/path object. This is a hard way, // linear search that will get slower as the number of unique objects grows. for (i = 0; i < objects.length; i += 1) { if (objects[i] === value) { return {$ref: paths[i]}; } } // Otherwise, accumulate the unique value and its path. objects.push(value); paths.push(path); // If it is an array, replicate the array. if (Object.prototype.toString.apply(value) === '[object Array]') { nu = []; for (i = 0; i < value.length; i += 1) { nu[i] = derez(value[i], path + '[' + i + ']'); } } else { // If it is an object, replicate the object. nu = {}; for (name in value) { if (Object.prototype.hasOwnProperty.call(value, name)) { nu[name] = derez(value[name], path + '[' + JSON.stringify(name) + ']'); } } } return nu; case 'number': case 'string': case 'boolean': return value; } }(object, '$')); }; cycle.retrocycle = function retrocycle($) { 'use strict'; // Restore an object that was reduced by decycle. Members whose values are // objects of the form // {$ref: PATH} // are replaced with references to the value found by the PATH. This will // restore cycles. The object will be mutated. // The eval function is used to locate the values described by a PATH. The // root object is kept in a $ variable. A regular expression is used to // assure that the PATH is extremely well formed. The regexp contains nested // * quantifiers. That has been known to have extremely bad performance // problems on some browsers for very long strings. A PATH is expected to be // reasonably short. A PATH is allowed to belong to a very restricted subset of // Goessner's JSONPath. // So, // var s = '[{"$ref":"$"}]'; // return JSON.retrocycle(JSON.parse(s)); // produces an array containing a single element which is the array itself. var px = /^\$(?:\[(?:\d+|\"(?:[^\\\"\u0000-\u001f]|\\([\\\"\/bfnrt]|u[0-9a-zA-Z]{4}))*\")\])*$/; (function rez(value) { // The rez function walks recursively through the object looking for $ref // properties. When it finds one that has a value that is a path, then it // replaces the $ref object with a reference to the value that is found by // the path. var i, item, name, path; if (value && typeof value === 'object') { if (Object.prototype.toString.apply(value) === '[object Array]') { for (i = 0; i < value.length; i += 1) { item = value[i]; if (item && typeof item === 'object') { path = item.$ref; if (typeof path === 'string' && px.test(path)) { value[i] = eval(path); } else { rez(item); } } } } else { for (name in value) { if (typeof value[name] === 'object') { item = value[name]; if (item) { path = item.$ref; if (typeof path === 'string' && px.test(path)) { value[name] = eval(path); } else { rez(item); } } } } } } }($)); return $; };
waganse/pj_admin
work/node_modules/grunt-ftp-deploy/node_modules/prompt/node_modules/winston/node_modules/cycle/cycle.js
JavaScript
mit
5,687
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html><head><title></title> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta name="generator" content="Doxygen 1.8.11"/> <link rel="stylesheet" type="text/css" href="search.css"/> <script type="text/javascript" src="classes_d.js"></script> <script type="text/javascript" src="search.js"></script> </head> <body class="SRPage"> <div id="SRIndex"> <div class="SRStatus" id="Loading">Loading...</div> <div id="SRResults"></div> <script type="text/javascript"><!-- createResults(); --></script> <div class="SRStatus" id="Searching">Searching...</div> <div class="SRStatus" id="NoMatches">No Matches</div> <script type="text/javascript"><!-- document.getElementById("Loading").style.display="none"; document.getElementById("NoMatches").style.display="none"; var searchResults = new SearchResults("searchResults"); searchResults.Search(); --></script> </div> </body> </html>
kipr/harrogate
shared/client/doc/search/classes_d.html
HTML
gpl-3.0
1,017
! { dg-do run } ! ! Contributed by by Richard Maine ! http://coding.derkeiler.com/Archive/Fortran/comp.lang.fortran/2006-10/msg00104.html ! module poly_list !-- Polymorphic lists using type extension. implicit none type, public :: node_type private class(node_type), pointer :: next => null() end type node_type type, public :: list_type private class(node_type), pointer :: head => null(), tail => null() end type list_type contains subroutine append_node (list, new_node) !-- Append a node to a list. !-- Caller is responsible for allocating the node. !---------- interface. type(list_type), intent(inout) :: list class(node_type), target :: new_node !---------- executable code. if (.not.associated(list%head)) list%head => new_node if (associated(list%tail)) list%tail%next => new_node list%tail => new_node return end subroutine append_node function first_node (list) !-- Get the first node of a list. !---------- interface. type(list_type), intent(in) :: list class(node_type), pointer :: first_node !---------- executable code. first_node => list%head return end function first_node function next_node (node) !-- Step to the next node of a list. !---------- interface. class(node_type), target :: node class(node_type), pointer :: next_node !---------- executable code. next_node => node%next return end function next_node subroutine destroy_list (list) !-- Delete (and deallocate) all the nodes of a list. !---------- interface. type(list_type), intent(inout) :: list !---------- local. class(node_type), pointer :: node, next !---------- executable code. node => list%head do while (associated(node)) next => node%next deallocate(node) node => next end do nullify(list%head, list%tail) return end subroutine destroy_list end module poly_list program main use poly_list implicit none integer :: cnt type, extends(node_type) :: real_node_type real :: x end type real_node_type type, extends(node_type) :: integer_node_type integer :: i end type integer_node_type type, extends(node_type) :: character_node_type character(1) :: c end type character_node_type type(list_type) :: list class(node_type), pointer :: node type(integer_node_type), pointer :: integer_node type(real_node_type), pointer :: real_node type(character_node_type), pointer :: character_node !---------- executable code. !----- Build the list. allocate(real_node) real_node%x = 1.23 call append_node(list, real_node) allocate(integer_node) integer_node%i = 42 call append_node(list, integer_node) allocate(node) call append_node(list, node) allocate(character_node) character_node%c = "z" call append_node(list, character_node) allocate(real_node) real_node%x = 4.56 call append_node(list, real_node) !----- Retrieve from it. node => first_node(list) cnt = 0 do while (associated(node)) cnt = cnt + 1 select type (node) type is (real_node_type) write (*,*) node%x if (.not.( (cnt == 1 .and. node%x == 1.23) & .or. (cnt == 5 .and. node%x == 4.56))) then call abort() end if type is (integer_node_type) write (*,*) node%i if (cnt /= 2 .or. node%i /= 42) call abort() type is (node_type) write (*,*) "Node with no data." if (cnt /= 3) call abort() class default Write (*,*) "Some other node type." if (cnt /= 4) call abort() end select node => next_node(node) end do if (cnt /= 5) call abort() call destroy_list(list) stop end program main
selmentdev/selment-toolchain
source/gcc-latest/gcc/testsuite/gfortran.dg/select_type_4.f90
FORTRAN
gpl-3.0
3,904
/* * net/key/af_key.c An implementation of PF_KEYv2 sockets. * * 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. * * Authors: Maxim Giryaev <[email protected]> * David S. Miller <[email protected]> * Alexey Kuznetsov <[email protected]> * Kunihiro Ishiguro <[email protected]> * Kazunori MIYAZAWA / USAGI Project <[email protected]> * Derek Atkins <[email protected]> */ #include <linux/capability.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/socket.h> #include <linux/pfkeyv2.h> #include <linux/ipsec.h> #include <linux/skbuff.h> #include <linux/rtnetlink.h> #include <linux/in.h> #include <linux/in6.h> #include <linux/proc_fs.h> #include <linux/init.h> #include <net/net_namespace.h> #include <net/netns/generic.h> #include <net/xfrm.h> #include <net/sock.h> #define _X2KEY(x) ((x) == XFRM_INF ? 0 : (x)) #define _KEY2X(x) ((x) == 0 ? XFRM_INF : (x)) static int pfkey_net_id; struct netns_pfkey { /* List of all pfkey sockets. */ struct hlist_head table; atomic_t socks_nr; }; static DECLARE_WAIT_QUEUE_HEAD(pfkey_table_wait); static DEFINE_RWLOCK(pfkey_table_lock); static atomic_t pfkey_table_users = ATOMIC_INIT(0); struct pfkey_sock { /* struct sock must be the first member of struct pfkey_sock */ struct sock sk; int registered; int promisc; struct { uint8_t msg_version; uint32_t msg_pid; int (*dump)(struct pfkey_sock *sk); void (*done)(struct pfkey_sock *sk); union { struct xfrm_policy_walk policy; struct xfrm_state_walk state; } u; struct sk_buff *skb; } dump; }; static inline struct pfkey_sock *pfkey_sk(struct sock *sk) { return (struct pfkey_sock *)sk; } static int pfkey_can_dump(struct sock *sk) { if (3 * atomic_read(&sk->sk_rmem_alloc) <= 2 * sk->sk_rcvbuf) return 1; return 0; } static void pfkey_terminate_dump(struct pfkey_sock *pfk) { if (pfk->dump.dump) { if (pfk->dump.skb) { kfree_skb(pfk->dump.skb); pfk->dump.skb = NULL; } pfk->dump.done(pfk); pfk->dump.dump = NULL; pfk->dump.done = NULL; } } static void pfkey_sock_destruct(struct sock *sk) { struct net *net = sock_net(sk); struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); pfkey_terminate_dump(pfkey_sk(sk)); skb_queue_purge(&sk->sk_receive_queue); if (!sock_flag(sk, SOCK_DEAD)) { printk("Attempt to release alive pfkey socket: %p\n", sk); return; } WARN_ON(atomic_read(&sk->sk_rmem_alloc)); WARN_ON(atomic_read(&sk->sk_wmem_alloc)); atomic_dec(&net_pfkey->socks_nr); } static void pfkey_table_grab(void) { write_lock_bh(&pfkey_table_lock); if (atomic_read(&pfkey_table_users)) { DECLARE_WAITQUEUE(wait, current); add_wait_queue_exclusive(&pfkey_table_wait, &wait); for(;;) { set_current_state(TASK_UNINTERRUPTIBLE); if (atomic_read(&pfkey_table_users) == 0) break; write_unlock_bh(&pfkey_table_lock); schedule(); write_lock_bh(&pfkey_table_lock); } __set_current_state(TASK_RUNNING); remove_wait_queue(&pfkey_table_wait, &wait); } } static __inline__ void pfkey_table_ungrab(void) { write_unlock_bh(&pfkey_table_lock); wake_up(&pfkey_table_wait); } static __inline__ void pfkey_lock_table(void) { /* read_lock() synchronizes us to pfkey_table_grab */ read_lock(&pfkey_table_lock); atomic_inc(&pfkey_table_users); read_unlock(&pfkey_table_lock); } static __inline__ void pfkey_unlock_table(void) { if (atomic_dec_and_test(&pfkey_table_users)) wake_up(&pfkey_table_wait); } static const struct proto_ops pfkey_ops; static void pfkey_insert(struct sock *sk) { struct net *net = sock_net(sk); struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); pfkey_table_grab(); sk_add_node(sk, &net_pfkey->table); pfkey_table_ungrab(); } static void pfkey_remove(struct sock *sk) { pfkey_table_grab(); sk_del_node_init(sk); pfkey_table_ungrab(); } static struct proto key_proto = { .name = "KEY", .owner = THIS_MODULE, .obj_size = sizeof(struct pfkey_sock), }; static int pfkey_create(struct net *net, struct socket *sock, int protocol) { struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); struct sock *sk; int err; if (!capable(CAP_NET_ADMIN)) return -EPERM; if (sock->type != SOCK_RAW) return -ESOCKTNOSUPPORT; if (protocol != PF_KEY_V2) return -EPROTONOSUPPORT; err = -ENOMEM; sk = sk_alloc(net, PF_KEY, GFP_KERNEL, &key_proto); if (sk == NULL) goto out; sock->ops = &pfkey_ops; sock_init_data(sock, sk); sk->sk_family = PF_KEY; sk->sk_destruct = pfkey_sock_destruct; atomic_inc(&net_pfkey->socks_nr); pfkey_insert(sk); return 0; out: return err; } static int pfkey_release(struct socket *sock) { struct sock *sk = sock->sk; if (!sk) return 0; pfkey_remove(sk); sock_orphan(sk); sock->sk = NULL; skb_queue_purge(&sk->sk_write_queue); sock_put(sk); return 0; } static int pfkey_broadcast_one(struct sk_buff *skb, struct sk_buff **skb2, gfp_t allocation, struct sock *sk) { int err = -ENOBUFS; sock_hold(sk); if (*skb2 == NULL) { if (atomic_read(&skb->users) != 1) { *skb2 = skb_clone(skb, allocation); } else { *skb2 = skb; atomic_inc(&skb->users); } } if (*skb2 != NULL) { if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf) { skb_orphan(*skb2); skb_set_owner_r(*skb2, sk); skb_queue_tail(&sk->sk_receive_queue, *skb2); sk->sk_data_ready(sk, (*skb2)->len); *skb2 = NULL; err = 0; } } sock_put(sk); return err; } /* Send SKB to all pfkey sockets matching selected criteria. */ #define BROADCAST_ALL 0 #define BROADCAST_ONE 1 #define BROADCAST_REGISTERED 2 #define BROADCAST_PROMISC_ONLY 4 static int pfkey_broadcast(struct sk_buff *skb, gfp_t allocation, int broadcast_flags, struct sock *one_sk, struct net *net) { struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); struct sock *sk; struct hlist_node *node; struct sk_buff *skb2 = NULL; int err = -ESRCH; /* XXX Do we need something like netlink_overrun? I think * XXX PF_KEY socket apps will not mind current behavior. */ if (!skb) return -ENOMEM; pfkey_lock_table(); sk_for_each(sk, node, &net_pfkey->table) { struct pfkey_sock *pfk = pfkey_sk(sk); int err2; /* Yes, it means that if you are meant to receive this * pfkey message you receive it twice as promiscuous * socket. */ if (pfk->promisc) pfkey_broadcast_one(skb, &skb2, allocation, sk); /* the exact target will be processed later */ if (sk == one_sk) continue; if (broadcast_flags != BROADCAST_ALL) { if (broadcast_flags & BROADCAST_PROMISC_ONLY) continue; if ((broadcast_flags & BROADCAST_REGISTERED) && !pfk->registered) continue; if (broadcast_flags & BROADCAST_ONE) continue; } err2 = pfkey_broadcast_one(skb, &skb2, allocation, sk); /* Error is cleare after succecful sending to at least one * registered KM */ if ((broadcast_flags & BROADCAST_REGISTERED) && err) err = err2; } pfkey_unlock_table(); if (one_sk != NULL) err = pfkey_broadcast_one(skb, &skb2, allocation, one_sk); if (skb2) kfree_skb(skb2); kfree_skb(skb); return err; } static int pfkey_do_dump(struct pfkey_sock *pfk) { struct sadb_msg *hdr; int rc; rc = pfk->dump.dump(pfk); if (rc == -ENOBUFS) return 0; if (pfk->dump.skb) { if (!pfkey_can_dump(&pfk->sk)) return 0; hdr = (struct sadb_msg *) pfk->dump.skb->data; hdr->sadb_msg_seq = 0; hdr->sadb_msg_errno = rc; pfkey_broadcast(pfk->dump.skb, GFP_ATOMIC, BROADCAST_ONE, &pfk->sk, sock_net(&pfk->sk)); pfk->dump.skb = NULL; } pfkey_terminate_dump(pfk); return rc; } static inline void pfkey_hdr_dup(struct sadb_msg *new, struct sadb_msg *orig) { *new = *orig; } static int pfkey_error(struct sadb_msg *orig, int err, struct sock *sk) { struct sk_buff *skb = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_KERNEL); struct sadb_msg *hdr; if (!skb) return -ENOBUFS; /* Woe be to the platform trying to support PFKEY yet * having normal errnos outside the 1-255 range, inclusive. */ err = -err; if (err == ERESTARTSYS || err == ERESTARTNOHAND || err == ERESTARTNOINTR) err = EINTR; if (err >= 512) err = EINVAL; BUG_ON(err <= 0 || err >= 256); hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg)); pfkey_hdr_dup(hdr, orig); hdr->sadb_msg_errno = (uint8_t) err; hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t)); pfkey_broadcast(skb, GFP_KERNEL, BROADCAST_ONE, sk, sock_net(sk)); return 0; } static u8 sadb_ext_min_len[] = { [SADB_EXT_RESERVED] = (u8) 0, [SADB_EXT_SA] = (u8) sizeof(struct sadb_sa), [SADB_EXT_LIFETIME_CURRENT] = (u8) sizeof(struct sadb_lifetime), [SADB_EXT_LIFETIME_HARD] = (u8) sizeof(struct sadb_lifetime), [SADB_EXT_LIFETIME_SOFT] = (u8) sizeof(struct sadb_lifetime), [SADB_EXT_ADDRESS_SRC] = (u8) sizeof(struct sadb_address), [SADB_EXT_ADDRESS_DST] = (u8) sizeof(struct sadb_address), [SADB_EXT_ADDRESS_PROXY] = (u8) sizeof(struct sadb_address), [SADB_EXT_KEY_AUTH] = (u8) sizeof(struct sadb_key), [SADB_EXT_KEY_ENCRYPT] = (u8) sizeof(struct sadb_key), [SADB_EXT_IDENTITY_SRC] = (u8) sizeof(struct sadb_ident), [SADB_EXT_IDENTITY_DST] = (u8) sizeof(struct sadb_ident), [SADB_EXT_SENSITIVITY] = (u8) sizeof(struct sadb_sens), [SADB_EXT_PROPOSAL] = (u8) sizeof(struct sadb_prop), [SADB_EXT_SUPPORTED_AUTH] = (u8) sizeof(struct sadb_supported), [SADB_EXT_SUPPORTED_ENCRYPT] = (u8) sizeof(struct sadb_supported), [SADB_EXT_SPIRANGE] = (u8) sizeof(struct sadb_spirange), [SADB_X_EXT_KMPRIVATE] = (u8) sizeof(struct sadb_x_kmprivate), [SADB_X_EXT_POLICY] = (u8) sizeof(struct sadb_x_policy), [SADB_X_EXT_SA2] = (u8) sizeof(struct sadb_x_sa2), [SADB_X_EXT_NAT_T_TYPE] = (u8) sizeof(struct sadb_x_nat_t_type), [SADB_X_EXT_NAT_T_SPORT] = (u8) sizeof(struct sadb_x_nat_t_port), [SADB_X_EXT_NAT_T_DPORT] = (u8) sizeof(struct sadb_x_nat_t_port), [SADB_X_EXT_NAT_T_OA] = (u8) sizeof(struct sadb_address), [SADB_X_EXT_SEC_CTX] = (u8) sizeof(struct sadb_x_sec_ctx), [SADB_X_EXT_KMADDRESS] = (u8) sizeof(struct sadb_x_kmaddress), }; /* Verify sadb_address_{len,prefixlen} against sa_family. */ static int verify_address_len(void *p) { struct sadb_address *sp = p; struct sockaddr *addr = (struct sockaddr *)(sp + 1); struct sockaddr_in *sin; #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) struct sockaddr_in6 *sin6; #endif int len; switch (addr->sa_family) { case AF_INET: len = DIV_ROUND_UP(sizeof(*sp) + sizeof(*sin), sizeof(uint64_t)); if (sp->sadb_address_len != len || sp->sadb_address_prefixlen > 32) return -EINVAL; break; #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) case AF_INET6: len = DIV_ROUND_UP(sizeof(*sp) + sizeof(*sin6), sizeof(uint64_t)); if (sp->sadb_address_len != len || sp->sadb_address_prefixlen > 128) return -EINVAL; break; #endif default: /* It is user using kernel to keep track of security * associations for another protocol, such as * OSPF/RSVP/RIPV2/MIP. It is user's job to verify * lengths. * * XXX Actually, association/policy database is not yet * XXX able to cope with arbitrary sockaddr families. * XXX When it can, remove this -EINVAL. -DaveM */ return -EINVAL; break; } return 0; } static inline int pfkey_sec_ctx_len(struct sadb_x_sec_ctx *sec_ctx) { return DIV_ROUND_UP(sizeof(struct sadb_x_sec_ctx) + sec_ctx->sadb_x_ctx_len, sizeof(uint64_t)); } static inline int verify_sec_ctx_len(void *p) { struct sadb_x_sec_ctx *sec_ctx = (struct sadb_x_sec_ctx *)p; int len = sec_ctx->sadb_x_ctx_len; if (len > PAGE_SIZE) return -EINVAL; len = pfkey_sec_ctx_len(sec_ctx); if (sec_ctx->sadb_x_sec_len != len) return -EINVAL; return 0; } static inline struct xfrm_user_sec_ctx *pfkey_sadb2xfrm_user_sec_ctx(struct sadb_x_sec_ctx *sec_ctx) { struct xfrm_user_sec_ctx *uctx = NULL; int ctx_size = sec_ctx->sadb_x_ctx_len; uctx = kmalloc((sizeof(*uctx)+ctx_size), GFP_KERNEL); if (!uctx) return NULL; uctx->len = pfkey_sec_ctx_len(sec_ctx); uctx->exttype = sec_ctx->sadb_x_sec_exttype; uctx->ctx_doi = sec_ctx->sadb_x_ctx_doi; uctx->ctx_alg = sec_ctx->sadb_x_ctx_alg; uctx->ctx_len = sec_ctx->sadb_x_ctx_len; memcpy(uctx + 1, sec_ctx + 1, uctx->ctx_len); return uctx; } static int present_and_same_family(struct sadb_address *src, struct sadb_address *dst) { struct sockaddr *s_addr, *d_addr; if (!src || !dst) return 0; s_addr = (struct sockaddr *)(src + 1); d_addr = (struct sockaddr *)(dst + 1); if (s_addr->sa_family != d_addr->sa_family) return 0; if (s_addr->sa_family != AF_INET #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) && s_addr->sa_family != AF_INET6 #endif ) return 0; return 1; } static int parse_exthdrs(struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs) { char *p = (char *) hdr; int len = skb->len; len -= sizeof(*hdr); p += sizeof(*hdr); while (len > 0) { struct sadb_ext *ehdr = (struct sadb_ext *) p; uint16_t ext_type; int ext_len; ext_len = ehdr->sadb_ext_len; ext_len *= sizeof(uint64_t); ext_type = ehdr->sadb_ext_type; if (ext_len < sizeof(uint64_t) || ext_len > len || ext_type == SADB_EXT_RESERVED) return -EINVAL; if (ext_type <= SADB_EXT_MAX) { int min = (int) sadb_ext_min_len[ext_type]; if (ext_len < min) return -EINVAL; if (ext_hdrs[ext_type-1] != NULL) return -EINVAL; if (ext_type == SADB_EXT_ADDRESS_SRC || ext_type == SADB_EXT_ADDRESS_DST || ext_type == SADB_EXT_ADDRESS_PROXY || ext_type == SADB_X_EXT_NAT_T_OA) { if (verify_address_len(p)) return -EINVAL; } if (ext_type == SADB_X_EXT_SEC_CTX) { if (verify_sec_ctx_len(p)) return -EINVAL; } ext_hdrs[ext_type-1] = p; } p += ext_len; len -= ext_len; } return 0; } static uint16_t pfkey_satype2proto(uint8_t satype) { switch (satype) { case SADB_SATYPE_UNSPEC: return IPSEC_PROTO_ANY; case SADB_SATYPE_AH: return IPPROTO_AH; case SADB_SATYPE_ESP: return IPPROTO_ESP; case SADB_X_SATYPE_IPCOMP: return IPPROTO_COMP; break; default: return 0; } /* NOTREACHED */ } static uint8_t pfkey_proto2satype(uint16_t proto) { switch (proto) { case IPPROTO_AH: return SADB_SATYPE_AH; case IPPROTO_ESP: return SADB_SATYPE_ESP; case IPPROTO_COMP: return SADB_X_SATYPE_IPCOMP; break; default: return 0; } /* NOTREACHED */ } /* BTW, this scheme means that there is no way with PFKEY2 sockets to * say specifically 'just raw sockets' as we encode them as 255. */ static uint8_t pfkey_proto_to_xfrm(uint8_t proto) { return (proto == IPSEC_PROTO_ANY ? 0 : proto); } static uint8_t pfkey_proto_from_xfrm(uint8_t proto) { return (proto ? proto : IPSEC_PROTO_ANY); } static inline int pfkey_sockaddr_len(sa_family_t family) { switch (family) { case AF_INET: return sizeof(struct sockaddr_in); #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) case AF_INET6: return sizeof(struct sockaddr_in6); #endif } return 0; } static int pfkey_sockaddr_extract(const struct sockaddr *sa, xfrm_address_t *xaddr) { switch (sa->sa_family) { case AF_INET: xaddr->a4 = ((struct sockaddr_in *)sa)->sin_addr.s_addr; return AF_INET; #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) case AF_INET6: memcpy(xaddr->a6, &((struct sockaddr_in6 *)sa)->sin6_addr, sizeof(struct in6_addr)); return AF_INET6; #endif } return 0; } static int pfkey_sadb_addr2xfrm_addr(struct sadb_address *addr, xfrm_address_t *xaddr) { return pfkey_sockaddr_extract((struct sockaddr *)(addr + 1), xaddr); } static struct xfrm_state *pfkey_xfrm_state_lookup(struct net *net, struct sadb_msg *hdr, void **ext_hdrs) { struct sadb_sa *sa; struct sadb_address *addr; uint16_t proto; unsigned short family; xfrm_address_t *xaddr; sa = (struct sadb_sa *) ext_hdrs[SADB_EXT_SA-1]; if (sa == NULL) return NULL; proto = pfkey_satype2proto(hdr->sadb_msg_satype); if (proto == 0) return NULL; /* sadb_address_len should be checked by caller */ addr = (struct sadb_address *) ext_hdrs[SADB_EXT_ADDRESS_DST-1]; if (addr == NULL) return NULL; family = ((struct sockaddr *)(addr + 1))->sa_family; switch (family) { case AF_INET: xaddr = (xfrm_address_t *)&((struct sockaddr_in *)(addr + 1))->sin_addr; break; #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) case AF_INET6: xaddr = (xfrm_address_t *)&((struct sockaddr_in6 *)(addr + 1))->sin6_addr; break; #endif default: xaddr = NULL; } if (!xaddr) return NULL; return xfrm_state_lookup(net, xaddr, sa->sadb_sa_spi, proto, family); } #define PFKEY_ALIGN8(a) (1 + (((a) - 1) | (8 - 1))) static int pfkey_sockaddr_size(sa_family_t family) { return PFKEY_ALIGN8(pfkey_sockaddr_len(family)); } static inline int pfkey_mode_from_xfrm(int mode) { switch(mode) { case XFRM_MODE_TRANSPORT: return IPSEC_MODE_TRANSPORT; case XFRM_MODE_TUNNEL: return IPSEC_MODE_TUNNEL; case XFRM_MODE_BEET: return IPSEC_MODE_BEET; default: return -1; } } static inline int pfkey_mode_to_xfrm(int mode) { switch(mode) { case IPSEC_MODE_ANY: /*XXX*/ case IPSEC_MODE_TRANSPORT: return XFRM_MODE_TRANSPORT; case IPSEC_MODE_TUNNEL: return XFRM_MODE_TUNNEL; case IPSEC_MODE_BEET: return XFRM_MODE_BEET; default: return -1; } } static unsigned int pfkey_sockaddr_fill(xfrm_address_t *xaddr, __be16 port, struct sockaddr *sa, unsigned short family) { switch (family) { case AF_INET: { struct sockaddr_in *sin = (struct sockaddr_in *)sa; sin->sin_family = AF_INET; sin->sin_port = port; sin->sin_addr.s_addr = xaddr->a4; memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); return 32; } #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) case AF_INET6: { struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa; sin6->sin6_family = AF_INET6; sin6->sin6_port = port; sin6->sin6_flowinfo = 0; ipv6_addr_copy(&sin6->sin6_addr, (struct in6_addr *)xaddr->a6); sin6->sin6_scope_id = 0; return 128; } #endif } return 0; } static struct sk_buff *__pfkey_xfrm_state2msg(struct xfrm_state *x, int add_keys, int hsc) { struct sk_buff *skb; struct sadb_msg *hdr; struct sadb_sa *sa; struct sadb_lifetime *lifetime; struct sadb_address *addr; struct sadb_key *key; struct sadb_x_sa2 *sa2; struct sadb_x_sec_ctx *sec_ctx; struct xfrm_sec_ctx *xfrm_ctx; int ctx_size = 0; int size; int auth_key_size = 0; int encrypt_key_size = 0; int sockaddr_size; struct xfrm_encap_tmpl *natt = NULL; int mode; /* address family check */ sockaddr_size = pfkey_sockaddr_size(x->props.family); if (!sockaddr_size) return ERR_PTR(-EINVAL); /* base, SA, (lifetime (HSC),) address(SD), (address(P),) key(AE), (identity(SD),) (sensitivity)> */ size = sizeof(struct sadb_msg) +sizeof(struct sadb_sa) + sizeof(struct sadb_lifetime) + ((hsc & 1) ? sizeof(struct sadb_lifetime) : 0) + ((hsc & 2) ? sizeof(struct sadb_lifetime) : 0) + sizeof(struct sadb_address)*2 + sockaddr_size*2 + sizeof(struct sadb_x_sa2); if ((xfrm_ctx = x->security)) { ctx_size = PFKEY_ALIGN8(xfrm_ctx->ctx_len); size += sizeof(struct sadb_x_sec_ctx) + ctx_size; } /* identity & sensitivity */ if (xfrm_addr_cmp(&x->sel.saddr, &x->props.saddr, x->props.family)) size += sizeof(struct sadb_address) + sockaddr_size; if (add_keys) { if (x->aalg && x->aalg->alg_key_len) { auth_key_size = PFKEY_ALIGN8((x->aalg->alg_key_len + 7) / 8); size += sizeof(struct sadb_key) + auth_key_size; } if (x->ealg && x->ealg->alg_key_len) { encrypt_key_size = PFKEY_ALIGN8((x->ealg->alg_key_len+7) / 8); size += sizeof(struct sadb_key) + encrypt_key_size; } } if (x->encap) natt = x->encap; if (natt && natt->encap_type) { size += sizeof(struct sadb_x_nat_t_type); size += sizeof(struct sadb_x_nat_t_port); size += sizeof(struct sadb_x_nat_t_port); } skb = alloc_skb(size + 16, GFP_ATOMIC); if (skb == NULL) return ERR_PTR(-ENOBUFS); /* call should fill header later */ hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg)); memset(hdr, 0, size); /* XXX do we need this ? */ hdr->sadb_msg_len = size / sizeof(uint64_t); /* sa */ sa = (struct sadb_sa *) skb_put(skb, sizeof(struct sadb_sa)); sa->sadb_sa_len = sizeof(struct sadb_sa)/sizeof(uint64_t); sa->sadb_sa_exttype = SADB_EXT_SA; sa->sadb_sa_spi = x->id.spi; sa->sadb_sa_replay = x->props.replay_window; switch (x->km.state) { case XFRM_STATE_VALID: sa->sadb_sa_state = x->km.dying ? SADB_SASTATE_DYING : SADB_SASTATE_MATURE; break; case XFRM_STATE_ACQ: sa->sadb_sa_state = SADB_SASTATE_LARVAL; break; default: sa->sadb_sa_state = SADB_SASTATE_DEAD; break; } sa->sadb_sa_auth = 0; if (x->aalg) { struct xfrm_algo_desc *a = xfrm_aalg_get_byname(x->aalg->alg_name, 0); sa->sadb_sa_auth = a ? a->desc.sadb_alg_id : 0; } sa->sadb_sa_encrypt = 0; BUG_ON(x->ealg && x->calg); if (x->ealg) { struct xfrm_algo_desc *a = xfrm_ealg_get_byname(x->ealg->alg_name, 0); sa->sadb_sa_encrypt = a ? a->desc.sadb_alg_id : 0; } /* KAME compatible: sadb_sa_encrypt is overloaded with calg id */ if (x->calg) { struct xfrm_algo_desc *a = xfrm_calg_get_byname(x->calg->alg_name, 0); sa->sadb_sa_encrypt = a ? a->desc.sadb_alg_id : 0; } sa->sadb_sa_flags = 0; if (x->props.flags & XFRM_STATE_NOECN) sa->sadb_sa_flags |= SADB_SAFLAGS_NOECN; if (x->props.flags & XFRM_STATE_DECAP_DSCP) sa->sadb_sa_flags |= SADB_SAFLAGS_DECAP_DSCP; if (x->props.flags & XFRM_STATE_NOPMTUDISC) sa->sadb_sa_flags |= SADB_SAFLAGS_NOPMTUDISC; /* hard time */ if (hsc & 2) { lifetime = (struct sadb_lifetime *) skb_put(skb, sizeof(struct sadb_lifetime)); lifetime->sadb_lifetime_len = sizeof(struct sadb_lifetime)/sizeof(uint64_t); lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD; lifetime->sadb_lifetime_allocations = _X2KEY(x->lft.hard_packet_limit); lifetime->sadb_lifetime_bytes = _X2KEY(x->lft.hard_byte_limit); lifetime->sadb_lifetime_addtime = x->lft.hard_add_expires_seconds; lifetime->sadb_lifetime_usetime = x->lft.hard_use_expires_seconds; } /* soft time */ if (hsc & 1) { lifetime = (struct sadb_lifetime *) skb_put(skb, sizeof(struct sadb_lifetime)); lifetime->sadb_lifetime_len = sizeof(struct sadb_lifetime)/sizeof(uint64_t); lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT; lifetime->sadb_lifetime_allocations = _X2KEY(x->lft.soft_packet_limit); lifetime->sadb_lifetime_bytes = _X2KEY(x->lft.soft_byte_limit); lifetime->sadb_lifetime_addtime = x->lft.soft_add_expires_seconds; lifetime->sadb_lifetime_usetime = x->lft.soft_use_expires_seconds; } /* current time */ lifetime = (struct sadb_lifetime *) skb_put(skb, sizeof(struct sadb_lifetime)); lifetime->sadb_lifetime_len = sizeof(struct sadb_lifetime)/sizeof(uint64_t); lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT; lifetime->sadb_lifetime_allocations = x->curlft.packets; lifetime->sadb_lifetime_bytes = x->curlft.bytes; lifetime->sadb_lifetime_addtime = x->curlft.add_time; lifetime->sadb_lifetime_usetime = x->curlft.use_time; /* src address */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC; /* "if the ports are non-zero, then the sadb_address_proto field, normally zero, MUST be filled in with the transport protocol's number." - RFC2367 */ addr->sadb_address_proto = 0; addr->sadb_address_reserved = 0; addr->sadb_address_prefixlen = pfkey_sockaddr_fill(&x->props.saddr, 0, (struct sockaddr *) (addr + 1), x->props.family); if (!addr->sadb_address_prefixlen) BUG(); /* dst address */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST; addr->sadb_address_proto = 0; addr->sadb_address_reserved = 0; addr->sadb_address_prefixlen = pfkey_sockaddr_fill(&x->id.daddr, 0, (struct sockaddr *) (addr + 1), x->props.family); if (!addr->sadb_address_prefixlen) BUG(); if (xfrm_addr_cmp(&x->sel.saddr, &x->props.saddr, x->props.family)) { addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_PROXY; addr->sadb_address_proto = pfkey_proto_from_xfrm(x->sel.proto); addr->sadb_address_prefixlen = x->sel.prefixlen_s; addr->sadb_address_reserved = 0; pfkey_sockaddr_fill(&x->sel.saddr, x->sel.sport, (struct sockaddr *) (addr + 1), x->props.family); } /* auth key */ if (add_keys && auth_key_size) { key = (struct sadb_key *) skb_put(skb, sizeof(struct sadb_key)+auth_key_size); key->sadb_key_len = (sizeof(struct sadb_key) + auth_key_size) / sizeof(uint64_t); key->sadb_key_exttype = SADB_EXT_KEY_AUTH; key->sadb_key_bits = x->aalg->alg_key_len; key->sadb_key_reserved = 0; memcpy(key + 1, x->aalg->alg_key, (x->aalg->alg_key_len+7)/8); } /* encrypt key */ if (add_keys && encrypt_key_size) { key = (struct sadb_key *) skb_put(skb, sizeof(struct sadb_key)+encrypt_key_size); key->sadb_key_len = (sizeof(struct sadb_key) + encrypt_key_size) / sizeof(uint64_t); key->sadb_key_exttype = SADB_EXT_KEY_ENCRYPT; key->sadb_key_bits = x->ealg->alg_key_len; key->sadb_key_reserved = 0; memcpy(key + 1, x->ealg->alg_key, (x->ealg->alg_key_len+7)/8); } /* sa */ sa2 = (struct sadb_x_sa2 *) skb_put(skb, sizeof(struct sadb_x_sa2)); sa2->sadb_x_sa2_len = sizeof(struct sadb_x_sa2)/sizeof(uint64_t); sa2->sadb_x_sa2_exttype = SADB_X_EXT_SA2; if ((mode = pfkey_mode_from_xfrm(x->props.mode)) < 0) { kfree_skb(skb); return ERR_PTR(-EINVAL); } sa2->sadb_x_sa2_mode = mode; sa2->sadb_x_sa2_reserved1 = 0; sa2->sadb_x_sa2_reserved2 = 0; sa2->sadb_x_sa2_sequence = 0; sa2->sadb_x_sa2_reqid = x->props.reqid; if (natt && natt->encap_type) { struct sadb_x_nat_t_type *n_type; struct sadb_x_nat_t_port *n_port; /* type */ n_type = (struct sadb_x_nat_t_type*) skb_put(skb, sizeof(*n_type)); n_type->sadb_x_nat_t_type_len = sizeof(*n_type)/sizeof(uint64_t); n_type->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE; n_type->sadb_x_nat_t_type_type = natt->encap_type; n_type->sadb_x_nat_t_type_reserved[0] = 0; n_type->sadb_x_nat_t_type_reserved[1] = 0; n_type->sadb_x_nat_t_type_reserved[2] = 0; /* source port */ n_port = (struct sadb_x_nat_t_port*) skb_put(skb, sizeof (*n_port)); n_port->sadb_x_nat_t_port_len = sizeof(*n_port)/sizeof(uint64_t); n_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_SPORT; n_port->sadb_x_nat_t_port_port = natt->encap_sport; n_port->sadb_x_nat_t_port_reserved = 0; /* dest port */ n_port = (struct sadb_x_nat_t_port*) skb_put(skb, sizeof (*n_port)); n_port->sadb_x_nat_t_port_len = sizeof(*n_port)/sizeof(uint64_t); n_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_DPORT; n_port->sadb_x_nat_t_port_port = natt->encap_dport; n_port->sadb_x_nat_t_port_reserved = 0; } /* security context */ if (xfrm_ctx) { sec_ctx = (struct sadb_x_sec_ctx *) skb_put(skb, sizeof(struct sadb_x_sec_ctx) + ctx_size); sec_ctx->sadb_x_sec_len = (sizeof(struct sadb_x_sec_ctx) + ctx_size) / sizeof(uint64_t); sec_ctx->sadb_x_sec_exttype = SADB_X_EXT_SEC_CTX; sec_ctx->sadb_x_ctx_doi = xfrm_ctx->ctx_doi; sec_ctx->sadb_x_ctx_alg = xfrm_ctx->ctx_alg; sec_ctx->sadb_x_ctx_len = xfrm_ctx->ctx_len; memcpy(sec_ctx + 1, xfrm_ctx->ctx_str, xfrm_ctx->ctx_len); } return skb; } static inline struct sk_buff *pfkey_xfrm_state2msg(struct xfrm_state *x) { struct sk_buff *skb; skb = __pfkey_xfrm_state2msg(x, 1, 3); return skb; } static inline struct sk_buff *pfkey_xfrm_state2msg_expire(struct xfrm_state *x, int hsc) { return __pfkey_xfrm_state2msg(x, 0, hsc); } static struct xfrm_state * pfkey_msg2xfrm_state(struct net *net, struct sadb_msg *hdr, void **ext_hdrs) { struct xfrm_state *x; struct sadb_lifetime *lifetime; struct sadb_sa *sa; struct sadb_key *key; struct sadb_x_sec_ctx *sec_ctx; uint16_t proto; int err; sa = (struct sadb_sa *) ext_hdrs[SADB_EXT_SA-1]; if (!sa || !present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1], ext_hdrs[SADB_EXT_ADDRESS_DST-1])) return ERR_PTR(-EINVAL); if (hdr->sadb_msg_satype == SADB_SATYPE_ESP && !ext_hdrs[SADB_EXT_KEY_ENCRYPT-1]) return ERR_PTR(-EINVAL); if (hdr->sadb_msg_satype == SADB_SATYPE_AH && !ext_hdrs[SADB_EXT_KEY_AUTH-1]) return ERR_PTR(-EINVAL); if (!!ext_hdrs[SADB_EXT_LIFETIME_HARD-1] != !!ext_hdrs[SADB_EXT_LIFETIME_SOFT-1]) return ERR_PTR(-EINVAL); proto = pfkey_satype2proto(hdr->sadb_msg_satype); if (proto == 0) return ERR_PTR(-EINVAL); /* default error is no buffer space */ err = -ENOBUFS; /* RFC2367: Only SADB_SASTATE_MATURE SAs may be submitted in an SADB_ADD message. SADB_SASTATE_LARVAL SAs are created by SADB_GETSPI and it is not sensible to add a new SA in the DYING or SADB_SASTATE_DEAD state. Therefore, the sadb_sa_state field of all submitted SAs MUST be SADB_SASTATE_MATURE and the kernel MUST return an error if this is not true. However, KAME setkey always uses SADB_SASTATE_LARVAL. Hence, we have to _ignore_ sadb_sa_state, which is also reasonable. */ if (sa->sadb_sa_auth > SADB_AALG_MAX || (hdr->sadb_msg_satype == SADB_X_SATYPE_IPCOMP && sa->sadb_sa_encrypt > SADB_X_CALG_MAX) || sa->sadb_sa_encrypt > SADB_EALG_MAX) return ERR_PTR(-EINVAL); key = (struct sadb_key*) ext_hdrs[SADB_EXT_KEY_AUTH-1]; if (key != NULL && sa->sadb_sa_auth != SADB_X_AALG_NULL && ((key->sadb_key_bits+7) / 8 == 0 || (key->sadb_key_bits+7) / 8 > key->sadb_key_len * sizeof(uint64_t))) return ERR_PTR(-EINVAL); key = ext_hdrs[SADB_EXT_KEY_ENCRYPT-1]; if (key != NULL && sa->sadb_sa_encrypt != SADB_EALG_NULL && ((key->sadb_key_bits+7) / 8 == 0 || (key->sadb_key_bits+7) / 8 > key->sadb_key_len * sizeof(uint64_t))) return ERR_PTR(-EINVAL); x = xfrm_state_alloc(net); if (x == NULL) return ERR_PTR(-ENOBUFS); x->id.proto = proto; x->id.spi = sa->sadb_sa_spi; x->props.replay_window = sa->sadb_sa_replay; if (sa->sadb_sa_flags & SADB_SAFLAGS_NOECN) x->props.flags |= XFRM_STATE_NOECN; if (sa->sadb_sa_flags & SADB_SAFLAGS_DECAP_DSCP) x->props.flags |= XFRM_STATE_DECAP_DSCP; if (sa->sadb_sa_flags & SADB_SAFLAGS_NOPMTUDISC) x->props.flags |= XFRM_STATE_NOPMTUDISC; lifetime = (struct sadb_lifetime*) ext_hdrs[SADB_EXT_LIFETIME_HARD-1]; if (lifetime != NULL) { x->lft.hard_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations); x->lft.hard_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes); x->lft.hard_add_expires_seconds = lifetime->sadb_lifetime_addtime; x->lft.hard_use_expires_seconds = lifetime->sadb_lifetime_usetime; } lifetime = (struct sadb_lifetime*) ext_hdrs[SADB_EXT_LIFETIME_SOFT-1]; if (lifetime != NULL) { x->lft.soft_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations); x->lft.soft_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes); x->lft.soft_add_expires_seconds = lifetime->sadb_lifetime_addtime; x->lft.soft_use_expires_seconds = lifetime->sadb_lifetime_usetime; } sec_ctx = (struct sadb_x_sec_ctx *) ext_hdrs[SADB_X_EXT_SEC_CTX-1]; if (sec_ctx != NULL) { struct xfrm_user_sec_ctx *uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx); if (!uctx) goto out; err = security_xfrm_state_alloc(x, uctx); kfree(uctx); if (err) goto out; } key = (struct sadb_key*) ext_hdrs[SADB_EXT_KEY_AUTH-1]; if (sa->sadb_sa_auth) { int keysize = 0; struct xfrm_algo_desc *a = xfrm_aalg_get_byid(sa->sadb_sa_auth); if (!a) { err = -ENOSYS; goto out; } if (key) keysize = (key->sadb_key_bits + 7) / 8; x->aalg = kmalloc(sizeof(*x->aalg) + keysize, GFP_KERNEL); if (!x->aalg) goto out; strcpy(x->aalg->alg_name, a->name); x->aalg->alg_key_len = 0; if (key) { x->aalg->alg_key_len = key->sadb_key_bits; memcpy(x->aalg->alg_key, key+1, keysize); } x->props.aalgo = sa->sadb_sa_auth; /* x->algo.flags = sa->sadb_sa_flags; */ } if (sa->sadb_sa_encrypt) { if (hdr->sadb_msg_satype == SADB_X_SATYPE_IPCOMP) { struct xfrm_algo_desc *a = xfrm_calg_get_byid(sa->sadb_sa_encrypt); if (!a) { err = -ENOSYS; goto out; } x->calg = kmalloc(sizeof(*x->calg), GFP_KERNEL); if (!x->calg) goto out; strcpy(x->calg->alg_name, a->name); x->props.calgo = sa->sadb_sa_encrypt; } else { int keysize = 0; struct xfrm_algo_desc *a = xfrm_ealg_get_byid(sa->sadb_sa_encrypt); if (!a) { err = -ENOSYS; goto out; } key = (struct sadb_key*) ext_hdrs[SADB_EXT_KEY_ENCRYPT-1]; if (key) keysize = (key->sadb_key_bits + 7) / 8; x->ealg = kmalloc(sizeof(*x->ealg) + keysize, GFP_KERNEL); if (!x->ealg) goto out; strcpy(x->ealg->alg_name, a->name); x->ealg->alg_key_len = 0; if (key) { x->ealg->alg_key_len = key->sadb_key_bits; memcpy(x->ealg->alg_key, key+1, keysize); } x->props.ealgo = sa->sadb_sa_encrypt; } } /* x->algo.flags = sa->sadb_sa_flags; */ x->props.family = pfkey_sadb_addr2xfrm_addr((struct sadb_address *) ext_hdrs[SADB_EXT_ADDRESS_SRC-1], &x->props.saddr); if (!x->props.family) { err = -EAFNOSUPPORT; goto out; } pfkey_sadb_addr2xfrm_addr((struct sadb_address *) ext_hdrs[SADB_EXT_ADDRESS_DST-1], &x->id.daddr); if (ext_hdrs[SADB_X_EXT_SA2-1]) { struct sadb_x_sa2 *sa2 = (void*)ext_hdrs[SADB_X_EXT_SA2-1]; int mode = pfkey_mode_to_xfrm(sa2->sadb_x_sa2_mode); if (mode < 0) { err = -EINVAL; goto out; } x->props.mode = mode; x->props.reqid = sa2->sadb_x_sa2_reqid; } if (ext_hdrs[SADB_EXT_ADDRESS_PROXY-1]) { struct sadb_address *addr = ext_hdrs[SADB_EXT_ADDRESS_PROXY-1]; /* Nobody uses this, but we try. */ x->sel.family = pfkey_sadb_addr2xfrm_addr(addr, &x->sel.saddr); x->sel.prefixlen_s = addr->sadb_address_prefixlen; } if (!x->sel.family) x->sel.family = x->props.family; if (ext_hdrs[SADB_X_EXT_NAT_T_TYPE-1]) { struct sadb_x_nat_t_type* n_type; struct xfrm_encap_tmpl *natt; x->encap = kmalloc(sizeof(*x->encap), GFP_KERNEL); if (!x->encap) goto out; natt = x->encap; n_type = ext_hdrs[SADB_X_EXT_NAT_T_TYPE-1]; natt->encap_type = n_type->sadb_x_nat_t_type_type; if (ext_hdrs[SADB_X_EXT_NAT_T_SPORT-1]) { struct sadb_x_nat_t_port* n_port = ext_hdrs[SADB_X_EXT_NAT_T_SPORT-1]; natt->encap_sport = n_port->sadb_x_nat_t_port_port; } if (ext_hdrs[SADB_X_EXT_NAT_T_DPORT-1]) { struct sadb_x_nat_t_port* n_port = ext_hdrs[SADB_X_EXT_NAT_T_DPORT-1]; natt->encap_dport = n_port->sadb_x_nat_t_port_port; } memset(&natt->encap_oa, 0, sizeof(natt->encap_oa)); } err = xfrm_init_state(x); if (err) goto out; x->km.seq = hdr->sadb_msg_seq; return x; out: x->km.state = XFRM_STATE_DEAD; xfrm_state_put(x); return ERR_PTR(err); } static int pfkey_reserved(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs) { return -EOPNOTSUPP; } static int pfkey_getspi(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs) { struct net *net = sock_net(sk); struct sk_buff *resp_skb; struct sadb_x_sa2 *sa2; struct sadb_address *saddr, *daddr; struct sadb_msg *out_hdr; struct sadb_spirange *range; struct xfrm_state *x = NULL; int mode; int err; u32 min_spi, max_spi; u32 reqid; u8 proto; unsigned short family; xfrm_address_t *xsaddr = NULL, *xdaddr = NULL; if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1], ext_hdrs[SADB_EXT_ADDRESS_DST-1])) return -EINVAL; proto = pfkey_satype2proto(hdr->sadb_msg_satype); if (proto == 0) return -EINVAL; if ((sa2 = ext_hdrs[SADB_X_EXT_SA2-1]) != NULL) { mode = pfkey_mode_to_xfrm(sa2->sadb_x_sa2_mode); if (mode < 0) return -EINVAL; reqid = sa2->sadb_x_sa2_reqid; } else { mode = 0; reqid = 0; } saddr = ext_hdrs[SADB_EXT_ADDRESS_SRC-1]; daddr = ext_hdrs[SADB_EXT_ADDRESS_DST-1]; family = ((struct sockaddr *)(saddr + 1))->sa_family; switch (family) { case AF_INET: xdaddr = (xfrm_address_t *)&((struct sockaddr_in *)(daddr + 1))->sin_addr.s_addr; xsaddr = (xfrm_address_t *)&((struct sockaddr_in *)(saddr + 1))->sin_addr.s_addr; break; #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) case AF_INET6: xdaddr = (xfrm_address_t *)&((struct sockaddr_in6 *)(daddr + 1))->sin6_addr; xsaddr = (xfrm_address_t *)&((struct sockaddr_in6 *)(saddr + 1))->sin6_addr; break; #endif } if (hdr->sadb_msg_seq) { x = xfrm_find_acq_byseq(net, hdr->sadb_msg_seq); if (x && xfrm_addr_cmp(&x->id.daddr, xdaddr, family)) { xfrm_state_put(x); x = NULL; } } if (!x) x = xfrm_find_acq(net, mode, reqid, proto, xdaddr, xsaddr, 1, family); if (x == NULL) return -ENOENT; min_spi = 0x100; max_spi = 0x0fffffff; range = ext_hdrs[SADB_EXT_SPIRANGE-1]; if (range) { min_spi = range->sadb_spirange_min; max_spi = range->sadb_spirange_max; } err = xfrm_alloc_spi(x, min_spi, max_spi); resp_skb = err ? ERR_PTR(err) : pfkey_xfrm_state2msg(x); if (IS_ERR(resp_skb)) { xfrm_state_put(x); return PTR_ERR(resp_skb); } out_hdr = (struct sadb_msg *) resp_skb->data; out_hdr->sadb_msg_version = hdr->sadb_msg_version; out_hdr->sadb_msg_type = SADB_GETSPI; out_hdr->sadb_msg_satype = pfkey_proto2satype(proto); out_hdr->sadb_msg_errno = 0; out_hdr->sadb_msg_reserved = 0; out_hdr->sadb_msg_seq = hdr->sadb_msg_seq; out_hdr->sadb_msg_pid = hdr->sadb_msg_pid; xfrm_state_put(x); pfkey_broadcast(resp_skb, GFP_KERNEL, BROADCAST_ONE, sk, net); return 0; } static int pfkey_acquire(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs) { struct net *net = sock_net(sk); struct xfrm_state *x; if (hdr->sadb_msg_len != sizeof(struct sadb_msg)/8) return -EOPNOTSUPP; if (hdr->sadb_msg_seq == 0 || hdr->sadb_msg_errno == 0) return 0; x = xfrm_find_acq_byseq(net, hdr->sadb_msg_seq); if (x == NULL) return 0; spin_lock_bh(&x->lock); if (x->km.state == XFRM_STATE_ACQ) { x->km.state = XFRM_STATE_ERROR; wake_up(&net->xfrm.km_waitq); } spin_unlock_bh(&x->lock); xfrm_state_put(x); return 0; } static inline int event2poltype(int event) { switch (event) { case XFRM_MSG_DELPOLICY: return SADB_X_SPDDELETE; case XFRM_MSG_NEWPOLICY: return SADB_X_SPDADD; case XFRM_MSG_UPDPOLICY: return SADB_X_SPDUPDATE; case XFRM_MSG_POLEXPIRE: // return SADB_X_SPDEXPIRE; default: printk("pfkey: Unknown policy event %d\n", event); break; } return 0; } static inline int event2keytype(int event) { switch (event) { case XFRM_MSG_DELSA: return SADB_DELETE; case XFRM_MSG_NEWSA: return SADB_ADD; case XFRM_MSG_UPDSA: return SADB_UPDATE; case XFRM_MSG_EXPIRE: return SADB_EXPIRE; default: printk("pfkey: Unknown SA event %d\n", event); break; } return 0; } /* ADD/UPD/DEL */ static int key_notify_sa(struct xfrm_state *x, struct km_event *c) { struct sk_buff *skb; struct sadb_msg *hdr; skb = pfkey_xfrm_state2msg(x); if (IS_ERR(skb)) return PTR_ERR(skb); hdr = (struct sadb_msg *) skb->data; hdr->sadb_msg_version = PF_KEY_V2; hdr->sadb_msg_type = event2keytype(c->event); hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto); hdr->sadb_msg_errno = 0; hdr->sadb_msg_reserved = 0; hdr->sadb_msg_seq = c->seq; hdr->sadb_msg_pid = c->pid; pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ALL, NULL, xs_net(x)); return 0; } static int pfkey_add(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs) { struct net *net = sock_net(sk); struct xfrm_state *x; int err; struct km_event c; x = pfkey_msg2xfrm_state(net, hdr, ext_hdrs); if (IS_ERR(x)) return PTR_ERR(x); xfrm_state_hold(x); if (hdr->sadb_msg_type == SADB_ADD) err = xfrm_state_add(x); else err = xfrm_state_update(x); xfrm_audit_state_add(x, err ? 0 : 1, audit_get_loginuid(current), audit_get_sessionid(current), 0); if (err < 0) { x->km.state = XFRM_STATE_DEAD; __xfrm_state_put(x); goto out; } if (hdr->sadb_msg_type == SADB_ADD) c.event = XFRM_MSG_NEWSA; else c.event = XFRM_MSG_UPDSA; c.seq = hdr->sadb_msg_seq; c.pid = hdr->sadb_msg_pid; km_state_notify(x, &c); out: xfrm_state_put(x); return err; } static int pfkey_delete(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs) { struct net *net = sock_net(sk); struct xfrm_state *x; struct km_event c; int err; if (!ext_hdrs[SADB_EXT_SA-1] || !present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1], ext_hdrs[SADB_EXT_ADDRESS_DST-1])) return -EINVAL; x = pfkey_xfrm_state_lookup(net, hdr, ext_hdrs); if (x == NULL) return -ESRCH; if ((err = security_xfrm_state_delete(x))) goto out; if (xfrm_state_kern(x)) { err = -EPERM; goto out; } err = xfrm_state_delete(x); if (err < 0) goto out; c.seq = hdr->sadb_msg_seq; c.pid = hdr->sadb_msg_pid; c.event = XFRM_MSG_DELSA; km_state_notify(x, &c); out: xfrm_audit_state_delete(x, err ? 0 : 1, audit_get_loginuid(current), audit_get_sessionid(current), 0); xfrm_state_put(x); return err; } static int pfkey_get(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs) { struct net *net = sock_net(sk); __u8 proto; struct sk_buff *out_skb; struct sadb_msg *out_hdr; struct xfrm_state *x; if (!ext_hdrs[SADB_EXT_SA-1] || !present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1], ext_hdrs[SADB_EXT_ADDRESS_DST-1])) return -EINVAL; x = pfkey_xfrm_state_lookup(net, hdr, ext_hdrs); if (x == NULL) return -ESRCH; out_skb = pfkey_xfrm_state2msg(x); proto = x->id.proto; xfrm_state_put(x); if (IS_ERR(out_skb)) return PTR_ERR(out_skb); out_hdr = (struct sadb_msg *) out_skb->data; out_hdr->sadb_msg_version = hdr->sadb_msg_version; out_hdr->sadb_msg_type = SADB_GET; out_hdr->sadb_msg_satype = pfkey_proto2satype(proto); out_hdr->sadb_msg_errno = 0; out_hdr->sadb_msg_reserved = 0; out_hdr->sadb_msg_seq = hdr->sadb_msg_seq; out_hdr->sadb_msg_pid = hdr->sadb_msg_pid; pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ONE, sk, sock_net(sk)); return 0; } static struct sk_buff *compose_sadb_supported(struct sadb_msg *orig, gfp_t allocation) { struct sk_buff *skb; struct sadb_msg *hdr; int len, auth_len, enc_len, i; auth_len = xfrm_count_auth_supported(); if (auth_len) { auth_len *= sizeof(struct sadb_alg); auth_len += sizeof(struct sadb_supported); } enc_len = xfrm_count_enc_supported(); if (enc_len) { enc_len *= sizeof(struct sadb_alg); enc_len += sizeof(struct sadb_supported); } len = enc_len + auth_len + sizeof(struct sadb_msg); skb = alloc_skb(len + 16, allocation); if (!skb) goto out_put_algs; hdr = (struct sadb_msg *) skb_put(skb, sizeof(*hdr)); pfkey_hdr_dup(hdr, orig); hdr->sadb_msg_errno = 0; hdr->sadb_msg_len = len / sizeof(uint64_t); if (auth_len) { struct sadb_supported *sp; struct sadb_alg *ap; sp = (struct sadb_supported *) skb_put(skb, auth_len); ap = (struct sadb_alg *) (sp + 1); sp->sadb_supported_len = auth_len / sizeof(uint64_t); sp->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH; for (i = 0; ; i++) { struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(i); if (!aalg) break; if (aalg->available) *ap++ = aalg->desc; } } if (enc_len) { struct sadb_supported *sp; struct sadb_alg *ap; sp = (struct sadb_supported *) skb_put(skb, enc_len); ap = (struct sadb_alg *) (sp + 1); sp->sadb_supported_len = enc_len / sizeof(uint64_t); sp->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT; for (i = 0; ; i++) { struct xfrm_algo_desc *ealg = xfrm_ealg_get_byidx(i); if (!ealg) break; if (ealg->available) *ap++ = ealg->desc; } } out_put_algs: return skb; } static int pfkey_register(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs) { struct pfkey_sock *pfk = pfkey_sk(sk); struct sk_buff *supp_skb; if (hdr->sadb_msg_satype > SADB_SATYPE_MAX) return -EINVAL; if (hdr->sadb_msg_satype != SADB_SATYPE_UNSPEC) { if (pfk->registered&(1<<hdr->sadb_msg_satype)) return -EEXIST; pfk->registered |= (1<<hdr->sadb_msg_satype); } xfrm_probe_algs(); supp_skb = compose_sadb_supported(hdr, GFP_KERNEL); if (!supp_skb) { if (hdr->sadb_msg_satype != SADB_SATYPE_UNSPEC) pfk->registered &= ~(1<<hdr->sadb_msg_satype); return -ENOBUFS; } pfkey_broadcast(supp_skb, GFP_KERNEL, BROADCAST_REGISTERED, sk, sock_net(sk)); return 0; } static int key_notify_sa_flush(struct km_event *c) { struct sk_buff *skb; struct sadb_msg *hdr; skb = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC); if (!skb) return -ENOBUFS; hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg)); hdr->sadb_msg_satype = pfkey_proto2satype(c->data.proto); hdr->sadb_msg_type = SADB_FLUSH; hdr->sadb_msg_seq = c->seq; hdr->sadb_msg_pid = c->pid; hdr->sadb_msg_version = PF_KEY_V2; hdr->sadb_msg_errno = (uint8_t) 0; hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t)); pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ALL, NULL, c->net); return 0; } static int pfkey_flush(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs) { struct net *net = sock_net(sk); unsigned proto; struct km_event c; struct xfrm_audit audit_info; int err; proto = pfkey_satype2proto(hdr->sadb_msg_satype); if (proto == 0) return -EINVAL; audit_info.loginuid = audit_get_loginuid(current); audit_info.sessionid = audit_get_sessionid(current); audit_info.secid = 0; err = xfrm_state_flush(net, proto, &audit_info); if (err) return err; c.data.proto = proto; c.seq = hdr->sadb_msg_seq; c.pid = hdr->sadb_msg_pid; c.event = XFRM_MSG_FLUSHSA; c.net = net; km_state_notify(NULL, &c); return 0; } static int dump_sa(struct xfrm_state *x, int count, void *ptr) { struct pfkey_sock *pfk = ptr; struct sk_buff *out_skb; struct sadb_msg *out_hdr; if (!pfkey_can_dump(&pfk->sk)) return -ENOBUFS; out_skb = pfkey_xfrm_state2msg(x); if (IS_ERR(out_skb)) return PTR_ERR(out_skb); out_hdr = (struct sadb_msg *) out_skb->data; out_hdr->sadb_msg_version = pfk->dump.msg_version; out_hdr->sadb_msg_type = SADB_DUMP; out_hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto); out_hdr->sadb_msg_errno = 0; out_hdr->sadb_msg_reserved = 0; out_hdr->sadb_msg_seq = count + 1; out_hdr->sadb_msg_pid = pfk->dump.msg_pid; if (pfk->dump.skb) pfkey_broadcast(pfk->dump.skb, GFP_ATOMIC, BROADCAST_ONE, &pfk->sk, sock_net(&pfk->sk)); pfk->dump.skb = out_skb; return 0; } static int pfkey_dump_sa(struct pfkey_sock *pfk) { struct net *net = sock_net(&pfk->sk); return xfrm_state_walk(net, &pfk->dump.u.state, dump_sa, (void *) pfk); } static void pfkey_dump_sa_done(struct pfkey_sock *pfk) { xfrm_state_walk_done(&pfk->dump.u.state); } static int pfkey_dump(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs) { u8 proto; struct pfkey_sock *pfk = pfkey_sk(sk); if (pfk->dump.dump != NULL) return -EBUSY; proto = pfkey_satype2proto(hdr->sadb_msg_satype); if (proto == 0) return -EINVAL; pfk->dump.msg_version = hdr->sadb_msg_version; pfk->dump.msg_pid = hdr->sadb_msg_pid; pfk->dump.dump = pfkey_dump_sa; pfk->dump.done = pfkey_dump_sa_done; xfrm_state_walk_init(&pfk->dump.u.state, proto); return pfkey_do_dump(pfk); } static int pfkey_promisc(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs) { struct pfkey_sock *pfk = pfkey_sk(sk); int satype = hdr->sadb_msg_satype; if (hdr->sadb_msg_len == (sizeof(*hdr) / sizeof(uint64_t))) { /* XXX we mangle packet... */ hdr->sadb_msg_errno = 0; if (satype != 0 && satype != 1) return -EINVAL; pfk->promisc = satype; } pfkey_broadcast(skb_clone(skb, GFP_KERNEL), GFP_KERNEL, BROADCAST_ALL, NULL, sock_net(sk)); return 0; } static int check_reqid(struct xfrm_policy *xp, int dir, int count, void *ptr) { int i; u32 reqid = *(u32*)ptr; for (i=0; i<xp->xfrm_nr; i++) { if (xp->xfrm_vec[i].reqid == reqid) return -EEXIST; } return 0; } static u32 gen_reqid(struct net *net) { struct xfrm_policy_walk walk; u32 start; int rc; static u32 reqid = IPSEC_MANUAL_REQID_MAX; start = reqid; do { ++reqid; if (reqid == 0) reqid = IPSEC_MANUAL_REQID_MAX+1; xfrm_policy_walk_init(&walk, XFRM_POLICY_TYPE_MAIN); rc = xfrm_policy_walk(net, &walk, check_reqid, (void*)&reqid); xfrm_policy_walk_done(&walk); if (rc != -EEXIST) return reqid; } while (reqid != start); return 0; } static int parse_ipsecrequest(struct xfrm_policy *xp, struct sadb_x_ipsecrequest *rq) { struct net *net = xp_net(xp); struct xfrm_tmpl *t = xp->xfrm_vec + xp->xfrm_nr; int mode; if (xp->xfrm_nr >= XFRM_MAX_DEPTH) return -ELOOP; if (rq->sadb_x_ipsecrequest_mode == 0) return -EINVAL; t->id.proto = rq->sadb_x_ipsecrequest_proto; /* XXX check proto */ if ((mode = pfkey_mode_to_xfrm(rq->sadb_x_ipsecrequest_mode)) < 0) return -EINVAL; t->mode = mode; if (rq->sadb_x_ipsecrequest_level == IPSEC_LEVEL_USE) t->optional = 1; else if (rq->sadb_x_ipsecrequest_level == IPSEC_LEVEL_UNIQUE) { t->reqid = rq->sadb_x_ipsecrequest_reqid; if (t->reqid > IPSEC_MANUAL_REQID_MAX) t->reqid = 0; if (!t->reqid && !(t->reqid = gen_reqid(net))) return -ENOBUFS; } /* addresses present only in tunnel mode */ if (t->mode == XFRM_MODE_TUNNEL) { u8 *sa = (u8 *) (rq + 1); int family, socklen; family = pfkey_sockaddr_extract((struct sockaddr *)sa, &t->saddr); if (!family) return -EINVAL; socklen = pfkey_sockaddr_len(family); if (pfkey_sockaddr_extract((struct sockaddr *)(sa + socklen), &t->id.daddr) != family) return -EINVAL; t->encap_family = family; } else t->encap_family = xp->family; /* No way to set this via kame pfkey */ t->allalgs = 1; xp->xfrm_nr++; return 0; } static int parse_ipsecrequests(struct xfrm_policy *xp, struct sadb_x_policy *pol) { int err; int len = pol->sadb_x_policy_len*8 - sizeof(struct sadb_x_policy); struct sadb_x_ipsecrequest *rq = (void*)(pol+1); while (len >= sizeof(struct sadb_x_ipsecrequest)) { if ((err = parse_ipsecrequest(xp, rq)) < 0) return err; len -= rq->sadb_x_ipsecrequest_len; rq = (void*)((u8*)rq + rq->sadb_x_ipsecrequest_len); } return 0; } static inline int pfkey_xfrm_policy2sec_ctx_size(struct xfrm_policy *xp) { struct xfrm_sec_ctx *xfrm_ctx = xp->security; if (xfrm_ctx) { int len = sizeof(struct sadb_x_sec_ctx); len += xfrm_ctx->ctx_len; return PFKEY_ALIGN8(len); } return 0; } static int pfkey_xfrm_policy2msg_size(struct xfrm_policy *xp) { struct xfrm_tmpl *t; int sockaddr_size = pfkey_sockaddr_size(xp->family); int socklen = 0; int i; for (i=0; i<xp->xfrm_nr; i++) { t = xp->xfrm_vec + i; socklen += pfkey_sockaddr_len(t->encap_family); } return sizeof(struct sadb_msg) + (sizeof(struct sadb_lifetime) * 3) + (sizeof(struct sadb_address) * 2) + (sockaddr_size * 2) + sizeof(struct sadb_x_policy) + (xp->xfrm_nr * sizeof(struct sadb_x_ipsecrequest)) + (socklen * 2) + pfkey_xfrm_policy2sec_ctx_size(xp); } static struct sk_buff * pfkey_xfrm_policy2msg_prep(struct xfrm_policy *xp) { struct sk_buff *skb; int size; size = pfkey_xfrm_policy2msg_size(xp); skb = alloc_skb(size + 16, GFP_ATOMIC); if (skb == NULL) return ERR_PTR(-ENOBUFS); return skb; } static int pfkey_xfrm_policy2msg(struct sk_buff *skb, struct xfrm_policy *xp, int dir) { struct sadb_msg *hdr; struct sadb_address *addr; struct sadb_lifetime *lifetime; struct sadb_x_policy *pol; struct sadb_x_sec_ctx *sec_ctx; struct xfrm_sec_ctx *xfrm_ctx; int i; int size; int sockaddr_size = pfkey_sockaddr_size(xp->family); int socklen = pfkey_sockaddr_len(xp->family); size = pfkey_xfrm_policy2msg_size(xp); /* call should fill header later */ hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg)); memset(hdr, 0, size); /* XXX do we need this ? */ /* src address */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC; addr->sadb_address_proto = pfkey_proto_from_xfrm(xp->selector.proto); addr->sadb_address_prefixlen = xp->selector.prefixlen_s; addr->sadb_address_reserved = 0; if (!pfkey_sockaddr_fill(&xp->selector.saddr, xp->selector.sport, (struct sockaddr *) (addr + 1), xp->family)) BUG(); /* dst address */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST; addr->sadb_address_proto = pfkey_proto_from_xfrm(xp->selector.proto); addr->sadb_address_prefixlen = xp->selector.prefixlen_d; addr->sadb_address_reserved = 0; pfkey_sockaddr_fill(&xp->selector.daddr, xp->selector.dport, (struct sockaddr *) (addr + 1), xp->family); /* hard time */ lifetime = (struct sadb_lifetime *) skb_put(skb, sizeof(struct sadb_lifetime)); lifetime->sadb_lifetime_len = sizeof(struct sadb_lifetime)/sizeof(uint64_t); lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD; lifetime->sadb_lifetime_allocations = _X2KEY(xp->lft.hard_packet_limit); lifetime->sadb_lifetime_bytes = _X2KEY(xp->lft.hard_byte_limit); lifetime->sadb_lifetime_addtime = xp->lft.hard_add_expires_seconds; lifetime->sadb_lifetime_usetime = xp->lft.hard_use_expires_seconds; /* soft time */ lifetime = (struct sadb_lifetime *) skb_put(skb, sizeof(struct sadb_lifetime)); lifetime->sadb_lifetime_len = sizeof(struct sadb_lifetime)/sizeof(uint64_t); lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT; lifetime->sadb_lifetime_allocations = _X2KEY(xp->lft.soft_packet_limit); lifetime->sadb_lifetime_bytes = _X2KEY(xp->lft.soft_byte_limit); lifetime->sadb_lifetime_addtime = xp->lft.soft_add_expires_seconds; lifetime->sadb_lifetime_usetime = xp->lft.soft_use_expires_seconds; /* current time */ lifetime = (struct sadb_lifetime *) skb_put(skb, sizeof(struct sadb_lifetime)); lifetime->sadb_lifetime_len = sizeof(struct sadb_lifetime)/sizeof(uint64_t); lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT; lifetime->sadb_lifetime_allocations = xp->curlft.packets; lifetime->sadb_lifetime_bytes = xp->curlft.bytes; lifetime->sadb_lifetime_addtime = xp->curlft.add_time; lifetime->sadb_lifetime_usetime = xp->curlft.use_time; pol = (struct sadb_x_policy *) skb_put(skb, sizeof(struct sadb_x_policy)); pol->sadb_x_policy_len = sizeof(struct sadb_x_policy)/sizeof(uint64_t); pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY; pol->sadb_x_policy_type = IPSEC_POLICY_DISCARD; if (xp->action == XFRM_POLICY_ALLOW) { if (xp->xfrm_nr) pol->sadb_x_policy_type = IPSEC_POLICY_IPSEC; else pol->sadb_x_policy_type = IPSEC_POLICY_NONE; } pol->sadb_x_policy_dir = dir+1; pol->sadb_x_policy_id = xp->index; pol->sadb_x_policy_priority = xp->priority; for (i=0; i<xp->xfrm_nr; i++) { struct sadb_x_ipsecrequest *rq; struct xfrm_tmpl *t = xp->xfrm_vec + i; int req_size; int mode; req_size = sizeof(struct sadb_x_ipsecrequest); if (t->mode == XFRM_MODE_TUNNEL) { socklen = pfkey_sockaddr_len(t->encap_family); req_size += socklen * 2; } else { size -= 2*socklen; } rq = (void*)skb_put(skb, req_size); pol->sadb_x_policy_len += req_size/8; memset(rq, 0, sizeof(*rq)); rq->sadb_x_ipsecrequest_len = req_size; rq->sadb_x_ipsecrequest_proto = t->id.proto; if ((mode = pfkey_mode_from_xfrm(t->mode)) < 0) return -EINVAL; rq->sadb_x_ipsecrequest_mode = mode; rq->sadb_x_ipsecrequest_level = IPSEC_LEVEL_REQUIRE; if (t->reqid) rq->sadb_x_ipsecrequest_level = IPSEC_LEVEL_UNIQUE; if (t->optional) rq->sadb_x_ipsecrequest_level = IPSEC_LEVEL_USE; rq->sadb_x_ipsecrequest_reqid = t->reqid; if (t->mode == XFRM_MODE_TUNNEL) { u8 *sa = (void *)(rq + 1); pfkey_sockaddr_fill(&t->saddr, 0, (struct sockaddr *)sa, t->encap_family); pfkey_sockaddr_fill(&t->id.daddr, 0, (struct sockaddr *) (sa + socklen), t->encap_family); } } /* security context */ if ((xfrm_ctx = xp->security)) { int ctx_size = pfkey_xfrm_policy2sec_ctx_size(xp); sec_ctx = (struct sadb_x_sec_ctx *) skb_put(skb, ctx_size); sec_ctx->sadb_x_sec_len = ctx_size / sizeof(uint64_t); sec_ctx->sadb_x_sec_exttype = SADB_X_EXT_SEC_CTX; sec_ctx->sadb_x_ctx_doi = xfrm_ctx->ctx_doi; sec_ctx->sadb_x_ctx_alg = xfrm_ctx->ctx_alg; sec_ctx->sadb_x_ctx_len = xfrm_ctx->ctx_len; memcpy(sec_ctx + 1, xfrm_ctx->ctx_str, xfrm_ctx->ctx_len); } hdr->sadb_msg_len = size / sizeof(uint64_t); hdr->sadb_msg_reserved = atomic_read(&xp->refcnt); return 0; } static int key_notify_policy(struct xfrm_policy *xp, int dir, struct km_event *c) { struct sk_buff *out_skb; struct sadb_msg *out_hdr; int err; out_skb = pfkey_xfrm_policy2msg_prep(xp); if (IS_ERR(out_skb)) { err = PTR_ERR(out_skb); goto out; } err = pfkey_xfrm_policy2msg(out_skb, xp, dir); if (err < 0) return err; out_hdr = (struct sadb_msg *) out_skb->data; out_hdr->sadb_msg_version = PF_KEY_V2; if (c->data.byid && c->event == XFRM_MSG_DELPOLICY) out_hdr->sadb_msg_type = SADB_X_SPDDELETE2; else out_hdr->sadb_msg_type = event2poltype(c->event); out_hdr->sadb_msg_errno = 0; out_hdr->sadb_msg_seq = c->seq; out_hdr->sadb_msg_pid = c->pid; pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ALL, NULL, xp_net(xp)); out: return 0; } static int pfkey_spdadd(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs) { struct net *net = sock_net(sk); int err = 0; struct sadb_lifetime *lifetime; struct sadb_address *sa; struct sadb_x_policy *pol; struct xfrm_policy *xp; struct km_event c; struct sadb_x_sec_ctx *sec_ctx; if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1], ext_hdrs[SADB_EXT_ADDRESS_DST-1]) || !ext_hdrs[SADB_X_EXT_POLICY-1]) return -EINVAL; pol = ext_hdrs[SADB_X_EXT_POLICY-1]; if (pol->sadb_x_policy_type > IPSEC_POLICY_IPSEC) return -EINVAL; if (!pol->sadb_x_policy_dir || pol->sadb_x_policy_dir >= IPSEC_DIR_MAX) return -EINVAL; xp = xfrm_policy_alloc(net, GFP_KERNEL); if (xp == NULL) return -ENOBUFS; xp->action = (pol->sadb_x_policy_type == IPSEC_POLICY_DISCARD ? XFRM_POLICY_BLOCK : XFRM_POLICY_ALLOW); xp->priority = pol->sadb_x_policy_priority; sa = ext_hdrs[SADB_EXT_ADDRESS_SRC-1], xp->family = pfkey_sadb_addr2xfrm_addr(sa, &xp->selector.saddr); if (!xp->family) { err = -EINVAL; goto out; } xp->selector.family = xp->family; xp->selector.prefixlen_s = sa->sadb_address_prefixlen; xp->selector.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto); xp->selector.sport = ((struct sockaddr_in *)(sa+1))->sin_port; if (xp->selector.sport) xp->selector.sport_mask = htons(0xffff); sa = ext_hdrs[SADB_EXT_ADDRESS_DST-1], pfkey_sadb_addr2xfrm_addr(sa, &xp->selector.daddr); xp->selector.prefixlen_d = sa->sadb_address_prefixlen; /* Amusing, we set this twice. KAME apps appear to set same value * in both addresses. */ xp->selector.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto); xp->selector.dport = ((struct sockaddr_in *)(sa+1))->sin_port; if (xp->selector.dport) xp->selector.dport_mask = htons(0xffff); sec_ctx = (struct sadb_x_sec_ctx *) ext_hdrs[SADB_X_EXT_SEC_CTX-1]; if (sec_ctx != NULL) { struct xfrm_user_sec_ctx *uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx); if (!uctx) { err = -ENOBUFS; goto out; } err = security_xfrm_policy_alloc(&xp->security, uctx); kfree(uctx); if (err) goto out; } xp->lft.soft_byte_limit = XFRM_INF; xp->lft.hard_byte_limit = XFRM_INF; xp->lft.soft_packet_limit = XFRM_INF; xp->lft.hard_packet_limit = XFRM_INF; if ((lifetime = ext_hdrs[SADB_EXT_LIFETIME_HARD-1]) != NULL) { xp->lft.hard_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations); xp->lft.hard_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes); xp->lft.hard_add_expires_seconds = lifetime->sadb_lifetime_addtime; xp->lft.hard_use_expires_seconds = lifetime->sadb_lifetime_usetime; } if ((lifetime = ext_hdrs[SADB_EXT_LIFETIME_SOFT-1]) != NULL) { xp->lft.soft_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations); xp->lft.soft_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes); xp->lft.soft_add_expires_seconds = lifetime->sadb_lifetime_addtime; xp->lft.soft_use_expires_seconds = lifetime->sadb_lifetime_usetime; } xp->xfrm_nr = 0; if (pol->sadb_x_policy_type == IPSEC_POLICY_IPSEC && (err = parse_ipsecrequests(xp, pol)) < 0) goto out; err = xfrm_policy_insert(pol->sadb_x_policy_dir-1, xp, hdr->sadb_msg_type != SADB_X_SPDUPDATE); xfrm_audit_policy_add(xp, err ? 0 : 1, audit_get_loginuid(current), audit_get_sessionid(current), 0); if (err) goto out; if (hdr->sadb_msg_type == SADB_X_SPDUPDATE) c.event = XFRM_MSG_UPDPOLICY; else c.event = XFRM_MSG_NEWPOLICY; c.seq = hdr->sadb_msg_seq; c.pid = hdr->sadb_msg_pid; km_policy_notify(xp, pol->sadb_x_policy_dir-1, &c); xfrm_pol_put(xp); return 0; out: xp->walk.dead = 1; xfrm_policy_destroy(xp); return err; } static int pfkey_spddelete(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs) { struct net *net = sock_net(sk); int err; struct sadb_address *sa; struct sadb_x_policy *pol; struct xfrm_policy *xp; struct xfrm_selector sel; struct km_event c; struct sadb_x_sec_ctx *sec_ctx; struct xfrm_sec_ctx *pol_ctx = NULL; if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1], ext_hdrs[SADB_EXT_ADDRESS_DST-1]) || !ext_hdrs[SADB_X_EXT_POLICY-1]) return -EINVAL; pol = ext_hdrs[SADB_X_EXT_POLICY-1]; if (!pol->sadb_x_policy_dir || pol->sadb_x_policy_dir >= IPSEC_DIR_MAX) return -EINVAL; memset(&sel, 0, sizeof(sel)); sa = ext_hdrs[SADB_EXT_ADDRESS_SRC-1], sel.family = pfkey_sadb_addr2xfrm_addr(sa, &sel.saddr); sel.prefixlen_s = sa->sadb_address_prefixlen; sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto); sel.sport = ((struct sockaddr_in *)(sa+1))->sin_port; if (sel.sport) sel.sport_mask = htons(0xffff); sa = ext_hdrs[SADB_EXT_ADDRESS_DST-1], pfkey_sadb_addr2xfrm_addr(sa, &sel.daddr); sel.prefixlen_d = sa->sadb_address_prefixlen; sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto); sel.dport = ((struct sockaddr_in *)(sa+1))->sin_port; if (sel.dport) sel.dport_mask = htons(0xffff); sec_ctx = (struct sadb_x_sec_ctx *) ext_hdrs[SADB_X_EXT_SEC_CTX-1]; if (sec_ctx != NULL) { struct xfrm_user_sec_ctx *uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx); if (!uctx) return -ENOMEM; err = security_xfrm_policy_alloc(&pol_ctx, uctx); kfree(uctx); if (err) return err; } xp = xfrm_policy_bysel_ctx(net, XFRM_POLICY_TYPE_MAIN, pol->sadb_x_policy_dir - 1, &sel, pol_ctx, 1, &err); security_xfrm_policy_free(pol_ctx); if (xp == NULL) return -ENOENT; xfrm_audit_policy_delete(xp, err ? 0 : 1, audit_get_loginuid(current), audit_get_sessionid(current), 0); if (err) goto out; c.seq = hdr->sadb_msg_seq; c.pid = hdr->sadb_msg_pid; c.data.byid = 0; c.event = XFRM_MSG_DELPOLICY; km_policy_notify(xp, pol->sadb_x_policy_dir-1, &c); out: xfrm_pol_put(xp); return err; } static int key_pol_get_resp(struct sock *sk, struct xfrm_policy *xp, struct sadb_msg *hdr, int dir) { int err; struct sk_buff *out_skb; struct sadb_msg *out_hdr; err = 0; out_skb = pfkey_xfrm_policy2msg_prep(xp); if (IS_ERR(out_skb)) { err = PTR_ERR(out_skb); goto out; } err = pfkey_xfrm_policy2msg(out_skb, xp, dir); if (err < 0) goto out; out_hdr = (struct sadb_msg *) out_skb->data; out_hdr->sadb_msg_version = hdr->sadb_msg_version; out_hdr->sadb_msg_type = hdr->sadb_msg_type; out_hdr->sadb_msg_satype = 0; out_hdr->sadb_msg_errno = 0; out_hdr->sadb_msg_seq = hdr->sadb_msg_seq; out_hdr->sadb_msg_pid = hdr->sadb_msg_pid; pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ONE, sk, xp_net(xp)); err = 0; out: return err; } #ifdef CONFIG_NET_KEY_MIGRATE static int pfkey_sockaddr_pair_size(sa_family_t family) { return PFKEY_ALIGN8(pfkey_sockaddr_len(family) * 2); } static int parse_sockaddr_pair(struct sockaddr *sa, int ext_len, xfrm_address_t *saddr, xfrm_address_t *daddr, u16 *family) { int af, socklen; if (ext_len < pfkey_sockaddr_pair_size(sa->sa_family)) return -EINVAL; af = pfkey_sockaddr_extract(sa, saddr); if (!af) return -EINVAL; socklen = pfkey_sockaddr_len(af); if (pfkey_sockaddr_extract((struct sockaddr *) (((u8 *)sa) + socklen), daddr) != af) return -EINVAL; *family = af; return 0; } static int ipsecrequests_to_migrate(struct sadb_x_ipsecrequest *rq1, int len, struct xfrm_migrate *m) { int err; struct sadb_x_ipsecrequest *rq2; int mode; if (len <= sizeof(struct sadb_x_ipsecrequest) || len < rq1->sadb_x_ipsecrequest_len) return -EINVAL; /* old endoints */ err = parse_sockaddr_pair((struct sockaddr *)(rq1 + 1), rq1->sadb_x_ipsecrequest_len, &m->old_saddr, &m->old_daddr, &m->old_family); if (err) return err; rq2 = (struct sadb_x_ipsecrequest *)((u8 *)rq1 + rq1->sadb_x_ipsecrequest_len); len -= rq1->sadb_x_ipsecrequest_len; if (len <= sizeof(struct sadb_x_ipsecrequest) || len < rq2->sadb_x_ipsecrequest_len) return -EINVAL; /* new endpoints */ err = parse_sockaddr_pair((struct sockaddr *)(rq2 + 1), rq2->sadb_x_ipsecrequest_len, &m->new_saddr, &m->new_daddr, &m->new_family); if (err) return err; if (rq1->sadb_x_ipsecrequest_proto != rq2->sadb_x_ipsecrequest_proto || rq1->sadb_x_ipsecrequest_mode != rq2->sadb_x_ipsecrequest_mode || rq1->sadb_x_ipsecrequest_reqid != rq2->sadb_x_ipsecrequest_reqid) return -EINVAL; m->proto = rq1->sadb_x_ipsecrequest_proto; if ((mode = pfkey_mode_to_xfrm(rq1->sadb_x_ipsecrequest_mode)) < 0) return -EINVAL; m->mode = mode; m->reqid = rq1->sadb_x_ipsecrequest_reqid; return ((int)(rq1->sadb_x_ipsecrequest_len + rq2->sadb_x_ipsecrequest_len)); } static int pfkey_migrate(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs) { int i, len, ret, err = -EINVAL; u8 dir; struct sadb_address *sa; struct sadb_x_kmaddress *kma; struct sadb_x_policy *pol; struct sadb_x_ipsecrequest *rq; struct xfrm_selector sel; struct xfrm_migrate m[XFRM_MAX_DEPTH]; struct xfrm_kmaddress k; if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC - 1], ext_hdrs[SADB_EXT_ADDRESS_DST - 1]) || !ext_hdrs[SADB_X_EXT_POLICY - 1]) { err = -EINVAL; goto out; } kma = ext_hdrs[SADB_X_EXT_KMADDRESS - 1]; pol = ext_hdrs[SADB_X_EXT_POLICY - 1]; if (pol->sadb_x_policy_dir >= IPSEC_DIR_MAX) { err = -EINVAL; goto out; } if (kma) { /* convert sadb_x_kmaddress to xfrm_kmaddress */ k.reserved = kma->sadb_x_kmaddress_reserved; ret = parse_sockaddr_pair((struct sockaddr *)(kma + 1), 8*(kma->sadb_x_kmaddress_len) - sizeof(*kma), &k.local, &k.remote, &k.family); if (ret < 0) { err = ret; goto out; } } dir = pol->sadb_x_policy_dir - 1; memset(&sel, 0, sizeof(sel)); /* set source address info of selector */ sa = ext_hdrs[SADB_EXT_ADDRESS_SRC - 1]; sel.family = pfkey_sadb_addr2xfrm_addr(sa, &sel.saddr); sel.prefixlen_s = sa->sadb_address_prefixlen; sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto); sel.sport = ((struct sockaddr_in *)(sa + 1))->sin_port; if (sel.sport) sel.sport_mask = htons(0xffff); /* set destination address info of selector */ sa = ext_hdrs[SADB_EXT_ADDRESS_DST - 1], pfkey_sadb_addr2xfrm_addr(sa, &sel.daddr); sel.prefixlen_d = sa->sadb_address_prefixlen; sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto); sel.dport = ((struct sockaddr_in *)(sa + 1))->sin_port; if (sel.dport) sel.dport_mask = htons(0xffff); rq = (struct sadb_x_ipsecrequest *)(pol + 1); /* extract ipsecrequests */ i = 0; len = pol->sadb_x_policy_len * 8 - sizeof(struct sadb_x_policy); while (len > 0 && i < XFRM_MAX_DEPTH) { ret = ipsecrequests_to_migrate(rq, len, &m[i]); if (ret < 0) { err = ret; goto out; } else { rq = (struct sadb_x_ipsecrequest *)((u8 *)rq + ret); len -= ret; i++; } } if (!i || len > 0) { err = -EINVAL; goto out; } return xfrm_migrate(&sel, dir, XFRM_POLICY_TYPE_MAIN, m, i, kma ? &k : NULL); out: return err; } #else static int pfkey_migrate(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs) { return -ENOPROTOOPT; } #endif static int pfkey_spdget(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs) { struct net *net = sock_net(sk); unsigned int dir; int err = 0, delete; struct sadb_x_policy *pol; struct xfrm_policy *xp; struct km_event c; if ((pol = ext_hdrs[SADB_X_EXT_POLICY-1]) == NULL) return -EINVAL; dir = xfrm_policy_id2dir(pol->sadb_x_policy_id); if (dir >= XFRM_POLICY_MAX) return -EINVAL; delete = (hdr->sadb_msg_type == SADB_X_SPDDELETE2); xp = xfrm_policy_byid(net, XFRM_POLICY_TYPE_MAIN, dir, pol->sadb_x_policy_id, delete, &err); if (xp == NULL) return -ENOENT; if (delete) { xfrm_audit_policy_delete(xp, err ? 0 : 1, audit_get_loginuid(current), audit_get_sessionid(current), 0); if (err) goto out; c.seq = hdr->sadb_msg_seq; c.pid = hdr->sadb_msg_pid; c.data.byid = 1; c.event = XFRM_MSG_DELPOLICY; km_policy_notify(xp, dir, &c); } else { err = key_pol_get_resp(sk, xp, hdr, dir); } out: xfrm_pol_put(xp); return err; } static int dump_sp(struct xfrm_policy *xp, int dir, int count, void *ptr) { struct pfkey_sock *pfk = ptr; struct sk_buff *out_skb; struct sadb_msg *out_hdr; int err; if (!pfkey_can_dump(&pfk->sk)) return -ENOBUFS; out_skb = pfkey_xfrm_policy2msg_prep(xp); if (IS_ERR(out_skb)) return PTR_ERR(out_skb); err = pfkey_xfrm_policy2msg(out_skb, xp, dir); if (err < 0) return err; out_hdr = (struct sadb_msg *) out_skb->data; out_hdr->sadb_msg_version = pfk->dump.msg_version; out_hdr->sadb_msg_type = SADB_X_SPDDUMP; out_hdr->sadb_msg_satype = SADB_SATYPE_UNSPEC; out_hdr->sadb_msg_errno = 0; out_hdr->sadb_msg_seq = count + 1; out_hdr->sadb_msg_pid = pfk->dump.msg_pid; if (pfk->dump.skb) pfkey_broadcast(pfk->dump.skb, GFP_ATOMIC, BROADCAST_ONE, &pfk->sk, sock_net(&pfk->sk)); pfk->dump.skb = out_skb; return 0; } static int pfkey_dump_sp(struct pfkey_sock *pfk) { struct net *net = sock_net(&pfk->sk); return xfrm_policy_walk(net, &pfk->dump.u.policy, dump_sp, (void *) pfk); } static void pfkey_dump_sp_done(struct pfkey_sock *pfk) { xfrm_policy_walk_done(&pfk->dump.u.policy); } static int pfkey_spddump(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs) { struct pfkey_sock *pfk = pfkey_sk(sk); if (pfk->dump.dump != NULL) return -EBUSY; pfk->dump.msg_version = hdr->sadb_msg_version; pfk->dump.msg_pid = hdr->sadb_msg_pid; pfk->dump.dump = pfkey_dump_sp; pfk->dump.done = pfkey_dump_sp_done; xfrm_policy_walk_init(&pfk->dump.u.policy, XFRM_POLICY_TYPE_MAIN); return pfkey_do_dump(pfk); } static int key_notify_policy_flush(struct km_event *c) { struct sk_buff *skb_out; struct sadb_msg *hdr; skb_out = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC); if (!skb_out) return -ENOBUFS; hdr = (struct sadb_msg *) skb_put(skb_out, sizeof(struct sadb_msg)); hdr->sadb_msg_type = SADB_X_SPDFLUSH; hdr->sadb_msg_seq = c->seq; hdr->sadb_msg_pid = c->pid; hdr->sadb_msg_version = PF_KEY_V2; hdr->sadb_msg_errno = (uint8_t) 0; hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t)); pfkey_broadcast(skb_out, GFP_ATOMIC, BROADCAST_ALL, NULL, c->net); return 0; } static int pfkey_spdflush(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs) { struct net *net = sock_net(sk); struct km_event c; struct xfrm_audit audit_info; int err; audit_info.loginuid = audit_get_loginuid(current); audit_info.sessionid = audit_get_sessionid(current); audit_info.secid = 0; err = xfrm_policy_flush(net, XFRM_POLICY_TYPE_MAIN, &audit_info); if (err) return err; c.data.type = XFRM_POLICY_TYPE_MAIN; c.event = XFRM_MSG_FLUSHPOLICY; c.pid = hdr->sadb_msg_pid; c.seq = hdr->sadb_msg_seq; c.net = net; km_policy_notify(NULL, 0, &c); return 0; } typedef int (*pfkey_handler)(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr, void **ext_hdrs); static pfkey_handler pfkey_funcs[SADB_MAX + 1] = { [SADB_RESERVED] = pfkey_reserved, [SADB_GETSPI] = pfkey_getspi, [SADB_UPDATE] = pfkey_add, [SADB_ADD] = pfkey_add, [SADB_DELETE] = pfkey_delete, [SADB_GET] = pfkey_get, [SADB_ACQUIRE] = pfkey_acquire, [SADB_REGISTER] = pfkey_register, [SADB_EXPIRE] = NULL, [SADB_FLUSH] = pfkey_flush, [SADB_DUMP] = pfkey_dump, [SADB_X_PROMISC] = pfkey_promisc, [SADB_X_PCHANGE] = NULL, [SADB_X_SPDUPDATE] = pfkey_spdadd, [SADB_X_SPDADD] = pfkey_spdadd, [SADB_X_SPDDELETE] = pfkey_spddelete, [SADB_X_SPDGET] = pfkey_spdget, [SADB_X_SPDACQUIRE] = NULL, [SADB_X_SPDDUMP] = pfkey_spddump, [SADB_X_SPDFLUSH] = pfkey_spdflush, [SADB_X_SPDSETIDX] = pfkey_spdadd, [SADB_X_SPDDELETE2] = pfkey_spdget, [SADB_X_MIGRATE] = pfkey_migrate, }; static int pfkey_process(struct sock *sk, struct sk_buff *skb, struct sadb_msg *hdr) { void *ext_hdrs[SADB_EXT_MAX]; int err; pfkey_broadcast(skb_clone(skb, GFP_KERNEL), GFP_KERNEL, BROADCAST_PROMISC_ONLY, NULL, sock_net(sk)); memset(ext_hdrs, 0, sizeof(ext_hdrs)); err = parse_exthdrs(skb, hdr, ext_hdrs); if (!err) { err = -EOPNOTSUPP; if (pfkey_funcs[hdr->sadb_msg_type]) err = pfkey_funcs[hdr->sadb_msg_type](sk, skb, hdr, ext_hdrs); } return err; } static struct sadb_msg *pfkey_get_base_msg(struct sk_buff *skb, int *errp) { struct sadb_msg *hdr = NULL; if (skb->len < sizeof(*hdr)) { *errp = -EMSGSIZE; } else { hdr = (struct sadb_msg *) skb->data; if (hdr->sadb_msg_version != PF_KEY_V2 || hdr->sadb_msg_reserved != 0 || (hdr->sadb_msg_type <= SADB_RESERVED || hdr->sadb_msg_type > SADB_MAX)) { hdr = NULL; *errp = -EINVAL; } else if (hdr->sadb_msg_len != (skb->len / sizeof(uint64_t)) || hdr->sadb_msg_len < (sizeof(struct sadb_msg) / sizeof(uint64_t))) { hdr = NULL; *errp = -EMSGSIZE; } else { *errp = 0; } } return hdr; } static inline int aalg_tmpl_set(struct xfrm_tmpl *t, struct xfrm_algo_desc *d) { unsigned int id = d->desc.sadb_alg_id; if (id >= sizeof(t->aalgos) * 8) return 0; return (t->aalgos >> id) & 1; } static inline int ealg_tmpl_set(struct xfrm_tmpl *t, struct xfrm_algo_desc *d) { unsigned int id = d->desc.sadb_alg_id; if (id >= sizeof(t->ealgos) * 8) return 0; return (t->ealgos >> id) & 1; } static int count_ah_combs(struct xfrm_tmpl *t) { int i, sz = 0; for (i = 0; ; i++) { struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(i); if (!aalg) break; if (aalg_tmpl_set(t, aalg) && aalg->available) sz += sizeof(struct sadb_comb); } return sz + sizeof(struct sadb_prop); } static int count_esp_combs(struct xfrm_tmpl *t) { int i, k, sz = 0; for (i = 0; ; i++) { struct xfrm_algo_desc *ealg = xfrm_ealg_get_byidx(i); if (!ealg) break; if (!(ealg_tmpl_set(t, ealg) && ealg->available)) continue; for (k = 1; ; k++) { struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(k); if (!aalg) break; if (aalg_tmpl_set(t, aalg) && aalg->available) sz += sizeof(struct sadb_comb); } } return sz + sizeof(struct sadb_prop); } static void dump_ah_combs(struct sk_buff *skb, struct xfrm_tmpl *t) { struct sadb_prop *p; int i; p = (struct sadb_prop*)skb_put(skb, sizeof(struct sadb_prop)); p->sadb_prop_len = sizeof(struct sadb_prop)/8; p->sadb_prop_exttype = SADB_EXT_PROPOSAL; p->sadb_prop_replay = 32; memset(p->sadb_prop_reserved, 0, sizeof(p->sadb_prop_reserved)); for (i = 0; ; i++) { struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(i); if (!aalg) break; if (aalg_tmpl_set(t, aalg) && aalg->available) { struct sadb_comb *c; c = (struct sadb_comb*)skb_put(skb, sizeof(struct sadb_comb)); memset(c, 0, sizeof(*c)); p->sadb_prop_len += sizeof(struct sadb_comb)/8; c->sadb_comb_auth = aalg->desc.sadb_alg_id; c->sadb_comb_auth_minbits = aalg->desc.sadb_alg_minbits; c->sadb_comb_auth_maxbits = aalg->desc.sadb_alg_maxbits; c->sadb_comb_hard_addtime = 24*60*60; c->sadb_comb_soft_addtime = 20*60*60; c->sadb_comb_hard_usetime = 8*60*60; c->sadb_comb_soft_usetime = 7*60*60; } } } static void dump_esp_combs(struct sk_buff *skb, struct xfrm_tmpl *t) { struct sadb_prop *p; int i, k; p = (struct sadb_prop*)skb_put(skb, sizeof(struct sadb_prop)); p->sadb_prop_len = sizeof(struct sadb_prop)/8; p->sadb_prop_exttype = SADB_EXT_PROPOSAL; p->sadb_prop_replay = 32; memset(p->sadb_prop_reserved, 0, sizeof(p->sadb_prop_reserved)); for (i=0; ; i++) { struct xfrm_algo_desc *ealg = xfrm_ealg_get_byidx(i); if (!ealg) break; if (!(ealg_tmpl_set(t, ealg) && ealg->available)) continue; for (k = 1; ; k++) { struct sadb_comb *c; struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(k); if (!aalg) break; if (!(aalg_tmpl_set(t, aalg) && aalg->available)) continue; c = (struct sadb_comb*)skb_put(skb, sizeof(struct sadb_comb)); memset(c, 0, sizeof(*c)); p->sadb_prop_len += sizeof(struct sadb_comb)/8; c->sadb_comb_auth = aalg->desc.sadb_alg_id; c->sadb_comb_auth_minbits = aalg->desc.sadb_alg_minbits; c->sadb_comb_auth_maxbits = aalg->desc.sadb_alg_maxbits; c->sadb_comb_encrypt = ealg->desc.sadb_alg_id; c->sadb_comb_encrypt_minbits = ealg->desc.sadb_alg_minbits; c->sadb_comb_encrypt_maxbits = ealg->desc.sadb_alg_maxbits; c->sadb_comb_hard_addtime = 24*60*60; c->sadb_comb_soft_addtime = 20*60*60; c->sadb_comb_hard_usetime = 8*60*60; c->sadb_comb_soft_usetime = 7*60*60; } } } static int key_notify_policy_expire(struct xfrm_policy *xp, struct km_event *c) { return 0; } static int key_notify_sa_expire(struct xfrm_state *x, struct km_event *c) { struct sk_buff *out_skb; struct sadb_msg *out_hdr; int hard; int hsc; hard = c->data.hard; if (hard) hsc = 2; else hsc = 1; out_skb = pfkey_xfrm_state2msg_expire(x, hsc); if (IS_ERR(out_skb)) return PTR_ERR(out_skb); out_hdr = (struct sadb_msg *) out_skb->data; out_hdr->sadb_msg_version = PF_KEY_V2; out_hdr->sadb_msg_type = SADB_EXPIRE; out_hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto); out_hdr->sadb_msg_errno = 0; out_hdr->sadb_msg_reserved = 0; out_hdr->sadb_msg_seq = 0; out_hdr->sadb_msg_pid = 0; pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_REGISTERED, NULL, xs_net(x)); return 0; } static int pfkey_send_notify(struct xfrm_state *x, struct km_event *c) { struct net *net = x ? xs_net(x) : c->net; struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); if (atomic_read(&net_pfkey->socks_nr) == 0) return 0; switch (c->event) { case XFRM_MSG_EXPIRE: return key_notify_sa_expire(x, c); case XFRM_MSG_DELSA: case XFRM_MSG_NEWSA: case XFRM_MSG_UPDSA: return key_notify_sa(x, c); case XFRM_MSG_FLUSHSA: return key_notify_sa_flush(c); case XFRM_MSG_NEWAE: /* not yet supported */ break; default: printk("pfkey: Unknown SA event %d\n", c->event); break; } return 0; } static int pfkey_send_policy_notify(struct xfrm_policy *xp, int dir, struct km_event *c) { if (xp && xp->type != XFRM_POLICY_TYPE_MAIN) return 0; switch (c->event) { case XFRM_MSG_POLEXPIRE: return key_notify_policy_expire(xp, c); case XFRM_MSG_DELPOLICY: case XFRM_MSG_NEWPOLICY: case XFRM_MSG_UPDPOLICY: return key_notify_policy(xp, dir, c); case XFRM_MSG_FLUSHPOLICY: if (c->data.type != XFRM_POLICY_TYPE_MAIN) break; return key_notify_policy_flush(c); default: printk("pfkey: Unknown policy event %d\n", c->event); break; } return 0; } static u32 get_acqseq(void) { u32 res; static u32 acqseq; static DEFINE_SPINLOCK(acqseq_lock); spin_lock_bh(&acqseq_lock); res = (++acqseq ? : ++acqseq); spin_unlock_bh(&acqseq_lock); return res; } static int pfkey_send_acquire(struct xfrm_state *x, struct xfrm_tmpl *t, struct xfrm_policy *xp, int dir) { struct sk_buff *skb; struct sadb_msg *hdr; struct sadb_address *addr; struct sadb_x_policy *pol; int sockaddr_size; int size; struct sadb_x_sec_ctx *sec_ctx; struct xfrm_sec_ctx *xfrm_ctx; int ctx_size = 0; sockaddr_size = pfkey_sockaddr_size(x->props.family); if (!sockaddr_size) return -EINVAL; size = sizeof(struct sadb_msg) + (sizeof(struct sadb_address) * 2) + (sockaddr_size * 2) + sizeof(struct sadb_x_policy); if (x->id.proto == IPPROTO_AH) size += count_ah_combs(t); else if (x->id.proto == IPPROTO_ESP) size += count_esp_combs(t); if ((xfrm_ctx = x->security)) { ctx_size = PFKEY_ALIGN8(xfrm_ctx->ctx_len); size += sizeof(struct sadb_x_sec_ctx) + ctx_size; } skb = alloc_skb(size + 16, GFP_ATOMIC); if (skb == NULL) return -ENOMEM; hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg)); hdr->sadb_msg_version = PF_KEY_V2; hdr->sadb_msg_type = SADB_ACQUIRE; hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto); hdr->sadb_msg_len = size / sizeof(uint64_t); hdr->sadb_msg_errno = 0; hdr->sadb_msg_reserved = 0; hdr->sadb_msg_seq = x->km.seq = get_acqseq(); hdr->sadb_msg_pid = 0; /* src address */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC; addr->sadb_address_proto = 0; addr->sadb_address_reserved = 0; addr->sadb_address_prefixlen = pfkey_sockaddr_fill(&x->props.saddr, 0, (struct sockaddr *) (addr + 1), x->props.family); if (!addr->sadb_address_prefixlen) BUG(); /* dst address */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST; addr->sadb_address_proto = 0; addr->sadb_address_reserved = 0; addr->sadb_address_prefixlen = pfkey_sockaddr_fill(&x->id.daddr, 0, (struct sockaddr *) (addr + 1), x->props.family); if (!addr->sadb_address_prefixlen) BUG(); pol = (struct sadb_x_policy *) skb_put(skb, sizeof(struct sadb_x_policy)); pol->sadb_x_policy_len = sizeof(struct sadb_x_policy)/sizeof(uint64_t); pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY; pol->sadb_x_policy_type = IPSEC_POLICY_IPSEC; pol->sadb_x_policy_dir = dir+1; pol->sadb_x_policy_id = xp->index; /* Set sadb_comb's. */ if (x->id.proto == IPPROTO_AH) dump_ah_combs(skb, t); else if (x->id.proto == IPPROTO_ESP) dump_esp_combs(skb, t); /* security context */ if (xfrm_ctx) { sec_ctx = (struct sadb_x_sec_ctx *) skb_put(skb, sizeof(struct sadb_x_sec_ctx) + ctx_size); sec_ctx->sadb_x_sec_len = (sizeof(struct sadb_x_sec_ctx) + ctx_size) / sizeof(uint64_t); sec_ctx->sadb_x_sec_exttype = SADB_X_EXT_SEC_CTX; sec_ctx->sadb_x_ctx_doi = xfrm_ctx->ctx_doi; sec_ctx->sadb_x_ctx_alg = xfrm_ctx->ctx_alg; sec_ctx->sadb_x_ctx_len = xfrm_ctx->ctx_len; memcpy(sec_ctx + 1, xfrm_ctx->ctx_str, xfrm_ctx->ctx_len); } return pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_REGISTERED, NULL, xs_net(x)); } static struct xfrm_policy *pfkey_compile_policy(struct sock *sk, int opt, u8 *data, int len, int *dir) { struct net *net = sock_net(sk); struct xfrm_policy *xp; struct sadb_x_policy *pol = (struct sadb_x_policy*)data; struct sadb_x_sec_ctx *sec_ctx; switch (sk->sk_family) { case AF_INET: if (opt != IP_IPSEC_POLICY) { *dir = -EOPNOTSUPP; return NULL; } break; #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) case AF_INET6: if (opt != IPV6_IPSEC_POLICY) { *dir = -EOPNOTSUPP; return NULL; } break; #endif default: *dir = -EINVAL; return NULL; } *dir = -EINVAL; if (len < sizeof(struct sadb_x_policy) || pol->sadb_x_policy_len*8 > len || pol->sadb_x_policy_type > IPSEC_POLICY_BYPASS || (!pol->sadb_x_policy_dir || pol->sadb_x_policy_dir > IPSEC_DIR_OUTBOUND)) return NULL; xp = xfrm_policy_alloc(net, GFP_ATOMIC); if (xp == NULL) { *dir = -ENOBUFS; return NULL; } xp->action = (pol->sadb_x_policy_type == IPSEC_POLICY_DISCARD ? XFRM_POLICY_BLOCK : XFRM_POLICY_ALLOW); xp->lft.soft_byte_limit = XFRM_INF; xp->lft.hard_byte_limit = XFRM_INF; xp->lft.soft_packet_limit = XFRM_INF; xp->lft.hard_packet_limit = XFRM_INF; xp->family = sk->sk_family; xp->xfrm_nr = 0; if (pol->sadb_x_policy_type == IPSEC_POLICY_IPSEC && (*dir = parse_ipsecrequests(xp, pol)) < 0) goto out; /* security context too */ if (len >= (pol->sadb_x_policy_len*8 + sizeof(struct sadb_x_sec_ctx))) { char *p = (char *)pol; struct xfrm_user_sec_ctx *uctx; p += pol->sadb_x_policy_len*8; sec_ctx = (struct sadb_x_sec_ctx *)p; if (len < pol->sadb_x_policy_len*8 + sec_ctx->sadb_x_sec_len) { *dir = -EINVAL; goto out; } if ((*dir = verify_sec_ctx_len(p))) goto out; uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx); *dir = security_xfrm_policy_alloc(&xp->security, uctx); kfree(uctx); if (*dir) goto out; } *dir = pol->sadb_x_policy_dir-1; return xp; out: xp->walk.dead = 1; xfrm_policy_destroy(xp); return NULL; } static int pfkey_send_new_mapping(struct xfrm_state *x, xfrm_address_t *ipaddr, __be16 sport) { struct sk_buff *skb; struct sadb_msg *hdr; struct sadb_sa *sa; struct sadb_address *addr; struct sadb_x_nat_t_port *n_port; int sockaddr_size; int size; __u8 satype = (x->id.proto == IPPROTO_ESP ? SADB_SATYPE_ESP : 0); struct xfrm_encap_tmpl *natt = NULL; sockaddr_size = pfkey_sockaddr_size(x->props.family); if (!sockaddr_size) return -EINVAL; if (!satype) return -EINVAL; if (!x->encap) return -EINVAL; natt = x->encap; /* Build an SADB_X_NAT_T_NEW_MAPPING message: * * HDR | SA | ADDRESS_SRC (old addr) | NAT_T_SPORT (old port) | * ADDRESS_DST (new addr) | NAT_T_DPORT (new port) */ size = sizeof(struct sadb_msg) + sizeof(struct sadb_sa) + (sizeof(struct sadb_address) * 2) + (sockaddr_size * 2) + (sizeof(struct sadb_x_nat_t_port) * 2); skb = alloc_skb(size + 16, GFP_ATOMIC); if (skb == NULL) return -ENOMEM; hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg)); hdr->sadb_msg_version = PF_KEY_V2; hdr->sadb_msg_type = SADB_X_NAT_T_NEW_MAPPING; hdr->sadb_msg_satype = satype; hdr->sadb_msg_len = size / sizeof(uint64_t); hdr->sadb_msg_errno = 0; hdr->sadb_msg_reserved = 0; hdr->sadb_msg_seq = x->km.seq = get_acqseq(); hdr->sadb_msg_pid = 0; /* SA */ sa = (struct sadb_sa *) skb_put(skb, sizeof(struct sadb_sa)); sa->sadb_sa_len = sizeof(struct sadb_sa)/sizeof(uint64_t); sa->sadb_sa_exttype = SADB_EXT_SA; sa->sadb_sa_spi = x->id.spi; sa->sadb_sa_replay = 0; sa->sadb_sa_state = 0; sa->sadb_sa_auth = 0; sa->sadb_sa_encrypt = 0; sa->sadb_sa_flags = 0; /* ADDRESS_SRC (old addr) */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC; addr->sadb_address_proto = 0; addr->sadb_address_reserved = 0; addr->sadb_address_prefixlen = pfkey_sockaddr_fill(&x->props.saddr, 0, (struct sockaddr *) (addr + 1), x->props.family); if (!addr->sadb_address_prefixlen) BUG(); /* NAT_T_SPORT (old port) */ n_port = (struct sadb_x_nat_t_port*) skb_put(skb, sizeof (*n_port)); n_port->sadb_x_nat_t_port_len = sizeof(*n_port)/sizeof(uint64_t); n_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_SPORT; n_port->sadb_x_nat_t_port_port = natt->encap_sport; n_port->sadb_x_nat_t_port_reserved = 0; /* ADDRESS_DST (new addr) */ addr = (struct sadb_address*) skb_put(skb, sizeof(struct sadb_address)+sockaddr_size); addr->sadb_address_len = (sizeof(struct sadb_address)+sockaddr_size)/ sizeof(uint64_t); addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST; addr->sadb_address_proto = 0; addr->sadb_address_reserved = 0; addr->sadb_address_prefixlen = pfkey_sockaddr_fill(ipaddr, 0, (struct sockaddr *) (addr + 1), x->props.family); if (!addr->sadb_address_prefixlen) BUG(); /* NAT_T_DPORT (new port) */ n_port = (struct sadb_x_nat_t_port*) skb_put(skb, sizeof (*n_port)); n_port->sadb_x_nat_t_port_len = sizeof(*n_port)/sizeof(uint64_t); n_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_DPORT; n_port->sadb_x_nat_t_port_port = sport; n_port->sadb_x_nat_t_port_reserved = 0; return pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_REGISTERED, NULL, xs_net(x)); } #ifdef CONFIG_NET_KEY_MIGRATE static int set_sadb_address(struct sk_buff *skb, int sasize, int type, struct xfrm_selector *sel) { struct sadb_address *addr; addr = (struct sadb_address *)skb_put(skb, sizeof(struct sadb_address) + sasize); addr->sadb_address_len = (sizeof(struct sadb_address) + sasize)/8; addr->sadb_address_exttype = type; addr->sadb_address_proto = sel->proto; addr->sadb_address_reserved = 0; switch (type) { case SADB_EXT_ADDRESS_SRC: addr->sadb_address_prefixlen = sel->prefixlen_s; pfkey_sockaddr_fill(&sel->saddr, 0, (struct sockaddr *)(addr + 1), sel->family); break; case SADB_EXT_ADDRESS_DST: addr->sadb_address_prefixlen = sel->prefixlen_d; pfkey_sockaddr_fill(&sel->daddr, 0, (struct sockaddr *)(addr + 1), sel->family); break; default: return -EINVAL; } return 0; } static int set_sadb_kmaddress(struct sk_buff *skb, struct xfrm_kmaddress *k) { struct sadb_x_kmaddress *kma; u8 *sa; int family = k->family; int socklen = pfkey_sockaddr_len(family); int size_req; size_req = (sizeof(struct sadb_x_kmaddress) + pfkey_sockaddr_pair_size(family)); kma = (struct sadb_x_kmaddress *)skb_put(skb, size_req); memset(kma, 0, size_req); kma->sadb_x_kmaddress_len = size_req / 8; kma->sadb_x_kmaddress_exttype = SADB_X_EXT_KMADDRESS; kma->sadb_x_kmaddress_reserved = k->reserved; sa = (u8 *)(kma + 1); if (!pfkey_sockaddr_fill(&k->local, 0, (struct sockaddr *)sa, family) || !pfkey_sockaddr_fill(&k->remote, 0, (struct sockaddr *)(sa+socklen), family)) return -EINVAL; return 0; } static int set_ipsecrequest(struct sk_buff *skb, uint8_t proto, uint8_t mode, int level, uint32_t reqid, uint8_t family, xfrm_address_t *src, xfrm_address_t *dst) { struct sadb_x_ipsecrequest *rq; u8 *sa; int socklen = pfkey_sockaddr_len(family); int size_req; size_req = sizeof(struct sadb_x_ipsecrequest) + pfkey_sockaddr_pair_size(family); rq = (struct sadb_x_ipsecrequest *)skb_put(skb, size_req); memset(rq, 0, size_req); rq->sadb_x_ipsecrequest_len = size_req; rq->sadb_x_ipsecrequest_proto = proto; rq->sadb_x_ipsecrequest_mode = mode; rq->sadb_x_ipsecrequest_level = level; rq->sadb_x_ipsecrequest_reqid = reqid; sa = (u8 *) (rq + 1); if (!pfkey_sockaddr_fill(src, 0, (struct sockaddr *)sa, family) || !pfkey_sockaddr_fill(dst, 0, (struct sockaddr *)(sa + socklen), family)) return -EINVAL; return 0; } #endif #ifdef CONFIG_NET_KEY_MIGRATE static int pfkey_send_migrate(struct xfrm_selector *sel, u8 dir, u8 type, struct xfrm_migrate *m, int num_bundles, struct xfrm_kmaddress *k) { int i; int sasize_sel; int size = 0; int size_pol = 0; struct sk_buff *skb; struct sadb_msg *hdr; struct sadb_x_policy *pol; struct xfrm_migrate *mp; if (type != XFRM_POLICY_TYPE_MAIN) return 0; if (num_bundles <= 0 || num_bundles > XFRM_MAX_DEPTH) return -EINVAL; if (k != NULL) { /* addresses for KM */ size += PFKEY_ALIGN8(sizeof(struct sadb_x_kmaddress) + pfkey_sockaddr_pair_size(k->family)); } /* selector */ sasize_sel = pfkey_sockaddr_size(sel->family); if (!sasize_sel) return -EINVAL; size += (sizeof(struct sadb_address) + sasize_sel) * 2; /* policy info */ size_pol += sizeof(struct sadb_x_policy); /* ipsecrequests */ for (i = 0, mp = m; i < num_bundles; i++, mp++) { /* old locator pair */ size_pol += sizeof(struct sadb_x_ipsecrequest) + pfkey_sockaddr_pair_size(mp->old_family); /* new locator pair */ size_pol += sizeof(struct sadb_x_ipsecrequest) + pfkey_sockaddr_pair_size(mp->new_family); } size += sizeof(struct sadb_msg) + size_pol; /* alloc buffer */ skb = alloc_skb(size, GFP_ATOMIC); if (skb == NULL) return -ENOMEM; hdr = (struct sadb_msg *)skb_put(skb, sizeof(struct sadb_msg)); hdr->sadb_msg_version = PF_KEY_V2; hdr->sadb_msg_type = SADB_X_MIGRATE; hdr->sadb_msg_satype = pfkey_proto2satype(m->proto); hdr->sadb_msg_len = size / 8; hdr->sadb_msg_errno = 0; hdr->sadb_msg_reserved = 0; hdr->sadb_msg_seq = 0; hdr->sadb_msg_pid = 0; /* Addresses to be used by KM for negotiation, if ext is available */ if (k != NULL && (set_sadb_kmaddress(skb, k) < 0)) return -EINVAL; /* selector src */ set_sadb_address(skb, sasize_sel, SADB_EXT_ADDRESS_SRC, sel); /* selector dst */ set_sadb_address(skb, sasize_sel, SADB_EXT_ADDRESS_DST, sel); /* policy information */ pol = (struct sadb_x_policy *)skb_put(skb, sizeof(struct sadb_x_policy)); pol->sadb_x_policy_len = size_pol / 8; pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY; pol->sadb_x_policy_type = IPSEC_POLICY_IPSEC; pol->sadb_x_policy_dir = dir + 1; pol->sadb_x_policy_id = 0; pol->sadb_x_policy_priority = 0; for (i = 0, mp = m; i < num_bundles; i++, mp++) { /* old ipsecrequest */ int mode = pfkey_mode_from_xfrm(mp->mode); if (mode < 0) goto err; if (set_ipsecrequest(skb, mp->proto, mode, (mp->reqid ? IPSEC_LEVEL_UNIQUE : IPSEC_LEVEL_REQUIRE), mp->reqid, mp->old_family, &mp->old_saddr, &mp->old_daddr) < 0) goto err; /* new ipsecrequest */ if (set_ipsecrequest(skb, mp->proto, mode, (mp->reqid ? IPSEC_LEVEL_UNIQUE : IPSEC_LEVEL_REQUIRE), mp->reqid, mp->new_family, &mp->new_saddr, &mp->new_daddr) < 0) goto err; } /* broadcast migrate message to sockets */ pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ALL, NULL, &init_net); return 0; err: kfree_skb(skb); return -EINVAL; } #else static int pfkey_send_migrate(struct xfrm_selector *sel, u8 dir, u8 type, struct xfrm_migrate *m, int num_bundles, struct xfrm_kmaddress *k) { return -ENOPROTOOPT; } #endif static int pfkey_sendmsg(struct kiocb *kiocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct sk_buff *skb = NULL; struct sadb_msg *hdr = NULL; int err; err = -EOPNOTSUPP; if (msg->msg_flags & MSG_OOB) goto out; err = -EMSGSIZE; if ((unsigned)len > sk->sk_sndbuf - 32) goto out; err = -ENOBUFS; skb = alloc_skb(len, GFP_KERNEL); if (skb == NULL) goto out; err = -EFAULT; if (memcpy_fromiovec(skb_put(skb,len), msg->msg_iov, len)) goto out; hdr = pfkey_get_base_msg(skb, &err); if (!hdr) goto out; mutex_lock(&xfrm_cfg_mutex); err = pfkey_process(sk, skb, hdr); mutex_unlock(&xfrm_cfg_mutex); out: if (err && hdr && pfkey_error(hdr, err, sk) == 0) err = 0; if (skb) kfree_skb(skb); return err ? : len; } static int pfkey_recvmsg(struct kiocb *kiocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sock *sk = sock->sk; struct pfkey_sock *pfk = pfkey_sk(sk); struct sk_buff *skb; int copied, err; err = -EINVAL; if (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT)) goto out; msg->msg_namelen = 0; skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err); if (skb == NULL) goto out; copied = skb->len; if (copied > len) { msg->msg_flags |= MSG_TRUNC; copied = len; } skb_reset_transport_header(skb); err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto out_free; sock_recv_timestamp(msg, sk, skb); err = (flags & MSG_TRUNC) ? skb->len : copied; if (pfk->dump.dump != NULL && 3 * atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf) pfkey_do_dump(pfk); out_free: skb_free_datagram(sk, skb); out: return err; } static const struct proto_ops pfkey_ops = { .family = PF_KEY, .owner = THIS_MODULE, /* Operations that make no sense on pfkey sockets. */ .bind = sock_no_bind, .connect = sock_no_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .getname = sock_no_getname, .ioctl = sock_no_ioctl, .listen = sock_no_listen, .shutdown = sock_no_shutdown, .setsockopt = sock_no_setsockopt, .getsockopt = sock_no_getsockopt, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, /* Now the operations that really occur. */ .release = pfkey_release, .poll = datagram_poll, .sendmsg = pfkey_sendmsg, .recvmsg = pfkey_recvmsg, }; static struct net_proto_family pfkey_family_ops = { .family = PF_KEY, .create = pfkey_create, .owner = THIS_MODULE, }; #ifdef CONFIG_PROC_FS static int pfkey_seq_show(struct seq_file *f, void *v) { struct sock *s; s = (struct sock *)v; if (v == SEQ_START_TOKEN) seq_printf(f ,"sk RefCnt Rmem Wmem User Inode\n"); else seq_printf(f ,"%p %-6d %-6u %-6u %-6u %-6lu\n", s, atomic_read(&s->sk_refcnt), atomic_read(&s->sk_rmem_alloc), atomic_read(&s->sk_wmem_alloc), sock_i_uid(s), sock_i_ino(s) ); return 0; } static void *pfkey_seq_start(struct seq_file *f, loff_t *ppos) { struct net *net = seq_file_net(f); struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); struct sock *s; struct hlist_node *node; loff_t pos = *ppos; read_lock(&pfkey_table_lock); if (pos == 0) return SEQ_START_TOKEN; sk_for_each(s, node, &net_pfkey->table) if (pos-- == 1) return s; return NULL; } static void *pfkey_seq_next(struct seq_file *f, void *v, loff_t *ppos) { struct net *net = seq_file_net(f); struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); ++*ppos; return (v == SEQ_START_TOKEN) ? sk_head(&net_pfkey->table) : sk_next((struct sock *)v); } static void pfkey_seq_stop(struct seq_file *f, void *v) { read_unlock(&pfkey_table_lock); } static struct seq_operations pfkey_seq_ops = { .start = pfkey_seq_start, .next = pfkey_seq_next, .stop = pfkey_seq_stop, .show = pfkey_seq_show, }; static int pfkey_seq_open(struct inode *inode, struct file *file) { return seq_open_net(inode, file, &pfkey_seq_ops, sizeof(struct seq_net_private)); } static struct file_operations pfkey_proc_ops = { .open = pfkey_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_net, }; static int __net_init pfkey_init_proc(struct net *net) { struct proc_dir_entry *e; e = proc_net_fops_create(net, "pfkey", 0, &pfkey_proc_ops); if (e == NULL) return -ENOMEM; return 0; } static void pfkey_exit_proc(struct net *net) { proc_net_remove(net, "pfkey"); } #else static int __net_init pfkey_init_proc(struct net *net) { return 0; } static void pfkey_exit_proc(struct net *net) { } #endif static struct xfrm_mgr pfkeyv2_mgr = { .id = "pfkeyv2", .notify = pfkey_send_notify, .acquire = pfkey_send_acquire, .compile_policy = pfkey_compile_policy, .new_mapping = pfkey_send_new_mapping, .notify_policy = pfkey_send_policy_notify, .migrate = pfkey_send_migrate, }; static int __net_init pfkey_net_init(struct net *net) { struct netns_pfkey *net_pfkey; int rv; net_pfkey = kmalloc(sizeof(struct netns_pfkey), GFP_KERNEL); if (!net_pfkey) { rv = -ENOMEM; goto out_kmalloc; } INIT_HLIST_HEAD(&net_pfkey->table); atomic_set(&net_pfkey->socks_nr, 0); rv = net_assign_generic(net, pfkey_net_id, net_pfkey); if (rv < 0) goto out_assign; rv = pfkey_init_proc(net); if (rv < 0) goto out_proc; return 0; out_proc: out_assign: kfree(net_pfkey); out_kmalloc: return rv; } static void __net_exit pfkey_net_exit(struct net *net) { struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id); pfkey_exit_proc(net); BUG_ON(!hlist_empty(&net_pfkey->table)); kfree(net_pfkey); } static struct pernet_operations pfkey_net_ops = { .init = pfkey_net_init, .exit = pfkey_net_exit, }; static void __exit ipsec_pfkey_exit(void) { unregister_pernet_gen_subsys(pfkey_net_id, &pfkey_net_ops); xfrm_unregister_km(&pfkeyv2_mgr); sock_unregister(PF_KEY); proto_unregister(&key_proto); } static int __init ipsec_pfkey_init(void) { int err = proto_register(&key_proto, 0); if (err != 0) goto out; err = sock_register(&pfkey_family_ops); if (err != 0) goto out_unregister_key_proto; err = xfrm_register_km(&pfkeyv2_mgr); if (err != 0) goto out_sock_unregister; err = register_pernet_gen_subsys(&pfkey_net_id, &pfkey_net_ops); if (err != 0) goto out_xfrm_unregister_km; out: return err; out_xfrm_unregister_km: xfrm_unregister_km(&pfkeyv2_mgr); out_sock_unregister: sock_unregister(PF_KEY); out_unregister_key_proto: proto_unregister(&key_proto); goto out; } module_init(ipsec_pfkey_init); module_exit(ipsec_pfkey_exit); MODULE_LICENSE("GPL"); MODULE_ALIAS_NETPROTO(PF_KEY);
felixhaedicke/nst-kernel
src/net/key/af_key.c
C
gpl-2.0
102,272
#ifndef _DATE_TIME_TIME_PARSING_HPP___ #define _DATE_TIME_TIME_PARSING_HPP___ /* Copyright (c) 2002,2003,2005 CrystalClear Software, Inc. * Use, modification and distribution is subject to the * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst * $Date: 2012-10-10 12:05:03 -0700 (Wed, 10 Oct 2012) $ */ #include "boost/tokenizer.hpp" #include "boost/lexical_cast.hpp" #include "boost/date_time/date_parsing.hpp" #include "boost/cstdint.hpp" #include <iostream> namespace boost { namespace date_time { //! computes exponential math like 2^8 => 256, only works with positive integers //Not general purpose, but needed b/c std::pow is not available //everywehere. Hasn't been tested with negatives and zeros template<class int_type> inline int_type power(int_type base, int_type exponent) { int_type result = 1; for(int i = 0; i < exponent; ++i){ result *= base; } return result; } //! Creates a time_duration object from a delimited string /*! Expected format for string is "[-]h[h][:mm][:ss][.fff]". * If the number of fractional digits provided is greater than the * precision of the time duration type then the extra digits are * truncated. * * A negative duration will be created if the first character in * string is a '-', all other '-' will be treated as delimiters. * Accepted delimiters are "-:,.". */ template<class time_duration, class char_type> inline time_duration str_from_delimited_time_duration(const std::basic_string<char_type>& s) { unsigned short min=0, sec =0; int hour =0; bool is_neg = (s.at(0) == '-'); boost::int64_t fs=0; int pos = 0; typedef typename std::basic_string<char_type>::traits_type traits_type; typedef boost::char_separator<char_type, traits_type> char_separator_type; typedef boost::tokenizer<char_separator_type, typename std::basic_string<char_type>::const_iterator, std::basic_string<char_type> > tokenizer; typedef typename boost::tokenizer<char_separator_type, typename std::basic_string<char_type>::const_iterator, typename std::basic_string<char_type> >::iterator tokenizer_iterator; char_type sep_chars[5] = {'-',':',',','.'}; char_separator_type sep(sep_chars); tokenizer tok(s,sep); for(tokenizer_iterator beg=tok.begin(); beg!=tok.end();++beg){ switch(pos) { case 0: { hour = boost::lexical_cast<int>(*beg); break; } case 1: { min = boost::lexical_cast<unsigned short>(*beg); break; } case 2: { sec = boost::lexical_cast<unsigned short>(*beg); break; }; case 3: { int digits = static_cast<int>(beg->length()); //Works around a bug in MSVC 6 library that does not support //operator>> thus meaning lexical_cast will fail to compile. #if (defined(BOOST_MSVC) && (_MSC_VER < 1300)) // msvc wouldn't compile 'time_duration::num_fractional_digits()' // (required template argument list) as a workaround a temp // time_duration object was used time_duration td(hour,min,sec,fs); int precision = td.num_fractional_digits(); // _atoi64 is an MS specific function if(digits >= precision) { // drop excess digits fs = _atoi64(beg->substr(0, precision).c_str()); } else { fs = _atoi64(beg->c_str()); } #else int precision = time_duration::num_fractional_digits(); if(digits >= precision) { // drop excess digits fs = boost::lexical_cast<boost::int64_t>(beg->substr(0, precision)); } else { fs = boost::lexical_cast<boost::int64_t>(*beg); } #endif if(digits < precision){ // trailing zeros get dropped from the string, // "1:01:01.1" would yield .000001 instead of .100000 // the power() compensates for the missing decimal places fs *= power(10, precision - digits); } break; } default: break; }//switch pos++; } if(is_neg) { return -time_duration(hour, min, sec, fs); } else { return time_duration(hour, min, sec, fs); } } //! Creates a time_duration object from a delimited string /*! Expected format for string is "[-]h[h][:mm][:ss][.fff]". * If the number of fractional digits provided is greater than the * precision of the time duration type then the extra digits are * truncated. * * A negative duration will be created if the first character in * string is a '-', all other '-' will be treated as delimiters. * Accepted delimiters are "-:,.". */ template<class time_duration> inline time_duration parse_delimited_time_duration(const std::string& s) { return str_from_delimited_time_duration<time_duration,char>(s); } //! Utility function to split appart string inline bool split(const std::string& s, char sep, std::string& first, std::string& second) { std::string::size_type sep_pos = s.find(sep); first = s.substr(0,sep_pos); if (sep_pos!=std::string::npos) second = s.substr(sep_pos+1); return true; } template<class time_type> inline time_type parse_delimited_time(const std::string& s, char sep) { typedef typename time_type::time_duration_type time_duration; typedef typename time_type::date_type date_type; //split date/time on a unique delimiter char such as ' ' or 'T' std::string date_string, tod_string; split(s, sep, date_string, tod_string); //call parse_date with first string date_type d = parse_date<date_type>(date_string); //call parse_time_duration with remaining string time_duration td = parse_delimited_time_duration<time_duration>(tod_string); //construct a time return time_type(d, td); } //! Parse time duration part of an iso time of form: [-]hhmmss[.fff...] (eg: 120259.123 is 12 hours, 2 min, 59 seconds, 123000 microseconds) template<class time_duration> inline time_duration parse_undelimited_time_duration(const std::string& s) { int precision = 0; { // msvc wouldn't compile 'time_duration::num_fractional_digits()' // (required template argument list) as a workaround, a temp // time_duration object was used time_duration tmp(0,0,0,1); precision = tmp.num_fractional_digits(); } // 'precision+1' is so we grab all digits, plus the decimal int offsets[] = {2,2,2, precision+1}; int pos = 0, sign = 0; int hours = 0; short min=0, sec=0; boost::int64_t fs=0; // increment one position if the string was "signed" if(s.at(sign) == '-') { ++sign; } // stlport choked when passing s.substr() to tokenizer // using a new string fixed the error std::string remain = s.substr(sign); /* We do not want the offset_separator to wrap the offsets, we * will never want to process more than: * 2 char, 2 char, 2 char, frac_sec length. * We *do* want the offset_separator to give us a partial for the * last characters if there were not enough provided in the input string. */ bool wrap_off = false; bool ret_part = true; boost::offset_separator osf(offsets, offsets+4, wrap_off, ret_part); typedef boost::tokenizer<boost::offset_separator, std::basic_string<char>::const_iterator, std::basic_string<char> > tokenizer; typedef boost::tokenizer<boost::offset_separator, std::basic_string<char>::const_iterator, std::basic_string<char> >::iterator tokenizer_iterator; tokenizer tok(remain, osf); for(tokenizer_iterator ti=tok.begin(); ti!=tok.end();++ti){ switch(pos) { case 0: { hours = boost::lexical_cast<int>(*ti); break; } case 1: { min = boost::lexical_cast<short>(*ti); break; } case 2: { sec = boost::lexical_cast<short>(*ti); break; } case 3: { std::string char_digits(ti->substr(1)); // digits w/no decimal int digits = static_cast<int>(char_digits.length()); //Works around a bug in MSVC 6 library that does not support //operator>> thus meaning lexical_cast will fail to compile. #if (defined(BOOST_MSVC) && (_MSC_VER <= 1200)) // 1200 == VC++ 6.0 // _atoi64 is an MS specific function if(digits >= precision) { // drop excess digits fs = _atoi64(char_digits.substr(0, precision).c_str()); } else if(digits == 0) { fs = 0; // just in case _atoi64 doesn't like an empty string } else { fs = _atoi64(char_digits.c_str()); } #else if(digits >= precision) { // drop excess digits fs = boost::lexical_cast<boost::int64_t>(char_digits.substr(0, precision)); } else if(digits == 0) { fs = 0; // lexical_cast doesn't like empty strings } else { fs = boost::lexical_cast<boost::int64_t>(char_digits); } #endif if(digits < precision){ // trailing zeros get dropped from the string, // "1:01:01.1" would yield .000001 instead of .100000 // the power() compensates for the missing decimal places fs *= power(10, precision - digits); } break; } default: break; }; pos++; } if(sign) { return -time_duration(hours, min, sec, fs); } else { return time_duration(hours, min, sec, fs); } } //! Parse time string of form YYYYMMDDThhmmss where T is delimeter between date and time template<class time_type> inline time_type parse_iso_time(const std::string& s, char sep) { typedef typename time_type::time_duration_type time_duration; typedef typename time_type::date_type date_type; //split date/time on a unique delimiter char such as ' ' or 'T' std::string date_string, tod_string; split(s, sep, date_string, tod_string); //call parse_date with first string date_type d = parse_undelimited_date<date_type>(date_string); //call parse_time_duration with remaining string time_duration td = parse_undelimited_time_duration<time_duration>(tod_string); //construct a time return time_type(d, td); } } }//namespace date_time #endif
hpl1nk/nonamegame
xray/SDK/include/boost/date_time/time_parsing.hpp
C++
gpl-3.0
11,012
@echo off rem Licensed to the Apache Software Foundation (ASF) under one or more rem contributor license agreements. See the NOTICE file distributed with rem this work for additional information regarding copyright ownership. rem The ASF licenses this file to You under the Apache License, Version 2.0 rem (the "License"); you may not use this file except in compliance with rem the License. You may obtain a copy of the License at rem rem http://www.apache.org/licenses/LICENSE-2.0 rem rem Unless required by applicable law or agreed to in writing, software rem distributed under the License is distributed on an "AS IS" BASIS, rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. rem See the License for the specific language governing permissions and rem limitations under the License. %~dp0kafka-run-class.bat kafka.tools.SimpleConsumerShell %*
karanjeets/crawl-evaluation
workspace/kafka/bin/windows/kafka-simple-consumer-shell.bat
Batchfile
apache-2.0
880
cask :v1 => 'chat' do version '1.0.3-1429112097' sha256 '430028e75c0a01ae2f8cad9b3b2bb64ae30893c5fc4ce524b5c5dd3a9413c123' # devmate.com is the official download host per the appcast feed url "http://dl.devmate.com/com.perma.chat/#{version.sub(%r{-.*$},'')}/#{version.sub(%r{.*?-},'')}/Chat-#{version.sub(%r{-.*$},'')}.zip" appcast 'http://updateinfo.devmate.com/com.perma.chat/updates.xml', :sha256 => '8009a30326218077e451fc3e3096eb37c7eaa1c667d32f5beccdece99c6c8a4b' name 'Chat' homepage 'https://chatformac.com/' license :gratis app 'Chat.app' end
bcaceiro/homebrew-cask
Casks/chat.rb
Ruby
bsd-2-clause
582
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright 2010-2011 Calxeda, Inc. */ #include <linux/clk.h> #include <linux/clkdev.h> #include <linux/clocksource.h> #include <linux/dma-map-ops.h> #include <linux/input.h> #include <linux/io.h> #include <linux/irqchip.h> #include <linux/pl320-ipc.h> #include <linux/of.h> #include <linux/of_irq.h> #include <linux/of_address.h> #include <linux/reboot.h> #include <linux/amba/bus.h> #include <linux/platform_device.h> #include <linux/psci.h> #include <asm/hardware/cache-l2x0.h> #include <asm/mach/arch.h> #include <asm/mach/map.h> #include "core.h" #include "sysregs.h" void __iomem *sregs_base; void __iomem *scu_base_addr; static void __init highbank_scu_map_io(void) { unsigned long base; /* Get SCU base */ asm("mrc p15, 4, %0, c15, c0, 0" : "=r" (base)); scu_base_addr = ioremap(base, SZ_4K); } static void highbank_l2c310_write_sec(unsigned long val, unsigned reg) { if (reg == L2X0_CTRL) highbank_smc1(0x102, val); else WARN_ONCE(1, "Highbank L2C310: ignoring write to reg 0x%x\n", reg); } static void __init highbank_init_irq(void) { irqchip_init(); if (of_find_compatible_node(NULL, NULL, "arm,cortex-a9")) highbank_scu_map_io(); } static void highbank_power_off(void) { highbank_set_pwr_shutdown(); while (1) cpu_do_idle(); } static int highbank_platform_notifier(struct notifier_block *nb, unsigned long event, void *__dev) { struct resource *res; int reg = -1; u32 val; struct device *dev = __dev; if (event != BUS_NOTIFY_ADD_DEVICE) return NOTIFY_DONE; if (of_device_is_compatible(dev->of_node, "calxeda,hb-ahci")) reg = 0xc; else if (of_device_is_compatible(dev->of_node, "calxeda,hb-sdhci")) reg = 0x18; else if (of_device_is_compatible(dev->of_node, "arm,pl330")) reg = 0x20; else if (of_device_is_compatible(dev->of_node, "calxeda,hb-xgmac")) { res = platform_get_resource(to_platform_device(dev), IORESOURCE_MEM, 0); if (res) { if (res->start == 0xfff50000) reg = 0; else if (res->start == 0xfff51000) reg = 4; } } if (reg < 0) return NOTIFY_DONE; if (of_property_read_bool(dev->of_node, "dma-coherent")) { val = readl(sregs_base + reg); writel(val | 0xff01, sregs_base + reg); set_dma_ops(dev, &arm_coherent_dma_ops); } return NOTIFY_OK; } static struct notifier_block highbank_amba_nb = { .notifier_call = highbank_platform_notifier, }; static struct notifier_block highbank_platform_nb = { .notifier_call = highbank_platform_notifier, }; static struct platform_device highbank_cpuidle_device = { .name = "cpuidle-calxeda", }; static int hb_keys_notifier(struct notifier_block *nb, unsigned long event, void *data) { u32 key = *(u32 *)data; if (event != 0x1000) return 0; if (key == KEY_POWER) orderly_poweroff(false); else if (key == 0xffff) ctrl_alt_del(); return 0; } static struct notifier_block hb_keys_nb = { .notifier_call = hb_keys_notifier, }; static void __init highbank_init(void) { struct device_node *np; /* Map system registers */ np = of_find_compatible_node(NULL, NULL, "calxeda,hb-sregs"); sregs_base = of_iomap(np, 0); WARN_ON(!sregs_base); pm_power_off = highbank_power_off; highbank_pm_init(); bus_register_notifier(&platform_bus_type, &highbank_platform_nb); bus_register_notifier(&amba_bustype, &highbank_amba_nb); pl320_ipc_register_notifier(&hb_keys_nb); if (psci_ops.cpu_suspend) platform_device_register(&highbank_cpuidle_device); } static const char *const highbank_match[] __initconst = { "calxeda,highbank", "calxeda,ecx-2000", NULL, }; DT_MACHINE_START(HIGHBANK, "Highbank") #if defined(CONFIG_ZONE_DMA) && defined(CONFIG_ARM_LPAE) .dma_zone_size = (4ULL * SZ_1G), #endif .l2c_aux_val = 0, .l2c_aux_mask = ~0, .l2c_write_sec = highbank_l2c310_write_sec, .init_irq = highbank_init_irq, .init_machine = highbank_init, .dt_compat = highbank_match, .restart = highbank_restart, MACHINE_END
GuillaumeSeren/linux
arch/arm/mach-highbank/highbank.c
C
gpl-2.0
3,945
/* * Copyright (C) ST-Ericsson AB 2010 * Author: Sjur Brendeland * License terms: GNU General Public License (GPL) version 2 */ #define pr_fmt(fmt) KBUILD_MODNAME ":%s(): " fmt, __func__ #include <linux/fs.h> #include <linux/init.h> #include <linux/module.h> #include <linux/sched.h> #include <linux/spinlock.h> #include <linux/mutex.h> #include <linux/list.h> #include <linux/wait.h> #include <linux/poll.h> #include <linux/tcp.h> #include <linux/uaccess.h> #include <linux/debugfs.h> #include <linux/caif/caif_socket.h> #include <linux/pkt_sched.h> #include <net/sock.h> #include <net/tcp_states.h> #include <net/caif/caif_layer.h> #include <net/caif/caif_dev.h> #include <net/caif/cfpkt.h> MODULE_LICENSE("GPL"); MODULE_ALIAS_NETPROTO(AF_CAIF); /* * CAIF state is re-using the TCP socket states. * caif_states stored in sk_state reflect the state as reported by * the CAIF stack, while sk_socket->state is the state of the socket. */ enum caif_states { CAIF_CONNECTED = TCP_ESTABLISHED, CAIF_CONNECTING = TCP_SYN_SENT, CAIF_DISCONNECTED = TCP_CLOSE }; #define TX_FLOW_ON_BIT 1 #define RX_FLOW_ON_BIT 2 struct caifsock { struct sock sk; /* must be first member */ struct cflayer layer; u32 flow_state; struct caif_connect_request conn_req; struct mutex readlock; struct dentry *debugfs_socket_dir; int headroom, tailroom, maxframe; }; static int rx_flow_is_on(struct caifsock *cf_sk) { return test_bit(RX_FLOW_ON_BIT, (void *) &cf_sk->flow_state); } static int tx_flow_is_on(struct caifsock *cf_sk) { return test_bit(TX_FLOW_ON_BIT, (void *) &cf_sk->flow_state); } static void set_rx_flow_off(struct caifsock *cf_sk) { clear_bit(RX_FLOW_ON_BIT, (void *) &cf_sk->flow_state); } static void set_rx_flow_on(struct caifsock *cf_sk) { set_bit(RX_FLOW_ON_BIT, (void *) &cf_sk->flow_state); } static void set_tx_flow_off(struct caifsock *cf_sk) { clear_bit(TX_FLOW_ON_BIT, (void *) &cf_sk->flow_state); } static void set_tx_flow_on(struct caifsock *cf_sk) { set_bit(TX_FLOW_ON_BIT, (void *) &cf_sk->flow_state); } static void caif_read_lock(struct sock *sk) { struct caifsock *cf_sk; cf_sk = container_of(sk, struct caifsock, sk); mutex_lock(&cf_sk->readlock); } static void caif_read_unlock(struct sock *sk) { struct caifsock *cf_sk; cf_sk = container_of(sk, struct caifsock, sk); mutex_unlock(&cf_sk->readlock); } static int sk_rcvbuf_lowwater(struct caifsock *cf_sk) { /* A quarter of full buffer is used a low water mark */ return cf_sk->sk.sk_rcvbuf / 4; } static void caif_flow_ctrl(struct sock *sk, int mode) { struct caifsock *cf_sk; cf_sk = container_of(sk, struct caifsock, sk); if (cf_sk->layer.dn && cf_sk->layer.dn->modemcmd) cf_sk->layer.dn->modemcmd(cf_sk->layer.dn, mode); } /* * Copied from sock.c:sock_queue_rcv_skb(), but changed so packets are * not dropped, but CAIF is sending flow off instead. */ static int caif_queue_rcv_skb(struct sock *sk, struct sk_buff *skb) { int err; int skb_len; unsigned long flags; struct sk_buff_head *list = &sk->sk_receive_queue; struct caifsock *cf_sk = container_of(sk, struct caifsock, sk); if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >= (unsigned int)sk->sk_rcvbuf && rx_flow_is_on(cf_sk)) { net_dbg_ratelimited("sending flow OFF (queue len = %d %d)\n", atomic_read(&cf_sk->sk.sk_rmem_alloc), sk_rcvbuf_lowwater(cf_sk)); set_rx_flow_off(cf_sk); caif_flow_ctrl(sk, CAIF_MODEMCMD_FLOW_OFF_REQ); } err = sk_filter(sk, skb); if (err) return err; if (!sk_rmem_schedule(sk, skb, skb->truesize) && rx_flow_is_on(cf_sk)) { set_rx_flow_off(cf_sk); net_dbg_ratelimited("sending flow OFF due to rmem_schedule\n"); caif_flow_ctrl(sk, CAIF_MODEMCMD_FLOW_OFF_REQ); } skb->dev = NULL; skb_set_owner_r(skb, sk); /* Cache the SKB length before we tack it onto the receive * queue. Once it is added it no longer belongs to us and * may be freed by other threads of control pulling packets * from the queue. */ skb_len = skb->len; spin_lock_irqsave(&list->lock, flags); if (!sock_flag(sk, SOCK_DEAD)) __skb_queue_tail(list, skb); spin_unlock_irqrestore(&list->lock, flags); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_data_ready(sk, skb_len); else kfree_skb(skb); return 0; } /* Packet Receive Callback function called from CAIF Stack */ static int caif_sktrecv_cb(struct cflayer *layr, struct cfpkt *pkt) { struct caifsock *cf_sk; struct sk_buff *skb; cf_sk = container_of(layr, struct caifsock, layer); skb = cfpkt_tonative(pkt); if (unlikely(cf_sk->sk.sk_state != CAIF_CONNECTED)) { kfree_skb(skb); return 0; } caif_queue_rcv_skb(&cf_sk->sk, skb); return 0; } static void cfsk_hold(struct cflayer *layr) { struct caifsock *cf_sk = container_of(layr, struct caifsock, layer); sock_hold(&cf_sk->sk); } static void cfsk_put(struct cflayer *layr) { struct caifsock *cf_sk = container_of(layr, struct caifsock, layer); sock_put(&cf_sk->sk); } /* Packet Control Callback function called from CAIF */ static void caif_ctrl_cb(struct cflayer *layr, enum caif_ctrlcmd flow, int phyid) { struct caifsock *cf_sk = container_of(layr, struct caifsock, layer); switch (flow) { case CAIF_CTRLCMD_FLOW_ON_IND: /* OK from modem to start sending again */ set_tx_flow_on(cf_sk); cf_sk->sk.sk_state_change(&cf_sk->sk); break; case CAIF_CTRLCMD_FLOW_OFF_IND: /* Modem asks us to shut up */ set_tx_flow_off(cf_sk); cf_sk->sk.sk_state_change(&cf_sk->sk); break; case CAIF_CTRLCMD_INIT_RSP: /* We're now connected */ caif_client_register_refcnt(&cf_sk->layer, cfsk_hold, cfsk_put); cf_sk->sk.sk_state = CAIF_CONNECTED; set_tx_flow_on(cf_sk); cf_sk->sk.sk_shutdown = 0; cf_sk->sk.sk_state_change(&cf_sk->sk); break; case CAIF_CTRLCMD_DEINIT_RSP: /* We're now disconnected */ cf_sk->sk.sk_state = CAIF_DISCONNECTED; cf_sk->sk.sk_state_change(&cf_sk->sk); break; case CAIF_CTRLCMD_INIT_FAIL_RSP: /* Connect request failed */ cf_sk->sk.sk_err = ECONNREFUSED; cf_sk->sk.sk_state = CAIF_DISCONNECTED; cf_sk->sk.sk_shutdown = SHUTDOWN_MASK; /* * Socket "standards" seems to require POLLOUT to * be set at connect failure. */ set_tx_flow_on(cf_sk); cf_sk->sk.sk_state_change(&cf_sk->sk); break; case CAIF_CTRLCMD_REMOTE_SHUTDOWN_IND: /* Modem has closed this connection, or device is down. */ cf_sk->sk.sk_shutdown = SHUTDOWN_MASK; cf_sk->sk.sk_err = ECONNRESET; set_rx_flow_on(cf_sk); cf_sk->sk.sk_error_report(&cf_sk->sk); break; default: pr_debug("Unexpected flow command %d\n", flow); } } static void caif_check_flow_release(struct sock *sk) { struct caifsock *cf_sk = container_of(sk, struct caifsock, sk); if (rx_flow_is_on(cf_sk)) return; if (atomic_read(&sk->sk_rmem_alloc) <= sk_rcvbuf_lowwater(cf_sk)) { set_rx_flow_on(cf_sk); caif_flow_ctrl(sk, CAIF_MODEMCMD_FLOW_ON_REQ); } } /* * Copied from unix_dgram_recvmsg, but removed credit checks, * changed locking, address handling and added MSG_TRUNC. */ static int caif_seqpkt_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *m, size_t len, int flags) { struct sock *sk = sock->sk; struct sk_buff *skb; int ret; int copylen; ret = -EOPNOTSUPP; if (m->msg_flags&MSG_OOB) goto read_error; skb = skb_recv_datagram(sk, flags, 0 , &ret); if (!skb) goto read_error; copylen = skb->len; if (len < copylen) { m->msg_flags |= MSG_TRUNC; copylen = len; } ret = skb_copy_datagram_iovec(skb, 0, m->msg_iov, copylen); if (ret) goto out_free; ret = (flags & MSG_TRUNC) ? skb->len : copylen; out_free: skb_free_datagram(sk, skb); caif_check_flow_release(sk); return ret; read_error: return ret; } /* Copied from unix_stream_wait_data, identical except for lock call. */ static long caif_stream_data_wait(struct sock *sk, long timeo) { DEFINE_WAIT(wait); lock_sock(sk); for (;;) { prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); if (!skb_queue_empty(&sk->sk_receive_queue) || sk->sk_err || sk->sk_state != CAIF_CONNECTED || sock_flag(sk, SOCK_DEAD) || (sk->sk_shutdown & RCV_SHUTDOWN) || signal_pending(current) || !timeo) break; set_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags); release_sock(sk); timeo = schedule_timeout(timeo); lock_sock(sk); clear_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags); } finish_wait(sk_sleep(sk), &wait); release_sock(sk); return timeo; } /* * Copied from unix_stream_recvmsg, but removed credit checks, * changed locking calls, changed address handling. */ static int caif_stream_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; int copied = 0; int target; int err = 0; long timeo; err = -EOPNOTSUPP; if (flags&MSG_OOB) goto out; /* * Lock the socket to prevent queue disordering * while sleeps in memcpy_tomsg */ err = -EAGAIN; if (sk->sk_state == CAIF_CONNECTING) goto out; caif_read_lock(sk); target = sock_rcvlowat(sk, flags&MSG_WAITALL, size); timeo = sock_rcvtimeo(sk, flags&MSG_DONTWAIT); do { int chunk; struct sk_buff *skb; lock_sock(sk); skb = skb_dequeue(&sk->sk_receive_queue); caif_check_flow_release(sk); if (skb == NULL) { if (copied >= target) goto unlock; /* * POSIX 1003.1g mandates this order. */ err = sock_error(sk); if (err) goto unlock; err = -ECONNRESET; if (sk->sk_shutdown & RCV_SHUTDOWN) goto unlock; err = -EPIPE; if (sk->sk_state != CAIF_CONNECTED) goto unlock; if (sock_flag(sk, SOCK_DEAD)) goto unlock; release_sock(sk); err = -EAGAIN; if (!timeo) break; caif_read_unlock(sk); timeo = caif_stream_data_wait(sk, timeo); if (signal_pending(current)) { err = sock_intr_errno(timeo); goto out; } caif_read_lock(sk); continue; unlock: release_sock(sk); break; } release_sock(sk); chunk = min_t(unsigned int, skb->len, size); if (memcpy_toiovec(msg->msg_iov, skb->data, chunk)) { skb_queue_head(&sk->sk_receive_queue, skb); if (copied == 0) copied = -EFAULT; break; } copied += chunk; size -= chunk; /* Mark read part of skb as used */ if (!(flags & MSG_PEEK)) { skb_pull(skb, chunk); /* put the skb back if we didn't use it up. */ if (skb->len) { skb_queue_head(&sk->sk_receive_queue, skb); break; } kfree_skb(skb); } else { /* * It is questionable, see note in unix_dgram_recvmsg. */ /* put message back and return */ skb_queue_head(&sk->sk_receive_queue, skb); break; } } while (size); caif_read_unlock(sk); out: return copied ? : err; } /* * Copied from sock.c:sock_wait_for_wmem, but change to wait for * CAIF flow-on and sock_writable. */ static long caif_wait_for_flow_on(struct caifsock *cf_sk, int wait_writeable, long timeo, int *err) { struct sock *sk = &cf_sk->sk; DEFINE_WAIT(wait); for (;;) { *err = 0; if (tx_flow_is_on(cf_sk) && (!wait_writeable || sock_writeable(&cf_sk->sk))) break; *err = -ETIMEDOUT; if (!timeo) break; *err = -ERESTARTSYS; if (signal_pending(current)) break; prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); *err = -ECONNRESET; if (sk->sk_shutdown & SHUTDOWN_MASK) break; *err = -sk->sk_err; if (sk->sk_err) break; *err = -EPIPE; if (cf_sk->sk.sk_state != CAIF_CONNECTED) break; timeo = schedule_timeout(timeo); } finish_wait(sk_sleep(sk), &wait); return timeo; } /* * Transmit a SKB. The device may temporarily request re-transmission * by returning EAGAIN. */ static int transmit_skb(struct sk_buff *skb, struct caifsock *cf_sk, int noblock, long timeo) { struct cfpkt *pkt; pkt = cfpkt_fromnative(CAIF_DIR_OUT, skb); memset(skb->cb, 0, sizeof(struct caif_payload_info)); cfpkt_set_prio(pkt, cf_sk->sk.sk_priority); if (cf_sk->layer.dn == NULL) { kfree_skb(skb); return -EINVAL; } return cf_sk->layer.dn->transmit(cf_sk->layer.dn, pkt); } /* Copied from af_unix:unix_dgram_sendmsg, and adapted to CAIF */ static int caif_seqpkt_sendmsg(struct kiocb *kiocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct caifsock *cf_sk = container_of(sk, struct caifsock, sk); int buffer_size; int ret = 0; struct sk_buff *skb = NULL; int noblock; long timeo; caif_assert(cf_sk); ret = sock_error(sk); if (ret) goto err; ret = -EOPNOTSUPP; if (msg->msg_flags&MSG_OOB) goto err; ret = -EOPNOTSUPP; if (msg->msg_namelen) goto err; ret = -EINVAL; if (unlikely(msg->msg_iov->iov_base == NULL)) goto err; noblock = msg->msg_flags & MSG_DONTWAIT; timeo = sock_sndtimeo(sk, noblock); timeo = caif_wait_for_flow_on(container_of(sk, struct caifsock, sk), 1, timeo, &ret); if (ret) goto err; ret = -EPIPE; if (cf_sk->sk.sk_state != CAIF_CONNECTED || sock_flag(sk, SOCK_DEAD) || (sk->sk_shutdown & RCV_SHUTDOWN)) goto err; /* Error if trying to write more than maximum frame size. */ ret = -EMSGSIZE; if (len > cf_sk->maxframe && cf_sk->sk.sk_protocol != CAIFPROTO_RFM) goto err; buffer_size = len + cf_sk->headroom + cf_sk->tailroom; ret = -ENOMEM; skb = sock_alloc_send_skb(sk, buffer_size, noblock, &ret); if (!skb || skb_tailroom(skb) < buffer_size) goto err; skb_reserve(skb, cf_sk->headroom); ret = memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len); if (ret) goto err; ret = transmit_skb(skb, cf_sk, noblock, timeo); if (ret < 0) /* skb is already freed */ return ret; return len; err: kfree_skb(skb); return ret; } /* * Copied from unix_stream_sendmsg and adapted to CAIF: * Changed removed permission handling and added waiting for flow on * and other minor adaptations. */ static int caif_stream_sendmsg(struct kiocb *kiocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct caifsock *cf_sk = container_of(sk, struct caifsock, sk); int err, size; struct sk_buff *skb; int sent = 0; long timeo; err = -EOPNOTSUPP; if (unlikely(msg->msg_flags&MSG_OOB)) goto out_err; if (unlikely(msg->msg_namelen)) goto out_err; timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT); timeo = caif_wait_for_flow_on(cf_sk, 1, timeo, &err); if (unlikely(sk->sk_shutdown & SEND_SHUTDOWN)) goto pipe_err; while (sent < len) { size = len-sent; if (size > cf_sk->maxframe) size = cf_sk->maxframe; /* If size is more than half of sndbuf, chop up message */ if (size > ((sk->sk_sndbuf >> 1) - 64)) size = (sk->sk_sndbuf >> 1) - 64; if (size > SKB_MAX_ALLOC) size = SKB_MAX_ALLOC; skb = sock_alloc_send_skb(sk, size + cf_sk->headroom + cf_sk->tailroom, msg->msg_flags&MSG_DONTWAIT, &err); if (skb == NULL) goto out_err; skb_reserve(skb, cf_sk->headroom); /* * If you pass two values to the sock_alloc_send_skb * it tries to grab the large buffer with GFP_NOFS * (which can fail easily), and if it fails grab the * fallback size buffer which is under a page and will * succeed. [Alan] */ size = min_t(int, size, skb_tailroom(skb)); err = memcpy_fromiovec(skb_put(skb, size), msg->msg_iov, size); if (err) { kfree_skb(skb); goto out_err; } err = transmit_skb(skb, cf_sk, msg->msg_flags&MSG_DONTWAIT, timeo); if (err < 0) /* skb is already freed */ goto pipe_err; sent += size; } return sent; pipe_err: if (sent == 0 && !(msg->msg_flags&MSG_NOSIGNAL)) send_sig(SIGPIPE, current, 0); err = -EPIPE; out_err: return sent ? : err; } static int setsockopt(struct socket *sock, int lvl, int opt, char __user *ov, unsigned int ol) { struct sock *sk = sock->sk; struct caifsock *cf_sk = container_of(sk, struct caifsock, sk); int linksel; if (cf_sk->sk.sk_socket->state != SS_UNCONNECTED) return -ENOPROTOOPT; switch (opt) { case CAIFSO_LINK_SELECT: if (ol < sizeof(int)) return -EINVAL; if (lvl != SOL_CAIF) goto bad_sol; if (copy_from_user(&linksel, ov, sizeof(int))) return -EINVAL; lock_sock(&(cf_sk->sk)); cf_sk->conn_req.link_selector = linksel; release_sock(&cf_sk->sk); return 0; case CAIFSO_REQ_PARAM: if (lvl != SOL_CAIF) goto bad_sol; if (cf_sk->sk.sk_protocol != CAIFPROTO_UTIL) return -ENOPROTOOPT; lock_sock(&(cf_sk->sk)); if (ol > sizeof(cf_sk->conn_req.param.data) || copy_from_user(&cf_sk->conn_req.param.data, ov, ol)) { release_sock(&cf_sk->sk); return -EINVAL; } cf_sk->conn_req.param.size = ol; release_sock(&cf_sk->sk); return 0; default: return -ENOPROTOOPT; } return 0; bad_sol: return -ENOPROTOOPT; } /* * caif_connect() - Connect a CAIF Socket * Copied and modified af_irda.c:irda_connect(). * * Note : by consulting "errno", the user space caller may learn the cause * of the failure. Most of them are visible in the function, others may come * from subroutines called and are listed here : * o -EAFNOSUPPORT: bad socket family or type. * o -ESOCKTNOSUPPORT: bad socket type or protocol * o -EINVAL: bad socket address, or CAIF link type * o -ECONNREFUSED: remote end refused the connection. * o -EINPROGRESS: connect request sent but timed out (or non-blocking) * o -EISCONN: already connected. * o -ETIMEDOUT: Connection timed out (send timeout) * o -ENODEV: No link layer to send request * o -ECONNRESET: Received Shutdown indication or lost link layer * o -ENOMEM: Out of memory * * State Strategy: * o sk_state: holds the CAIF_* protocol state, it's updated by * caif_ctrl_cb. * o sock->state: holds the SS_* socket state and is updated by connect and * disconnect. */ static int caif_connect(struct socket *sock, struct sockaddr *uaddr, int addr_len, int flags) { struct sock *sk = sock->sk; struct caifsock *cf_sk = container_of(sk, struct caifsock, sk); long timeo; int err; int ifindex, headroom, tailroom; unsigned int mtu; struct net_device *dev; lock_sock(sk); err = -EAFNOSUPPORT; if (uaddr->sa_family != AF_CAIF) goto out; switch (sock->state) { case SS_UNCONNECTED: /* Normal case, a fresh connect */ caif_assert(sk->sk_state == CAIF_DISCONNECTED); break; case SS_CONNECTING: switch (sk->sk_state) { case CAIF_CONNECTED: sock->state = SS_CONNECTED; err = -EISCONN; goto out; case CAIF_DISCONNECTED: /* Reconnect allowed */ break; case CAIF_CONNECTING: err = -EALREADY; if (flags & O_NONBLOCK) goto out; goto wait_connect; } break; case SS_CONNECTED: caif_assert(sk->sk_state == CAIF_CONNECTED || sk->sk_state == CAIF_DISCONNECTED); if (sk->sk_shutdown & SHUTDOWN_MASK) { /* Allow re-connect after SHUTDOWN_IND */ caif_disconnect_client(sock_net(sk), &cf_sk->layer); caif_free_client(&cf_sk->layer); break; } /* No reconnect on a seqpacket socket */ err = -EISCONN; goto out; case SS_DISCONNECTING: case SS_FREE: caif_assert(1); /*Should never happen */ break; } sk->sk_state = CAIF_DISCONNECTED; sock->state = SS_UNCONNECTED; sk_stream_kill_queues(&cf_sk->sk); err = -EINVAL; if (addr_len != sizeof(struct sockaddr_caif)) goto out; memcpy(&cf_sk->conn_req.sockaddr, uaddr, sizeof(struct sockaddr_caif)); /* Move to connecting socket, start sending Connect Requests */ sock->state = SS_CONNECTING; sk->sk_state = CAIF_CONNECTING; /* Check priority value comming from socket */ /* if priority value is out of range it will be ajusted */ if (cf_sk->sk.sk_priority > CAIF_PRIO_MAX) cf_sk->conn_req.priority = CAIF_PRIO_MAX; else if (cf_sk->sk.sk_priority < CAIF_PRIO_MIN) cf_sk->conn_req.priority = CAIF_PRIO_MIN; else cf_sk->conn_req.priority = cf_sk->sk.sk_priority; /*ifindex = id of the interface.*/ cf_sk->conn_req.ifindex = cf_sk->sk.sk_bound_dev_if; cf_sk->layer.receive = caif_sktrecv_cb; err = caif_connect_client(sock_net(sk), &cf_sk->conn_req, &cf_sk->layer, &ifindex, &headroom, &tailroom); if (err < 0) { cf_sk->sk.sk_socket->state = SS_UNCONNECTED; cf_sk->sk.sk_state = CAIF_DISCONNECTED; goto out; } err = -ENODEV; rcu_read_lock(); dev = dev_get_by_index_rcu(sock_net(sk), ifindex); if (!dev) { rcu_read_unlock(); goto out; } cf_sk->headroom = LL_RESERVED_SPACE_EXTRA(dev, headroom); mtu = dev->mtu; rcu_read_unlock(); cf_sk->tailroom = tailroom; cf_sk->maxframe = mtu - (headroom + tailroom); if (cf_sk->maxframe < 1) { pr_warn("CAIF Interface MTU too small (%d)\n", dev->mtu); err = -ENODEV; goto out; } err = -EINPROGRESS; wait_connect: if (sk->sk_state != CAIF_CONNECTED && (flags & O_NONBLOCK)) goto out; timeo = sock_sndtimeo(sk, flags & O_NONBLOCK); release_sock(sk); err = -ERESTARTSYS; timeo = wait_event_interruptible_timeout(*sk_sleep(sk), sk->sk_state != CAIF_CONNECTING, timeo); lock_sock(sk); if (timeo < 0) goto out; /* -ERESTARTSYS */ err = -ETIMEDOUT; if (timeo == 0 && sk->sk_state != CAIF_CONNECTED) goto out; if (sk->sk_state != CAIF_CONNECTED) { sock->state = SS_UNCONNECTED; err = sock_error(sk); if (!err) err = -ECONNREFUSED; goto out; } sock->state = SS_CONNECTED; err = 0; out: release_sock(sk); return err; } /* * caif_release() - Disconnect a CAIF Socket * Copied and modified af_irda.c:irda_release(). */ static int caif_release(struct socket *sock) { struct sock *sk = sock->sk; struct caifsock *cf_sk = container_of(sk, struct caifsock, sk); if (!sk) return 0; set_tx_flow_off(cf_sk); /* * Ensure that packets are not queued after this point in time. * caif_queue_rcv_skb checks SOCK_DEAD holding the queue lock, * this ensures no packets when sock is dead. */ spin_lock_bh(&sk->sk_receive_queue.lock); sock_set_flag(sk, SOCK_DEAD); spin_unlock_bh(&sk->sk_receive_queue.lock); sock->sk = NULL; WARN_ON(IS_ERR(cf_sk->debugfs_socket_dir)); if (cf_sk->debugfs_socket_dir != NULL) debugfs_remove_recursive(cf_sk->debugfs_socket_dir); lock_sock(&(cf_sk->sk)); sk->sk_state = CAIF_DISCONNECTED; sk->sk_shutdown = SHUTDOWN_MASK; caif_disconnect_client(sock_net(sk), &cf_sk->layer); cf_sk->sk.sk_socket->state = SS_DISCONNECTING; wake_up_interruptible_poll(sk_sleep(sk), POLLERR|POLLHUP); sock_orphan(sk); sk_stream_kill_queues(&cf_sk->sk); release_sock(sk); sock_put(sk); return 0; } /* Copied from af_unix.c:unix_poll(), added CAIF tx_flow handling */ static unsigned int caif_poll(struct file *file, struct socket *sock, poll_table *wait) { struct sock *sk = sock->sk; unsigned int mask; struct caifsock *cf_sk = container_of(sk, struct caifsock, sk); sock_poll_wait(file, sk_sleep(sk), wait); mask = 0; /* exceptional events? */ if (sk->sk_err) mask |= POLLERR; if (sk->sk_shutdown == SHUTDOWN_MASK) mask |= POLLHUP; if (sk->sk_shutdown & RCV_SHUTDOWN) mask |= POLLRDHUP; /* readable? */ if (!skb_queue_empty(&sk->sk_receive_queue) || (sk->sk_shutdown & RCV_SHUTDOWN)) mask |= POLLIN | POLLRDNORM; /* * we set writable also when the other side has shut down the * connection. This prevents stuck sockets. */ if (sock_writeable(sk) && tx_flow_is_on(cf_sk)) mask |= POLLOUT | POLLWRNORM | POLLWRBAND; return mask; } static const struct proto_ops caif_seqpacket_ops = { .family = PF_CAIF, .owner = THIS_MODULE, .release = caif_release, .bind = sock_no_bind, .connect = caif_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .getname = sock_no_getname, .poll = caif_poll, .ioctl = sock_no_ioctl, .listen = sock_no_listen, .shutdown = sock_no_shutdown, .setsockopt = setsockopt, .getsockopt = sock_no_getsockopt, .sendmsg = caif_seqpkt_sendmsg, .recvmsg = caif_seqpkt_recvmsg, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, }; static const struct proto_ops caif_stream_ops = { .family = PF_CAIF, .owner = THIS_MODULE, .release = caif_release, .bind = sock_no_bind, .connect = caif_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .getname = sock_no_getname, .poll = caif_poll, .ioctl = sock_no_ioctl, .listen = sock_no_listen, .shutdown = sock_no_shutdown, .setsockopt = setsockopt, .getsockopt = sock_no_getsockopt, .sendmsg = caif_stream_sendmsg, .recvmsg = caif_stream_recvmsg, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, }; /* This function is called when a socket is finally destroyed. */ static void caif_sock_destructor(struct sock *sk) { struct caifsock *cf_sk = container_of(sk, struct caifsock, sk); caif_assert(!atomic_read(&sk->sk_wmem_alloc)); caif_assert(sk_unhashed(sk)); caif_assert(!sk->sk_socket); if (!sock_flag(sk, SOCK_DEAD)) { WARN(1, "Attempt to release alive CAIF socket: %p\n", sk); return; } sk_stream_kill_queues(&cf_sk->sk); caif_free_client(&cf_sk->layer); } static int caif_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk = NULL; struct caifsock *cf_sk = NULL; static struct proto prot = {.name = "PF_CAIF", .owner = THIS_MODULE, .obj_size = sizeof(struct caifsock), }; if (!capable(CAP_SYS_ADMIN) && !capable(CAP_NET_ADMIN)) return -EPERM; /* * The sock->type specifies the socket type to use. * The CAIF socket is a packet stream in the sense * that it is packet based. CAIF trusts the reliability * of the link, no resending is implemented. */ if (sock->type == SOCK_SEQPACKET) sock->ops = &caif_seqpacket_ops; else if (sock->type == SOCK_STREAM) sock->ops = &caif_stream_ops; else return -ESOCKTNOSUPPORT; if (protocol < 0 || protocol >= CAIFPROTO_MAX) return -EPROTONOSUPPORT; /* * Set the socket state to unconnected. The socket state * is really not used at all in the net/core or socket.c but the * initialization makes sure that sock->state is not uninitialized. */ sk = sk_alloc(net, PF_CAIF, GFP_KERNEL, &prot); if (!sk) return -ENOMEM; cf_sk = container_of(sk, struct caifsock, sk); /* Store the protocol */ sk->sk_protocol = (unsigned char) protocol; /* Initialize default priority for well-known cases */ switch (protocol) { case CAIFPROTO_AT: sk->sk_priority = TC_PRIO_CONTROL; break; case CAIFPROTO_RFM: sk->sk_priority = TC_PRIO_INTERACTIVE_BULK; break; default: sk->sk_priority = TC_PRIO_BESTEFFORT; } /* * Lock in order to try to stop someone from opening the socket * too early. */ lock_sock(&(cf_sk->sk)); /* Initialize the nozero default sock structure data. */ sock_init_data(sock, sk); sk->sk_destruct = caif_sock_destructor; mutex_init(&cf_sk->readlock); /* single task reading lock */ cf_sk->layer.ctrlcmd = caif_ctrl_cb; cf_sk->sk.sk_socket->state = SS_UNCONNECTED; cf_sk->sk.sk_state = CAIF_DISCONNECTED; set_tx_flow_off(cf_sk); set_rx_flow_on(cf_sk); /* Set default options on configuration */ cf_sk->conn_req.link_selector = CAIF_LINK_LOW_LATENCY; cf_sk->conn_req.protocol = protocol; release_sock(&cf_sk->sk); return 0; } static struct net_proto_family caif_family_ops = { .family = PF_CAIF, .create = caif_create, .owner = THIS_MODULE, }; static int __init caif_sktinit_module(void) { int err = sock_register(&caif_family_ops); if (!err) return err; return 0; } static void __exit caif_sktexit_module(void) { sock_unregister(PF_CAIF); } module_init(caif_sktinit_module); module_exit(caif_sktexit_module);
NicholasPace/android_kernel_motorola_msm8916
net/caif/caif_socket.c
C
gpl-2.0
27,306
/** The YUI module contains the components required for building the YUI seed file. This includes the script loading mechanism, a simple queue, and the core utilities for the library. @module yui @main yui @submodule yui-base **/ /*jshint eqeqeq: false*/ if (typeof YUI != 'undefined') { YUI._YUI = YUI; } /** The YUI global namespace object. This is the constructor for all YUI instances. This is a self-instantiable factory function, meaning you don't need to precede it with the `new` operator. You can invoke it directly like this: YUI().use('*', function (Y) { // Y is a new YUI instance. }); But it also works like this: var Y = YUI(); The `YUI` constructor accepts an optional config object, like this: YUI({ debug: true, combine: false }).use('node', function (Y) { // Y.Node is ready to use. }); See the API docs for the <a href="config.html">Config</a> class for the complete list of supported configuration properties accepted by the YUI constuctor. If a global `YUI` object is already defined, the existing YUI object will not be overwritten, to ensure that defined namespaces are preserved. Each YUI instance has full custom event support, but only if the event system is available. @class YUI @uses EventTarget @constructor @global @param {Object} [config]* Zero or more optional configuration objects. Config values are stored in the `Y.config` property. See the <a href="config.html">Config</a> docs for the list of supported properties. **/ /*global YUI*/ /*global YUI_config*/ var YUI = function() { var i = 0, Y = this, args = arguments, l = args.length, instanceOf = function(o, type) { return (o && o.hasOwnProperty && (o instanceof type)); }, gconf = (typeof YUI_config !== 'undefined') && YUI_config; if (!(instanceOf(Y, YUI))) { Y = new YUI(); } else { // set up the core environment Y._init(); /** Master configuration that might span multiple contexts in a non- browser environment. It is applied first to all instances in all contexts. @example YUI.GlobalConfig = { filter: 'debug' }; YUI().use('node', function (Y) { // debug files used here }); YUI({ filter: 'min' }).use('node', function (Y) { // min files used here }); @property {Object} GlobalConfig @global @static **/ if (YUI.GlobalConfig) { Y.applyConfig(YUI.GlobalConfig); } /** Page-level config applied to all YUI instances created on the current page. This is applied after `YUI.GlobalConfig` and before any instance-level configuration. @example // Single global var to include before YUI seed file YUI_config = { filter: 'debug' }; YUI().use('node', function (Y) { // debug files used here }); YUI({ filter: 'min' }).use('node', function (Y) { // min files used here }); @property {Object} YUI_config @global **/ if (gconf) { Y.applyConfig(gconf); } // bind the specified additional modules for this instance if (!l) { Y._setup(); } } if (l) { // Each instance can accept one or more configuration objects. // These are applied after YUI.GlobalConfig and YUI_Config, // overriding values set in those config files if there is a // matching property. for (; i < l; i++) { Y.applyConfig(args[i]); } Y._setup(); } Y.instanceOf = instanceOf; return Y; }; (function() { var proto, prop, VERSION = '@VERSION@', PERIOD = '.', BASE = 'http://yui.yahooapis.com/', /* These CSS class names can't be generated by getClassName since it is not available at the time they are being used. */ DOC_LABEL = 'yui3-js-enabled', CSS_STAMP_EL = 'yui3-css-stamp', NOOP = function() {}, SLICE = Array.prototype.slice, APPLY_TO_AUTH = { 'io.xdrReady': 1, // the functions applyTo 'io.xdrResponse': 1, // can call. this should 'SWF.eventHandler': 1 }, // be done at build time hasWin = (typeof window != 'undefined'), win = (hasWin) ? window : null, doc = (hasWin) ? win.document : null, docEl = doc && doc.documentElement, docClass = docEl && docEl.className, instances = {}, time = new Date().getTime(), add = function(el, type, fn, capture) { if (el && el.addEventListener) { el.addEventListener(type, fn, capture); } else if (el && el.attachEvent) { el.attachEvent('on' + type, fn); } }, remove = function(el, type, fn, capture) { if (el && el.removeEventListener) { // this can throw an uncaught exception in FF try { el.removeEventListener(type, fn, capture); } catch (ex) {} } else if (el && el.detachEvent) { el.detachEvent('on' + type, fn); } }, handleLoad = function() { YUI.Env.windowLoaded = true; YUI.Env.DOMReady = true; if (hasWin) { remove(window, 'load', handleLoad); } }, getLoader = function(Y, o) { var loader = Y.Env._loader, lCore = [ 'loader-base' ], G_ENV = YUI.Env, mods = G_ENV.mods; if (loader) { //loader._config(Y.config); loader.ignoreRegistered = false; loader.onEnd = null; loader.data = null; loader.required = []; loader.loadType = null; } else { loader = new Y.Loader(Y.config); Y.Env._loader = loader; } if (mods && mods.loader) { lCore = [].concat(lCore, YUI.Env.loaderExtras); } YUI.Env.core = Y.Array.dedupe([].concat(YUI.Env.core, lCore)); return loader; }, clobber = function(r, s) { for (var i in s) { if (s.hasOwnProperty(i)) { r[i] = s[i]; } } }, ALREADY_DONE = { success: true }; // Stamp the documentElement (HTML) with a class of "yui-loaded" to // enable styles that need to key off of JS being enabled. if (docEl && docClass.indexOf(DOC_LABEL) == -1) { if (docClass) { docClass += ' '; } docClass += DOC_LABEL; docEl.className = docClass; } if (VERSION.indexOf('@') > -1) { VERSION = '3.5.0'; // dev time hack for cdn test } proto = { /** Applies a new configuration object to the config of this YUI instance. This will merge new group/module definitions, and will also update the loader cache if necessary. Updating `Y.config` directly will not update the cache. @method applyConfig @param {Object} o the configuration object. @since 3.2.0 **/ applyConfig: function(o) { o = o || NOOP; var attr, name, // detail, config = this.config, mods = config.modules, groups = config.groups, aliases = config.aliases, loader = this.Env._loader; for (name in o) { if (o.hasOwnProperty(name)) { attr = o[name]; if (mods && name == 'modules') { clobber(mods, attr); } else if (aliases && name == 'aliases') { clobber(aliases, attr); } else if (groups && name == 'groups') { clobber(groups, attr); } else if (name == 'win') { config[name] = (attr && attr.contentWindow) || attr; config.doc = config[name] ? config[name].document : null; } else if (name == '_yuid') { // preserve the guid } else { config[name] = attr; } } } if (loader) { loader._config(o); } }, /** Old way to apply a config to this instance (calls `applyConfig` under the hood). @private @method _config @param {Object} o The config to apply **/ _config: function(o) { this.applyConfig(o); }, /** Initializes this YUI instance. @private @method _init **/ _init: function() { var filter, el, Y = this, G_ENV = YUI.Env, Env = Y.Env, prop; /** The version number of this YUI instance. This value is typically updated by a script when a YUI release is built, so it may not reflect the correct version number when YUI is run from the development source tree. @property {String} version **/ Y.version = VERSION; if (!Env) { Y.Env = { core: ['get', 'features', 'intl-base', 'yui-log', 'yui-later'], loaderExtras: ['loader-rollup', 'loader-yui3'], mods: {}, // flat module map versions: {}, // version module map base: BASE, cdn: BASE + VERSION + '/build/', // bootstrapped: false, _idx: 0, _used: {}, _attached: {}, _missed: [], _yidx: 0, _uidx: 0, _guidp: 'y', _loaded: {}, // serviced: {}, // Regex in English: // I'll start at the \b(simpleyui). // 1. Look in the test string for "simpleyui" or "yui" or // "yui-base" or "yui-davglass" or "yui-foobar" that comes after a word break. That is, it // can't match "foyui" or "i_heart_simpleyui". This can be anywhere in the string. // 2. After #1 must come a forward slash followed by the string matched in #1, so // "yui-base/yui-base" or "simpleyui/simpleyui" or "yui-pants/yui-pants". // 3. The second occurence of the #1 token can optionally be followed by "-debug" or "-min", // so "yui/yui-min", "yui/yui-debug", "yui-base/yui-base-debug". NOT "yui/yui-tshirt". // 4. This is followed by ".js", so "yui/yui.js", "simpleyui/simpleyui-min.js" // 0. Going back to the beginning, now. If all that stuff in 1-4 comes after a "?" in the string, // then capture the junk between the LAST "&" and the string in 1-4. So // "blah?foo/yui/yui.js" will capture "foo/" and "blah?some/thing.js&3.3.0/build/yui-davglass/yui-davglass.js" // will capture "3.3.0/build/" // // Regex Exploded: // (?:\? Find a ? // (?:[^&]*&) followed by 0..n characters followed by an & // * in fact, find as many sets of characters followed by a & as you can // ([^&]*) capture the stuff after the last & in \1 // )? but it's ok if all this ?junk&more_junk stuff isn't even there // \b(simpleyui| after a word break find either the string "simpleyui" or // yui(?:-\w+)? the string "yui" optionally followed by a -, then more characters // ) and store the simpleyui or yui-* string in \2 // \/\2 then comes a / followed by the simpleyui or yui-* string in \2 // (?:-(min|debug))? optionally followed by "-min" or "-debug" // .js and ending in ".js" _BASE_RE: /(?:\?(?:[^&]*&)*([^&]*))?\b(simpleyui|yui(?:-\w+)?)\/\2(?:-(min|debug))?\.js/, parseBasePath: function(src, pattern) { var match = src.match(pattern), path, filter; if (match) { path = RegExp.leftContext || src.slice(0, src.indexOf(match[0])); // this is to set up the path to the loader. The file // filter for loader should match the yui include. filter = match[3]; // extract correct path for mixed combo urls // http://yuilibrary.com/projects/yui3/ticket/2528423 if (match[1]) { path += '?' + match[1]; } path = { filter: filter, path: path }; } return path; }, getBase: G_ENV && G_ENV.getBase || function(pattern) { var nodes = (doc && doc.getElementsByTagName('script')) || [], path = Env.cdn, parsed, i, len, src; for (i = 0, len = nodes.length; i < len; ++i) { src = nodes[i].src; if (src) { parsed = Y.Env.parseBasePath(src, pattern); if (parsed) { filter = parsed.filter; path = parsed.path; break; } } } // use CDN default return path; } }; Env = Y.Env; Env._loaded[VERSION] = {}; if (G_ENV && Y !== YUI) { Env._yidx = ++G_ENV._yidx; Env._guidp = ('yui_' + VERSION + '_' + Env._yidx + '_' + time).replace(/[^a-z0-9_]+/g, '_'); } else if (YUI._YUI) { G_ENV = YUI._YUI.Env; Env._yidx += G_ENV._yidx; Env._uidx += G_ENV._uidx; for (prop in G_ENV) { if (!(prop in Env)) { Env[prop] = G_ENV[prop]; } } delete YUI._YUI; } Y.id = Y.stamp(Y); instances[Y.id] = Y; } Y.constructor = YUI; // configuration defaults Y.config = Y.config || { bootstrap: true, cacheUse: true, debug: true, doc: doc, fetchCSS: true, throwFail: true, useBrowserConsole: true, useNativeES5: true, win: win, global: Function('return this')() }; //Register the CSS stamp element if (doc && !doc.getElementById(CSS_STAMP_EL)) { el = doc.createElement('div'); el.innerHTML = '<div id="' + CSS_STAMP_EL + '" style="position: absolute !important; visibility: hidden !important"></div>'; YUI.Env.cssStampEl = el.firstChild; if (doc.body) { doc.body.appendChild(YUI.Env.cssStampEl); } else { docEl.insertBefore(YUI.Env.cssStampEl, docEl.firstChild); } } else if (doc && doc.getElementById(CSS_STAMP_EL) && !YUI.Env.cssStampEl) { YUI.Env.cssStampEl = doc.getElementById(CSS_STAMP_EL); } Y.config.lang = Y.config.lang || 'en-US'; Y.config.base = YUI.config.base || Y.Env.getBase(Y.Env._BASE_RE); if (!filter || (!('mindebug').indexOf(filter))) { filter = 'min'; } filter = (filter) ? '-' + filter : filter; Y.config.loaderPath = YUI.config.loaderPath || 'loader/loader' + filter + '.js'; }, /** Finishes the instance setup. Attaches whatever YUI modules were defined at the time that this instance was created. @method _setup @private **/ _setup: function() { var i, Y = this, core = [], mods = YUI.Env.mods, extras = Y.config.core || [].concat(YUI.Env.core); //Clone it.. for (i = 0; i < extras.length; i++) { if (mods[extras[i]]) { core.push(extras[i]); } } Y._attach(['yui-base']); Y._attach(core); if (Y.Loader) { getLoader(Y); } // Y.log(Y.id + ' initialized', 'info', 'yui'); }, /** Executes the named method on the specified YUI instance if that method is whitelisted. @method applyTo @param {String} id YUI instance id. @param {String} method Name of the method to execute. For example: 'Object.keys'. @param {Array} args Arguments to apply to the method. @return {Mixed} Return value from the applied method, or `null` if the specified instance was not found or the method was not whitelisted. **/ applyTo: function(id, method, args) { if (!(method in APPLY_TO_AUTH)) { this.log(method + ': applyTo not allowed', 'warn', 'yui'); return null; } var instance = instances[id], nest, m, i; if (instance) { nest = method.split('.'); m = instance; for (i = 0; i < nest.length; i = i + 1) { m = m[nest[i]]; if (!m) { this.log('applyTo not found: ' + method, 'warn', 'yui'); } } return m && m.apply(instance, args); } return null; }, /** Registers a YUI module and makes it available for use in a `YUI().use()` call or as a dependency for other modules. The easiest way to create a first-class YUI module is to use <a href="http://yui.github.com/shifter/">Shifter</a>, the YUI component build tool. Shifter will automatically wrap your module code in a `YUI.add()` call along with any configuration info required for the module. @example YUI.add('davglass', function (Y) { Y.davglass = function () { Y.log('Dav was here!'); }; }, '3.4.0', { requires: ['harley-davidson', 'mt-dew'] }); @method add @param {String} name Module name. @param {Function} fn Function containing module code. This function will be executed whenever the module is attached to a specific YUI instance. @param {YUI} fn.Y The YUI instance to which this module is attached. @param {String} fn.name Name of the module @param {String} version Module version number. This is currently used only for informational purposes, and is not used internally by YUI. @param {Object} [config] Module config. @param {Array} [config.requires] Array of other module names that must be attached before this module can be attached. @param {Array} [config.optional] Array of optional module names that should be attached before this module is attached if they've already been loaded. If the `loadOptional` YUI option is `true`, optional modules that have not yet been loaded will be loaded just as if they were hard requirements. @param {Array} [config.use] Array of module names that are included within or otherwise provided by this module, and which should be attached automatically when this module is attached. This makes it possible to create "virtual rollup" modules that simply attach a collection of other modules or submodules. @return {YUI} This YUI instance. **/ add: function(name, fn, version, details) { details = details || {}; var env = YUI.Env, mod = { name: name, fn: fn, version: version, details: details }, //Instance hash so we don't apply it to the same instance twice applied = {}, loader, inst, i, versions = env.versions; env.mods[name] = mod; versions[version] = versions[version] || {}; versions[version][name] = mod; for (i in instances) { if (instances.hasOwnProperty(i)) { inst = instances[i]; if (!applied[inst.id]) { applied[inst.id] = true; loader = inst.Env._loader; if (loader) { if (!loader.moduleInfo[name] || loader.moduleInfo[name].temp) { loader.addModule(details, name); } } } } } return this; }, /** Executes the callback function associated with each required module, attaching the module to this YUI instance. @method _attach @param {Array} r The array of modules to attach @param {Boolean} [moot=false] If `true`, don't throw a warning if the module is not attached. @private **/ _attach: function(r, moot) { var i, name, mod, details, req, use, after, mods = YUI.Env.mods, aliases = YUI.Env.aliases, Y = this, j, cache = YUI.Env._renderedMods, loader = Y.Env._loader, done = Y.Env._attached, len = r.length, loader, def, go, c = []; //Check for conditional modules (in a second+ instance) and add their requirements //TODO I hate this entire method, it needs to be fixed ASAP (3.5.0) ^davglass for (i = 0; i < len; i++) { name = r[i]; mod = mods[name]; c.push(name); if (loader && loader.conditions[name]) { for (j in loader.conditions[name]) { if (loader.conditions[name].hasOwnProperty(j)) { def = loader.conditions[name][j]; go = def && ((def.ua && Y.UA[def.ua]) || (def.test && def.test(Y))); if (go) { c.push(def.name); } } } } } r = c; len = r.length; for (i = 0; i < len; i++) { if (!done[r[i]]) { name = r[i]; mod = mods[name]; if (aliases && aliases[name] && !mod) { Y._attach(aliases[name]); continue; } if (!mod) { if (loader && loader.moduleInfo[name]) { mod = loader.moduleInfo[name]; moot = true; } // Y.log('no js def for: ' + name, 'info', 'yui'); //if (!loader || !loader.moduleInfo[name]) { //if ((!loader || !loader.moduleInfo[name]) && !moot) { if (!moot && name) { if ((name.indexOf('skin-') === -1) && (name.indexOf('css') === -1)) { Y.Env._missed.push(name); Y.Env._missed = Y.Array.dedupe(Y.Env._missed); Y.message('NOT loaded: ' + name, 'warn', 'yui'); } } } else { done[name] = true; //Don't like this, but in case a mod was asked for once, then we fetch it //We need to remove it from the missed list ^davglass for (j = 0; j < Y.Env._missed.length; j++) { if (Y.Env._missed[j] === name) { Y.message('Found: ' + name + ' (was reported as missing earlier)', 'warn', 'yui'); Y.Env._missed.splice(j, 1); } } /* If it's a temp module, we need to redo it's requirements if it's already loaded since it may have been loaded by another instance and it's dependencies might have been redefined inside the fetched file. */ if (loader && cache && cache[name] && cache[name].temp) { loader.getRequires(cache[name]); req = []; for (j in loader.moduleInfo[name].expanded_map) { if (loader.moduleInfo[name].expanded_map.hasOwnProperty(j)) { req.push(j); } } Y._attach(req); } details = mod.details; req = details.requires; use = details.use; after = details.after; //Force Intl load if there is a language (Loader logic) @todo fix this shit if (details.lang) { req = req || []; req.unshift('intl'); } if (req) { for (j = 0; j < req.length; j++) { if (!done[req[j]]) { if (!Y._attach(req)) { return false; } break; } } } if (after) { for (j = 0; j < after.length; j++) { if (!done[after[j]]) { if (!Y._attach(after, true)) { return false; } break; } } } if (mod.fn) { if (Y.config.throwFail) { mod.fn(Y, name); } else { try { mod.fn(Y, name); } catch (e) { Y.error('Attach error: ' + name, e, name); return false; } } } if (use) { for (j = 0; j < use.length; j++) { if (!done[use[j]]) { if (!Y._attach(use)) { return false; } break; } } } } } } return true; }, /** Delays the `use` callback until another event has taken place such as `window.onload`, `domready`, `contentready`, or `available`. @private @method _delayCallback @param {Function} cb The original `use` callback. @param {String|Object} until Either an event name ('load', 'domready', etc.) or an object containing event/args keys for contentready/available. @return {Function} **/ _delayCallback: function(cb, until) { var Y = this, mod = ['event-base']; until = (Y.Lang.isObject(until) ? until : { event: until }); if (until.event === 'load') { mod.push('event-synthetic'); } Y.log('Delaying use callback until: ' + until.event, 'info', 'yui'); return function() { Y.log('Use callback fired, waiting on delay', 'info', 'yui'); var args = arguments; Y._use(mod, function() { Y.log('Delayed use wrapper callback after dependencies', 'info', 'yui'); Y.on(until.event, function() { args[1].delayUntil = until.event; Y.log('Delayed use callback done after ' + until.event, 'info', 'yui'); cb.apply(Y, args); }, until.args); }); }; }, /** Attaches one or more modules to this YUI instance. When this is executed, the requirements of the desired modules are analyzed, and one of several things can happen: * All required modules have already been loaded, and just need to be attached to this YUI instance. In this case, the `use()` callback will be executed synchronously after the modules are attached. * One or more modules have not yet been loaded, or the Get utility is not available, or the `bootstrap` config option is `false`. In this case, a warning is issued indicating that modules are missing, but all available modules will still be attached and the `use()` callback will be executed synchronously. * One or more modules are missing and the Loader is not available but the Get utility is, and `bootstrap` is not `false`. In this case, the Get utility will be used to load the Loader, and we will then proceed to the following state: * One or more modules are missing and the Loader is available. In this case, the Loader will be used to resolve the dependency tree for the missing modules and load them and their dependencies. When the Loader is finished loading modules, the `use()` callback will be executed asynchronously. @example // Loads and attaches dd and its dependencies. YUI().use('dd', function (Y) { // ... }); // Loads and attaches dd and node as well as all of their dependencies. YUI().use(['dd', 'node'], function (Y) { // ... }); // Attaches all modules that have already been loaded. YUI().use('*', function (Y) { // ... }); // Attaches a gallery module. YUI().use('gallery-yql', function (Y) { // ... }); // Attaches a YUI 2in3 module. YUI().use('yui2-datatable', function (Y) { // ... }); @method use @param {String|Array} modules* One or more module names to attach. @param {Function} [callback] Callback function to be executed once all specified modules and their dependencies have been attached. @param {YUI} callback.Y The YUI instance created for this sandbox. @param {Object} callback.status Object containing `success`, `msg` and `data` properties. @chainable **/ use: function() { var args = SLICE.call(arguments, 0), callback = args[args.length - 1], Y = this, i = 0, name, Env = Y.Env, provisioned = true; // The last argument supplied to use can be a load complete callback if (Y.Lang.isFunction(callback)) { args.pop(); if (Y.config.delayUntil) { callback = Y._delayCallback(callback, Y.config.delayUntil); } } else { callback = null; } if (Y.Lang.isArray(args[0])) { args = args[0]; } if (Y.config.cacheUse) { while ((name = args[i++])) { if (!Env._attached[name]) { provisioned = false; break; } } if (provisioned) { if (args.length) { Y.log('already provisioned: ' + args, 'info', 'yui'); } Y._notify(callback, ALREADY_DONE, args); return Y; } } if (Y._loading) { Y._useQueue = Y._useQueue || new Y.Queue(); Y._useQueue.add([args, callback]); } else { Y._use(args, function(Y, response) { Y._notify(callback, response, args); }); } return Y; }, /** Handles Loader notifications about attachment/load errors. @method _notify @param {Function} callback Callback to pass to `Y.config.loadErrorFn`. @param {Object} response Response returned from Loader. @param {Array} args Arguments passed from Loader. @private **/ _notify: function(callback, response, args) { if (!response.success && this.config.loadErrorFn) { this.config.loadErrorFn.call(this, this, callback, response, args); } else if (callback) { if (this.Env._missed && this.Env._missed.length) { response.msg = 'Missing modules: ' + this.Env._missed.join(); response.success = false; } if (this.config.throwFail) { callback(this, response); } else { try { callback(this, response); } catch (e) { this.error('use callback error', e, args); } } } }, /** Called from the `use` method queue to ensure that only one set of loading logic is performed at a time. @method _use @param {String} args* One or more modules to attach. @param {Function} [callback] Function to call once all required modules have been attached. @private **/ _use: function(args, callback) { if (!this.Array) { this._attach(['yui-base']); } var len, loader, handleBoot, Y = this, G_ENV = YUI.Env, mods = G_ENV.mods, Env = Y.Env, used = Env._used, aliases = G_ENV.aliases, queue = G_ENV._loaderQueue, firstArg = args[0], YArray = Y.Array, config = Y.config, boot = config.bootstrap, missing = [], i, r = [], ret = true, fetchCSS = config.fetchCSS, process = function(names, skip) { var i = 0, a = [], name, len, m, req, use; if (!names.length) { return; } if (aliases) { len = names.length; for (i = 0; i < len; i++) { if (aliases[names[i]] && !mods[names[i]]) { a = [].concat(a, aliases[names[i]]); } else { a.push(names[i]); } } names = a; } len = names.length; for (i = 0; i < len; i++) { name = names[i]; if (!skip) { r.push(name); } // only attach a module once if (used[name]) { continue; } m = mods[name]; req = null; use = null; if (m) { used[name] = true; req = m.details.requires; use = m.details.use; } else { // CSS files don't register themselves, see if it has // been loaded if (!G_ENV._loaded[VERSION][name]) { missing.push(name); } else { used[name] = true; // probably css } } // make sure requirements are attached if (req && req.length) { process(req); } // make sure we grab the submodule dependencies too if (use && use.length) { process(use, 1); } } }, handleLoader = function(fromLoader) { var response = fromLoader || { success: true, msg: 'not dynamic' }, redo, origMissing, ret = true, data = response.data; Y._loading = false; if (data) { origMissing = missing; missing = []; r = []; process(data); redo = missing.length; if (redo) { if ([].concat(missing).sort().join() == origMissing.sort().join()) { redo = false; } } } if (redo && data) { Y._loading = true; Y._use(missing, function() { Y.log('Nested use callback: ' + data, 'info', 'yui'); if (Y._attach(data)) { Y._notify(callback, response, data); } }); } else { if (data) { // Y.log('attaching from loader: ' + data, 'info', 'yui'); ret = Y._attach(data); } if (ret) { Y._notify(callback, response, args); } } if (Y._useQueue && Y._useQueue.size() && !Y._loading) { Y._use.apply(Y, Y._useQueue.next()); } }; // Y.log(Y.id + ': use called: ' + a + ' :: ' + callback, 'info', 'yui'); // YUI().use('*'); // bind everything available if (firstArg === '*') { args = []; for (i in mods) { if (mods.hasOwnProperty(i)) { args.push(i); } } ret = Y._attach(args); if (ret) { handleLoader(); } return Y; } if ((mods.loader || mods['loader-base']) && !Y.Loader) { Y.log('Loader was found in meta, but it is not attached. Attaching..', 'info', 'yui'); Y._attach(['loader' + ((!mods.loader) ? '-base' : '')]); } // Y.log('before loader requirements: ' + args, 'info', 'yui'); // use loader to expand dependencies and sort the // requirements if it is available. if (boot && Y.Loader && args.length) { Y.log('Using loader to expand dependencies', 'info', 'yui'); loader = getLoader(Y); loader.require(args); loader.ignoreRegistered = true; loader._boot = true; loader.calculate(null, (fetchCSS) ? null : 'js'); args = loader.sorted; loader._boot = false; } process(args); len = missing.length; if (len) { missing = YArray.dedupe(missing); len = missing.length; Y.log('Modules missing: ' + missing + ', ' + missing.length, 'info', 'yui'); } // dynamic load if (boot && len && Y.Loader) { // Y.log('Using loader to fetch missing deps: ' + missing, 'info', 'yui'); Y.log('Using Loader', 'info', 'yui'); Y._loading = true; loader = getLoader(Y); loader.onEnd = handleLoader; loader.context = Y; loader.data = args; loader.ignoreRegistered = false; loader.require(missing); loader.insert(null, (fetchCSS) ? null : 'js'); } else if (boot && len && Y.Get && !Env.bootstrapped) { Y._loading = true; handleBoot = function() { Y._loading = false; queue.running = false; Env.bootstrapped = true; G_ENV._bootstrapping = false; if (Y._attach(['loader'])) { Y._use(args, callback); } }; if (G_ENV._bootstrapping) { Y.log('Waiting for loader', 'info', 'yui'); queue.add(handleBoot); } else { G_ENV._bootstrapping = true; Y.log('Fetching loader: ' + config.base + config.loaderPath, 'info', 'yui'); Y.Get.script(config.base + config.loaderPath, { onEnd: handleBoot }); } } else { Y.log('Attaching available dependencies: ' + args, 'info', 'yui'); ret = Y._attach(args); if (ret) { handleLoader(); } } return Y; }, /** Utility method for safely creating namespaces if they don't already exist. May be called statically on the YUI global object or as a method on a YUI instance. When called statically, a namespace will be created on the YUI global object: // Create `YUI.your.namespace.here` as nested objects, preserving any // objects that already exist instead of overwriting them. YUI.namespace('your.namespace.here'); When called as a method on a YUI instance, a namespace will be created on that instance: // Creates `Y.property.package`. Y.namespace('property.package'); Dots in the input string cause `namespace` to create nested objects for each token. If any part of the requested namespace already exists, the current object will be left in place and will not be overwritten. This allows multiple calls to `namespace` to preserve existing namespaced properties. If the first token in the namespace string is "YAHOO", that token is discarded. This is legacy behavior for backwards compatibility with YUI 2. Be careful with namespace tokens. Reserved words may work in some browsers and not others. For instance, the following will fail in some browsers because the supported version of JavaScript reserves the word "long": Y.namespace('really.long.nested.namespace'); Note: If you pass multiple arguments to create multiple namespaces, only the last one created is returned from this function. @method namespace @param {String} namespace* One or more namespaces to create. @return {Object} Reference to the last namespace object created. **/ namespace: function() { var a = arguments, o, i = 0, j, d, arg; for (; i < a.length; i++) { o = this; //Reset base object per argument or it will get reused from the last arg = a[i]; if (arg.indexOf(PERIOD) > -1) { //Skip this if no "." is present d = arg.split(PERIOD); for (j = (d[0] == 'YAHOO') ? 1 : 0; j < d.length; j++) { o[d[j]] = o[d[j]] || {}; o = o[d[j]]; } } else { o[arg] = o[arg] || {}; o = o[arg]; //Reset base object to the new object so it's returned } } return o; }, // this is replaced if the log module is included log: NOOP, message: NOOP, // this is replaced if the dump module is included dump: function (o) { return ''+o; }, /** Reports an error. The reporting mechanism is controlled by the `throwFail` configuration attribute. If `throwFail` is falsy, the message is logged. If `throwFail` is truthy, a JS exception is thrown. If an `errorFn` is specified in the config it must return `true` to indicate that the exception was handled and keep it from being thrown. @method error @param {String} msg Error message. @param {Error|String} [e] JavaScript error object or an error string. @param {String} [src] Source of the error (such as the name of the module in which the error occurred). @chainable **/ error: function(msg, e, src) { //TODO Add check for window.onerror here var Y = this, ret; if (Y.config.errorFn) { ret = Y.config.errorFn.apply(Y, arguments); } if (!ret) { throw (e || new Error(msg)); } else { Y.message(msg, 'error', ''+src); // don't scrub this one } return Y; }, /** Generates an id string that is unique among all YUI instances in this execution context. @method guid @param {String} [pre] Prefix. @return {String} Unique id. **/ guid: function(pre) { var id = this.Env._guidp + '_' + (++this.Env._uidx); return (pre) ? (pre + id) : id; }, /** Returns a unique id associated with the given object and (if *readOnly* is falsy) stamps the object with that id so it can be identified in the future. Stamping an object involves adding a `_yuid` property to it that contains the object's id. One exception to this is that in Internet Explorer, DOM nodes have a `uniqueID` property that contains a browser-generated unique id, which will be used instead of a YUI-generated id when available. @method stamp @param {Object} o Object to stamp. @param {Boolean} readOnly If truthy and the given object has not already been stamped, the object will not be modified and `null` will be returned. @return {String} Object's unique id, or `null` if *readOnly* was truthy and the given object was not already stamped. **/ stamp: function(o, readOnly) { var uid; if (!o) { return o; } // IE generates its own unique ID for dom nodes // The uniqueID property of a document node returns a new ID if (o.uniqueID && o.nodeType && o.nodeType !== 9) { uid = o.uniqueID; } else { uid = (typeof o === 'string') ? o : o._yuid; } if (!uid) { uid = this.guid(); if (!readOnly) { try { o._yuid = uid; } catch (e) { uid = null; } } } return uid; }, /** Destroys this YUI instance. @method destroy @since 3.3.0 **/ destroy: function() { var Y = this; if (Y.Event) { Y.Event._unload(); } delete instances[Y.id]; delete Y.Env; delete Y.config; } /** Safe `instanceof` wrapper that works around a memory leak in IE when the object being tested is `window` or `document`. Unless you are testing objects that may be `window` or `document`, you should use the native `instanceof` operator instead of this method. @method instanceOf @param {Object} o Object to check. @param {Object} type Class to check against. @since 3.3.0 **/ }; YUI.prototype = proto; // inheritance utilities are not available yet for (prop in proto) { if (proto.hasOwnProperty(prop)) { YUI[prop] = proto[prop]; } } /** Applies a configuration to all YUI instances in this execution context. The main use case for this method is in "mashups" where several third-party scripts need to write to a global YUI config, but cannot share a single centrally-managed config object. This way they can all call `YUI.applyConfig({})` instead of overwriting the single global config. @example YUI.applyConfig({ modules: { davglass: { fullpath: './davglass.js' } } }); YUI.applyConfig({ modules: { foo: { fullpath: './foo.js' } } }); YUI().use('davglass', function (Y) { // Module davglass will be available here. }); @method applyConfig @param {Object} o Configuration object to apply. @static @since 3.5.0 **/ YUI.applyConfig = function(o) { if (!o) { return; } //If there is a GlobalConfig, apply it first to set the defaults if (YUI.GlobalConfig) { this.prototype.applyConfig.call(this, YUI.GlobalConfig); } //Apply this config to it this.prototype.applyConfig.call(this, o); //Reset GlobalConfig to the combined config YUI.GlobalConfig = this.config; }; // set up the environment YUI._init(); if (hasWin) { // add a window load event at load time so we can capture // the case where it fires before dynamic loading is // complete. add(window, 'load', handleLoad); } else { handleLoad(); } YUI.Env.add = add; YUI.Env.remove = remove; /*global exports*/ // Support the CommonJS method for exporting our single global if (typeof exports == 'object') { exports.YUI = YUI; /** * Set a method to be called when `Get.script` is called in Node.js * `Get` will open the file, then pass it's content and it's path * to this method before attaching it. Commonly used for code coverage * instrumentation. <strong>Calling this multiple times will only * attach the last hook method</strong>. This method is only * available in Node.js. * @method setLoadHook * @static * @param {Function} fn The function to set * @param {String} fn.data The content of the file * @param {String} fn.path The file path of the file */ YUI.setLoadHook = function(fn) { YUI._getLoadHook = fn; }; /** * Load hook for `Y.Get.script` in Node.js, see `YUI.setLoadHook` * @method _getLoadHook * @private * @param {String} data The content of the file * @param {String} path The file path of the file */ YUI._getLoadHook = null; } }()); /** Config object that contains all of the configuration options for this `YUI` instance. This object is supplied by the implementer when instantiating YUI. Some properties have default values if they are not supplied by the implementer. This object should not be updated directly because some values are cached. Use `applyConfig()` to update the config object on a YUI instance that has already been configured. @class config @static **/ /** If `true` (the default), YUI will "bootstrap" the YUI Loader and module metadata if they're needed to load additional dependencies and aren't already available. Setting this to `false` will prevent YUI from automatically loading the Loader and module metadata, so you will need to manually ensure that they're available or handle dependency resolution yourself. @property {Boolean} bootstrap @default true **/ /** If `true`, `Y.log()` messages will be written to the browser's debug console when available and when `useBrowserConsole` is also `true`. @property {Boolean} debug @default true **/ /** Log messages to the browser console if `debug` is `true` and the browser has a supported console. @property {Boolean} useBrowserConsole @default true **/ /** A hash of log sources that should be logged. If specified, only messages from these sources will be logged. Others will be discarded. @property {Object} logInclude @type object **/ /** A hash of log sources that should be not be logged. If specified, all sources will be logged *except* those on this list. @property {Object} logExclude **/ /** When the YUI seed file is dynamically loaded after the `window.onload` event has fired, set this to `true` to tell YUI that it shouldn't wait for `window.onload` to occur. This ensures that components that rely on `window.onload` and the `domready` custom event will work as expected even when YUI is dynamically injected. @property {Boolean} injected @default false **/ /** If `true`, `Y.error()` will generate or re-throw a JavaScript error. Otherwise, errors are merely logged silently. @property {Boolean} throwFail @default true **/ /** Reference to the global object for this execution context. In a browser, this is the current `window` object. In Node.js, this is the Node.js `global` object. @property {Object} global **/ /** The browser window or frame that this YUI instance should operate in. When running in Node.js, this property is `undefined`, since there is no `window` object. Use `global` to get a reference to the global object that will work in both browsers and Node.js. @property {Window} win **/ /** The browser `document` object associated with this YUI instance's `win` object. When running in Node.js, this property is `undefined`, since there is no `document` object. @property {Document} doc **/ /** A list of modules that defines the YUI core (overrides the default list). @property {Array} core @type Array @default ['get', 'features', 'intl-base', 'yui-log', 'yui-later', 'loader-base', 'loader-rollup', 'loader-yui3'] **/ /** A list of languages to use in order of preference. This list is matched against the list of available languages in modules that the YUI instance uses to determine the best possible localization of language sensitive modules. Languages are represented using BCP 47 language tags, such as "en-GB" for English as used in the United Kingdom, or "zh-Hans-CN" for simplified Chinese as used in China. The list may be provided as a comma-separated string or as an array. @property {String|String[]} lang **/ /** Default date format. @property {String} dateFormat @deprecated Use configuration in `DataType.Date.format()` instead. **/ /** Default locale. @property {String} locale @deprecated Use `config.lang` instead. **/ /** Default generic polling interval in milliseconds. @property {Number} pollInterval @default 20 **/ /** The number of dynamic `<script>` nodes to insert by default before automatically removing them when loading scripts. This applies only to script nodes because removing the node will not make the evaluated script unavailable. Dynamic CSS nodes are not auto purged, because removing a linked style sheet will also remove the style definitions. @property {Number} purgethreshold @default 20 **/ /** Delay in milliseconds to wait after a window `resize` event before firing the event. If another `resize` event occurs before this delay has elapsed, the delay will start over to ensure that `resize` events are throttled. @property {Number} windowResizeDelay @default 40 **/ /** Base directory for dynamic loading. @property {String} base **/ /** Base URL for a dynamic combo handler. This will be used to make combo-handled module requests if `combine` is set to `true. @property {String} comboBase @default "http://yui.yahooapis.com/combo?" **/ /** Root path to prepend to each module path when creating a combo-handled request. This is updated for each YUI release to point to a specific version of the library; for example: "3.8.0/build/". @property {String} root **/ /** Filter to apply to module urls. This filter will modify the default path for all modules. The default path for the YUI library is the minified version of the files (e.g., event-min.js). The filter property can be a predefined filter or a custom filter. The valid predefined filters are: - **debug**: Loads debug versions of modules (e.g., event-debug.js). - **raw**: Loads raw, non-minified versions of modules without debug logging (e.g., event.js). You can also define a custom filter, which must be an object literal containing a search regular expression and a replacement string: myFilter: { searchExp : "-min\\.js", replaceStr: "-debug.js" } @property {Object|String} filter **/ /** Skin configuration and customizations. @property {Object} skin @param {String} [skin.defaultSkin='sam'] Default skin name. This skin will be applied automatically to skinnable components if not overridden by a component-specific skin name. @param {String} [skin.base='assets/skins/'] Default base path for a skin, relative to Loader's `base` path. @param {Object} [skin.overrides] Component-specific skin name overrides. Specify a component name as the key and, as the value, a string or array of strings for a skin or skins that should be loaded for that component instead of the `defaultSkin`. **/ /** Hash of per-component filter specifications. If specified for a given component, this overrides the global `filter` config. @property {Object} filters **/ /** If `true`, YUI will use a combo handler to load multiple modules in as few requests as possible. The YUI CDN (which YUI uses by default) supports combo handling, but other servers may not. If the server from which you're loading YUI does not support combo handling, set this to `false`. Providing a value for the `base` config property will cause `combine` to default to `false` instead of `true`. @property {Boolean} combine @default true */ /** Array of module names that should never be dynamically loaded. @property {String[]} ignore **/ /** Array of module names that should always be loaded when required, even if already present on the page. @property {String[]} force **/ /** DOM element or id that should be used as the insertion point for dynamically added `<script>` and `<link>` nodes. @property {HTMLElement|String} insertBefore **/ /** Object hash containing attributes to add to dynamically added `<script>` nodes. @property {Object} jsAttributes **/ /** Object hash containing attributes to add to dynamically added `<link>` nodes. @property {Object} cssAttributes **/ /** Timeout in milliseconds before a dynamic JS or CSS request will be considered a failure. If not set, no timeout will be enforced. @property {Number} timeout **/ /** Callback for the 'CSSComplete' event. When dynamically loading YUI components with CSS, this property fires when the CSS is finished loading. This provides an opportunity to enhance the presentation of a loading page a little bit before the entire loading process is done. @property {Function} onCSS **/ /** A hash of module definitions to add to the list of available YUI modules. These modules can then be dynamically loaded via the `use()` method. This is a hash in which keys are module names and values are objects containing module metadata. See `Loader.addModule()` for the supported module metadata fields. Also see `groups`, which provides a way to configure the base and combo spec for a set of modules. @example modules: { mymod1: { requires: ['node'], fullpath: '/mymod1/mymod1.js' }, mymod2: { requires: ['mymod1'], fullpath: '/mymod2/mymod2.js' }, mymod3: '/js/mymod3.js', mycssmod: '/css/mycssmod.css' } @property {Object} modules **/ /** Aliases are dynamic groups of modules that can be used as shortcuts. @example YUI({ aliases: { davglass: [ 'node', 'yql', 'dd' ], mine: [ 'davglass', 'autocomplete'] } }).use('mine', function (Y) { // Node, YQL, DD & AutoComplete available here. }); @property {Object} aliases **/ /** A hash of module group definitions. For each group you can specify a list of modules and the base path and combo spec to use when dynamically loading the modules. @example groups: { yui2: { // specify whether or not this group has a combo service combine: true, // The comboSeperator to use with this group's combo handler comboSep: ';', // The maxURLLength for this server maxURLLength: 500, // the base path for non-combo paths base: 'http://yui.yahooapis.com/2.8.0r4/build/', // the path to the combo service comboBase: 'http://yui.yahooapis.com/combo?', // a fragment to prepend to the path attribute when // when building combo urls root: '2.8.0r4/build/', // the module definitions modules: { yui2_yde: { path: "yahoo-dom-event/yahoo-dom-event.js" }, yui2_anim: { path: "animation/animation.js", requires: ['yui2_yde'] } } } } @property {Object} groups **/ /** Path to the Loader JS file, relative to the `base` path. This is used to dynamically bootstrap the Loader when it's needed and isn't yet available. @property {String} loaderPath @default "loader/loader-min.js" **/ /** If `true`, YUI will attempt to load CSS dependencies and skins. Set this to `false` to prevent YUI from loading any CSS, or set it to the string `"force"` to force CSS dependencies to be loaded even if their associated JS modules are already loaded. @property {Boolean|String} fetchCSS @default true **/ /** Default gallery version used to build gallery module urls. @property {String} gallery @since 3.1.0 **/ /** Default YUI 2 version used to build YUI 2 module urls. This is used for intrinsic YUI 2 support via the 2in3 project. Also see the `2in3` config for pulling different revisions of the wrapped YUI 2 modules. @property {String} yui2 @default "2.9.0" @since 3.1.0 **/ /** Revision number of YUI 2in3 modules that should be used when loading YUI 2in3. @property {String} 2in3 @default "4" @since 3.1.0 **/ /** Alternate console log function that should be used in environments without a supported native console. This function is executed with the YUI instance as its `this` object. @property {Function} logFn @since 3.1.0 **/ /** Callback to execute when `Y.error()` is called. It receives the error message and a JavaScript error object if one was provided. This function is executed with the YUI instance as its `this` object. Returning `true` from this function will prevent an exception from being thrown. @property {Function} errorFn @param {String} errorFn.msg Error message @param {Object} [errorFn.err] Error object (if one was provided). @since 3.2.0 **/ /** A callback to execute when Loader fails to load one or more resources. This could be because of a script load failure. It could also be because a module fails to register itself when the `requireRegistration` config is `true`. If this function is defined, the `use()` callback will only be called when the loader succeeds. Otherwise, `use()` will always executes unless there was a JavaScript error when attaching a module. @property {Function} loadErrorFn @since 3.3.0 **/ /** If `true`, Loader will expect all loaded scripts to be first-class YUI modules that register themselves with the YUI global, and will trigger a failure if a loaded script does not register a YUI module. @property {Boolean} requireRegistration @default false @since 3.3.0 **/ /** Cache serviced use() requests. @property {Boolean} cacheUse @default true @since 3.3.0 @deprecated No longer used. **/ /** Whether or not YUI should use native ES5 functionality when available for features like `Y.Array.each()`, `Y.Object()`, etc. When `false`, YUI will always use its own fallback implementations instead of relying on ES5 functionality, even when ES5 functionality is available. @property {Boolean} useNativeES5 @default true @since 3.5.0 **/ /** * Leverage native JSON stringify if the browser has a native * implementation. In general, this is a good idea. See the Known Issues * section in the JSON user guide for caveats. The default value is true * for browsers with native JSON support. * * @property useNativeJSONStringify * @type Boolean * @default true * @since 3.8.0 */ /** * Leverage native JSON parse if the browser has a native implementation. * In general, this is a good idea. See the Known Issues section in the * JSON user guide for caveats. The default value is true for browsers with * native JSON support. * * @property useNativeJSONParse * @type Boolean * @default true * @since 3.8.0 */ /** Delay the `use` callback until a specific event has passed (`load`, `domready`, `contentready` or `available`) @property delayUntil @type String|Object @since 3.6.0 @example You can use `load` or `domready` strings by default: YUI({ delayUntil: 'domready' }, function (Y) { // This will not execute until 'domeready' occurs. }); Or you can delay until a node is available (with `available` or `contentready`): YUI({ delayUntil: { event: 'available', args : '#foo' } }, function (Y) { // This will not execute until a node matching the selector "#foo" is // available in the DOM. }); @property {Object|String} delayUntil @since 3.6.0 **/ YUI.add('yui-base', function (Y, NAME) { /* * YUI stub * @module yui * @submodule yui-base */ /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Provides core language utilites and extensions used throughout YUI. * * @class Lang * @static */ var L = Y.Lang || (Y.Lang = {}), STRING_PROTO = String.prototype, TOSTRING = Object.prototype.toString, TYPES = { 'undefined' : 'undefined', 'number' : 'number', 'boolean' : 'boolean', 'string' : 'string', '[object Function]': 'function', '[object RegExp]' : 'regexp', '[object Array]' : 'array', '[object Date]' : 'date', '[object Error]' : 'error' }, SUBREGEX = /\{\s*([^|}]+?)\s*(?:\|([^}]*))?\s*\}/g, TRIMREGEX = /^\s+|\s+$/g, NATIVE_FN_REGEX = /\{\s*\[(?:native code|function)\]\s*\}/i; // -- Protected Methods -------------------------------------------------------- /** Returns `true` if the given function appears to be implemented in native code, `false` otherwise. Will always return `false` -- even in ES5-capable browsers -- if the `useNativeES5` YUI config option is set to `false`. This isn't guaranteed to be 100% accurate and won't work for anything other than functions, but it can be useful for determining whether a function like `Array.prototype.forEach` is native or a JS shim provided by another library. There's a great article by @kangax discussing certain flaws with this technique: <http://perfectionkills.com/detecting-built-in-host-methods/> While his points are valid, it's still possible to benefit from this function as long as it's used carefully and sparingly, and in such a way that false negatives have minimal consequences. It's used internally to avoid using potentially broken non-native ES5 shims that have been added to the page by other libraries. @method _isNative @param {Function} fn Function to test. @return {Boolean} `true` if _fn_ appears to be native, `false` otherwise. @static @protected @since 3.5.0 **/ L._isNative = function (fn) { return !!(Y.config.useNativeES5 && fn && NATIVE_FN_REGEX.test(fn)); }; // -- Public Methods ----------------------------------------------------------- /** * Determines whether or not the provided item is an array. * * Returns `false` for array-like collections such as the function `arguments` * collection or `HTMLElement` collections. Use `Y.Array.test()` if you want to * test for an array-like collection. * * @method isArray * @param o The object to test. * @return {boolean} true if o is an array. * @static */ L.isArray = L._isNative(Array.isArray) ? Array.isArray : function (o) { return L.type(o) === 'array'; }; /** * Determines whether or not the provided item is a boolean. * @method isBoolean * @static * @param o The object to test. * @return {boolean} true if o is a boolean. */ L.isBoolean = function(o) { return typeof o === 'boolean'; }; /** * Determines whether or not the supplied item is a date instance. * @method isDate * @static * @param o The object to test. * @return {boolean} true if o is a date. */ L.isDate = function(o) { return L.type(o) === 'date' && o.toString() !== 'Invalid Date' && !isNaN(o); }; /** * <p> * Determines whether or not the provided item is a function. * Note: Internet Explorer thinks certain functions are objects: * </p> * * <pre> * var obj = document.createElement("object"); * Y.Lang.isFunction(obj.getAttribute) // reports false in IE * &nbsp; * var input = document.createElement("input"); // append to body * Y.Lang.isFunction(input.focus) // reports false in IE * </pre> * * <p> * You will have to implement additional tests if these functions * matter to you. * </p> * * @method isFunction * @static * @param o The object to test. * @return {boolean} true if o is a function. */ L.isFunction = function(o) { return L.type(o) === 'function'; }; /** * Determines whether or not the provided item is null. * @method isNull * @static * @param o The object to test. * @return {boolean} true if o is null. */ L.isNull = function(o) { return o === null; }; /** * Determines whether or not the provided item is a legal number. * @method isNumber * @static * @param o The object to test. * @return {boolean} true if o is a number. */ L.isNumber = function(o) { return typeof o === 'number' && isFinite(o); }; /** * Determines whether or not the provided item is of type object * or function. Note that arrays are also objects, so * <code>Y.Lang.isObject([]) === true</code>. * @method isObject * @static * @param o The object to test. * @param failfn {boolean} fail if the input is a function. * @return {boolean} true if o is an object. * @see isPlainObject */ L.isObject = function(o, failfn) { var t = typeof o; return (o && (t === 'object' || (!failfn && (t === 'function' || L.isFunction(o))))) || false; }; /** * Determines whether or not the provided item is a string. * @method isString * @static * @param o The object to test. * @return {boolean} true if o is a string. */ L.isString = function(o) { return typeof o === 'string'; }; /** * Determines whether or not the provided item is undefined. * @method isUndefined * @static * @param o The object to test. * @return {boolean} true if o is undefined. */ L.isUndefined = function(o) { return typeof o === 'undefined'; }; /** * A convenience method for detecting a legitimate non-null value. * Returns false for null/undefined/NaN, true for other values, * including 0/false/'' * @method isValue * @static * @param o The item to test. * @return {boolean} true if it is not null/undefined/NaN || false. */ L.isValue = function(o) { var t = L.type(o); switch (t) { case 'number': return isFinite(o); case 'null': // fallthru case 'undefined': return false; default: return !!t; } }; /** * Returns the current time in milliseconds. * * @method now * @return {Number} Current time in milliseconds. * @static * @since 3.3.0 */ L.now = Date.now || function () { return new Date().getTime(); }; /** * Lightweight version of <code>Y.substitute</code>. Uses the same template * structure as <code>Y.substitute</code>, but doesn't support recursion, * auto-object coersion, or formats. * @method sub * @param {string} s String to be modified. * @param {object} o Object containing replacement values. * @return {string} the substitute result. * @static * @since 3.2.0 */ L.sub = function(s, o) { return s.replace ? s.replace(SUBREGEX, function (match, key) { return L.isUndefined(o[key]) ? match : o[key]; }) : s; }; /** * Returns a string without any leading or trailing whitespace. If * the input is not a string, the input will be returned untouched. * @method trim * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trim = STRING_PROTO.trim ? function(s) { return s && s.trim ? s.trim() : s; } : function (s) { try { return s.replace(TRIMREGEX, ''); } catch (e) { return s; } }; /** * Returns a string without any leading whitespace. * @method trimLeft * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimLeft = STRING_PROTO.trimLeft ? function (s) { return s.trimLeft(); } : function (s) { return s.replace(/^\s+/, ''); }; /** * Returns a string without any trailing whitespace. * @method trimRight * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimRight = STRING_PROTO.trimRight ? function (s) { return s.trimRight(); } : function (s) { return s.replace(/\s+$/, ''); }; /** Returns one of the following strings, representing the type of the item passed in: * "array" * "boolean" * "date" * "error" * "function" * "null" * "number" * "object" * "regexp" * "string" * "undefined" Known issues: * `typeof HTMLElementCollection` returns function in Safari, but `Y.Lang.type()` reports "object", which could be a good thing -- but it actually caused the logic in <code>Y.Lang.isObject</code> to fail. @method type @param o the item to test. @return {string} the detected type. @static **/ L.type = function(o) { return TYPES[typeof o] || TYPES[TOSTRING.call(o)] || (o ? 'object' : 'null'); }; /** @module yui @submodule yui-base */ var Lang = Y.Lang, Native = Array.prototype, hasOwn = Object.prototype.hasOwnProperty; /** Provides utility methods for working with arrays. Additional array helpers can be found in the `collection` and `array-extras` modules. `Y.Array(thing)` returns a native array created from _thing_. Depending on _thing_'s type, one of the following will happen: * Arrays are returned unmodified unless a non-zero _startIndex_ is specified. * Array-like collections (see `Array.test()`) are converted to arrays. * For everything else, a new array is created with _thing_ as the sole item. Note: elements that are also collections, such as `<form>` and `<select>` elements, are not automatically converted to arrays. To force a conversion, pass `true` as the value of the _force_ parameter. @class Array @constructor @param {Any} thing The thing to arrayify. @param {Number} [startIndex=0] If non-zero and _thing_ is an array or array-like collection, a subset of items starting at the specified index will be returned. @param {Boolean} [force=false] If `true`, _thing_ will be treated as an array-like collection no matter what. @return {Array} A native array created from _thing_, according to the rules described above. **/ function YArray(thing, startIndex, force) { var len, result; /*jshint expr: true*/ startIndex || (startIndex = 0); if (force || YArray.test(thing)) { // IE throws when trying to slice HTMLElement collections. try { return Native.slice.call(thing, startIndex); } catch (ex) { result = []; for (len = thing.length; startIndex < len; ++startIndex) { result.push(thing[startIndex]); } return result; } } return [thing]; } Y.Array = YArray; /** Dedupes an array of strings, returning an array that's guaranteed to contain only one copy of a given string. This method differs from `Array.unique()` in that it's optimized for use only with strings, whereas `unique` may be used with other types (but is slower). Using `dedupe()` with non-string values may result in unexpected behavior. @method dedupe @param {String[]} array Array of strings to dedupe. @return {Array} Deduped copy of _array_. @static @since 3.4.0 **/ YArray.dedupe = function (array) { var hash = {}, results = [], i, item, len; for (i = 0, len = array.length; i < len; ++i) { item = array[i]; if (!hasOwn.call(hash, item)) { hash[item] = 1; results.push(item); } } return results; }; /** Executes the supplied function on each item in the array. This method wraps the native ES5 `Array.forEach()` method if available. @method each @param {Array} array Array to iterate. @param {Function} fn Function to execute on each item in the array. The function will receive the following arguments: @param {Any} fn.item Current array item. @param {Number} fn.index Current array index. @param {Array} fn.array Array being iterated. @param {Object} [thisObj] `this` object to use when calling _fn_. @return {YUI} The YUI instance. @static **/ YArray.each = YArray.forEach = Lang._isNative(Native.forEach) ? function (array, fn, thisObj) { Native.forEach.call(array || [], fn, thisObj || Y); return Y; } : function (array, fn, thisObj) { for (var i = 0, len = (array && array.length) || 0; i < len; ++i) { if (i in array) { fn.call(thisObj || Y, array[i], i, array); } } return Y; }; /** Alias for `each()`. @method forEach @static **/ /** Returns an object using the first array as keys and the second as values. If the second array is not provided, or if it doesn't contain the same number of values as the first array, then `true` will be used in place of the missing values. @example Y.Array.hash(['a', 'b', 'c'], ['foo', 'bar']); // => {a: 'foo', b: 'bar', c: true} @method hash @param {String[]} keys Array of strings to use as keys. @param {Array} [values] Array to use as values. @return {Object} Hash using the first array as keys and the second as values. @static **/ YArray.hash = function (keys, values) { var hash = {}, vlen = (values && values.length) || 0, i, len; for (i = 0, len = keys.length; i < len; ++i) { if (i in keys) { hash[keys[i]] = vlen > i && i in values ? values[i] : true; } } return hash; }; /** Returns the index of the first item in the array that's equal (using a strict equality check) to the specified _value_, or `-1` if the value isn't found. This method wraps the native ES5 `Array.indexOf()` method if available. @method indexOf @param {Array} array Array to search. @param {Any} value Value to search for. @param {Number} [from=0] The index at which to begin the search. @return {Number} Index of the item strictly equal to _value_, or `-1` if not found. @static **/ YArray.indexOf = Lang._isNative(Native.indexOf) ? function (array, value, from) { return Native.indexOf.call(array, value, from); } : function (array, value, from) { // http://es5.github.com/#x15.4.4.14 var len = array.length; from = +from || 0; from = (from > 0 || -1) * Math.floor(Math.abs(from)); if (from < 0) { from += len; if (from < 0) { from = 0; } } for (; from < len; ++from) { if (from in array && array[from] === value) { return from; } } return -1; }; /** Numeric sort convenience function. The native `Array.prototype.sort()` function converts values to strings and sorts them in lexicographic order, which is unsuitable for sorting numeric values. Provide `Array.numericSort` as a custom sort function when you want to sort values in numeric order. @example [42, 23, 8, 16, 4, 15].sort(Y.Array.numericSort); // => [4, 8, 15, 16, 23, 42] @method numericSort @param {Number} a First value to compare. @param {Number} b Second value to compare. @return {Number} Difference between _a_ and _b_. @static **/ YArray.numericSort = function (a, b) { return a - b; }; /** Executes the supplied function on each item in the array. Returning a truthy value from the function will stop the processing of remaining items. @method some @param {Array} array Array to iterate over. @param {Function} fn Function to execute on each item. The function will receive the following arguments: @param {Any} fn.value Current array item. @param {Number} fn.index Current array index. @param {Array} fn.array Array being iterated over. @param {Object} [thisObj] `this` object to use when calling _fn_. @return {Boolean} `true` if the function returns a truthy value on any of the items in the array; `false` otherwise. @static **/ YArray.some = Lang._isNative(Native.some) ? function (array, fn, thisObj) { return Native.some.call(array, fn, thisObj); } : function (array, fn, thisObj) { for (var i = 0, len = array.length; i < len; ++i) { if (i in array && fn.call(thisObj, array[i], i, array)) { return true; } } return false; }; /** Evaluates _obj_ to determine if it's an array, an array-like collection, or something else. This is useful when working with the function `arguments` collection and `HTMLElement` collections. Note: This implementation doesn't consider elements that are also collections, such as `<form>` and `<select>`, to be array-like. @method test @param {Object} obj Object to test. @return {Number} A number indicating the results of the test: * 0: Neither an array nor an array-like collection. * 1: Real array. * 2: Array-like collection. @static **/ YArray.test = function (obj) { var result = 0; if (Lang.isArray(obj)) { result = 1; } else if (Lang.isObject(obj)) { try { // indexed, but no tagName (element) or scrollTo/document (window. From DOM.isWindow test which we can't use here), // or functions without apply/call (Safari // HTMLElementCollection bug). if ('length' in obj && !obj.tagName && !(obj.scrollTo && obj.document) && !obj.apply) { result = 2; } } catch (ex) {} } return result; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * A simple FIFO queue. Items are added to the Queue with add(1..n items) and * removed using next(). * * @class Queue * @constructor * @param {MIXED} item* 0..n items to seed the queue. */ function Queue() { this._init(); this.add.apply(this, arguments); } Queue.prototype = { /** * Initialize the queue * * @method _init * @protected */ _init: function() { /** * The collection of enqueued items * * @property _q * @type Array * @protected */ this._q = []; }, /** * Get the next item in the queue. FIFO support * * @method next * @return {MIXED} the next item in the queue. */ next: function() { return this._q.shift(); }, /** * Get the last in the queue. LIFO support. * * @method last * @return {MIXED} the last item in the queue. */ last: function() { return this._q.pop(); }, /** * Add 0..n items to the end of the queue. * * @method add * @param {MIXED} item* 0..n items. * @return {object} this queue. */ add: function() { this._q.push.apply(this._q, arguments); return this; }, /** * Returns the current number of queued items. * * @method size * @return {Number} The size. */ size: function() { return this._q.length; } }; Y.Queue = Queue; YUI.Env._loaderQueue = YUI.Env._loaderQueue || new Queue(); /** The YUI module contains the components required for building the YUI seed file. This includes the script loading mechanism, a simple queue, and the core utilities for the library. @module yui @submodule yui-base **/ var CACHED_DELIMITER = '__', hasOwn = Object.prototype.hasOwnProperty, isObject = Y.Lang.isObject; /** Returns a wrapper for a function which caches the return value of that function, keyed off of the combined string representation of the argument values provided when the wrapper is called. Calling this function again with the same arguments will return the cached value rather than executing the wrapped function. Note that since the cache is keyed off of the string representation of arguments passed to the wrapper function, arguments that aren't strings and don't provide a meaningful `toString()` method may result in unexpected caching behavior. For example, the objects `{}` and `{foo: 'bar'}` would both be converted to the string `[object Object]` when used as a cache key. @method cached @param {Function} source The function to memoize. @param {Object} [cache={}] Object in which to store cached values. You may seed this object with pre-existing cached values if desired. @param {any} [refetch] If supplied, this value is compared with the cached value using a `==` comparison. If the values are equal, the wrapped function is executed again even though a cached value exists. @return {Function} Wrapped function. @for YUI **/ Y.cached = function (source, cache, refetch) { /*jshint expr: true*/ cache || (cache = {}); return function (arg) { var key = arguments.length > 1 ? Array.prototype.join.call(arguments, CACHED_DELIMITER) : String(arg); /*jshint eqeqeq: false*/ if (!(key in cache) || (refetch && cache[key] == refetch)) { cache[key] = source.apply(source, arguments); } return cache[key]; }; }; /** Returns the `location` object from the window/frame in which this YUI instance operates, or `undefined` when executing in a non-browser environment (e.g. Node.js). It is _not_ recommended to hold references to the `window.location` object outside of the scope of a function in which its properties are being accessed or its methods are being called. This is because of a nasty bug/issue that exists in both Safari and MobileSafari browsers: [WebKit Bug 34679](https://bugs.webkit.org/show_bug.cgi?id=34679). @method getLocation @return {location} The `location` object from the window/frame in which this YUI instance operates. @since 3.5.0 **/ Y.getLocation = function () { // It is safer to look this up every time because yui-base is attached to a // YUI instance before a user's config is applied; i.e. `Y.config.win` does // not point the correct window object when this file is loaded. var win = Y.config.win; // It is not safe to hold a reference to the `location` object outside the // scope in which it is being used. The WebKit engine used in Safari and // MobileSafari will "disconnect" the `location` object from the `window` // when a page is restored from back/forward history cache. return win && win.location; }; /** Returns a new object containing all of the properties of all the supplied objects. The properties from later objects will overwrite those in earlier objects. Passing in a single object will create a shallow copy of it. For a deep copy, use `clone()`. @method merge @param {Object} objects* One or more objects to merge. @return {Object} A new merged object. **/ Y.merge = function () { var i = 0, len = arguments.length, result = {}, key, obj; for (; i < len; ++i) { obj = arguments[i]; for (key in obj) { if (hasOwn.call(obj, key)) { result[key] = obj[key]; } } } return result; }; /** Mixes _supplier_'s properties into _receiver_. Properties on _receiver_ or _receiver_'s prototype will not be overwritten or shadowed unless the _overwrite_ parameter is `true`, and will not be merged unless the _merge_ parameter is `true`. In the default mode (0), only properties the supplier owns are copied (prototype properties are not copied). The following copying modes are available: * `0`: _Default_. Object to object. * `1`: Prototype to prototype. * `2`: Prototype to prototype and object to object. * `3`: Prototype to object. * `4`: Object to prototype. @method mix @param {Function|Object} receiver The object or function to receive the mixed properties. @param {Function|Object} supplier The object or function supplying the properties to be mixed. @param {Boolean} [overwrite=false] If `true`, properties that already exist on the receiver will be overwritten with properties from the supplier. @param {String[]} [whitelist] An array of property names to copy. If specified, only the whitelisted properties will be copied, and all others will be ignored. @param {Number} [mode=0] Mix mode to use. See above for available modes. @param {Boolean} [merge=false] If `true`, objects and arrays that already exist on the receiver will have the corresponding object/array from the supplier merged into them, rather than being skipped or overwritten. When both _overwrite_ and _merge_ are `true`, _merge_ takes precedence. @return {Function|Object|YUI} The receiver, or the YUI instance if the specified receiver is falsy. **/ Y.mix = function(receiver, supplier, overwrite, whitelist, mode, merge) { var alwaysOverwrite, exists, from, i, key, len, to; // If no supplier is given, we return the receiver. If no receiver is given, // we return Y. Returning Y doesn't make much sense to me, but it's // grandfathered in for backcompat reasons. if (!receiver || !supplier) { return receiver || Y; } if (mode) { // In mode 2 (prototype to prototype and object to object), we recurse // once to do the proto to proto mix. The object to object mix will be // handled later on. if (mode === 2) { Y.mix(receiver.prototype, supplier.prototype, overwrite, whitelist, 0, merge); } // Depending on which mode is specified, we may be copying from or to // the prototypes of the supplier and receiver. from = mode === 1 || mode === 3 ? supplier.prototype : supplier; to = mode === 1 || mode === 4 ? receiver.prototype : receiver; // If either the supplier or receiver doesn't actually have a // prototype property, then we could end up with an undefined `from` // or `to`. If that happens, we abort and return the receiver. if (!from || !to) { return receiver; } } else { from = supplier; to = receiver; } // If `overwrite` is truthy and `merge` is falsy, then we can skip a // property existence check on each iteration and save some time. alwaysOverwrite = overwrite && !merge; if (whitelist) { for (i = 0, len = whitelist.length; i < len; ++i) { key = whitelist[i]; // We call `Object.prototype.hasOwnProperty` instead of calling // `hasOwnProperty` on the object itself, since the object's // `hasOwnProperty` method may have been overridden or removed. // Also, some native objects don't implement a `hasOwnProperty` // method. if (!hasOwn.call(from, key)) { continue; } // The `key in to` check here is (sadly) intentional for backwards // compatibility reasons. It prevents undesired shadowing of // prototype members on `to`. exists = alwaysOverwrite ? false : key in to; if (merge && exists && isObject(to[key], true) && isObject(from[key], true)) { // If we're in merge mode, and the key is present on both // objects, and the value on both objects is either an object or // an array (but not a function), then we recurse to merge the // `from` value into the `to` value instead of overwriting it. // // Note: It's intentional that the whitelist isn't passed to the // recursive call here. This is legacy behavior that lots of // code still depends on. Y.mix(to[key], from[key], overwrite, null, 0, merge); } else if (overwrite || !exists) { // We're not in merge mode, so we'll only copy the `from` value // to the `to` value if we're in overwrite mode or if the // current key doesn't exist on the `to` object. to[key] = from[key]; } } } else { for (key in from) { // The code duplication here is for runtime performance reasons. // Combining whitelist and non-whitelist operations into a single // loop or breaking the shared logic out into a function both result // in worse performance, and Y.mix is critical enough that the byte // tradeoff is worth it. if (!hasOwn.call(from, key)) { continue; } // The `key in to` check here is (sadly) intentional for backwards // compatibility reasons. It prevents undesired shadowing of // prototype members on `to`. exists = alwaysOverwrite ? false : key in to; if (merge && exists && isObject(to[key], true) && isObject(from[key], true)) { Y.mix(to[key], from[key], overwrite, null, 0, merge); } else if (overwrite || !exists) { to[key] = from[key]; } } // If this is an IE browser with the JScript enumeration bug, force // enumeration of the buggy properties by making a recursive call with // the buggy properties as the whitelist. if (Y.Object._hasEnumBug) { Y.mix(to, from, overwrite, Y.Object._forceEnum, mode, merge); } } return receiver; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Adds utilities to the YUI instance for working with objects. * * @class Object */ var Lang = Y.Lang, hasOwn = Object.prototype.hasOwnProperty, UNDEFINED, // <-- Note the comma. We're still declaring vars. /** * Returns a new object that uses _obj_ as its prototype. This method wraps the * native ES5 `Object.create()` method if available, but doesn't currently * pass through `Object.create()`'s second argument (properties) in order to * ensure compatibility with older browsers. * * @method () * @param {Object} obj Prototype object. * @return {Object} New object using _obj_ as its prototype. * @static */ O = Y.Object = Lang._isNative(Object.create) ? function (obj) { // We currently wrap the native Object.create instead of simply aliasing it // to ensure consistency with our fallback shim, which currently doesn't // support Object.create()'s second argument (properties). Once we have a // safe fallback for the properties arg, we can stop wrapping // Object.create(). return Object.create(obj); } : (function () { // Reusable constructor function for the Object.create() shim. function F() {} // The actual shim. return function (obj) { F.prototype = obj; return new F(); }; }()), /** * Property names that IE doesn't enumerate in for..in loops, even when they * should be enumerable. When `_hasEnumBug` is `true`, it's necessary to * manually enumerate these properties. * * @property _forceEnum * @type String[] * @protected * @static */ forceEnum = O._forceEnum = [ 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toString', 'toLocaleString', 'valueOf' ], /** * `true` if this browser has the JScript enumeration bug that prevents * enumeration of the properties named in the `_forceEnum` array, `false` * otherwise. * * See: * - <https://developer.mozilla.org/en/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug> * - <http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation> * * @property _hasEnumBug * @type Boolean * @protected * @static */ hasEnumBug = O._hasEnumBug = !{valueOf: 0}.propertyIsEnumerable('valueOf'), /** * `true` if this browser incorrectly considers the `prototype` property of * functions to be enumerable. Currently known to affect Opera 11.50. * * @property _hasProtoEnumBug * @type Boolean * @protected * @static */ hasProtoEnumBug = O._hasProtoEnumBug = (function () {}).propertyIsEnumerable('prototype'), /** * Returns `true` if _key_ exists on _obj_, `false` if _key_ doesn't exist or * exists only on _obj_'s prototype. This is essentially a safer version of * `obj.hasOwnProperty()`. * * @method owns * @param {Object} obj Object to test. * @param {String} key Property name to look for. * @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise. * @static */ owns = O.owns = function (obj, key) { return !!obj && hasOwn.call(obj, key); }; // <-- End of var declarations. /** * Alias for `owns()`. * * @method hasKey * @param {Object} obj Object to test. * @param {String} key Property name to look for. * @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise. * @static */ O.hasKey = owns; /** * Returns an array containing the object's enumerable keys. Does not include * prototype keys or non-enumerable keys. * * Note that keys are returned in enumeration order (that is, in the same order * that they would be enumerated by a `for-in` loop), which may not be the same * as the order in which they were defined. * * This method is an alias for the native ES5 `Object.keys()` method if * available. * * @example * * Y.Object.keys({a: 'foo', b: 'bar', c: 'baz'}); * // => ['a', 'b', 'c'] * * @method keys * @param {Object} obj An object. * @return {String[]} Array of keys. * @static */ O.keys = Lang._isNative(Object.keys) ? Object.keys : function (obj) { if (!Lang.isObject(obj)) { throw new TypeError('Object.keys called on a non-object'); } var keys = [], i, key, len; if (hasProtoEnumBug && typeof obj === 'function') { for (key in obj) { if (owns(obj, key) && key !== 'prototype') { keys.push(key); } } } else { for (key in obj) { if (owns(obj, key)) { keys.push(key); } } } if (hasEnumBug) { for (i = 0, len = forceEnum.length; i < len; ++i) { key = forceEnum[i]; if (owns(obj, key)) { keys.push(key); } } } return keys; }; /** * Returns an array containing the values of the object's enumerable keys. * * Note that values are returned in enumeration order (that is, in the same * order that they would be enumerated by a `for-in` loop), which may not be the * same as the order in which they were defined. * * @example * * Y.Object.values({a: 'foo', b: 'bar', c: 'baz'}); * // => ['foo', 'bar', 'baz'] * * @method values * @param {Object} obj An object. * @return {Array} Array of values. * @static */ O.values = function (obj) { var keys = O.keys(obj), i = 0, len = keys.length, values = []; for (; i < len; ++i) { values.push(obj[keys[i]]); } return values; }; /** * Returns the number of enumerable keys owned by an object. * * @method size * @param {Object} obj An object. * @return {Number} The object's size. * @static */ O.size = function (obj) { try { return O.keys(obj).length; } catch (ex) { return 0; // Legacy behavior for non-objects. } }; /** * Returns `true` if the object owns an enumerable property with the specified * value. * * @method hasValue * @param {Object} obj An object. * @param {any} value The value to search for. * @return {Boolean} `true` if _obj_ contains _value_, `false` otherwise. * @static */ O.hasValue = function (obj, value) { return Y.Array.indexOf(O.values(obj), value) > -1; }; /** * Executes a function on each enumerable property in _obj_. The function * receives the value, the key, and the object itself as parameters (in that * order). * * By default, only properties owned by _obj_ are enumerated. To include * prototype properties, set the _proto_ parameter to `true`. * * @method each * @param {Object} obj Object to enumerate. * @param {Function} fn Function to execute on each enumerable property. * @param {mixed} fn.value Value of the current property. * @param {String} fn.key Key of the current property. * @param {Object} fn.obj Object being enumerated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @param {Boolean} [proto=false] Include prototype properties. * @return {YUI} the YUI instance. * @chainable * @static */ O.each = function (obj, fn, thisObj, proto) { var key; for (key in obj) { if (proto || owns(obj, key)) { fn.call(thisObj || Y, obj[key], key, obj); } } return Y; }; /** * Executes a function on each enumerable property in _obj_, but halts if the * function returns a truthy value. The function receives the value, the key, * and the object itself as paramters (in that order). * * By default, only properties owned by _obj_ are enumerated. To include * prototype properties, set the _proto_ parameter to `true`. * * @method some * @param {Object} obj Object to enumerate. * @param {Function} fn Function to execute on each enumerable property. * @param {mixed} fn.value Value of the current property. * @param {String} fn.key Key of the current property. * @param {Object} fn.obj Object being enumerated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @param {Boolean} [proto=false] Include prototype properties. * @return {Boolean} `true` if any execution of _fn_ returns a truthy value, * `false` otherwise. * @static */ O.some = function (obj, fn, thisObj, proto) { var key; for (key in obj) { if (proto || owns(obj, key)) { if (fn.call(thisObj || Y, obj[key], key, obj)) { return true; } } } return false; }; /** * Retrieves the sub value at the provided path, * from the value object provided. * * @method getValue * @static * @param o The object from which to extract the property value. * @param path {Array} A path array, specifying the object traversal path * from which to obtain the sub value. * @return {Any} The value stored in the path, undefined if not found, * undefined if the source is not an object. Returns the source object * if an empty path is provided. */ O.getValue = function(o, path) { if (!Lang.isObject(o)) { return UNDEFINED; } var i, p = Y.Array(path), l = p.length; for (i = 0; o !== UNDEFINED && i < l; i++) { o = o[p[i]]; } return o; }; /** * Sets the sub-attribute value at the provided path on the * value object. Returns the modified value object, or * undefined if the path is invalid. * * @method setValue * @static * @param o The object on which to set the sub value. * @param path {Array} A path array, specifying the object traversal path * at which to set the sub value. * @param val {Any} The new value for the sub-attribute. * @return {Object} The modified object, with the new sub value set, or * undefined, if the path was invalid. */ O.setValue = function(o, path, val) { var i, p = Y.Array(path), leafIdx = p.length - 1, ref = o; if (leafIdx >= 0) { for (i = 0; ref !== UNDEFINED && i < leafIdx; i++) { ref = ref[p[i]]; } if (ref !== UNDEFINED) { ref[p[i]] = val; } else { return UNDEFINED; } } return o; }; /** * Returns `true` if the object has no enumerable properties of its own. * * @method isEmpty * @param {Object} obj An object. * @return {Boolean} `true` if the object is empty. * @static * @since 3.2.0 */ O.isEmpty = function (obj) { return !O.keys(Object(obj)).length; }; /** * The YUI module contains the components required for building the YUI seed * file. This includes the script loading mechanism, a simple queue, and the * core utilities for the library. * @module yui * @submodule yui-base */ /** * YUI user agent detection. * Do not fork for a browser if it can be avoided. Use feature detection when * you can. Use the user agent as a last resort. For all fields listed * as @type float, UA stores a version number for the browser engine, * 0 otherwise. This value may or may not map to the version number of * the browser using the engine. The value is presented as a float so * that it can easily be used for boolean evaluation as well as for * looking for a particular range of versions. Because of this, * some of the granularity of the version info may be lost. The fields that * are @type string default to null. The API docs list the values that * these fields can have. * @class UA * @static */ /** * Static method on `YUI.Env` for parsing a UA string. Called at instantiation * to populate `Y.UA`. * * @static * @method parseUA * @param {String} [subUA=navigator.userAgent] UA string to parse * @return {Object} The Y.UA object */ YUI.Env.parseUA = function(subUA) { var numberify = function(s) { var c = 0; return parseFloat(s.replace(/\./g, function() { return (c++ === 1) ? '' : '.'; })); }, win = Y.config.win, nav = win && win.navigator, o = { /** * Internet Explorer version number or 0. Example: 6 * @property ie * @type float * @static */ ie: 0, /** * Opera version number or 0. Example: 9.2 * @property opera * @type float * @static */ opera: 0, /** * Gecko engine revision number. Will evaluate to 1 if Gecko * is detected but the revision could not be found. Other browsers * will be 0. Example: 1.8 * <pre> * Firefox 1.0.0.4: 1.7.8 <-- Reports 1.7 * Firefox 1.5.0.9: 1.8.0.9 <-- 1.8 * Firefox 2.0.0.3: 1.8.1.3 <-- 1.81 * Firefox 3.0 <-- 1.9 * Firefox 3.5 <-- 1.91 * </pre> * @property gecko * @type float * @static */ gecko: 0, /** * AppleWebKit version. KHTML browsers that are not WebKit browsers * will evaluate to 1, other browsers 0. Example: 418.9 * <pre> * Safari 1.3.2 (312.6): 312.8.1 <-- Reports 312.8 -- currently the * latest available for Mac OSX 10.3. * Safari 2.0.2: 416 <-- hasOwnProperty introduced * Safari 2.0.4: 418 <-- preventDefault fixed * Safari 2.0.4 (419.3): 418.9.1 <-- One version of Safari may run * different versions of webkit * Safari 2.0.4 (419.3): 419 <-- Tiger installations that have been * updated, but not updated * to the latest patch. * Webkit 212 nightly: 522+ <-- Safari 3.0 precursor (with native * SVG and many major issues fixed). * Safari 3.0.4 (523.12) 523.12 <-- First Tiger release - automatic * update from 2.x via the 10.4.11 OS patch. * Webkit nightly 1/2008:525+ <-- Supports DOMContentLoaded event. * yahoo.com user agent hack removed. * </pre> * http://en.wikipedia.org/wiki/Safari_version_history * @property webkit * @type float * @static */ webkit: 0, /** * Safari will be detected as webkit, but this property will also * be populated with the Safari version number * @property safari * @type float * @static */ safari: 0, /** * Chrome will be detected as webkit, but this property will also * be populated with the Chrome version number * @property chrome * @type float * @static */ chrome: 0, /** * The mobile property will be set to a string containing any relevant * user agent information when a modern mobile browser is detected. * Currently limited to Safari on the iPhone/iPod Touch, Nokia N-series * devices with the WebKit-based browser, and Opera Mini. * @property mobile * @type string * @default null * @static */ mobile: null, /** * Adobe AIR version number or 0. Only populated if webkit is detected. * Example: 1.0 * @property air * @type float */ air: 0, /** * PhantomJS version number or 0. Only populated if webkit is detected. * Example: 1.0 * @property phantomjs * @type float */ phantomjs: 0, /** * Detects Apple iPad's OS version * @property ipad * @type float * @static */ ipad: 0, /** * Detects Apple iPhone's OS version * @property iphone * @type float * @static */ iphone: 0, /** * Detects Apples iPod's OS version * @property ipod * @type float * @static */ ipod: 0, /** * General truthy check for iPad, iPhone or iPod * @property ios * @type Boolean * @default null * @static */ ios: null, /** * Detects Googles Android OS version * @property android * @type float * @static */ android: 0, /** * Detects Kindle Silk * @property silk * @type float * @static */ silk: 0, /** * Detects Kindle Silk Acceleration * @property accel * @type Boolean * @static */ accel: false, /** * Detects Palms WebOS version * @property webos * @type float * @static */ webos: 0, /** * Google Caja version number or 0. * @property caja * @type float */ caja: nav && nav.cajaVersion, /** * Set to true if the page appears to be in SSL * @property secure * @type boolean * @static */ secure: false, /** * The operating system. Currently only detecting windows or macintosh * @property os * @type string * @default null * @static */ os: null, /** * The Nodejs Version * @property nodejs * @type float * @default 0 * @static */ nodejs: 0, /** * Window8/IE10 Application host environment * @property winjs * @type Boolean * @static */ winjs: !!((typeof Windows !== "undefined") && Windows.System), /** * Are touch/msPointer events available on this device * @property touchEnabled * @type Boolean * @static */ touchEnabled: false }, ua = subUA || nav && nav.userAgent, loc = win && win.location, href = loc && loc.href, m; /** * The User Agent string that was parsed * @property userAgent * @type String * @static */ o.userAgent = ua; o.secure = href && (href.toLowerCase().indexOf('https') === 0); if (ua) { if ((/windows|win32/i).test(ua)) { o.os = 'windows'; } else if ((/macintosh|mac_powerpc/i).test(ua)) { o.os = 'macintosh'; } else if ((/android/i).test(ua)) { o.os = 'android'; } else if ((/symbos/i).test(ua)) { o.os = 'symbos'; } else if ((/linux/i).test(ua)) { o.os = 'linux'; } else if ((/rhino/i).test(ua)) { o.os = 'rhino'; } // Modern KHTML browsers should qualify as Safari X-Grade if ((/KHTML/).test(ua)) { o.webkit = 1; } if ((/IEMobile|XBLWP7/).test(ua)) { o.mobile = 'windows'; } if ((/Fennec/).test(ua)) { o.mobile = 'gecko'; } // Modern WebKit browsers are at least X-Grade m = ua.match(/AppleWebKit\/([^\s]*)/); if (m && m[1]) { o.webkit = numberify(m[1]); o.safari = o.webkit; if (/PhantomJS/.test(ua)) { m = ua.match(/PhantomJS\/([^\s]*)/); if (m && m[1]) { o.phantomjs = numberify(m[1]); } } // Mobile browser check if (/ Mobile\//.test(ua) || (/iPad|iPod|iPhone/).test(ua)) { o.mobile = 'Apple'; // iPhone or iPod Touch m = ua.match(/OS ([^\s]*)/); if (m && m[1]) { m = numberify(m[1].replace('_', '.')); } o.ios = m; o.os = 'ios'; o.ipad = o.ipod = o.iphone = 0; m = ua.match(/iPad|iPod|iPhone/); if (m && m[0]) { o[m[0].toLowerCase()] = o.ios; } } else { m = ua.match(/NokiaN[^\/]*|webOS\/\d\.\d/); if (m) { // Nokia N-series, webOS, ex: NokiaN95 o.mobile = m[0]; } if (/webOS/.test(ua)) { o.mobile = 'WebOS'; m = ua.match(/webOS\/([^\s]*);/); if (m && m[1]) { o.webos = numberify(m[1]); } } if (/ Android/.test(ua)) { if (/Mobile/.test(ua)) { o.mobile = 'Android'; } m = ua.match(/Android ([^\s]*);/); if (m && m[1]) { o.android = numberify(m[1]); } } if (/Silk/.test(ua)) { m = ua.match(/Silk\/([^\s]*)\)/); if (m && m[1]) { o.silk = numberify(m[1]); } if (!o.android) { o.android = 2.34; //Hack for desktop mode in Kindle o.os = 'Android'; } if (/Accelerated=true/.test(ua)) { o.accel = true; } } } m = ua.match(/(Chrome|CrMo|CriOS)\/([^\s]*)/); if (m && m[1] && m[2]) { o.chrome = numberify(m[2]); // Chrome o.safari = 0; //Reset safari back to 0 if (m[1] === 'CrMo') { o.mobile = 'chrome'; } } else { m = ua.match(/AdobeAIR\/([^\s]*)/); if (m) { o.air = m[0]; // Adobe AIR 1.0 or better } } } if (!o.webkit) { // not webkit // @todo check Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4509/1316; fi; U; ssr) if (/Opera/.test(ua)) { m = ua.match(/Opera[\s\/]([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); } m = ua.match(/Version\/([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); // opera 10+ } if (/Opera Mobi/.test(ua)) { o.mobile = 'opera'; m = ua.replace('Opera Mobi', '').match(/Opera ([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); } } m = ua.match(/Opera Mini[^;]*/); if (m) { o.mobile = m[0]; // ex: Opera Mini/2.0.4509/1316 } } else { // not opera or webkit m = ua.match(/MSIE\s([^;]*)/); if (m && m[1]) { o.ie = numberify(m[1]); } else { // not opera, webkit, or ie m = ua.match(/Gecko\/([^\s]*)/); if (m) { o.gecko = 1; // Gecko detected, look for revision m = ua.match(/rv:([^\s\)]*)/); if (m && m[1]) { o.gecko = numberify(m[1]); } } } } } } //Check for known properties to tell if touch events are enabled on this device or if //the number of MSPointer touchpoints on this device is greater than 0. if (win && nav && !(o.chrome && o.chrome < 6)) { o.touchEnabled = (("ontouchstart" in win) || (("msMaxTouchPoints" in nav) && (nav.msMaxTouchPoints > 0))); } //It was a parsed UA, do not assign the global value. if (!subUA) { if (typeof process === 'object') { if (process.versions && process.versions.node) { //NodeJS o.os = process.platform; o.nodejs = numberify(process.versions.node); } } YUI.Env.UA = o; } return o; }; Y.UA = YUI.Env.UA || YUI.Env.parseUA(); /** Performs a simple comparison between two version numbers, accounting for standard versioning logic such as the fact that "535.8" is a lower version than "535.24", even though a simple numerical comparison would indicate that it's greater. Also accounts for cases such as "1.1" vs. "1.1.0", which are considered equivalent. Returns -1 if version _a_ is lower than version _b_, 0 if they're equivalent, 1 if _a_ is higher than _b_. Versions may be numbers or strings containing numbers and dots. For example, both `535` and `"535.8.10"` are acceptable. A version string containing non-numeric characters, like `"535.8.beta"`, may produce unexpected results. @method compareVersions @param {Number|String} a First version number to compare. @param {Number|String} b Second version number to compare. @return -1 if _a_ is lower than _b_, 0 if they're equivalent, 1 if _a_ is higher than _b_. **/ Y.UA.compareVersions = function (a, b) { var aPart, aParts, bPart, bParts, i, len; if (a === b) { return 0; } aParts = (a + '').split('.'); bParts = (b + '').split('.'); for (i = 0, len = Math.max(aParts.length, bParts.length); i < len; ++i) { aPart = parseInt(aParts[i], 10); bPart = parseInt(bParts[i], 10); /*jshint expr: true*/ isNaN(aPart) && (aPart = 0); isNaN(bPart) && (bPart = 0); if (aPart < bPart) { return -1; } if (aPart > bPart) { return 1; } } return 0; }; YUI.Env.aliases = { "anim": ["anim-base","anim-color","anim-curve","anim-easing","anim-node-plugin","anim-scroll","anim-xy"], "anim-shape-transform": ["anim-shape"], "app": ["app-base","app-content","app-transitions","lazy-model-list","model","model-list","model-sync-rest","router","view","view-node-map"], "attribute": ["attribute-base","attribute-complex"], "attribute-events": ["attribute-observable"], "autocomplete": ["autocomplete-base","autocomplete-sources","autocomplete-list","autocomplete-plugin"], "axes": ["axis-numeric","axis-category","axis-time","axis-stacked"], "axes-base": ["axis-numeric-base","axis-category-base","axis-time-base","axis-stacked-base"], "base": ["base-base","base-pluginhost","base-build"], "cache": ["cache-base","cache-offline","cache-plugin"], "charts": ["charts-base"], "collection": ["array-extras","arraylist","arraylist-add","arraylist-filter","array-invoke"], "color": ["color-base","color-hsl","color-harmony"], "controller": ["router"], "dataschema": ["dataschema-base","dataschema-json","dataschema-xml","dataschema-array","dataschema-text"], "datasource": ["datasource-local","datasource-io","datasource-get","datasource-function","datasource-cache","datasource-jsonschema","datasource-xmlschema","datasource-arrayschema","datasource-textschema","datasource-polling"], "datatable": ["datatable-core","datatable-table","datatable-head","datatable-body","datatable-base","datatable-column-widths","datatable-message","datatable-mutable","datatable-sort","datatable-datasource"], "datatype": ["datatype-date","datatype-number","datatype-xml"], "datatype-date": ["datatype-date-parse","datatype-date-format","datatype-date-math"], "datatype-number": ["datatype-number-parse","datatype-number-format"], "datatype-xml": ["datatype-xml-parse","datatype-xml-format"], "dd": ["dd-ddm-base","dd-ddm","dd-ddm-drop","dd-drag","dd-proxy","dd-constrain","dd-drop","dd-scroll","dd-delegate"], "dom": ["dom-base","dom-screen","dom-style","selector-native","selector"], "editor": ["frame","editor-selection","exec-command","editor-base","editor-para","editor-br","editor-bidi","editor-tab","createlink-base"], "event": ["event-base","event-delegate","event-synthetic","event-mousewheel","event-mouseenter","event-key","event-focus","event-resize","event-hover","event-outside","event-touch","event-move","event-flick","event-valuechange","event-tap"], "event-custom": ["event-custom-base","event-custom-complex"], "event-gestures": ["event-flick","event-move"], "handlebars": ["handlebars-compiler"], "highlight": ["highlight-base","highlight-accentfold"], "history": ["history-base","history-hash","history-hash-ie","history-html5"], "io": ["io-base","io-xdr","io-form","io-upload-iframe","io-queue"], "json": ["json-parse","json-stringify"], "loader": ["loader-base","loader-rollup","loader-yui3"], "node": ["node-base","node-event-delegate","node-pluginhost","node-screen","node-style"], "pluginhost": ["pluginhost-base","pluginhost-config"], "querystring": ["querystring-parse","querystring-stringify"], "recordset": ["recordset-base","recordset-sort","recordset-filter","recordset-indexer"], "resize": ["resize-base","resize-proxy","resize-constrain"], "series-cartesian": ["series-line","series-marker","series-area","series-spline","series-column","series-bar","series-areaspline","series-combo","series-combospline"], "series-cartesian-stacked": ["series-line-stacked","series-marker-stacked","series-area-stacked","series-spline-stacked","series-column-stacked","series-bar-stacked","series-areaspline-stacked","series-combo-stacked","series-combospline-stacked"], "slider": ["slider-base","slider-value-range","clickable-rail","range-slider"], "template": ["template-base","template-micro"], "text": ["text-accentfold","text-wordbreak"], "widget": ["widget-base","widget-htmlparser","widget-skin","widget-uievents"] }; }, '@VERSION@', {"use": ["get", "features", "intl-base", "yui-log", "yui-later"]}); YUI.add('get', function (Y, NAME) { /*jslint boss:true, expr:true, laxbreak: true */ /** Provides dynamic loading of remote JavaScript and CSS resources. @module get @class Get @static **/ var Lang = Y.Lang, CUSTOM_ATTRS, // defined lazily in Y.Get.Transaction._createNode() Get, Transaction; Y.Get = Get = { // -- Public Properties ---------------------------------------------------- /** Default options for CSS requests. Options specified here will override global defaults for CSS requests. See the `options` property for all available options. @property cssOptions @type Object @static @since 3.5.0 **/ cssOptions: { attributes: { rel: 'stylesheet' }, doc : Y.config.linkDoc || Y.config.doc, pollInterval: 50 }, /** Default options for JS requests. Options specified here will override global defaults for JS requests. See the `options` property for all available options. @property jsOptions @type Object @static @since 3.5.0 **/ jsOptions: { autopurge: true, doc : Y.config.scriptDoc || Y.config.doc }, /** Default options to use for all requests. Note that while all available options are documented here for ease of discovery, some options (like callback functions) only make sense at the transaction level. Callback functions specified via the options object or the `options` parameter of the `css()`, `js()`, or `load()` methods will receive the transaction object as a parameter. See `Y.Get.Transaction` for details on the properties and methods available on transactions. @static @since 3.5.0 @property {Object} options @property {Boolean} [options.async=false] Whether or not to load scripts asynchronously, meaning they're requested in parallel and execution order is not guaranteed. Has no effect on CSS, since CSS is always loaded asynchronously. @property {Object} [options.attributes] HTML attribute name/value pairs that should be added to inserted nodes. By default, the `charset` attribute will be set to "utf-8" and nodes will be given an auto-generated `id` attribute, but you can override these with your own values if desired. @property {Boolean} [options.autopurge] Whether or not to automatically purge inserted nodes after the purge threshold is reached. This is `true` by default for JavaScript, but `false` for CSS since purging a CSS node will also remove any styling applied by the referenced file. @property {Object} [options.context] `this` object to use when calling callback functions. Defaults to the transaction object. @property {Mixed} [options.data] Arbitrary data object to pass to "on*" callbacks. @property {Document} [options.doc] Document into which nodes should be inserted. By default, the current document is used. @property {HTMLElement|String} [options.insertBefore] HTML element or id string of an element before which all generated nodes should be inserted. If not specified, Get will automatically determine the best place to insert nodes for maximum compatibility. @property {Function} [options.onEnd] Callback to execute after a transaction is complete, regardless of whether it succeeded or failed. @property {Function} [options.onFailure] Callback to execute after a transaction fails, times out, or is aborted. @property {Function} [options.onProgress] Callback to execute after each individual request in a transaction either succeeds or fails. @property {Function} [options.onSuccess] Callback to execute after a transaction completes successfully with no errors. Note that in browsers that don't support the `error` event on CSS `<link>` nodes, a failed CSS request may still be reported as a success because in these browsers it can be difficult or impossible to distinguish between success and failure for CSS resources. @property {Function} [options.onTimeout] Callback to execute after a transaction times out. @property {Number} [options.pollInterval=50] Polling interval (in milliseconds) for detecting CSS load completion in browsers that don't support the `load` event on `<link>` nodes. This isn't used for JavaScript. @property {Number} [options.purgethreshold=20] Number of nodes to insert before triggering an automatic purge when `autopurge` is `true`. @property {Number} [options.timeout] Number of milliseconds to wait before aborting a transaction. When a timeout occurs, the `onTimeout` callback is called, followed by `onFailure` and finally `onEnd`. By default, there is no timeout. @property {String} [options.type] Resource type ("css" or "js"). This option is set automatically by the `css()` and `js()` functions and will be ignored there, but may be useful when using the `load()` function. If not specified, the type will be inferred from the URL, defaulting to "js" if the URL doesn't contain a recognizable file extension. **/ options: { attributes: { charset: 'utf-8' }, purgethreshold: 20 }, // -- Protected Properties ------------------------------------------------- /** Regex that matches a CSS URL. Used to guess the file type when it's not specified. @property REGEX_CSS @type RegExp @final @protected @static @since 3.5.0 **/ REGEX_CSS: /\.css(?:[?;].*)?$/i, /** Regex that matches a JS URL. Used to guess the file type when it's not specified. @property REGEX_JS @type RegExp @final @protected @static @since 3.5.0 **/ REGEX_JS : /\.js(?:[?;].*)?$/i, /** Contains information about the current environment, such as what script and link injection features it supports. This object is created and populated the first time the `_getEnv()` method is called. @property _env @type Object @protected @static @since 3.5.0 **/ /** Mapping of document _yuid strings to <head> or <base> node references so we don't have to look the node up each time we want to insert a request node. @property _insertCache @type Object @protected @static @since 3.5.0 **/ _insertCache: {}, /** Information about the currently pending transaction, if any. This is actually an object with two properties: `callback`, containing the optional callback passed to `css()`, `load()`, or `js()`; and `transaction`, containing the actual transaction instance. @property _pending @type Object @protected @static @since 3.5.0 **/ _pending: null, /** HTML nodes eligible to be purged next time autopurge is triggered. @property _purgeNodes @type HTMLElement[] @protected @static @since 3.5.0 **/ _purgeNodes: [], /** Queued transactions and associated callbacks. @property _queue @type Object[] @protected @static @since 3.5.0 **/ _queue: [], // -- Public Methods ------------------------------------------------------- /** Aborts the specified transaction. This will cause the transaction's `onFailure` callback to be called and will prevent any new script and link nodes from being added to the document, but any resources that have already been requested will continue loading (there's no safe way to prevent this, unfortunately). *Note:* This method is deprecated as of 3.5.0, and will be removed in a future version of YUI. Use the transaction-level `abort()` method instead. @method abort @param {Get.Transaction} transaction Transaction to abort. @deprecated Use the `abort()` method on the transaction instead. @static **/ abort: function (transaction) { var i, id, item, len, pending; Y.log('`Y.Get.abort()` is deprecated as of 3.5.0. Use the `abort()` method on the transaction instead.', 'warn', 'get'); if (!transaction.abort) { id = transaction; pending = this._pending; transaction = null; if (pending && pending.transaction.id === id) { transaction = pending.transaction; this._pending = null; } else { for (i = 0, len = this._queue.length; i < len; ++i) { item = this._queue[i].transaction; if (item.id === id) { transaction = item; this._queue.splice(i, 1); break; } } } } transaction && transaction.abort(); }, /** Loads one or more CSS files. The _urls_ parameter may be provided as a URL string, a request object, or an array of URL strings and/or request objects. A request object is just an object that contains a `url` property and zero or more options that should apply specifically to that request. Request-specific options take priority over transaction-level options and default options. URLs may be relative or absolute, and do not have to have the same origin as the current page. The `options` parameter may be omitted completely and a callback passed in its place, if desired. @example // Load a single CSS file and log a message on completion. Y.Get.css('foo.css', function (err) { if (err) { Y.log('foo.css failed to load!'); } else { Y.log('foo.css was loaded successfully'); } }); // Load multiple CSS files and log a message when all have finished // loading. var urls = ['foo.css', 'http://example.com/bar.css', 'baz/quux.css']; Y.Get.css(urls, function (err) { if (err) { Y.log('one or more files failed to load!'); } else { Y.log('all files loaded successfully'); } }); // Specify transaction-level options, which will apply to all requests // within the transaction. Y.Get.css(urls, { attributes: {'class': 'my-css'}, timeout : 5000 }); // Specify per-request options, which override transaction-level and // default options. Y.Get.css([ {url: 'foo.css', attributes: {id: 'foo'}}, {url: 'bar.css', attributes: {id: 'bar', charset: 'iso-8859-1'}} ]); @method css @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} callback.err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} callback.transaction Transaction object. @return {Get.Transaction} Transaction object. @static **/ css: function (urls, options, callback) { return this._load('css', urls, options, callback); }, /** Loads one or more JavaScript resources. The _urls_ parameter may be provided as a URL string, a request object, or an array of URL strings and/or request objects. A request object is just an object that contains a `url` property and zero or more options that should apply specifically to that request. Request-specific options take priority over transaction-level options and default options. URLs may be relative or absolute, and do not have to have the same origin as the current page. The `options` parameter may be omitted completely and a callback passed in its place, if desired. Scripts will be executed in the order they're specified unless the `async` option is `true`, in which case they'll be loaded in parallel and executed in whatever order they finish loading. @example // Load a single JS file and log a message on completion. Y.Get.js('foo.js', function (err) { if (err) { Y.log('foo.js failed to load!'); } else { Y.log('foo.js was loaded successfully'); } }); // Load multiple JS files, execute them in order, and log a message when // all have finished loading. var urls = ['foo.js', 'http://example.com/bar.js', 'baz/quux.js']; Y.Get.js(urls, function (err) { if (err) { Y.log('one or more files failed to load!'); } else { Y.log('all files loaded successfully'); } }); // Specify transaction-level options, which will apply to all requests // within the transaction. Y.Get.js(urls, { attributes: {'class': 'my-js'}, timeout : 5000 }); // Specify per-request options, which override transaction-level and // default options. Y.Get.js([ {url: 'foo.js', attributes: {id: 'foo'}}, {url: 'bar.js', attributes: {id: 'bar', charset: 'iso-8859-1'}} ]); @method js @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} callback.err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} callback.transaction Transaction object. @return {Get.Transaction} Transaction object. @since 3.5.0 @static **/ js: function (urls, options, callback) { return this._load('js', urls, options, callback); }, /** Loads one or more CSS and/or JavaScript resources in the same transaction. Use this method when you want to load both CSS and JavaScript in a single transaction and be notified when all requested URLs have finished loading, regardless of type. Behavior and options are the same as for the `css()` and `js()` methods. If a resource type isn't specified in per-request options or transaction-level options, Get will guess the file type based on the URL's extension (`.css` or `.js`, with or without a following query string). If the file type can't be guessed from the URL, a warning will be logged and Get will assume the URL is a JavaScript resource. @example // Load both CSS and JS files in a single transaction, and log a message // when all files have finished loading. Y.Get.load(['foo.css', 'bar.js', 'baz.css'], function (err) { if (err) { Y.log('one or more files failed to load!'); } else { Y.log('all files loaded successfully'); } }); @method load @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} Transaction object. @return {Get.Transaction} Transaction object. @since 3.5.0 @static **/ load: function (urls, options, callback) { return this._load(null, urls, options, callback); }, // -- Protected Methods ---------------------------------------------------- /** Triggers an automatic purge if the purge threshold has been reached. @method _autoPurge @param {Number} threshold Purge threshold to use, in milliseconds. @protected @since 3.5.0 @static **/ _autoPurge: function (threshold) { if (threshold && this._purgeNodes.length >= threshold) { Y.log('autopurge triggered after ' + this._purgeNodes.length + ' nodes', 'info', 'get'); this._purge(this._purgeNodes); } }, /** Populates the `_env` property with information about the current environment. @method _getEnv @return {Object} Environment information. @protected @since 3.5.0 @static **/ _getEnv: function () { var doc = Y.config.doc, ua = Y.UA; // Note: some of these checks require browser sniffs since it's not // feasible to load test files on every pageview just to perform a // feature test. I'm sorry if this makes you sad. return (this._env = { // True if this is a browser that supports disabling async mode on // dynamically created script nodes. See // https://developer.mozilla.org/En/HTML/Element/Script#Attributes // IE10 doesn't return true for the MDN feature test, so setting it explicitly, // because it is async by default, and allows you to disable async by setting it to false async: (doc && doc.createElement('script').async === true) || (ua.ie >= 10), // True if this browser fires an event when a dynamically injected // link node fails to load. This is currently true for Firefox 9+ // and WebKit 535.24+ cssFail: ua.gecko >= 9 || ua.compareVersions(ua.webkit, 535.24) >= 0, // True if this browser fires an event when a dynamically injected // link node finishes loading. This is currently true for IE, Opera, // Firefox 9+, and WebKit 535.24+. Note that IE versions <9 fire the // DOM 0 "onload" event, but not "load". All versions of IE fire // "onload". // davglass: Seems that Chrome on Android needs this to be false. cssLoad: ( (!ua.gecko && !ua.webkit) || ua.gecko >= 9 || ua.compareVersions(ua.webkit, 535.24) >= 0 ) && !(ua.chrome && ua.chrome <= 18), // True if this browser preserves script execution order while // loading scripts in parallel as long as the script node's `async` // attribute is set to false to explicitly disable async execution. preservesScriptOrder: !!(ua.gecko || ua.opera || (ua.ie && ua.ie >= 10)) }); }, _getTransaction: function (urls, options) { var requests = [], i, len, req, url; if (!Lang.isArray(urls)) { urls = [urls]; } options = Y.merge(this.options, options); // Clone the attributes object so we don't end up modifying it by ref. options.attributes = Y.merge(this.options.attributes, options.attributes); for (i = 0, len = urls.length; i < len; ++i) { url = urls[i]; req = {attributes: {}}; // If `url` is a string, we create a URL object for it, then mix in // global options and request-specific options. If it's an object // with a "url" property, we assume it's a request object containing // URL-specific options. if (typeof url === 'string') { req.url = url; } else if (url.url) { // URL-specific options override both global defaults and // request-specific options. Y.mix(req, url, false, null, 0, true); url = url.url; // Make url a string so we can use it later. } else { Y.log('URL must be a string or an object with a `url` property.', 'error', 'get'); continue; } Y.mix(req, options, false, null, 0, true); // If we didn't get an explicit type for this URL either in the // request options or the URL-specific options, try to determine // one from the file extension. if (!req.type) { if (this.REGEX_CSS.test(url)) { req.type = 'css'; } else { if (!this.REGEX_JS.test(url)) { Y.log("Can't guess file type from URL. Assuming JS: " + url, 'warn', 'get'); } req.type = 'js'; } } // Mix in type-specific default options, but don't overwrite any // options that have already been set. Y.mix(req, req.type === 'js' ? this.jsOptions : this.cssOptions, false, null, 0, true); // Give the node an id attribute if it doesn't already have one. req.attributes.id || (req.attributes.id = Y.guid()); // Backcompat for <3.5.0 behavior. if (req.win) { Y.log('The `win` option is deprecated as of 3.5.0. Use `doc` instead.', 'warn', 'get'); req.doc = req.win.document; } else { req.win = req.doc.defaultView || req.doc.parentWindow; } if (req.charset) { Y.log('The `charset` option is deprecated as of 3.5.0. Set `attributes.charset` instead.', 'warn', 'get'); req.attributes.charset = req.charset; } requests.push(req); } return new Transaction(requests, options); }, _load: function (type, urls, options, callback) { var transaction; // Allow callback as third param. if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); options.type = type; options._onFinish = Get._onTransactionFinish; if (!this._env) { this._getEnv(); } transaction = this._getTransaction(urls, options); this._queue.push({ callback : callback, transaction: transaction }); this._next(); return transaction; }, _onTransactionFinish : function() { Get._pending = null; Get._next(); }, _next: function () { var item; if (this._pending) { return; } item = this._queue.shift(); if (item) { this._pending = item; item.transaction.execute(item.callback); } }, _purge: function (nodes) { var purgeNodes = this._purgeNodes, isTransaction = nodes !== purgeNodes, index, node; while (node = nodes.pop()) { // assignment // Don't purge nodes that haven't finished loading (or errored out), // since this can hang the transaction. if (!node._yuiget_finished) { continue; } node.parentNode && node.parentNode.removeChild(node); // If this is a transaction-level purge and this node also exists in // the Get-level _purgeNodes array, we need to remove it from // _purgeNodes to avoid creating a memory leak. The indexOf lookup // sucks, but until we get WeakMaps, this is the least troublesome // way to do this (we can't just hold onto node ids because they may // not be in the same document). if (isTransaction) { index = Y.Array.indexOf(purgeNodes, node); if (index > -1) { purgeNodes.splice(index, 1); } } } } }; /** Alias for `js()`. @method script @static **/ Get.script = Get.js; /** Represents a Get transaction, which may contain requests for one or more JS or CSS files. This class should not be instantiated manually. Instances will be created and returned as needed by Y.Get's `css()`, `js()`, and `load()` methods. @class Get.Transaction @constructor @since 3.5.0 **/ Get.Transaction = Transaction = function (requests, options) { var self = this; self.id = Transaction._lastId += 1; self.data = options.data; self.errors = []; self.nodes = []; self.options = options; self.requests = requests; self._callbacks = []; // callbacks to call after execution finishes self._queue = []; self._reqsWaiting = 0; // Deprecated pre-3.5.0 properties. self.tId = self.id; // Use `id` instead. self.win = options.win || Y.config.win; }; /** Arbitrary data object associated with this transaction. This object comes from the options passed to `Get.css()`, `Get.js()`, or `Get.load()`, and will be `undefined` if no data object was specified. @property {Object} data **/ /** Array of errors that have occurred during this transaction, if any. @since 3.5.0 @property {Object[]} errors @property {String} errors.error Error message. @property {Object} errors.request Request object related to the error. **/ /** Numeric id for this transaction, unique among all transactions within the same YUI sandbox in the current pageview. @property {Number} id @since 3.5.0 **/ /** HTMLElement nodes (native ones, not YUI Node instances) that have been inserted during the current transaction. @property {HTMLElement[]} nodes **/ /** Options associated with this transaction. See `Get.options` for the full list of available options. @property {Object} options @since 3.5.0 **/ /** Request objects contained in this transaction. Each request object represents one CSS or JS URL that will be (or has been) requested and loaded into the page. @property {Object} requests @since 3.5.0 **/ /** Id of the most recent transaction. @property _lastId @type Number @protected @static **/ Transaction._lastId = 0; Transaction.prototype = { // -- Public Properties ---------------------------------------------------- /** Current state of this transaction. One of "new", "executing", or "done". @property _state @type String @protected **/ _state: 'new', // "new", "executing", or "done" // -- Public Methods ------------------------------------------------------- /** Aborts this transaction. This will cause the transaction's `onFailure` callback to be called and will prevent any new script and link nodes from being added to the document, but any resources that have already been requested will continue loading (there's no safe way to prevent this, unfortunately). @method abort @param {String} [msg="Aborted."] Optional message to use in the `errors` array describing why the transaction was aborted. **/ abort: function (msg) { this._pending = null; this._pendingCSS = null; this._pollTimer = clearTimeout(this._pollTimer); this._queue = []; this._reqsWaiting = 0; this.errors.push({error: msg || 'Aborted'}); this._finish(); }, /** Begins execting the transaction. There's usually no reason to call this manually, since Get will call it automatically when other pending transactions have finished. If you really want to execute your transaction before Get does, you can, but be aware that this transaction's scripts may end up executing before the scripts in other pending transactions. If the transaction is already executing, the specified callback (if any) will be queued and called after execution finishes. If the transaction has already finished, the callback will be called immediately (the transaction will not be executed again). @method execute @param {Function} callback Callback function to execute after all requests in the transaction are complete, or after the transaction is aborted. **/ execute: function (callback) { var self = this, requests = self.requests, state = self._state, i, len, queue, req; if (state === 'done') { callback && callback(self.errors.length ? self.errors : null, self); return; } else { callback && self._callbacks.push(callback); if (state === 'executing') { return; } } self._state = 'executing'; self._queue = queue = []; if (self.options.timeout) { self._timeout = setTimeout(function () { self.abort('Timeout'); }, self.options.timeout); } self._reqsWaiting = requests.length; for (i = 0, len = requests.length; i < len; ++i) { req = requests[i]; if (req.async || req.type === 'css') { // No need to queue CSS or fully async JS. self._insert(req); } else { queue.push(req); } } self._next(); }, /** Manually purges any `<script>` or `<link>` nodes this transaction has created. Be careful when purging a transaction that contains CSS requests, since removing `<link>` nodes will also remove any styles they applied. @method purge **/ purge: function () { Get._purge(this.nodes); }, // -- Protected Methods ---------------------------------------------------- _createNode: function (name, attrs, doc) { var node = doc.createElement(name), attr, testEl; if (!CUSTOM_ATTRS) { // IE6 and IE7 expect property names rather than attribute names for // certain attributes. Rather than sniffing, we do a quick feature // test the first time _createNode() runs to determine whether we // need to provide a workaround. testEl = doc.createElement('div'); testEl.setAttribute('class', 'a'); CUSTOM_ATTRS = testEl.className === 'a' ? {} : { 'for' : 'htmlFor', 'class': 'className' }; } for (attr in attrs) { if (attrs.hasOwnProperty(attr)) { node.setAttribute(CUSTOM_ATTRS[attr] || attr, attrs[attr]); } } return node; }, _finish: function () { var errors = this.errors.length ? this.errors : null, options = this.options, thisObj = options.context || this, data, i, len; if (this._state === 'done') { return; } this._state = 'done'; for (i = 0, len = this._callbacks.length; i < len; ++i) { this._callbacks[i].call(thisObj, errors, this); } data = this._getEventData(); if (errors) { if (options.onTimeout && errors[errors.length - 1].error === 'Timeout') { options.onTimeout.call(thisObj, data); } if (options.onFailure) { options.onFailure.call(thisObj, data); } } else if (options.onSuccess) { options.onSuccess.call(thisObj, data); } if (options.onEnd) { options.onEnd.call(thisObj, data); } if (options._onFinish) { options._onFinish(); } }, _getEventData: function (req) { if (req) { // This merge is necessary for backcompat. I hate it. return Y.merge(this, { abort : this.abort, // have to copy these because the prototype isn't preserved purge : this.purge, request: req, url : req.url, win : req.win }); } else { return this; } }, _getInsertBefore: function (req) { var doc = req.doc, el = req.insertBefore, cache, docStamp; if (el) { return typeof el === 'string' ? doc.getElementById(el) : el; } cache = Get._insertCache; docStamp = Y.stamp(doc); if ((el = cache[docStamp])) { // assignment return el; } // Inserting before a <base> tag apparently works around an IE bug // (according to a comment from pre-3.5.0 Y.Get), but I'm not sure what // bug that is, exactly. Better safe than sorry? if ((el = doc.getElementsByTagName('base')[0])) { // assignment return (cache[docStamp] = el); } // Look for a <head> element. el = doc.head || doc.getElementsByTagName('head')[0]; if (el) { // Create a marker node at the end of <head> to use as an insertion // point. Inserting before this node will ensure that all our CSS // gets inserted in the correct order, to maintain style precedence. el.appendChild(doc.createTextNode('')); return (cache[docStamp] = el.lastChild); } // If all else fails, just insert before the first script node on the // page, which is virtually guaranteed to exist. return (cache[docStamp] = doc.getElementsByTagName('script')[0]); }, _insert: function (req) { var env = Get._env, insertBefore = this._getInsertBefore(req), isScript = req.type === 'js', node = req.node, self = this, ua = Y.UA, cssTimeout, nodeType; if (!node) { if (isScript) { nodeType = 'script'; } else if (!env.cssLoad && ua.gecko) { nodeType = 'style'; } else { nodeType = 'link'; } node = req.node = this._createNode(nodeType, req.attributes, req.doc); } function onError() { self._progress('Failed to load ' + req.url, req); } function onLoad() { if (cssTimeout) { clearTimeout(cssTimeout); } self._progress(null, req); } // Deal with script asynchronicity. if (isScript) { node.setAttribute('src', req.url); if (req.async) { // Explicitly indicate that we want the browser to execute this // script asynchronously. This is necessary for older browsers // like Firefox <4. node.async = true; } else { if (env.async) { // This browser treats injected scripts as async by default // (standard HTML5 behavior) but asynchronous loading isn't // desired, so tell the browser not to mark this script as // async. node.async = false; } // If this browser doesn't preserve script execution order based // on insertion order, we'll need to avoid inserting other // scripts until this one finishes loading. if (!env.preservesScriptOrder) { this._pending = req; } } } else { if (!env.cssLoad && ua.gecko) { // In Firefox <9, we can import the requested URL into a <style> // node and poll for the existence of node.sheet.cssRules. This // gives us a reliable way to determine CSS load completion that // also works for cross-domain stylesheets. // // Props to Zach Leatherman for calling my attention to this // technique. node.innerHTML = (req.attributes.charset ? '@charset "' + req.attributes.charset + '";' : '') + '@import "' + req.url + '";'; } else { node.setAttribute('href', req.url); } } // Inject the node. if (isScript && ua.ie && (ua.ie < 9 || (document.documentMode && document.documentMode < 9))) { // Script on IE < 9, and IE 9+ when in IE 8 or older modes, including quirks mode. node.onreadystatechange = function () { if (/loaded|complete/.test(node.readyState)) { node.onreadystatechange = null; onLoad(); } }; } else if (!isScript && !env.cssLoad) { // CSS on Firefox <9 or WebKit. this._poll(req); } else { // Script or CSS on everything else. Using DOM 0 events because that // evens the playing field with older IEs. if (ua.ie >= 10) { // We currently need to introduce a timeout for IE10, since it // calls onerror/onload synchronously for 304s - messing up existing // program flow. // Remove this block if the following bug gets fixed by GA /*jshint maxlen: 1500 */ // https://connect.microsoft.com/IE/feedback/details/763871/dynamically-loaded-scripts-with-304s-responses-interrupt-the-currently-executing-js-thread-onload node.onerror = function() { setTimeout(onError, 0); }; node.onload = function() { setTimeout(onLoad, 0); }; } else { node.onerror = onError; node.onload = onLoad; } // If this browser doesn't fire an event when CSS fails to load, // fail after a timeout to avoid blocking the transaction queue. if (!env.cssFail && !isScript) { cssTimeout = setTimeout(onError, req.timeout || 3000); } } this.nodes.push(node); insertBefore.parentNode.insertBefore(node, insertBefore); }, _next: function () { if (this._pending) { return; } // If there are requests in the queue, insert the next queued request. // Otherwise, if we're waiting on already-inserted requests to finish, // wait longer. If there are no queued requests and we're not waiting // for anything to load, then we're done! if (this._queue.length) { this._insert(this._queue.shift()); } else if (!this._reqsWaiting) { this._finish(); } }, _poll: function (newReq) { var self = this, pendingCSS = self._pendingCSS, isWebKit = Y.UA.webkit, i, hasRules, j, nodeHref, req, sheets; if (newReq) { pendingCSS || (pendingCSS = self._pendingCSS = []); pendingCSS.push(newReq); if (self._pollTimer) { // A poll timeout is already pending, so no need to create a // new one. return; } } self._pollTimer = null; // Note: in both the WebKit and Gecko hacks below, a CSS URL that 404s // will still be treated as a success. There's no good workaround for // this. for (i = 0; i < pendingCSS.length; ++i) { req = pendingCSS[i]; if (isWebKit) { // Look for a stylesheet matching the pending URL. sheets = req.doc.styleSheets; j = sheets.length; nodeHref = req.node.href; while (--j >= 0) { if (sheets[j].href === nodeHref) { pendingCSS.splice(i, 1); i -= 1; self._progress(null, req); break; } } } else { // Many thanks to Zach Leatherman for calling my attention to // the @import-based cross-domain technique used here, and to // Oleg Slobodskoi for an earlier same-domain implementation. // // See Zach's blog for more details: // http://www.zachleat.com/web/2010/07/29/load-css-dynamically/ try { // We don't really need to store this value since we never // use it again, but if we don't store it, Closure Compiler // assumes the code is useless and removes it. hasRules = !!req.node.sheet.cssRules; // If we get here, the stylesheet has loaded. pendingCSS.splice(i, 1); i -= 1; self._progress(null, req); } catch (ex) { // An exception means the stylesheet is still loading. } } } if (pendingCSS.length) { self._pollTimer = setTimeout(function () { self._poll.call(self); }, self.options.pollInterval); } }, _progress: function (err, req) { var options = this.options; if (err) { req.error = err; this.errors.push({ error : err, request: req }); Y.log(err, 'error', 'get'); } req.node._yuiget_finished = req.finished = true; if (options.onProgress) { options.onProgress.call(options.context || this, this._getEventData(req)); } if (req.autopurge) { // Pre-3.5.0 Get always excludes the most recent node from an // autopurge. I find this odd, but I'm keeping that behavior for // the sake of backcompat. Get._autoPurge(this.options.purgethreshold); Get._purgeNodes.push(req.node); } if (this._pending === req) { this._pending = null; } this._reqsWaiting -= 1; this._next(); } }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('features', function (Y, NAME) { var feature_tests = {}; /** Contains the core of YUI's feature test architecture. @module features */ /** * Feature detection * @class Features * @static */ Y.mix(Y.namespace('Features'), { /** * Object hash of all registered feature tests * @property tests * @type Object */ tests: feature_tests, /** * Add a test to the system * * ``` * Y.Features.add("load", "1", {}); * ``` * * @method add * @param {String} cat The category, right now only 'load' is supported * @param {String} name The number sequence of the test, how it's reported in the URL or config: 1, 2, 3 * @param {Object} o Object containing test properties * @param {String} o.name The name of the test * @param {Function} o.test The test function to execute, the only argument to the function is the `Y` instance * @param {String} o.trigger The module that triggers this test. */ add: function(cat, name, o) { feature_tests[cat] = feature_tests[cat] || {}; feature_tests[cat][name] = o; }, /** * Execute all tests of a given category and return the serialized results * * ``` * caps=1:1;2:1;3:0 * ``` * @method all * @param {String} cat The category to execute * @param {Array} args The arguments to pass to the test function * @return {String} A semi-colon separated string of tests and their success/failure: 1:1;2:1;3:0 */ all: function(cat, args) { var cat_o = feature_tests[cat], // results = {}; result = []; if (cat_o) { Y.Object.each(cat_o, function(v, k) { result.push(k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0)); }); } return (result.length) ? result.join(';') : ''; }, /** * Run a sepecific test and return a Boolean response. * * ``` * Y.Features.test("load", "1"); * ``` * * @method test * @param {String} cat The category of the test to run * @param {String} name The name of the test to run * @param {Array} args The arguments to pass to the test function * @return {Boolean} True or false if the test passed/failed. */ test: function(cat, name, args) { args = args || []; var result, ua, test, cat_o = feature_tests[cat], feature = cat_o && cat_o[name]; if (!feature) { Y.log('Feature test ' + cat + ', ' + name + ' not found'); } else { result = feature.result; if (Y.Lang.isUndefined(result)) { ua = feature.ua; if (ua) { result = (Y.UA[ua]); } test = feature.test; if (test && ((!ua) || result)) { result = test.apply(Y, args); } feature.result = result; } } return result; } }); // Y.Features.add("load", "1", {}); // Y.Features.test("load", "1"); // caps=1:1;2:0;3:1; /* This file is auto-generated by (yogi loader --yes --mix --start ../) */ var add = Y.Features.add; // app-transitions-native add('load', '0', { "name": "app-transitions-native", "test": function (Y) { var doc = Y.config.doc, node = doc ? doc.documentElement : null; if (node && node.style) { return ('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return false; }, "trigger": "app-transitions" }); // autocomplete-list-keys add('load', '1', { "name": "autocomplete-list-keys", "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }); // dd-gestures add('load', '2', { "name": "dd-gestures", "trigger": "dd-drag", "ua": "touchEnabled" }); // dom-style-ie add('load', '3', { "name": "dom-style-ie", "test": function (Y) { var testFeature = Y.Features.test, addFeature = Y.Features.add, WINDOW = Y.config.win, DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', ret = false; addFeature('style', 'computedStyle', { test: function() { return WINDOW && 'getComputedStyle' in WINDOW; } }); addFeature('style', 'opacity', { test: function() { return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style; } }); ret = (!testFeature('style', 'opacity') && !testFeature('style', 'computedStyle')); return ret; }, "trigger": "dom-style" }); // editor-para-ie add('load', '4', { "name": "editor-para-ie", "trigger": "editor-para", "ua": "ie", "when": "instead" }); // event-base-ie add('load', '5', { "name": "event-base-ie", "test": function(Y) { var imp = Y.config.doc && Y.config.doc.implementation; return (imp && (!imp.hasFeature('Events', '2.0'))); }, "trigger": "node-base" }); // graphics-canvas add('load', '6', { "name": "graphics-canvas", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-canvas-default add('load', '7', { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-svg add('load', '8', { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-svg-default add('load', '9', { "name": "graphics-svg-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-vml add('load', '10', { "name": "graphics-vml", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // graphics-vml-default add('load', '11', { "name": "graphics-vml-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // history-hash-ie add('load', '12', { "name": "history-hash-ie", "test": function (Y) { var docMode = Y.config.doc && Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }); // io-nodejs add('load', '13', { "name": "io-nodejs", "trigger": "io-base", "ua": "nodejs" }); // json-parse-shim add('load', '14', { "name": "json-parse-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONParse !== false && !!Native; function workingNative( k, v ) { return k === "ok" ? true : v; } // Double check basic functionality. This is mainly to catch early broken // implementations of the JSON API in Firefox 3.1 beta1 and beta2 if ( nativeSupport ) { try { nativeSupport = ( Native.parse( '{"ok":false}', workingNative ) ).ok; } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-parse" }); // json-stringify-shim add('load', '15', { "name": "json-stringify-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONStringify !== false && !!Native; // Double check basic native functionality. This is primarily to catch broken // early JSON API implementations in Firefox 3.1 beta1 and beta2. if ( nativeSupport ) { try { nativeSupport = ( '0' === Native.stringify(0) ); } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-stringify" }); // scrollview-base-ie add('load', '16', { "name": "scrollview-base-ie", "trigger": "scrollview-base", "ua": "ie" }); // selector-css2 add('load', '17', { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }); // transition-timer add('load', '18', { "name": "transition-timer", "test": function (Y) { var DOCUMENT = Y.config.doc, node = (DOCUMENT) ? DOCUMENT.documentElement: null, ret = true; if (node && node.style) { ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return ret; }, "trigger": "transition" }); // widget-base-ie add('load', '19', { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }); // yql-jsonp add('load', '20', { "name": "yql-jsonp", "test": function (Y) { /* Only load the JSONP module when not in nodejs or winjs TODO Make the winjs module a CORS module */ return (!Y.UA.nodejs && !Y.UA.winjs); }, "trigger": "yql", "when": "after" }); // yql-nodejs add('load', '21', { "name": "yql-nodejs", "trigger": "yql", "ua": "nodejs", "when": "after" }); // yql-winjs add('load', '22', { "name": "yql-winjs", "trigger": "yql", "ua": "winjs", "when": "after" }); }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('intl-base', function (Y, NAME) { /** * The Intl utility provides a central location for managing sets of * localized resources (strings and formatting patterns). * * @class Intl * @uses EventTarget * @static */ var SPLIT_REGEX = /[, ]/; Y.mix(Y.namespace('Intl'), { /** * Returns the language among those available that * best matches the preferred language list, using the Lookup * algorithm of BCP 47. * If none of the available languages meets the user's preferences, * then "" is returned. * Extended language ranges are not supported. * * @method lookupBestLang * @param {String[] | String} preferredLanguages The list of preferred * languages in descending preference order, represented as BCP 47 * language tags. A string array or a comma-separated list. * @param {String[]} availableLanguages The list of languages * that the application supports, represented as BCP 47 language * tags. * * @return {String} The available language that best matches the * preferred language list, or "". * @since 3.1.0 */ lookupBestLang: function(preferredLanguages, availableLanguages) { var i, language, result, index; // check whether the list of available languages contains language; // if so return it function scan(language) { var i; for (i = 0; i < availableLanguages.length; i += 1) { if (language.toLowerCase() === availableLanguages[i].toLowerCase()) { return availableLanguages[i]; } } } if (Y.Lang.isString(preferredLanguages)) { preferredLanguages = preferredLanguages.split(SPLIT_REGEX); } for (i = 0; i < preferredLanguages.length; i += 1) { language = preferredLanguages[i]; if (!language || language === '*') { continue; } // check the fallback sequence for one language while (language.length > 0) { result = scan(language); if (result) { return result; } else { index = language.lastIndexOf('-'); if (index >= 0) { language = language.substring(0, index); // one-character subtags get cut along with the // following subtag if (index >= 2 && language.charAt(index - 2) === '-') { language = language.substring(0, index - 2); } } else { // nothing available for this language break; } } } } return ''; } }); }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('yui-log', function (Y, NAME) { /** * Provides console log capability and exposes a custom event for * console implementations. This module is a `core` YUI module, * <a href="../classes/YUI.html#method_log">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-log */ var INSTANCE = Y, LOGEVENT = 'yui:log', UNDEFINED = 'undefined', LEVELS = { debug: 1, info: 1, warn: 1, error: 1 }; /** * If the 'debug' config is true, a 'yui:log' event will be * dispatched, which the Console widget and anything else * can consume. If the 'useBrowserConsole' config is true, it will * write to the browser console if available. YUI-specific log * messages will only be present in the -debug versions of the * JS files. The build system is supposed to remove log statements * from the raw and minified versions of the files. * * @method log * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.log = function(msg, cat, src, silent) { var bail, excl, incl, m, f, Y = INSTANCE, c = Y.config, publisher = (Y.fire) ? Y : YUI.Env.globalEvents; // suppress log message if the config is off or the event stack // or the event call stack contains a consumer of the yui:log event if (c.debug) { // apply source filters src = src || ""; if (typeof src !== "undefined") { excl = c.logExclude; incl = c.logInclude; if (incl && !(src in incl)) { bail = 1; } else if (incl && (src in incl)) { bail = !incl[src]; } else if (excl && (src in excl)) { bail = excl[src]; } } if (!bail) { if (c.useBrowserConsole) { m = (src) ? src + ': ' + msg : msg; if (Y.Lang.isFunction(c.logFn)) { c.logFn.call(Y, msg, cat, src); } else if (typeof console !== UNDEFINED && console.log) { f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log'; console[f](m); } else if (typeof opera !== UNDEFINED) { opera.postError(m); } } if (publisher && !silent) { if (publisher === Y && (!publisher.getEvent(LOGEVENT))) { publisher.publish(LOGEVENT, { broadcast: 2 }); } publisher.fire(LOGEVENT, { msg: msg, cat: cat, src: src }); } } } return Y; }; /** * Write a system message. This message will be preserved in the * minified and raw versions of the YUI files, unlike log statements. * @method message * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.message = function() { return INSTANCE.log.apply(INSTANCE, arguments); }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('yui-later', function (Y, NAME) { /** * Provides a setTimeout/setInterval wrapper. This module is a `core` YUI module, * <a href="../classes/YUI.html#method_later">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-later */ var NO_ARGS = []; /** * Executes the supplied function in the context of the supplied * object 'when' milliseconds later. Executes the function a * single time unless periodic is set to true. * @for YUI * @method later * @param when {int} the number of milliseconds to wait until the fn * is executed. * @param o the context object. * @param fn {Function|String} the function to execute or the name of * the method in the 'o' object to execute. * @param data [Array] data that is provided to the function. This * accepts either a single item or an array. If an array is provided, * the function is executed with one parameter for each array item. * If you need to pass a single array parameter, it needs to be wrapped * in an array [myarray]. * * Note: native methods in IE may not have the call and apply methods. * In this case, it will work, but you are limited to four arguments. * * @param periodic {boolean} if true, executes continuously at supplied * interval until canceled. * @return {object} a timer object. Call the cancel() method on this * object to stop the timer. */ Y.later = function(when, o, fn, data, periodic) { when = when || 0; data = (!Y.Lang.isUndefined(data)) ? Y.Array(data) : NO_ARGS; o = o || Y.config.win || Y; var cancelled = false, method = (o && Y.Lang.isString(fn)) ? o[fn] : fn, wrapper = function() { // IE 8- may execute a setInterval callback one last time // after clearInterval was called, so in order to preserve // the cancel() === no more runny-run, we have to jump through // an extra hoop. if (!cancelled) { if (!method.apply) { method(data[0], data[1], data[2], data[3]); } else { method.apply(o, data || NO_ARGS); } } }, id = (periodic) ? setInterval(wrapper, when) : setTimeout(wrapper, when); return { id: id, interval: periodic, cancel: function() { cancelled = true; if (this.interval) { clearInterval(id); } else { clearTimeout(id); } } }; }; Y.Lang.later = Y.later; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('yui', function (Y, NAME) {}, '@VERSION@', {"use": ["get", "features", "intl-base", "yui-log", "yui-later"]}); YUI.add('oop', function (Y, NAME) { /** Adds object inheritance and manipulation utilities to the YUI instance. This module is required by most YUI components. @module oop **/ var L = Y.Lang, A = Y.Array, OP = Object.prototype, CLONE_MARKER = '_~yuim~_', hasOwn = OP.hasOwnProperty, toString = OP.toString; function dispatch(o, f, c, proto, action) { if (o && o[action] && o !== Y) { return o[action].call(o, f, c); } else { switch (A.test(o)) { case 1: return A[action](o, f, c); case 2: return A[action](Y.Array(o, 0, true), f, c); default: return Y.Object[action](o, f, c, proto); } } } /** Augments the _receiver_ with prototype properties from the _supplier_. The receiver may be a constructor function or an object. The supplier must be a constructor function. If the _receiver_ is an object, then the _supplier_ constructor will be called immediately after _receiver_ is augmented, with _receiver_ as the `this` object. If the _receiver_ is a constructor function, then all prototype methods of _supplier_ that are copied to _receiver_ will be sequestered, and the _supplier_ constructor will not be called immediately. The first time any sequestered method is called on the _receiver_'s prototype, all sequestered methods will be immediately copied to the _receiver_'s prototype, the _supplier_'s constructor will be executed, and finally the newly unsequestered method that was called will be executed. This sequestering logic sounds like a bunch of complicated voodoo, but it makes it cheap to perform frequent augmentation by ensuring that suppliers' constructors are only called if a supplied method is actually used. If none of the supplied methods is ever used, then there's no need to take the performance hit of calling the _supplier_'s constructor. @method augment @param {Function|Object} receiver Object or function to be augmented. @param {Function} supplier Function that supplies the prototype properties with which to augment the _receiver_. @param {Boolean} [overwrite=false] If `true`, properties already on the receiver will be overwritten if found on the supplier's prototype. @param {String[]} [whitelist] An array of property names. If specified, only the whitelisted prototype properties will be applied to the receiver, and all others will be ignored. @param {Array|any} [args] Argument or array of arguments to pass to the supplier's constructor when initializing. @return {Function} Augmented object. @for YUI **/ Y.augment = function (receiver, supplier, overwrite, whitelist, args) { var rProto = receiver.prototype, sequester = rProto && supplier, sProto = supplier.prototype, to = rProto || receiver, copy, newPrototype, replacements, sequestered, unsequester; args = args ? Y.Array(args) : []; if (sequester) { newPrototype = {}; replacements = {}; sequestered = {}; copy = function (value, key) { if (overwrite || !(key in rProto)) { if (toString.call(value) === '[object Function]') { sequestered[key] = value; newPrototype[key] = replacements[key] = function () { return unsequester(this, value, arguments); }; } else { newPrototype[key] = value; } } }; unsequester = function (instance, fn, fnArgs) { // Unsequester all sequestered functions. for (var key in sequestered) { if (hasOwn.call(sequestered, key) && instance[key] === replacements[key]) { instance[key] = sequestered[key]; } } // Execute the supplier constructor. supplier.apply(instance, args); // Finally, execute the original sequestered function. return fn.apply(instance, fnArgs); }; if (whitelist) { Y.Array.each(whitelist, function (name) { if (name in sProto) { copy(sProto[name], name); } }); } else { Y.Object.each(sProto, copy, null, true); } } Y.mix(to, newPrototype || sProto, overwrite, whitelist); if (!sequester) { supplier.apply(to, args); } return receiver; }; /** * Copies object properties from the supplier to the receiver. If the target has * the property, and the property is an object, the target object will be * augmented with the supplier's value. * * @method aggregate * @param {Object} receiver Object to receive the augmentation. * @param {Object} supplier Object that supplies the properties with which to * augment the receiver. * @param {Boolean} [overwrite=false] If `true`, properties already on the receiver * will be overwritten if found on the supplier. * @param {String[]} [whitelist] Whitelist. If supplied, only properties in this * list will be applied to the receiver. * @return {Object} Augmented object. */ Y.aggregate = function(r, s, ov, wl) { return Y.mix(r, s, ov, wl, 0, true); }; /** * Utility to set up the prototype, constructor and superclass properties to * support an inheritance strategy that can chain constructors and methods. * Static members will not be inherited. * * @method extend * @param {function} r the object to modify. * @param {function} s the object to inherit. * @param {object} px prototype properties to add/override. * @param {object} sx static properties to add/override. * @return {object} the extended object. */ Y.extend = function(r, s, px, sx) { if (!s || !r) { Y.error('extend failed, verify dependencies'); } var sp = s.prototype, rp = Y.Object(sp); r.prototype = rp; rp.constructor = r; r.superclass = sp; // assign constructor property if (s != Object && sp.constructor == OP.constructor) { sp.constructor = s; } // add prototype overrides if (px) { Y.mix(rp, px, true); } // add object overrides if (sx) { Y.mix(r, sx, true); } return r; }; /** * Executes the supplied function for each item in * a collection. Supports arrays, objects, and * NodeLists * @method each * @param {object} o the object to iterate. * @param {function} f the function to execute. This function * receives the value, key, and object as parameters. * @param {object} c the execution context for the function. * @param {boolean} proto if true, prototype properties are * iterated on objects. * @return {YUI} the YUI instance. */ Y.each = function(o, f, c, proto) { return dispatch(o, f, c, proto, 'each'); }; /** * Executes the supplied function for each item in * a collection. The operation stops if the function * returns true. Supports arrays, objects, and * NodeLists. * @method some * @param {object} o the object to iterate. * @param {function} f the function to execute. This function * receives the value, key, and object as parameters. * @param {object} c the execution context for the function. * @param {boolean} proto if true, prototype properties are * iterated on objects. * @return {boolean} true if the function ever returns true, * false otherwise. */ Y.some = function(o, f, c, proto) { return dispatch(o, f, c, proto, 'some'); }; /** * Deep object/array copy. Function clones are actually * wrappers around the original function. * Array-like objects are treated as arrays. * Primitives are returned untouched. Optionally, a * function can be provided to handle other data types, * filter keys, validate values, etc. * * NOTE: Cloning a non-trivial object is a reasonably heavy operation, due to * the need to recurrsively iterate down non-primitive properties. Clone * should be used only when a deep clone down to leaf level properties * is explicitly required. * * In many cases (for example, when trying to isolate objects used as * hashes for configuration properties), a shallow copy, using Y.merge is * normally sufficient. If more than one level of isolation is required, * Y.merge can be used selectively at each level which needs to be * isolated from the original without going all the way to leaf properties. * * @method clone * @param {object} o what to clone. * @param {boolean} safe if true, objects will not have prototype * items from the source. If false, they will. In this case, the * original is initially protected, but the clone is not completely * immune from changes to the source object prototype. Also, cloned * prototype items that are deleted from the clone will result * in the value of the source prototype being exposed. If operating * on a non-safe clone, items should be nulled out rather than deleted. * @param {function} f optional function to apply to each item in a * collection; it will be executed prior to applying the value to * the new object. Return false to prevent the copy. * @param {object} c optional execution context for f. * @param {object} owner Owner object passed when clone is iterating * an object. Used to set up context for cloned functions. * @param {object} cloned hash of previously cloned objects to avoid * multiple clones. * @return {Array|Object} the cloned object. */ Y.clone = function(o, safe, f, c, owner, cloned) { if (!L.isObject(o)) { return o; } // @todo cloning YUI instances doesn't currently work if (Y.instanceOf(o, YUI)) { return o; } var o2, marked = cloned || {}, stamp, yeach = Y.each; switch (L.type(o)) { case 'date': return new Date(o); case 'regexp': // if we do this we need to set the flags too // return new RegExp(o.source); return o; case 'function': // o2 = Y.bind(o, owner); // break; return o; case 'array': o2 = []; break; default: // #2528250 only one clone of a given object should be created. if (o[CLONE_MARKER]) { return marked[o[CLONE_MARKER]]; } stamp = Y.guid(); o2 = (safe) ? {} : Y.Object(o); o[CLONE_MARKER] = stamp; marked[stamp] = o; } // #2528250 don't try to clone element properties if (!o.addEventListener && !o.attachEvent) { yeach(o, function(v, k) { if ((k || k === 0) && (!f || (f.call(c || this, v, k, this, o) !== false))) { if (k !== CLONE_MARKER) { if (k == 'prototype') { // skip the prototype // } else if (o[k] === o) { // this[k] = this; } else { this[k] = Y.clone(v, safe, f, c, owner || o, marked); } } } }, o2); } if (!cloned) { Y.Object.each(marked, function(v, k) { if (v[CLONE_MARKER]) { try { delete v[CLONE_MARKER]; } catch (e) { v[CLONE_MARKER] = null; } } }, this); marked = null; } return o2; }; /** * Returns a function that will execute the supplied function in the * supplied object's context, optionally adding any additional * supplied parameters to the beginning of the arguments collection the * supplied to the function. * * @method bind * @param {Function|String} f the function to bind, or a function name * to execute on the context object. * @param {object} c the execution context. * @param {any} args* 0..n arguments to include before the arguments the * function is executed with. * @return {function} the wrapped function. */ Y.bind = function(f, c) { var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null; return function() { var fn = L.isString(f) ? c[f] : f, args = (xargs) ? xargs.concat(Y.Array(arguments, 0, true)) : arguments; return fn.apply(c || fn, args); }; }; /** * Returns a function that will execute the supplied function in the * supplied object's context, optionally adding any additional * supplied parameters to the end of the arguments the function * is executed with. * * @method rbind * @param {Function|String} f the function to bind, or a function name * to execute on the context object. * @param {object} c the execution context. * @param {any} args* 0..n arguments to append to the end of * arguments collection supplied to the function. * @return {function} the wrapped function. */ Y.rbind = function(f, c) { var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null; return function() { var fn = L.isString(f) ? c[f] : f, args = (xargs) ? Y.Array(arguments, 0, true).concat(xargs) : arguments; return fn.apply(c || fn, args); }; }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('features', function (Y, NAME) { var feature_tests = {}; /** Contains the core of YUI's feature test architecture. @module features */ /** * Feature detection * @class Features * @static */ Y.mix(Y.namespace('Features'), { /** * Object hash of all registered feature tests * @property tests * @type Object */ tests: feature_tests, /** * Add a test to the system * * ``` * Y.Features.add("load", "1", {}); * ``` * * @method add * @param {String} cat The category, right now only 'load' is supported * @param {String} name The number sequence of the test, how it's reported in the URL or config: 1, 2, 3 * @param {Object} o Object containing test properties * @param {String} o.name The name of the test * @param {Function} o.test The test function to execute, the only argument to the function is the `Y` instance * @param {String} o.trigger The module that triggers this test. */ add: function(cat, name, o) { feature_tests[cat] = feature_tests[cat] || {}; feature_tests[cat][name] = o; }, /** * Execute all tests of a given category and return the serialized results * * ``` * caps=1:1;2:1;3:0 * ``` * @method all * @param {String} cat The category to execute * @param {Array} args The arguments to pass to the test function * @return {String} A semi-colon separated string of tests and their success/failure: 1:1;2:1;3:0 */ all: function(cat, args) { var cat_o = feature_tests[cat], // results = {}; result = []; if (cat_o) { Y.Object.each(cat_o, function(v, k) { result.push(k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0)); }); } return (result.length) ? result.join(';') : ''; }, /** * Run a sepecific test and return a Boolean response. * * ``` * Y.Features.test("load", "1"); * ``` * * @method test * @param {String} cat The category of the test to run * @param {String} name The name of the test to run * @param {Array} args The arguments to pass to the test function * @return {Boolean} True or false if the test passed/failed. */ test: function(cat, name, args) { args = args || []; var result, ua, test, cat_o = feature_tests[cat], feature = cat_o && cat_o[name]; if (!feature) { Y.log('Feature test ' + cat + ', ' + name + ' not found'); } else { result = feature.result; if (Y.Lang.isUndefined(result)) { ua = feature.ua; if (ua) { result = (Y.UA[ua]); } test = feature.test; if (test && ((!ua) || result)) { result = test.apply(Y, args); } feature.result = result; } } return result; } }); // Y.Features.add("load", "1", {}); // Y.Features.test("load", "1"); // caps=1:1;2:0;3:1; /* This file is auto-generated by (yogi loader --yes --mix --start ../) */ var add = Y.Features.add; // app-transitions-native add('load', '0', { "name": "app-transitions-native", "test": function (Y) { var doc = Y.config.doc, node = doc ? doc.documentElement : null; if (node && node.style) { return ('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return false; }, "trigger": "app-transitions" }); // autocomplete-list-keys add('load', '1', { "name": "autocomplete-list-keys", "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }); // dd-gestures add('load', '2', { "name": "dd-gestures", "trigger": "dd-drag", "ua": "touchEnabled" }); // dom-style-ie add('load', '3', { "name": "dom-style-ie", "test": function (Y) { var testFeature = Y.Features.test, addFeature = Y.Features.add, WINDOW = Y.config.win, DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', ret = false; addFeature('style', 'computedStyle', { test: function() { return WINDOW && 'getComputedStyle' in WINDOW; } }); addFeature('style', 'opacity', { test: function() { return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style; } }); ret = (!testFeature('style', 'opacity') && !testFeature('style', 'computedStyle')); return ret; }, "trigger": "dom-style" }); // editor-para-ie add('load', '4', { "name": "editor-para-ie", "trigger": "editor-para", "ua": "ie", "when": "instead" }); // event-base-ie add('load', '5', { "name": "event-base-ie", "test": function(Y) { var imp = Y.config.doc && Y.config.doc.implementation; return (imp && (!imp.hasFeature('Events', '2.0'))); }, "trigger": "node-base" }); // graphics-canvas add('load', '6', { "name": "graphics-canvas", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-canvas-default add('load', '7', { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-svg add('load', '8', { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-svg-default add('load', '9', { "name": "graphics-svg-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-vml add('load', '10', { "name": "graphics-vml", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // graphics-vml-default add('load', '11', { "name": "graphics-vml-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // history-hash-ie add('load', '12', { "name": "history-hash-ie", "test": function (Y) { var docMode = Y.config.doc && Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }); // io-nodejs add('load', '13', { "name": "io-nodejs", "trigger": "io-base", "ua": "nodejs" }); // json-parse-shim add('load', '14', { "name": "json-parse-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONParse !== false && !!Native; function workingNative( k, v ) { return k === "ok" ? true : v; } // Double check basic functionality. This is mainly to catch early broken // implementations of the JSON API in Firefox 3.1 beta1 and beta2 if ( nativeSupport ) { try { nativeSupport = ( Native.parse( '{"ok":false}', workingNative ) ).ok; } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-parse" }); // json-stringify-shim add('load', '15', { "name": "json-stringify-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONStringify !== false && !!Native; // Double check basic native functionality. This is primarily to catch broken // early JSON API implementations in Firefox 3.1 beta1 and beta2. if ( nativeSupport ) { try { nativeSupport = ( '0' === Native.stringify(0) ); } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-stringify" }); // scrollview-base-ie add('load', '16', { "name": "scrollview-base-ie", "trigger": "scrollview-base", "ua": "ie" }); // selector-css2 add('load', '17', { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }); // transition-timer add('load', '18', { "name": "transition-timer", "test": function (Y) { var DOCUMENT = Y.config.doc, node = (DOCUMENT) ? DOCUMENT.documentElement: null, ret = true; if (node && node.style) { ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return ret; }, "trigger": "transition" }); // widget-base-ie add('load', '19', { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }); // yql-jsonp add('load', '20', { "name": "yql-jsonp", "test": function (Y) { /* Only load the JSONP module when not in nodejs or winjs TODO Make the winjs module a CORS module */ return (!Y.UA.nodejs && !Y.UA.winjs); }, "trigger": "yql", "when": "after" }); // yql-nodejs add('load', '21', { "name": "yql-nodejs", "trigger": "yql", "ua": "nodejs", "when": "after" }); // yql-winjs add('load', '22', { "name": "yql-winjs", "trigger": "yql", "ua": "winjs", "when": "after" }); }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('dom-core', function (Y, NAME) { var NODE_TYPE = 'nodeType', OWNER_DOCUMENT = 'ownerDocument', DOCUMENT_ELEMENT = 'documentElement', DEFAULT_VIEW = 'defaultView', PARENT_WINDOW = 'parentWindow', TAG_NAME = 'tagName', PARENT_NODE = 'parentNode', PREVIOUS_SIBLING = 'previousSibling', NEXT_SIBLING = 'nextSibling', CONTAINS = 'contains', COMPARE_DOCUMENT_POSITION = 'compareDocumentPosition', EMPTY_ARRAY = [], // IE < 8 throws on node.contains(textNode) supportsContainsTextNode = (function() { var node = Y.config.doc.createElement('div'), textNode = node.appendChild(Y.config.doc.createTextNode('')), result = false; try { result = node.contains(textNode); } catch(e) {} return result; })(), /** * The DOM utility provides a cross-browser abtraction layer * normalizing DOM tasks, and adds extra helper functionality * for other common tasks. * @module dom * @main dom * @submodule dom-base * @for DOM * */ /** * Provides DOM helper methods. * @class DOM * */ Y_DOM = { /** * Returns the HTMLElement with the given ID (Wrapper for document.getElementById). * @method byId * @param {String} id the id attribute * @param {Object} doc optional The document to search. Defaults to current document * @return {HTMLElement | null} The HTMLElement with the id, or null if none found. */ byId: function(id, doc) { // handle dupe IDs and IE name collision return Y_DOM.allById(id, doc)[0] || null; }, getId: function(node) { var id; // HTMLElement returned from FORM when INPUT name === "id" // IE < 8: HTMLCollection returned when INPUT id === "id" // via both getAttribute and form.id if (node.id && !node.id.tagName && !node.id.item) { id = node.id; } else if (node.attributes && node.attributes.id) { id = node.attributes.id.value; } return id; }, setId: function(node, id) { if (node.setAttribute) { node.setAttribute('id', id); } else { node.id = id; } }, /* * Finds the ancestor of the element. * @method ancestor * @param {HTMLElement} element The html element. * @param {Function} fn optional An optional boolean test to apply. * The optional function is passed the current DOM node being tested as its only argument. * If no function is given, the parentNode is returned. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @return {HTMLElement | null} The matching DOM node or null if none found. */ ancestor: function(element, fn, testSelf, stopFn) { var ret = null; if (testSelf) { ret = (!fn || fn(element)) ? element : null; } return ret || Y_DOM.elementByAxis(element, PARENT_NODE, fn, null, stopFn); }, /* * Finds the ancestors of the element. * @method ancestors * @param {HTMLElement} element The html element. * @param {Function} fn optional An optional boolean test to apply. * The optional function is passed the current DOM node being tested as its only argument. * If no function is given, all ancestors are returned. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @return {Array} An array containing all matching DOM nodes. */ ancestors: function(element, fn, testSelf, stopFn) { var ancestor = element, ret = []; while ((ancestor = Y_DOM.ancestor(ancestor, fn, testSelf, stopFn))) { testSelf = false; if (ancestor) { ret.unshift(ancestor); if (stopFn && stopFn(ancestor)) { return ret; } } } return ret; }, /** * Searches the element by the given axis for the first matching element. * @method elementByAxis * @param {HTMLElement} element The html element. * @param {String} axis The axis to search (parentNode, nextSibling, previousSibling). * @param {Function} fn optional An optional boolean test to apply. * @param {Boolean} all optional Whether all node types should be returned, or just element nodes. * The optional function is passed the current HTMLElement being tested as its only argument. * If no function is given, the first element is returned. * @return {HTMLElement | null} The matching element or null if none found. */ elementByAxis: function(element, axis, fn, all, stopAt) { while (element && (element = element[axis])) { // NOTE: assignment if ( (all || element[TAG_NAME]) && (!fn || fn(element)) ) { return element; } if (stopAt && stopAt(element)) { return null; } } return null; }, /** * Determines whether or not one HTMLElement is or contains another HTMLElement. * @method contains * @param {HTMLElement} element The containing html element. * @param {HTMLElement} needle The html element that may be contained. * @return {Boolean} Whether or not the element is or contains the needle. */ contains: function(element, needle) { var ret = false; if ( !needle || !element || !needle[NODE_TYPE] || !element[NODE_TYPE]) { ret = false; } else if (element[CONTAINS] && // IE < 8 throws on node.contains(textNode) so fall back to brute. // Falling back for other nodeTypes as well. (needle[NODE_TYPE] === 1 || supportsContainsTextNode)) { ret = element[CONTAINS](needle); } else if (element[COMPARE_DOCUMENT_POSITION]) { // Match contains behavior (node.contains(node) === true). // Needed for Firefox < 4. if (element === needle || !!(element[COMPARE_DOCUMENT_POSITION](needle) & 16)) { ret = true; } } else { ret = Y_DOM._bruteContains(element, needle); } return ret; }, /** * Determines whether or not the HTMLElement is part of the document. * @method inDoc * @param {HTMLElement} element The containing html element. * @param {HTMLElement} doc optional The document to check. * @return {Boolean} Whether or not the element is attached to the document. */ inDoc: function(element, doc) { var ret = false, rootNode; if (element && element.nodeType) { (doc) || (doc = element[OWNER_DOCUMENT]); rootNode = doc[DOCUMENT_ELEMENT]; // contains only works with HTML_ELEMENT if (rootNode && rootNode.contains && element.tagName) { ret = rootNode.contains(element); } else { ret = Y_DOM.contains(rootNode, element); } } return ret; }, allById: function(id, root) { root = root || Y.config.doc; var nodes = [], ret = [], i, node; if (root.querySelectorAll) { ret = root.querySelectorAll('[id="' + id + '"]'); } else if (root.all) { nodes = root.all(id); if (nodes) { // root.all may return HTMLElement or HTMLCollection. // some elements are also HTMLCollection (FORM, SELECT). if (nodes.nodeName) { if (nodes.id === id) { // avoid false positive on name ret.push(nodes); nodes = EMPTY_ARRAY; // done, no need to filter } else { // prep for filtering nodes = [nodes]; } } if (nodes.length) { // filter out matches on node.name // and element.id as reference to element with id === 'id' for (i = 0; node = nodes[i++];) { if (node.id === id || (node.attributes && node.attributes.id && node.attributes.id.value === id)) { ret.push(node); } } } } } else { ret = [Y_DOM._getDoc(root).getElementById(id)]; } return ret; }, isWindow: function(obj) { return !!(obj && obj.scrollTo && obj.document); }, _removeChildNodes: function(node) { while (node.firstChild) { node.removeChild(node.firstChild); } }, siblings: function(node, fn) { var nodes = [], sibling = node; while ((sibling = sibling[PREVIOUS_SIBLING])) { if (sibling[TAG_NAME] && (!fn || fn(sibling))) { nodes.unshift(sibling); } } sibling = node; while ((sibling = sibling[NEXT_SIBLING])) { if (sibling[TAG_NAME] && (!fn || fn(sibling))) { nodes.push(sibling); } } return nodes; }, /** * Brute force version of contains. * Used for browsers without contains support for non-HTMLElement Nodes (textNodes, etc). * @method _bruteContains * @private * @param {HTMLElement} element The containing html element. * @param {HTMLElement} needle The html element that may be contained. * @return {Boolean} Whether or not the element is or contains the needle. */ _bruteContains: function(element, needle) { while (needle) { if (element === needle) { return true; } needle = needle.parentNode; } return false; }, // TODO: move to Lang? /** * Memoizes dynamic regular expressions to boost runtime performance. * @method _getRegExp * @private * @param {String} str The string to convert to a regular expression. * @param {String} flags optional An optinal string of flags. * @return {RegExp} An instance of RegExp */ _getRegExp: function(str, flags) { flags = flags || ''; Y_DOM._regexCache = Y_DOM._regexCache || {}; if (!Y_DOM._regexCache[str + flags]) { Y_DOM._regexCache[str + flags] = new RegExp(str, flags); } return Y_DOM._regexCache[str + flags]; }, // TODO: make getDoc/Win true privates? /** * returns the appropriate document. * @method _getDoc * @private * @param {HTMLElement} element optional Target element. * @return {Object} The document for the given element or the default document. */ _getDoc: function(element) { var doc = Y.config.doc; if (element) { doc = (element[NODE_TYPE] === 9) ? element : // element === document element[OWNER_DOCUMENT] || // element === DOM node element.document || // element === window Y.config.doc; // default } return doc; }, /** * returns the appropriate window. * @method _getWin * @private * @param {HTMLElement} element optional Target element. * @return {Object} The window for the given element or the default window. */ _getWin: function(element) { var doc = Y_DOM._getDoc(element); return doc[DEFAULT_VIEW] || doc[PARENT_WINDOW] || Y.config.win; }, _batch: function(nodes, fn, arg1, arg2, arg3, etc) { fn = (typeof fn === 'string') ? Y_DOM[fn] : fn; var result, i = 0, node, ret; if (fn && nodes) { while ((node = nodes[i++])) { result = result = fn.call(Y_DOM, node, arg1, arg2, arg3, etc); if (typeof result !== 'undefined') { (ret) || (ret = []); ret.push(result); } } } return (typeof ret !== 'undefined') ? ret : nodes; }, generateID: function(el) { var id = el.id; if (!id) { id = Y.stamp(el); el.id = id; } return id; } }; Y.DOM = Y_DOM; }, '@VERSION@', {"requires": ["oop", "features"]}); YUI.add('dom-base', function (Y, NAME) { /** * @for DOM * @module dom */ var documentElement = Y.config.doc.documentElement, Y_DOM = Y.DOM, TAG_NAME = 'tagName', OWNER_DOCUMENT = 'ownerDocument', EMPTY_STRING = '', addFeature = Y.Features.add, testFeature = Y.Features.test; Y.mix(Y_DOM, { /** * Returns the text content of the HTMLElement. * @method getText * @param {HTMLElement} element The html element. * @return {String} The text content of the element (includes text of any descending elements). */ getText: (documentElement.textContent !== undefined) ? function(element) { var ret = ''; if (element) { ret = element.textContent; } return ret || ''; } : function(element) { var ret = ''; if (element) { ret = element.innerText || element.nodeValue; // might be a textNode } return ret || ''; }, /** * Sets the text content of the HTMLElement. * @method setText * @param {HTMLElement} element The html element. * @param {String} content The content to add. */ setText: (documentElement.textContent !== undefined) ? function(element, content) { if (element) { element.textContent = content; } } : function(element, content) { if ('innerText' in element) { element.innerText = content; } else if ('nodeValue' in element) { element.nodeValue = content; } }, CUSTOM_ATTRIBUTES: (!documentElement.hasAttribute) ? { // IE < 8 'for': 'htmlFor', 'class': 'className' } : { // w3c 'htmlFor': 'for', 'className': 'class' }, /** * Provides a normalized attribute interface. * @method setAttribute * @param {HTMLElement} el The target element for the attribute. * @param {String} attr The attribute to set. * @param {String} val The value of the attribute. */ setAttribute: function(el, attr, val, ieAttr) { if (el && attr && el.setAttribute) { attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr; el.setAttribute(attr, val, ieAttr); } else { Y.log('bad input to setAttribute', 'warn', 'dom'); } }, /** * Provides a normalized attribute interface. * @method getAttribute * @param {HTMLElement} el The target element for the attribute. * @param {String} attr The attribute to get. * @return {String} The current value of the attribute. */ getAttribute: function(el, attr, ieAttr) { ieAttr = (ieAttr !== undefined) ? ieAttr : 2; var ret = ''; if (el && attr && el.getAttribute) { attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr; ret = el.getAttribute(attr, ieAttr); if (ret === null) { ret = ''; // per DOM spec } } else { Y.log('bad input to getAttribute', 'warn', 'dom'); } return ret; }, VALUE_SETTERS: {}, VALUE_GETTERS: {}, getValue: function(node) { var ret = '', // TODO: return null? getter; if (node && node[TAG_NAME]) { getter = Y_DOM.VALUE_GETTERS[node[TAG_NAME].toLowerCase()]; if (getter) { ret = getter(node); } else { ret = node.value; } } // workaround for IE8 JSON stringify bug // which converts empty string values to null if (ret === EMPTY_STRING) { ret = EMPTY_STRING; // for real } return (typeof ret === 'string') ? ret : ''; }, setValue: function(node, val) { var setter; if (node && node[TAG_NAME]) { setter = Y_DOM.VALUE_SETTERS[node[TAG_NAME].toLowerCase()]; if (setter) { setter(node, val); } else { node.value = val; } } }, creators: {} }); addFeature('value-set', 'select', { test: function() { var node = Y.config.doc.createElement('select'); node.innerHTML = '<option>1</option><option>2</option>'; node.value = '2'; return (node.value && node.value === '2'); } }); if (!testFeature('value-set', 'select')) { Y_DOM.VALUE_SETTERS.select = function(node, val) { for (var i = 0, options = node.getElementsByTagName('option'), option; option = options[i++];) { if (Y_DOM.getValue(option) === val) { option.selected = true; //Y_DOM.setAttribute(option, 'selected', 'selected'); break; } } }; } Y.mix(Y_DOM.VALUE_GETTERS, { button: function(node) { return (node.attributes && node.attributes.value) ? node.attributes.value.value : ''; } }); Y.mix(Y_DOM.VALUE_SETTERS, { // IE: node.value changes the button text, which should be handled via innerHTML button: function(node, val) { var attr = node.attributes.value; if (!attr) { attr = node[OWNER_DOCUMENT].createAttribute('value'); node.setAttributeNode(attr); } attr.value = val; } }); Y.mix(Y_DOM.VALUE_GETTERS, { option: function(node) { var attrs = node.attributes; return (attrs.value && attrs.value.specified) ? node.value : node.text; }, select: function(node) { var val = node.value, options = node.options; if (options && options.length) { // TODO: implement multipe select if (node.multiple) { Y.log('multiple select normalization not implemented', 'warn', 'DOM'); } else if (node.selectedIndex > -1) { val = Y_DOM.getValue(options[node.selectedIndex]); } } return val; } }); var addClass, hasClass, removeClass; Y.mix(Y.DOM, { /** * Determines whether a DOM element has the given className. * @method hasClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to search for * @return {Boolean} Whether or not the element has the given class. */ hasClass: function(node, className) { var re = Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)'); return re.test(node.className); }, /** * Adds a class name to a given DOM element. * @method addClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to add to the class attribute */ addClass: function(node, className) { if (!Y.DOM.hasClass(node, className)) { // skip if already present node.className = Y.Lang.trim([node.className, className].join(' ')); } }, /** * Removes a class name from a given element. * @method removeClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to remove from the class attribute */ removeClass: function(node, className) { if (className && hasClass(node, className)) { node.className = Y.Lang.trim(node.className.replace(Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)'), ' ')); if ( hasClass(node, className) ) { // in case of multiple adjacent removeClass(node, className); } } }, /** * Replace a class with another class for a given element. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @for DOM * @param {HTMLElement} element The DOM element * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name */ replaceClass: function(node, oldC, newC) { //Y.log('replaceClass replacing ' + oldC + ' with ' + newC, 'info', 'Node'); removeClass(node, oldC); // remove first in case oldC === newC addClass(node, newC); }, /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @for DOM * @param {HTMLElement} element The DOM element * @param {String} className the class name to be toggled * @param {Boolean} addClass optional boolean to indicate whether class * should be added or removed regardless of current state */ toggleClass: function(node, className, force) { var add = (force !== undefined) ? force : !(hasClass(node, className)); if (add) { addClass(node, className); } else { removeClass(node, className); } } }); hasClass = Y.DOM.hasClass; removeClass = Y.DOM.removeClass; addClass = Y.DOM.addClass; var re_tag = /<([a-z]+)/i, Y_DOM = Y.DOM, addFeature = Y.Features.add, testFeature = Y.Features.test, creators = {}, createFromDIV = function(html, tag) { var div = Y.config.doc.createElement('div'), ret = true; div.innerHTML = html; if (!div.firstChild || div.firstChild.tagName !== tag.toUpperCase()) { ret = false; } return ret; }, re_tbody = /(?:\/(?:thead|tfoot|tbody|caption|col|colgroup)>)+\s*<tbody/, TABLE_OPEN = '<table>', TABLE_CLOSE = '</table>'; Y.mix(Y.DOM, { _fragClones: {}, _create: function(html, doc, tag) { tag = tag || 'div'; var frag = Y_DOM._fragClones[tag]; if (frag) { frag = frag.cloneNode(false); } else { frag = Y_DOM._fragClones[tag] = doc.createElement(tag); } frag.innerHTML = html; return frag; }, _children: function(node, tag) { var i = 0, children = node.children, childNodes, hasComments, child; if (children && children.tags) { // use tags filter when possible if (tag) { children = node.children.tags(tag); } else { // IE leaks comments into children hasComments = children.tags('!').length; } } if (!children || (!children.tags && tag) || hasComments) { childNodes = children || node.childNodes; children = []; while ((child = childNodes[i++])) { if (child.nodeType === 1) { if (!tag || tag === child.tagName) { children.push(child); } } } } return children || []; }, /** * Creates a new dom node using the provided markup string. * @method create * @param {String} html The markup used to create the element * @param {HTMLDocument} doc An optional document context * @return {HTMLElement|DocumentFragment} returns a single HTMLElement * when creating one node, and a documentFragment when creating * multiple nodes. */ create: function(html, doc) { if (typeof html === 'string') { html = Y.Lang.trim(html); // match IE which trims whitespace from innerHTML } doc = doc || Y.config.doc; var m = re_tag.exec(html), create = Y_DOM._create, custom = creators, ret = null, creator, tag, nodes; if (html != undefined) { // not undefined or null if (m && m[1]) { creator = custom[m[1].toLowerCase()]; if (typeof creator === 'function') { create = creator; } else { tag = creator; } } nodes = create(html, doc, tag).childNodes; if (nodes.length === 1) { // return single node, breaking parentNode ref from "fragment" ret = nodes[0].parentNode.removeChild(nodes[0]); } else if (nodes[0] && nodes[0].className === 'yui3-big-dummy') { // using dummy node to preserve some attributes (e.g. OPTION not selected) if (nodes.length === 2) { ret = nodes[0].nextSibling; } else { nodes[0].parentNode.removeChild(nodes[0]); ret = Y_DOM._nl2frag(nodes, doc); } } else { // return multiple nodes as a fragment ret = Y_DOM._nl2frag(nodes, doc); } } return ret; }, _nl2frag: function(nodes, doc) { var ret = null, i, len; if (nodes && (nodes.push || nodes.item) && nodes[0]) { doc = doc || nodes[0].ownerDocument; ret = doc.createDocumentFragment(); if (nodes.item) { // convert live list to static array nodes = Y.Array(nodes, 0, true); } for (i = 0, len = nodes.length; i < len; i++) { ret.appendChild(nodes[i]); } } // else inline with log for minification return ret; }, /** * Inserts content in a node at the given location * @method addHTML * @param {HTMLElement} node The node to insert into * @param {HTMLElement | Array | HTMLCollection} content The content to be inserted * @param {HTMLElement} where Where to insert the content * If no "where" is given, content is appended to the node * Possible values for "where" * <dl> * <dt>HTMLElement</dt> * <dd>The element to insert before</dd> * <dt>"replace"</dt> * <dd>Replaces the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts before the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts content before the node</dd> * <dt>"after"</dt> * <dd>Inserts content after the node</dd> * </dl> */ addHTML: function(node, content, where) { var nodeParent = node.parentNode, i = 0, item, ret = content, newNode; if (content != undefined) { // not null or undefined (maybe 0) if (content.nodeType) { // DOM node, just add it newNode = content; } else if (typeof content == 'string' || typeof content == 'number') { ret = newNode = Y_DOM.create(content); } else if (content[0] && content[0].nodeType) { // array or collection newNode = Y.config.doc.createDocumentFragment(); while ((item = content[i++])) { newNode.appendChild(item); // append to fragment for insertion } } } if (where) { if (newNode && where.parentNode) { // insert regardless of relationship to node where.parentNode.insertBefore(newNode, where); } else { switch (where) { case 'replace': while (node.firstChild) { node.removeChild(node.firstChild); } if (newNode) { // allow empty content to clear node node.appendChild(newNode); } break; case 'before': if (newNode) { nodeParent.insertBefore(newNode, node); } break; case 'after': if (newNode) { if (node.nextSibling) { // IE errors if refNode is null nodeParent.insertBefore(newNode, node.nextSibling); } else { nodeParent.appendChild(newNode); } } break; default: if (newNode) { node.appendChild(newNode); } } } } else if (newNode) { node.appendChild(newNode); } return ret; }, wrap: function(node, html) { var parent = (html && html.nodeType) ? html : Y.DOM.create(html), nodes = parent.getElementsByTagName('*'); if (nodes.length) { parent = nodes[nodes.length - 1]; } if (node.parentNode) { node.parentNode.replaceChild(parent, node); } parent.appendChild(node); }, unwrap: function(node) { var parent = node.parentNode, lastChild = parent.lastChild, next = node, grandparent; if (parent) { grandparent = parent.parentNode; if (grandparent) { node = parent.firstChild; while (node !== lastChild) { next = node.nextSibling; grandparent.insertBefore(node, parent); node = next; } grandparent.replaceChild(lastChild, parent); } else { parent.removeChild(node); } } } }); addFeature('innerhtml', 'table', { test: function() { var node = Y.config.doc.createElement('table'); try { node.innerHTML = '<tbody></tbody>'; } catch(e) { return false; } return (node.firstChild && node.firstChild.nodeName === 'TBODY'); } }); addFeature('innerhtml-div', 'tr', { test: function() { return createFromDIV('<tr></tr>', 'tr'); } }); addFeature('innerhtml-div', 'script', { test: function() { return createFromDIV('<script></script>', 'script'); } }); if (!testFeature('innerhtml', 'table')) { // TODO: thead/tfoot with nested tbody // IE adds TBODY when creating TABLE elements (which may share this impl) creators.tbody = function(html, doc) { var frag = Y_DOM.create(TABLE_OPEN + html + TABLE_CLOSE, doc), tb = Y.DOM._children(frag, 'tbody')[0]; if (frag.children.length > 1 && tb && !re_tbody.test(html)) { tb.parentNode.removeChild(tb); // strip extraneous tbody } return frag; }; } if (!testFeature('innerhtml-div', 'script')) { creators.script = function(html, doc) { var frag = doc.createElement('div'); frag.innerHTML = '-' + html; frag.removeChild(frag.firstChild); return frag; }; creators.link = creators.style = creators.script; } if (!testFeature('innerhtml-div', 'tr')) { Y.mix(creators, { option: function(html, doc) { return Y_DOM.create('<select><option class="yui3-big-dummy" selected></option>' + html + '</select>', doc); }, tr: function(html, doc) { return Y_DOM.create('<tbody>' + html + '</tbody>', doc); }, td: function(html, doc) { return Y_DOM.create('<tr>' + html + '</tr>', doc); }, col: function(html, doc) { return Y_DOM.create('<colgroup>' + html + '</colgroup>', doc); }, tbody: 'table' }); Y.mix(creators, { legend: 'fieldset', th: creators.td, thead: creators.tbody, tfoot: creators.tbody, caption: creators.tbody, colgroup: creators.tbody, optgroup: creators.option }); } Y_DOM.creators = creators; Y.mix(Y.DOM, { /** * Sets the width of the element to the given size, regardless * of box model, border, padding, etc. * @method setWidth * @param {HTMLElement} element The DOM element. * @param {String|Number} size The pixel height to size to */ setWidth: function(node, size) { Y.DOM._setSize(node, 'width', size); }, /** * Sets the height of the element to the given size, regardless * of box model, border, padding, etc. * @method setHeight * @param {HTMLElement} element The DOM element. * @param {String|Number} size The pixel height to size to */ setHeight: function(node, size) { Y.DOM._setSize(node, 'height', size); }, _setSize: function(node, prop, val) { val = (val > 0) ? val : 0; var size = 0; node.style[prop] = val + 'px'; size = (prop === 'height') ? node.offsetHeight : node.offsetWidth; if (size > val) { val = val - (size - val); if (val < 0) { val = 0; } node.style[prop] = val + 'px'; } } }); }, '@VERSION@', {"requires": ["dom-core"]}); YUI.add('dom-style', function (Y, NAME) { (function(Y) { /** * Add style management functionality to DOM. * @module dom * @submodule dom-style * @for DOM */ var DOCUMENT_ELEMENT = 'documentElement', DEFAULT_VIEW = 'defaultView', OWNER_DOCUMENT = 'ownerDocument', STYLE = 'style', FLOAT = 'float', CSS_FLOAT = 'cssFloat', STYLE_FLOAT = 'styleFloat', TRANSPARENT = 'transparent', GET_COMPUTED_STYLE = 'getComputedStyle', GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect', WINDOW = Y.config.win, DOCUMENT = Y.config.doc, UNDEFINED = undefined, Y_DOM = Y.DOM, TRANSFORM = 'transform', TRANSFORMORIGIN = 'transformOrigin', VENDOR_TRANSFORM = [ 'WebkitTransform', 'MozTransform', 'OTransform', 'msTransform' ], re_color = /color$/i, re_unit = /width|height|top|left|right|bottom|margin|padding/i; Y.Array.each(VENDOR_TRANSFORM, function(val) { if (val in DOCUMENT[DOCUMENT_ELEMENT].style) { TRANSFORM = val; TRANSFORMORIGIN = val + "Origin"; } }); Y.mix(Y_DOM, { DEFAULT_UNIT: 'px', CUSTOM_STYLES: { }, /** * Sets a style property for a given element. * @method setStyle * @param {HTMLElement} An HTMLElement to apply the style to. * @param {String} att The style property to set. * @param {String|Number} val The value. */ setStyle: function(node, att, val, style) { style = style || node.style; var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES; if (style) { if (val === null || val === '') { // normalize unsetting val = ''; } else if (!isNaN(new Number(val)) && re_unit.test(att)) { // number values may need a unit val += Y_DOM.DEFAULT_UNIT; } if (att in CUSTOM_STYLES) { if (CUSTOM_STYLES[att].set) { CUSTOM_STYLES[att].set(node, val, style); return; // NOTE: return } else if (typeof CUSTOM_STYLES[att] === 'string') { att = CUSTOM_STYLES[att]; } } else if (att === '') { // unset inline styles att = 'cssText'; val = ''; } style[att] = val; } }, /** * Returns the current style value for the given property. * @method getStyle * @param {HTMLElement} An HTMLElement to get the style from. * @param {String} att The style property to get. */ getStyle: function(node, att, style) { style = style || node.style; var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES, val = ''; if (style) { if (att in CUSTOM_STYLES) { if (CUSTOM_STYLES[att].get) { return CUSTOM_STYLES[att].get(node, att, style); // NOTE: return } else if (typeof CUSTOM_STYLES[att] === 'string') { att = CUSTOM_STYLES[att]; } } val = style[att]; if (val === '') { // TODO: is empty string sufficient? val = Y_DOM[GET_COMPUTED_STYLE](node, att); } } return val; }, /** * Sets multiple style properties. * @method setStyles * @param {HTMLElement} node An HTMLElement to apply the styles to. * @param {Object} hash An object literal of property:value pairs. */ setStyles: function(node, hash) { var style = node.style; Y.each(hash, function(v, n) { Y_DOM.setStyle(node, n, v, style); }, Y_DOM); }, /** * Returns the computed style for the given node. * @method getComputedStyle * @param {HTMLElement} An HTMLElement to get the style from. * @param {String} att The style property to get. * @return {String} The computed value of the style property. */ getComputedStyle: function(node, att) { var val = '', doc = node[OWNER_DOCUMENT], computed; if (node[STYLE] && doc[DEFAULT_VIEW] && doc[DEFAULT_VIEW][GET_COMPUTED_STYLE]) { computed = doc[DEFAULT_VIEW][GET_COMPUTED_STYLE](node, null); if (computed) { // FF may be null in some cases (ticket #2530548) val = computed[att]; } } return val; } }); // normalize reserved word float alternatives ("cssFloat" or "styleFloat") if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][CSS_FLOAT] !== UNDEFINED) { Y_DOM.CUSTOM_STYLES[FLOAT] = CSS_FLOAT; } else if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][STYLE_FLOAT] !== UNDEFINED) { Y_DOM.CUSTOM_STYLES[FLOAT] = STYLE_FLOAT; } // fix opera computedStyle default color unit (convert to rgb) if (Y.UA.opera) { Y_DOM[GET_COMPUTED_STYLE] = function(node, att) { var view = node[OWNER_DOCUMENT][DEFAULT_VIEW], val = view[GET_COMPUTED_STYLE](node, '')[att]; if (re_color.test(att)) { val = Y.Color.toRGB(val); } return val; }; } // safari converts transparent to rgba(), others use "transparent" if (Y.UA.webkit) { Y_DOM[GET_COMPUTED_STYLE] = function(node, att) { var view = node[OWNER_DOCUMENT][DEFAULT_VIEW], val = view[GET_COMPUTED_STYLE](node, '')[att]; if (val === 'rgba(0, 0, 0, 0)') { val = TRANSPARENT; } return val; }; } Y.DOM._getAttrOffset = function(node, attr) { var val = Y.DOM[GET_COMPUTED_STYLE](node, attr), offsetParent = node.offsetParent, position, parentOffset, offset; if (val === 'auto') { position = Y.DOM.getStyle(node, 'position'); if (position === 'static' || position === 'relative') { val = 0; } else if (offsetParent && offsetParent[GET_BOUNDING_CLIENT_RECT]) { parentOffset = offsetParent[GET_BOUNDING_CLIENT_RECT]()[attr]; offset = node[GET_BOUNDING_CLIENT_RECT]()[attr]; if (attr === 'left' || attr === 'top') { val = offset - parentOffset; } else { val = parentOffset - node[GET_BOUNDING_CLIENT_RECT]()[attr]; } } } return val; }; Y.DOM._getOffset = function(node) { var pos, xy = null; if (node) { pos = Y_DOM.getStyle(node, 'position'); xy = [ parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'left'), 10), parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'top'), 10) ]; if ( isNaN(xy[0]) ) { // in case of 'auto' xy[0] = parseInt(Y_DOM.getStyle(node, 'left'), 10); // try inline if ( isNaN(xy[0]) ) { // default to offset value xy[0] = (pos === 'relative') ? 0 : node.offsetLeft || 0; } } if ( isNaN(xy[1]) ) { // in case of 'auto' xy[1] = parseInt(Y_DOM.getStyle(node, 'top'), 10); // try inline if ( isNaN(xy[1]) ) { // default to offset value xy[1] = (pos === 'relative') ? 0 : node.offsetTop || 0; } } } return xy; }; Y_DOM.CUSTOM_STYLES.transform = { set: function(node, val, style) { style[TRANSFORM] = val; }, get: function(node, style) { return Y_DOM[GET_COMPUTED_STYLE](node, TRANSFORM); } }; Y_DOM.CUSTOM_STYLES.transformOrigin = { set: function(node, val, style) { style[TRANSFORMORIGIN] = val; }, get: function(node, style) { return Y_DOM[GET_COMPUTED_STYLE](node, TRANSFORMORIGIN); } }; })(Y); (function(Y) { var PARSE_INT = parseInt, RE = RegExp; Y.Color = { KEYWORDS: { black: '000', silver: 'c0c0c0', gray: '808080', white: 'fff', maroon: '800000', red: 'f00', purple: '800080', fuchsia: 'f0f', green: '008000', lime: '0f0', olive: '808000', yellow: 'ff0', navy: '000080', blue: '00f', teal: '008080', aqua: '0ff' }, re_RGB: /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i, re_hex: /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i, re_hex3: /([0-9A-F])/gi, toRGB: function(val) { if (!Y.Color.re_RGB.test(val)) { val = Y.Color.toHex(val); } if(Y.Color.re_hex.exec(val)) { val = 'rgb(' + [ PARSE_INT(RE.$1, 16), PARSE_INT(RE.$2, 16), PARSE_INT(RE.$3, 16) ].join(', ') + ')'; } return val; }, toHex: function(val) { val = Y.Color.KEYWORDS[val] || val; if (Y.Color.re_RGB.exec(val)) { val = [ Number(RE.$1).toString(16), Number(RE.$2).toString(16), Number(RE.$3).toString(16) ]; for (var i = 0; i < val.length; i++) { if (val[i].length < 2) { val[i] = '0' + val[i]; } } val = val.join(''); } if (val.length < 6) { val = val.replace(Y.Color.re_hex3, '$1$1'); } if (val !== 'transparent' && val.indexOf('#') < 0) { val = '#' + val; } return val.toUpperCase(); } }; })(Y); }, '@VERSION@', {"requires": ["dom-base"]}); YUI.add('dom-style-ie', function (Y, NAME) { (function(Y) { var HAS_LAYOUT = 'hasLayout', PX = 'px', FILTER = 'filter', FILTERS = 'filters', OPACITY = 'opacity', AUTO = 'auto', BORDER_WIDTH = 'borderWidth', BORDER_TOP_WIDTH = 'borderTopWidth', BORDER_RIGHT_WIDTH = 'borderRightWidth', BORDER_BOTTOM_WIDTH = 'borderBottomWidth', BORDER_LEFT_WIDTH = 'borderLeftWidth', WIDTH = 'width', HEIGHT = 'height', TRANSPARENT = 'transparent', VISIBLE = 'visible', GET_COMPUTED_STYLE = 'getComputedStyle', UNDEFINED = undefined, documentElement = Y.config.doc.documentElement, testFeature = Y.Features.test, addFeature = Y.Features.add, // TODO: unit-less lineHeight (e.g. 1.22) re_unit = /^(\d[.\d]*)+(em|ex|px|gd|rem|vw|vh|vm|ch|mm|cm|in|pt|pc|deg|rad|ms|s|hz|khz|%){1}?/i, isIE8 = (Y.UA.ie >= 8), _getStyleObj = function(node) { return node.currentStyle || node.style; }, ComputedStyle = { CUSTOM_STYLES: {}, get: function(el, property) { var value = '', current; if (el) { current = _getStyleObj(el)[property]; if (property === OPACITY && Y.DOM.CUSTOM_STYLES[OPACITY]) { value = Y.DOM.CUSTOM_STYLES[OPACITY].get(el); } else if (!current || (current.indexOf && current.indexOf(PX) > -1)) { // no need to convert value = current; } else if (Y.DOM.IE.COMPUTED[property]) { // use compute function value = Y.DOM.IE.COMPUTED[property](el, property); } else if (re_unit.test(current)) { // convert to pixel value = ComputedStyle.getPixel(el, property) + PX; } else { value = current; } } return value; }, sizeOffsets: { width: ['Left', 'Right'], height: ['Top', 'Bottom'], top: ['Top'], bottom: ['Bottom'] }, getOffset: function(el, prop) { var current = _getStyleObj(el)[prop], // value of "width", "top", etc. capped = prop.charAt(0).toUpperCase() + prop.substr(1), // "Width", "Top", etc. offset = 'offset' + capped, // "offsetWidth", "offsetTop", etc. pixel = 'pixel' + capped, // "pixelWidth", "pixelTop", etc. sizeOffsets = ComputedStyle.sizeOffsets[prop], mode = el.ownerDocument.compatMode, value = ''; // IE pixelWidth incorrect for percent // manually compute by subtracting padding and border from offset size // NOTE: clientWidth/Height (size minus border) is 0 when current === AUTO so offsetHeight is used // reverting to auto from auto causes position stacking issues (old impl) if (current === AUTO || current.indexOf('%') > -1) { value = el['offset' + capped]; if (mode !== 'BackCompat') { if (sizeOffsets[0]) { value -= ComputedStyle.getPixel(el, 'padding' + sizeOffsets[0]); value -= ComputedStyle.getBorderWidth(el, 'border' + sizeOffsets[0] + 'Width', 1); } if (sizeOffsets[1]) { value -= ComputedStyle.getPixel(el, 'padding' + sizeOffsets[1]); value -= ComputedStyle.getBorderWidth(el, 'border' + sizeOffsets[1] + 'Width', 1); } } } else { // use style.pixelWidth, etc. to convert to pixels // need to map style.width to currentStyle (no currentStyle.pixelWidth) if (!el.style[pixel] && !el.style[prop]) { el.style[prop] = current; } value = el.style[pixel]; } return value + PX; }, borderMap: { thin: (isIE8) ? '1px' : '2px', medium: (isIE8) ? '3px': '4px', thick: (isIE8) ? '5px' : '6px' }, getBorderWidth: function(el, property, omitUnit) { var unit = omitUnit ? '' : PX, current = el.currentStyle[property]; if (current.indexOf(PX) < 0) { // look up keywords if a border exists if (ComputedStyle.borderMap[current] && el.currentStyle.borderStyle !== 'none') { current = ComputedStyle.borderMap[current]; } else { // otherwise no border (default is "medium") current = 0; } } return (omitUnit) ? parseFloat(current) : current; }, getPixel: function(node, att) { // use pixelRight to convert to px var val = null, style = _getStyleObj(node), styleRight = style.right, current = style[att]; node.style.right = current; val = node.style.pixelRight; node.style.right = styleRight; // revert return val; }, getMargin: function(node, att) { var val, style = _getStyleObj(node); if (style[att] == AUTO) { val = 0; } else { val = ComputedStyle.getPixel(node, att); } return val + PX; }, getVisibility: function(node, att) { var current; while ( (current = node.currentStyle) && current[att] == 'inherit') { // NOTE: assignment in test node = node.parentNode; } return (current) ? current[att] : VISIBLE; }, getColor: function(node, att) { var current = _getStyleObj(node)[att]; if (!current || current === TRANSPARENT) { Y.DOM.elementByAxis(node, 'parentNode', null, function(parent) { current = _getStyleObj(parent)[att]; if (current && current !== TRANSPARENT) { node = parent; return true; } }); } return Y.Color.toRGB(current); }, getBorderColor: function(node, att) { var current = _getStyleObj(node), val = current[att] || current.color; return Y.Color.toRGB(Y.Color.toHex(val)); } }, //fontSize: getPixelFont, IEComputed = {}; addFeature('style', 'computedStyle', { test: function() { return 'getComputedStyle' in Y.config.win; } }); addFeature('style', 'opacity', { test: function() { return 'opacity' in documentElement.style; } }); addFeature('style', 'filter', { test: function() { return 'filters' in documentElement; } }); // use alpha filter for IE opacity if (!testFeature('style', 'opacity') && testFeature('style', 'filter')) { Y.DOM.CUSTOM_STYLES[OPACITY] = { get: function(node) { var val = 100; try { // will error if no DXImageTransform val = node[FILTERS]['DXImageTransform.Microsoft.Alpha'][OPACITY]; } catch(e) { try { // make sure its in the document val = node[FILTERS]('alpha')[OPACITY]; } catch(err) { Y.log('getStyle: IE opacity filter not found; returning 1', 'warn', 'dom-style'); } } return val / 100; }, set: function(node, val, style) { var current, styleObj = _getStyleObj(node), currentFilter = styleObj[FILTER]; style = style || node.style; if (val === '') { // normalize inline style behavior current = (OPACITY in styleObj) ? styleObj[OPACITY] : 1; // revert to original opacity val = current; } if (typeof currentFilter == 'string') { // in case not appended style[FILTER] = currentFilter.replace(/alpha([^)]*\))/gi, '') + ((val < 1) ? 'alpha(' + OPACITY + '=' + val * 100 + ')' : ''); if (!style[FILTER]) { style.removeAttribute(FILTER); } if (!styleObj[HAS_LAYOUT]) { style.zoom = 1; // needs layout } } } }; } try { Y.config.doc.createElement('div').style.height = '-1px'; } catch(e) { // IE throws error on invalid style set; trap common cases Y.DOM.CUSTOM_STYLES.height = { set: function(node, val, style) { var floatVal = parseFloat(val); if (floatVal >= 0 || val === 'auto' || val === '') { style.height = val; } else { Y.log('invalid style value for height: ' + val, 'warn', 'dom-style'); } } }; Y.DOM.CUSTOM_STYLES.width = { set: function(node, val, style) { var floatVal = parseFloat(val); if (floatVal >= 0 || val === 'auto' || val === '') { style.width = val; } else { Y.log('invalid style value for width: ' + val, 'warn', 'dom-style'); } } }; } if (!testFeature('style', 'computedStyle')) { // TODO: top, right, bottom, left IEComputed[WIDTH] = IEComputed[HEIGHT] = ComputedStyle.getOffset; IEComputed.color = IEComputed.backgroundColor = ComputedStyle.getColor; IEComputed[BORDER_WIDTH] = IEComputed[BORDER_TOP_WIDTH] = IEComputed[BORDER_RIGHT_WIDTH] = IEComputed[BORDER_BOTTOM_WIDTH] = IEComputed[BORDER_LEFT_WIDTH] = ComputedStyle.getBorderWidth; IEComputed.marginTop = IEComputed.marginRight = IEComputed.marginBottom = IEComputed.marginLeft = ComputedStyle.getMargin; IEComputed.visibility = ComputedStyle.getVisibility; IEComputed.borderColor = IEComputed.borderTopColor = IEComputed.borderRightColor = IEComputed.borderBottomColor = IEComputed.borderLeftColor = ComputedStyle.getBorderColor; Y.DOM[GET_COMPUTED_STYLE] = ComputedStyle.get; Y.namespace('DOM.IE'); Y.DOM.IE.COMPUTED = IEComputed; Y.DOM.IE.ComputedStyle = ComputedStyle; } })(Y); }, '@VERSION@', {"requires": ["dom-style"]}); YUI.add('dom-screen', function (Y, NAME) { (function(Y) { /** * Adds position and region management functionality to DOM. * @module dom * @submodule dom-screen * @for DOM */ var DOCUMENT_ELEMENT = 'documentElement', COMPAT_MODE = 'compatMode', POSITION = 'position', FIXED = 'fixed', RELATIVE = 'relative', LEFT = 'left', TOP = 'top', _BACK_COMPAT = 'BackCompat', MEDIUM = 'medium', BORDER_LEFT_WIDTH = 'borderLeftWidth', BORDER_TOP_WIDTH = 'borderTopWidth', GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect', GET_COMPUTED_STYLE = 'getComputedStyle', Y_DOM = Y.DOM, // TODO: how about thead/tbody/tfoot/tr? // TODO: does caption matter? RE_TABLE = /^t(?:able|d|h)$/i, SCROLL_NODE; if (Y.UA.ie) { if (Y.config.doc[COMPAT_MODE] !== 'BackCompat') { SCROLL_NODE = DOCUMENT_ELEMENT; } else { SCROLL_NODE = 'body'; } } Y.mix(Y_DOM, { /** * Returns the inner height of the viewport (exludes scrollbar). * @method winHeight * @return {Number} The current height of the viewport. */ winHeight: function(node) { var h = Y_DOM._getWinSize(node).height; Y.log('winHeight returning ' + h, 'info', 'dom-screen'); return h; }, /** * Returns the inner width of the viewport (exludes scrollbar). * @method winWidth * @return {Number} The current width of the viewport. */ winWidth: function(node) { var w = Y_DOM._getWinSize(node).width; Y.log('winWidth returning ' + w, 'info', 'dom-screen'); return w; }, /** * Document height * @method docHeight * @return {Number} The current height of the document. */ docHeight: function(node) { var h = Y_DOM._getDocSize(node).height; Y.log('docHeight returning ' + h, 'info', 'dom-screen'); return Math.max(h, Y_DOM._getWinSize(node).height); }, /** * Document width * @method docWidth * @return {Number} The current width of the document. */ docWidth: function(node) { var w = Y_DOM._getDocSize(node).width; Y.log('docWidth returning ' + w, 'info', 'dom-screen'); return Math.max(w, Y_DOM._getWinSize(node).width); }, /** * Amount page has been scroll horizontally * @method docScrollX * @return {Number} The current amount the screen is scrolled horizontally. */ docScrollX: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; // perf optimization var dv = doc.defaultView, pageOffset = (dv) ? dv.pageXOffset : 0; return Math.max(doc[DOCUMENT_ELEMENT].scrollLeft, doc.body.scrollLeft, pageOffset); }, /** * Amount page has been scroll vertically * @method docScrollY * @return {Number} The current amount the screen is scrolled vertically. */ docScrollY: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; // perf optimization var dv = doc.defaultView, pageOffset = (dv) ? dv.pageYOffset : 0; return Math.max(doc[DOCUMENT_ELEMENT].scrollTop, doc.body.scrollTop, pageOffset); }, /** * Gets the current position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getXY * @param element The target element * @return {Array} The XY position of the element TODO: test inDocument/display? */ getXY: function() { if (Y.config.doc[DOCUMENT_ELEMENT][GET_BOUNDING_CLIENT_RECT]) { return function(node) { var xy = null, scrollLeft, scrollTop, mode, box, offX, offY, doc, win, inDoc, rootNode; if (node && node.tagName) { doc = node.ownerDocument; mode = doc[COMPAT_MODE]; if (mode !== _BACK_COMPAT) { rootNode = doc[DOCUMENT_ELEMENT]; } else { rootNode = doc.body; } // inline inDoc check for perf if (rootNode.contains) { inDoc = rootNode.contains(node); } else { inDoc = Y.DOM.contains(rootNode, node); } if (inDoc) { win = doc.defaultView; // inline scroll calc for perf if (win && 'pageXOffset' in win) { scrollLeft = win.pageXOffset; scrollTop = win.pageYOffset; } else { scrollLeft = (SCROLL_NODE) ? doc[SCROLL_NODE].scrollLeft : Y_DOM.docScrollX(node, doc); scrollTop = (SCROLL_NODE) ? doc[SCROLL_NODE].scrollTop : Y_DOM.docScrollY(node, doc); } if (Y.UA.ie) { // IE < 8, quirks, or compatMode if (!doc.documentMode || doc.documentMode < 8 || mode === _BACK_COMPAT) { offX = rootNode.clientLeft; offY = rootNode.clientTop; } } box = node[GET_BOUNDING_CLIENT_RECT](); xy = [box.left, box.top]; if (offX || offY) { xy[0] -= offX; xy[1] -= offY; } if ((scrollTop || scrollLeft)) { if (!Y.UA.ios || (Y.UA.ios >= 4.2)) { xy[0] += scrollLeft; xy[1] += scrollTop; } } } else { xy = Y_DOM._getOffset(node); } } return xy; }; } else { return function(node) { // manually calculate by crawling up offsetParents //Calculate the Top and Left border sizes (assumes pixels) var xy = null, doc, parentNode, bCheck, scrollTop, scrollLeft; if (node) { if (Y_DOM.inDoc(node)) { xy = [node.offsetLeft, node.offsetTop]; doc = node.ownerDocument; parentNode = node; // TODO: refactor with !! or just falsey bCheck = ((Y.UA.gecko || Y.UA.webkit > 519) ? true : false); // TODO: worth refactoring for TOP/LEFT only? while ((parentNode = parentNode.offsetParent)) { xy[0] += parentNode.offsetLeft; xy[1] += parentNode.offsetTop; if (bCheck) { xy = Y_DOM._calcBorders(parentNode, xy); } } // account for any scrolled ancestors if (Y_DOM.getStyle(node, POSITION) != FIXED) { parentNode = node; while ((parentNode = parentNode.parentNode)) { scrollTop = parentNode.scrollTop; scrollLeft = parentNode.scrollLeft; //Firefox does something funky with borders when overflow is not visible. if (Y.UA.gecko && (Y_DOM.getStyle(parentNode, 'overflow') !== 'visible')) { xy = Y_DOM._calcBorders(parentNode, xy); } if (scrollTop || scrollLeft) { xy[0] -= scrollLeft; xy[1] -= scrollTop; } } xy[0] += Y_DOM.docScrollX(node, doc); xy[1] += Y_DOM.docScrollY(node, doc); } else { //Fix FIXED position -- add scrollbars xy[0] += Y_DOM.docScrollX(node, doc); xy[1] += Y_DOM.docScrollY(node, doc); } } else { xy = Y_DOM._getOffset(node); } } return xy; }; } }(),// NOTE: Executing for loadtime branching /** Gets the width of vertical scrollbars on overflowed containers in the body content. @method getScrollbarWidth @return {Number} Pixel width of a scrollbar in the current browser **/ getScrollbarWidth: Y.cached(function () { var doc = Y.config.doc, testNode = doc.createElement('div'), body = doc.getElementsByTagName('body')[0], // 0.1 because cached doesn't support falsy refetch values width = 0.1; if (body) { testNode.style.cssText = "position:absolute;visibility:hidden;overflow:scroll;width:20px;"; testNode.appendChild(doc.createElement('p')).style.height = '1px'; body.insertBefore(testNode, body.firstChild); width = testNode.offsetWidth - testNode.clientWidth; body.removeChild(testNode); } return width; }, null, 0.1), /** * Gets the current X position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getX * @param element The target element * @return {Number} The X position of the element */ getX: function(node) { return Y_DOM.getXY(node)[0]; }, /** * Gets the current Y position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getY * @param element The target element * @return {Number} The Y position of the element */ getY: function(node) { return Y_DOM.getXY(node)[1]; }, /** * Set the position of an html element in page coordinates. * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setXY * @param element The target element * @param {Array} xy Contains X & Y values for new position (coordinates are page-based) * @param {Boolean} noRetry By default we try and set the position a second time if the first fails */ setXY: function(node, xy, noRetry) { var setStyle = Y_DOM.setStyle, pos, delta, newXY, currentXY; if (node && xy) { pos = Y_DOM.getStyle(node, POSITION); delta = Y_DOM._getOffset(node); if (pos == 'static') { // default to relative pos = RELATIVE; setStyle(node, POSITION, pos); } currentXY = Y_DOM.getXY(node); if (xy[0] !== null) { setStyle(node, LEFT, xy[0] - currentXY[0] + delta[0] + 'px'); } if (xy[1] !== null) { setStyle(node, TOP, xy[1] - currentXY[1] + delta[1] + 'px'); } if (!noRetry) { newXY = Y_DOM.getXY(node); if (newXY[0] !== xy[0] || newXY[1] !== xy[1]) { Y_DOM.setXY(node, xy, true); } } Y.log('setXY setting position to ' + xy, 'info', 'dom-screen'); } else { Y.log('setXY failed to set ' + node + ' to ' + xy, 'info', 'dom-screen'); } }, /** * Set the X position of an html element in page coordinates, regardless of how the element is positioned. * The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setX * @param element The target element * @param {Number} x The X values for new position (coordinates are page-based) */ setX: function(node, x) { return Y_DOM.setXY(node, [x, null]); }, /** * Set the Y position of an html element in page coordinates, regardless of how the element is positioned. * The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setY * @param element The target element * @param {Number} y The Y values for new position (coordinates are page-based) */ setY: function(node, y) { return Y_DOM.setXY(node, [null, y]); }, /** * @method swapXY * @description Swap the xy position with another node * @param {Node} node The node to swap with * @param {Node} otherNode The other node to swap with * @return {Node} */ swapXY: function(node, otherNode) { var xy = Y_DOM.getXY(node); Y_DOM.setXY(node, Y_DOM.getXY(otherNode)); Y_DOM.setXY(otherNode, xy); }, _calcBorders: function(node, xy2) { var t = parseInt(Y_DOM[GET_COMPUTED_STYLE](node, BORDER_TOP_WIDTH), 10) || 0, l = parseInt(Y_DOM[GET_COMPUTED_STYLE](node, BORDER_LEFT_WIDTH), 10) || 0; if (Y.UA.gecko) { if (RE_TABLE.test(node.tagName)) { t = 0; l = 0; } } xy2[0] += l; xy2[1] += t; return xy2; }, _getWinSize: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; var win = doc.defaultView || doc.parentWindow, mode = doc[COMPAT_MODE], h = win.innerHeight, w = win.innerWidth, root = doc[DOCUMENT_ELEMENT]; if ( mode && !Y.UA.opera ) { // IE, Gecko if (mode != 'CSS1Compat') { // Quirks root = doc.body; } h = root.clientHeight; w = root.clientWidth; } return { height: h, width: w }; }, _getDocSize: function(node) { var doc = (node) ? Y_DOM._getDoc(node) : Y.config.doc, root = doc[DOCUMENT_ELEMENT]; if (doc[COMPAT_MODE] != 'CSS1Compat') { root = doc.body; } return { height: root.scrollHeight, width: root.scrollWidth }; } }); })(Y); (function(Y) { var TOP = 'top', RIGHT = 'right', BOTTOM = 'bottom', LEFT = 'left', getOffsets = function(r1, r2) { var t = Math.max(r1[TOP], r2[TOP]), r = Math.min(r1[RIGHT], r2[RIGHT]), b = Math.min(r1[BOTTOM], r2[BOTTOM]), l = Math.max(r1[LEFT], r2[LEFT]), ret = {}; ret[TOP] = t; ret[RIGHT] = r; ret[BOTTOM] = b; ret[LEFT] = l; return ret; }, DOM = Y.DOM; Y.mix(DOM, { /** * Returns an Object literal containing the following about this element: (top, right, bottom, left) * @for DOM * @method region * @param {HTMLElement} element The DOM element. * @return {Object} Object literal containing the following about this element: (top, right, bottom, left) */ region: function(node) { var xy = DOM.getXY(node), ret = false; if (node && xy) { ret = DOM._getRegion( xy[1], // top xy[0] + node.offsetWidth, // right xy[1] + node.offsetHeight, // bottom xy[0] // left ); } return ret; }, /** * Find the intersect information for the passed nodes. * @method intersect * @for DOM * @param {HTMLElement} element The first element * @param {HTMLElement | Object} element2 The element or region to check the interect with * @param {Object} altRegion An object literal containing the region for the first element if we already have the data (for performance e.g. DragDrop) * @return {Object} Object literal containing the following intersection data: (top, right, bottom, left, area, yoff, xoff, inRegion) */ intersect: function(node, node2, altRegion) { var r = altRegion || DOM.region(node), region = {}, n = node2, off; if (n.tagName) { region = DOM.region(n); } else if (Y.Lang.isObject(node2)) { region = node2; } else { return false; } off = getOffsets(region, r); return { top: off[TOP], right: off[RIGHT], bottom: off[BOTTOM], left: off[LEFT], area: ((off[BOTTOM] - off[TOP]) * (off[RIGHT] - off[LEFT])), yoff: ((off[BOTTOM] - off[TOP])), xoff: (off[RIGHT] - off[LEFT]), inRegion: DOM.inRegion(node, node2, false, altRegion) }; }, /** * Check if any part of this node is in the passed region * @method inRegion * @for DOM * @param {Object} node The node to get the region from * @param {Object} node2 The second node to get the region from or an Object literal of the region * @param {Boolean} all Should all of the node be inside the region * @param {Object} altRegion An object literal containing the region for this node if we already have the data (for performance e.g. DragDrop) * @return {Boolean} True if in region, false if not. */ inRegion: function(node, node2, all, altRegion) { var region = {}, r = altRegion || DOM.region(node), n = node2, off; if (n.tagName) { region = DOM.region(n); } else if (Y.Lang.isObject(node2)) { region = node2; } else { return false; } if (all) { return ( r[LEFT] >= region[LEFT] && r[RIGHT] <= region[RIGHT] && r[TOP] >= region[TOP] && r[BOTTOM] <= region[BOTTOM] ); } else { off = getOffsets(region, r); if (off[BOTTOM] >= off[TOP] && off[RIGHT] >= off[LEFT]) { return true; } else { return false; } } }, /** * Check if any part of this element is in the viewport * @method inViewportRegion * @for DOM * @param {HTMLElement} element The DOM element. * @param {Boolean} all Should all of the node be inside the region * @param {Object} altRegion An object literal containing the region for this node if we already have the data (for performance e.g. DragDrop) * @return {Boolean} True if in region, false if not. */ inViewportRegion: function(node, all, altRegion) { return DOM.inRegion(node, DOM.viewportRegion(node), all, altRegion); }, _getRegion: function(t, r, b, l) { var region = {}; region[TOP] = region[1] = t; region[LEFT] = region[0] = l; region[BOTTOM] = b; region[RIGHT] = r; region.width = region[RIGHT] - region[LEFT]; region.height = region[BOTTOM] - region[TOP]; return region; }, /** * Returns an Object literal containing the following about the visible region of viewport: (top, right, bottom, left) * @method viewportRegion * @for DOM * @return {Object} Object literal containing the following about the visible region of the viewport: (top, right, bottom, left) */ viewportRegion: function(node) { node = node || Y.config.doc.documentElement; var ret = false, scrollX, scrollY; if (node) { scrollX = DOM.docScrollX(node); scrollY = DOM.docScrollY(node); ret = DOM._getRegion(scrollY, // top DOM.winWidth(node) + scrollX, // right scrollY + DOM.winHeight(node), // bottom scrollX); // left } return ret; } }); })(Y); }, '@VERSION@', {"requires": ["dom-base", "dom-style"]}); YUI.add('selector-native', function (Y, NAME) { (function(Y) { /** * The selector-native module provides support for native querySelector * @module dom * @submodule selector-native * @for Selector */ /** * Provides support for using CSS selectors to query the DOM * @class Selector * @static * @for Selector */ Y.namespace('Selector'); // allow native module to standalone var COMPARE_DOCUMENT_POSITION = 'compareDocumentPosition', OWNER_DOCUMENT = 'ownerDocument'; var Selector = { _types: { esc: { token: '\uE000', re: /\\[:\[\]\(\)#\.\'\>+~"]/gi }, attr: { token: '\uE001', re: /(\[[^\]]*\])/g }, pseudo: { token: '\uE002', re: /(\([^\)]*\))/g } }, useNative: true, _escapeId: function(id) { if (id) { id = id.replace(/([:\[\]\(\)#\.'<>+~"])/g,'\\$1'); } return id; }, _compare: ('sourceIndex' in Y.config.doc.documentElement) ? function(nodeA, nodeB) { var a = nodeA.sourceIndex, b = nodeB.sourceIndex; if (a === b) { return 0; } else if (a > b) { return 1; } return -1; } : (Y.config.doc.documentElement[COMPARE_DOCUMENT_POSITION] ? function(nodeA, nodeB) { if (nodeA[COMPARE_DOCUMENT_POSITION](nodeB) & 4) { return -1; } else { return 1; } } : function(nodeA, nodeB) { var rangeA, rangeB, compare; if (nodeA && nodeB) { rangeA = nodeA[OWNER_DOCUMENT].createRange(); rangeA.setStart(nodeA, 0); rangeB = nodeB[OWNER_DOCUMENT].createRange(); rangeB.setStart(nodeB, 0); compare = rangeA.compareBoundaryPoints(1, rangeB); // 1 === Range.START_TO_END } return compare; }), _sort: function(nodes) { if (nodes) { nodes = Y.Array(nodes, 0, true); if (nodes.sort) { nodes.sort(Selector._compare); } } return nodes; }, _deDupe: function(nodes) { var ret = [], i, node; for (i = 0; (node = nodes[i++]);) { if (!node._found) { ret[ret.length] = node; node._found = true; } } for (i = 0; (node = ret[i++]);) { node._found = null; node.removeAttribute('_found'); } return ret; }, /** * Retrieves a set of nodes based on a given CSS selector. * @method query * * @param {string} selector The CSS Selector to test the node against. * @param {HTMLElement} root optional An HTMLElement to start the query from. Defaults to Y.config.doc * @param {Boolean} firstOnly optional Whether or not to return only the first match. * @return {Array} An array of nodes that match the given selector. * @static */ query: function(selector, root, firstOnly, skipNative) { root = root || Y.config.doc; var ret = [], useNative = (Y.Selector.useNative && Y.config.doc.querySelector && !skipNative), queries = [[selector, root]], query, result, i, fn = (useNative) ? Y.Selector._nativeQuery : Y.Selector._bruteQuery; if (selector && fn) { // split group into seperate queries if (!skipNative && // already done if skipping (!useNative || root.tagName)) { // split native when element scoping is needed queries = Selector._splitQueries(selector, root); } for (i = 0; (query = queries[i++]);) { result = fn(query[0], query[1], firstOnly); if (!firstOnly) { // coerce DOM Collection to Array result = Y.Array(result, 0, true); } if (result) { ret = ret.concat(result); } } if (queries.length > 1) { // remove dupes and sort by doc order ret = Selector._sort(Selector._deDupe(ret)); } } Y.log('query: ' + selector + ' returning: ' + ret.length, 'info', 'Selector'); return (firstOnly) ? (ret[0] || null) : ret; }, _replaceSelector: function(selector) { var esc = Y.Selector._parse('esc', selector), // pull escaped colon, brackets, etc. attrs, pseudos; // first replace escaped chars, which could be present in attrs or pseudos selector = Y.Selector._replace('esc', selector); // then replace pseudos before attrs to avoid replacing :not([foo]) pseudos = Y.Selector._parse('pseudo', selector); selector = Selector._replace('pseudo', selector); attrs = Y.Selector._parse('attr', selector); selector = Y.Selector._replace('attr', selector); return { esc: esc, attrs: attrs, pseudos: pseudos, selector: selector }; }, _restoreSelector: function(replaced) { var selector = replaced.selector; selector = Y.Selector._restore('attr', selector, replaced.attrs); selector = Y.Selector._restore('pseudo', selector, replaced.pseudos); selector = Y.Selector._restore('esc', selector, replaced.esc); return selector; }, _replaceCommas: function(selector) { var replaced = Y.Selector._replaceSelector(selector), selector = replaced.selector; if (selector) { selector = selector.replace(/,/g, '\uE007'); replaced.selector = selector; selector = Y.Selector._restoreSelector(replaced); } return selector; }, // allows element scoped queries to begin with combinator // e.g. query('> p', document.body) === query('body > p') _splitQueries: function(selector, node) { if (selector.indexOf(',') > -1) { selector = Y.Selector._replaceCommas(selector); } var groups = selector.split('\uE007'), // split on replaced comma token queries = [], prefix = '', id, i, len; if (node) { // enforce for element scoping if (node.nodeType === 1) { // Elements only id = Y.Selector._escapeId(Y.DOM.getId(node)); if (!id) { id = Y.guid(); Y.DOM.setId(node, id); } prefix = '[id="' + id + '"] '; } for (i = 0, len = groups.length; i < len; ++i) { selector = prefix + groups[i]; queries.push([selector, node]); } } return queries; }, _nativeQuery: function(selector, root, one) { if (Y.UA.webkit && selector.indexOf(':checked') > -1 && (Y.Selector.pseudos && Y.Selector.pseudos.checked)) { // webkit (chrome, safari) fails to pick up "selected" with "checked" return Y.Selector.query(selector, root, one, true); // redo with skipNative true to try brute query } try { //Y.log('trying native query with: ' + selector, 'info', 'selector-native'); return root['querySelector' + (one ? '' : 'All')](selector); } catch(e) { // fallback to brute if available //Y.log('native query error; reverting to brute query with: ' + selector, 'info', 'selector-native'); return Y.Selector.query(selector, root, one, true); // redo with skipNative true } }, filter: function(nodes, selector) { var ret = [], i, node; if (nodes && selector) { for (i = 0; (node = nodes[i++]);) { if (Y.Selector.test(node, selector)) { ret[ret.length] = node; } } } else { Y.log('invalid filter input (nodes: ' + nodes + ', selector: ' + selector + ')', 'warn', 'Selector'); } return ret; }, test: function(node, selector, root) { var ret = false, useFrag = false, groups, parent, item, items, frag, id, i, j, group; if (node && node.tagName) { // only test HTMLElements if (typeof selector == 'function') { // test with function ret = selector.call(node, node); } else { // test with query // we need a root if off-doc groups = selector.split(','); if (!root && !Y.DOM.inDoc(node)) { parent = node.parentNode; if (parent) { root = parent; } else { // only use frag when no parent to query frag = node[OWNER_DOCUMENT].createDocumentFragment(); frag.appendChild(node); root = frag; useFrag = true; } } root = root || node[OWNER_DOCUMENT]; id = Y.Selector._escapeId(Y.DOM.getId(node)); if (!id) { id = Y.guid(); Y.DOM.setId(node, id); } for (i = 0; (group = groups[i++]);) { // TODO: off-dom test group += '[id="' + id + '"]'; items = Y.Selector.query(group, root); for (j = 0; item = items[j++];) { if (item === node) { ret = true; break; } } if (ret) { break; } } if (useFrag) { // cleanup frag.removeChild(node); } }; } return ret; }, /** * A convenience function to emulate Y.Node's aNode.ancestor(selector). * @param {HTMLElement} element An HTMLElement to start the query from. * @param {String} selector The CSS selector to test the node against. * @return {HTMLElement} The ancestor node matching the selector, or null. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @static * @method ancestor */ ancestor: function (element, selector, testSelf) { return Y.DOM.ancestor(element, function(n) { return Y.Selector.test(n, selector); }, testSelf); }, _parse: function(name, selector) { return selector.match(Y.Selector._types[name].re); }, _replace: function(name, selector) { var o = Y.Selector._types[name]; return selector.replace(o.re, o.token); }, _restore: function(name, selector, items) { if (items) { var token = Y.Selector._types[name].token, i, len; for (i = 0, len = items.length; i < len; ++i) { selector = selector.replace(token, items[i]); } } return selector; } }; Y.mix(Y.Selector, Selector, true); })(Y); }, '@VERSION@', {"requires": ["dom-base"]}); YUI.add('selector', function (Y, NAME) { }, '@VERSION@', {"requires": ["selector-native"]}); YUI.add('event-custom-base', function (Y, NAME) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ var DO_BEFORE = 0, DO_AFTER = 1, DO = { /** * Cache of objects touched by the utility * @property objs * @static * @deprecated Since 3.6.0. The `_yuiaop` property on the AOP'd object * replaces the role of this property, but is considered to be private, and * is only mentioned to provide a migration path. * * If you have a use case which warrants migration to the _yuiaop property, * please file a ticket to let us know what it's used for and we can see if * we need to expose hooks for that functionality more formally. */ objs: null, /** * <p>Execute the supplied method before the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt> * <dd>Replace the arguments that the original function will be * called with.</dd> * <dt></code>Y.Do.Prevent(message)</code></dt> * <dd>Don't execute the wrapped function. Other before phase * wrappers will be executed.</dd> * </dl> * * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {string} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { // Y.log('Do before: ' + sFn, 'info', 'event'); var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_BEFORE, f, obj, sFn); }, /** * <p>Execute the supplied method after the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt> * <dd>Return <code>returnValue</code> instead of the wrapped * method's original return value. This can be further altered by * other after phase wrappers.</dd> * </dl> * * <p>The static properties <code>Y.Do.originalRetVal</code> and * <code>Y.Do.currentRetVal</code> will be populated for reference.</p> * * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return {string} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_AFTER, f, obj, sFn); }, /** * Execute the supplied method before or after the specified function. * Used by <code>before</code> and <code>after</code>. * * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (!obj._yuiaop) { // create a map entry for the obj if it doesn't exist, to hold overridden methods obj._yuiaop = {}; } o = obj._yuiaop; if (!o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription. * * @method detach * @param handle {string} the subscription handle * @static */ detach: function(handle) { if (handle.detach) { handle.detach(); } }, _unload: function(e, me) { } }; Y.Do = DO; ////////////////////////////////////////////////////////////////////////// /** * Contains the return value from the wrapped method, accessible * by 'after' event listeners. * * @property originalRetVal * @static * @since 3.2.0 */ /** * Contains the current state of the return value, consumable by * 'after' event listeners, and updated if an after subscriber * changes the return value generated by the wrapped function. * * @property currentRetVal * @static * @since 3.2.0 */ ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ DO.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype._delete = function (sid) { // Y.log('Y.Do._delete: ' + sid, 'info', 'Event'); delete this.before[sid]; delete this.after[sid]; }; /** * <p>Execute the wrapped method. All arguments are passed into the wrapping * functions. If any of the before wrappers return an instance of * <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped * function nor any after phase subscribers will be executed.</p> * * <p>The return value will be the return value of the wrapped function or one * provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or * <code>Y.Do.AlterReturn</code>. * * @method exec * @param arg* {any} Arguments are passed to the wrapping and wrapped functions * @return {any} Return value of wrapped function unless overwritten (see above) */ DO.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case DO.Halt: return ret.retVal; case DO.AlterArgs: args = ret.newArgs; break; case DO.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } DO.originalRetVal = ret; DO.currentRetVal = ret; // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor == DO.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor == DO.AlterReturn) { ret = newRet.newRetVal; // Update the static retval state DO.currentRetVal = ret; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. Useful for Do.before subscribers. An * example would be a service that scrubs out illegal characters prior to * executing the core business logic. * @class Do.AlterArgs * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newArgs {Array} Call parameters to be used for the original method * instead of the arguments originally passed in. */ DO.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller. Useful for Do.after subscribers. * @class Do.AlterReturn * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newRetVal {any} Return value passed to code that invoked the wrapped * function. */ DO.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. Useful for Do.before subscribers. * @class Do.Halt * @constructor * @param msg {String} (optional) Explanation of why the termination was done * @param retVal {any} Return value passed to code that invoked the wrapped * function. */ DO.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute. Useful * for Do.before subscribers. * @class Do.Prevent * @constructor * @param msg {String} (optional) Explanation of why the termination was done */ DO.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param retVal {any} Return value passed to code that invoked the wrapped * function. * @deprecated use Y.Do.Halt or Y.Do.Prevent */ DO.Error = DO.Halt; ////////////////////////////////////////////////////////////////////////// // Y["Event"] && Y.Event.addListener(window, "unload", Y.Do._unload, Y.Do); /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ // var onsubscribeType = "_event:onsub", var YArray = Y.Array, AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], CONFIGS_HASH = YArray.hash(CONFIGS), nativeSlice = Array.prototype.slice, YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log', mixConfigs = function(r, s, ov) { var p; for (p in s) { if (CONFIGS_HASH[p] && (ov || !(p in r))) { r[p] = s[p]; } } return r; }; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires. * @param {object} o configuration object. * @class CustomEvent * @constructor */ Y.CustomEvent = function(type, o) { this._kds = Y.CustomEvent.keepDeprecatedSubs; o = o || {}; this.id = Y.stamp(this); /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ this.type = type; /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ this.context = Y; /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ // this.monitored = false; this.logSystem = (type == YUI_LOG); /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ // this.broadcast = 0; /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ this.silent = this.logSystem; /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ // this.queuable = false; /** * The subscribers to this event * @property subscribers * @type Subscriber {} * @deprecated */ if (this._kds) { this.subscribers = {}; } /** * The subscribers to this event * @property _subscribers * @type Subscriber [] * @private */ this._subscribers = []; /** * 'After' subscribers * @property afters * @type Subscriber {} */ if (this._kds) { this.afters = {}; } /** * 'After' subscribers * @property _afters * @type Subscriber [] * @private */ this._afters = []; /** * This event has fired if true * * @property fired * @type boolean * @default false; */ // this.fired = false; /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ // this.firedWith; /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ // this.fireOnce = false; /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default false */ //this.async = false; /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ // this.stopped = 0; /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ // this.prevented = 0; /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ // this.host = null; /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ // this.defaultFn = null; /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ // this.stoppedFn = null; /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ // this.preventedFn = null; /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ this.preventable = true; /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * * Events can only bubble if emitFacade is true. * * @property bubbles * @type boolean * @default true */ this.bubbles = true; /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ this.signature = YUI3_SIGNATURE; // this.subCount = 0; // this.afterCount = 0; // this.hasSubscribers = false; // this.hasAfters = false; /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ // this.emitFacade = false; this.applyConfig(o, true); // this.log("Creating " + this.type); }; /** * Static flag to enable population of the <a href="#property_subscribers">`subscribers`</a> * and <a href="#property_subscribers">`afters`</a> properties held on a `CustomEvent` instance. * * These properties were changed to private properties (`_subscribers` and `_afters`), and * converted from objects to arrays for performance reasons. * * Setting this property to true will populate the deprecated `subscribers` and `afters` * properties for people who may be using them (which is expected to be rare). There will * be a performance hit, compared to the new array based implementation. * * If you are using these deprecated properties for a use case which the public API * does not support, please file an enhancement request, and we can provide an alternate * public implementation which doesn't have the performance cost required to maintiain the * properties as objects. * * @property keepDeprecatedSubs * @static * @for CustomEvent * @type boolean * @default false * @deprecated */ Y.CustomEvent.keepDeprecatedSubs = false; Y.CustomEvent.mixConfigs = mixConfigs; Y.CustomEvent.prototype = { constructor: Y.CustomEvent, /** * Returns the number of subscribers for this event as the sum of the on() * subscribers and after() subscribers. * * @method hasSubs * @return Number */ hasSubs: function(when) { var s = this._subscribers.length, a = this._afters.length, sib = this.sibling; if (sib) { s += sib._subscribers.length; a += sib._afters.length; } if (when) { return (when == 'after') ? a : s; } return (s + a); }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('detach', 'attach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { this.monitored = true; var type = this.id + '|' + this.type + '_' + what, args = nativeSlice.call(arguments, 0); args[0] = type; return this.host.on.apply(this.host, args); }, /** * Get all of the subscribers to this event and any sibling event * @method getSubs * @return {Array} first item is the on subscribers, second the after. */ getSubs: function() { var s = this._subscribers, a = this._afters, sib = this.sibling; s = (sib) ? s.concat(sib._subscribers) : s.concat(); a = (sib) ? a.concat(sib._afters) : a.concat(); return [s, a]; }, /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply. * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { mixConfigs(this, o, force); }, /** * Create the Subscription for subscribing function, context, and bound * arguments. If this is a fireOnce event, the subscriber is immediately * notified. * * @method _on * @param fn {Function} Subscription callback * @param [context] {Object} Override `this` in the callback * @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire() * @param [when] {String} "after" to slot into after subscribers * @return {EventHandle} * @protected */ _on: function(fn, context, args, when) { if (!fn) { this.log('Invalid callback for CE: ' + this.type); } var s = new Y.Subscriber(fn, context, args, when); if (this.fireOnce && this.fired) { if (this.async) { setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0); } else { this._notify(s, this.firedWith); } } if (when == AFTER) { this._afters.push(s); } else { this._subscribers.push(s); } if (this._kds) { if (when == AFTER) { this.afters[s.id] = s; } else { this.subscribers[s.id] = s; } } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute. * @return {EventHandle} Unsubscribe handle. * @deprecated use on. */ subscribe: function(fn, context) { Y.log('ce.subscribe deprecated, use "on"', 'warn', 'deprecated'); var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} An object with a detach method to detch the handler(s). */ on: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; if (this.monitored && this.host) { this.host._monitor('attach', this, { args: arguments }); } return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle Unsubscribe handle. */ after: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int} returns the number of subscribers unsubscribed. */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var i, s, found = 0, subs = this._subscribers, afters = this._afters; for (i = subs.length; i >= 0; i--) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, subs, i); found++; } } for (i = afters.length; i >= 0; i--) { s = afters[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, afters, i); found++; } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int|undefined} returns the number of subscribers unsubscribed. * @deprecated use detach. */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param {Subscriber} s the subscriber. * @param {Array} args the arguments array to apply to the listener. * @protected */ _notify: function(s, args, ef) { this.log(this.type + '->' + 'sub: ' + s.id); var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { this.log(this.type + ' cancelled by subscriber'); return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param {string} msg message to log. * @param {string} cat log category. */ log: function(msg, cat) { if (!this.silent) { Y.log(this.id + ': ' + msg, cat || 'info', 'event'); } }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise. * */ fire: function() { if (this.fireOnce && this.fired) { this.log('fireOnce event: ' + this.type + ' already fired'); return true; } else { var args = nativeSlice.call(arguments, 0); // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); this.fired = true; if (this.fireOnce) { this.firedWith = args; } if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, /** * Set up for notifying subscribers of non-emitFacade events. * * @method fireSimple * @param args {Array} Arguments passed to fire() * @return Boolean false if a subscriber returned false * @protected */ fireSimple: function(args) { this.stopped = 0; this.prevented = 0; if (this.hasSubs()) { var subs = this.getSubs(); this._procSubs(subs[0], args); this._procSubs(subs[1], args); } this._broadcast(args); return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { this.log('Missing event-custom-complex needed to emit a facade for: ' + this.type); args[0] = args[0] || {}; return this.fireSimple(args); }, /** * Notifies a list of subscribers. * * @method _procSubs * @param subs {Array} List of subscribers * @param args {Array} Arguments passed to fire() * @param ef {} * @return Boolean false if a subscriber returns false or stops the event * propagation via e.stopPropagation(), * e.stopImmediatePropagation(), or e.halt() * @private */ _procSubs: function(subs, args, ef) { var s, i, l; for (i = 0, l = subs.length; i < l; i++) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped == 2) { return false; } } } return true; }, /** * Notifies the YUI instance if the event is configured with broadcast = 1, * and both the YUI instance and Y.Global if configured with broadcast = 2. * * @method _broadcast * @param args {Array} Arguments sent to fire() * @private */ _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = args.concat(); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast == 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed. * @deprecated use detachAll. */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {int} The number of listeners unsubscribed. */ detachAll: function() { return this.detach(); }, /** * Deletes the subscriber from the internal store of on() and after() * subscribers. * * @method _delete * @param s subscriber object. * @param subs (optional) on or after subscriber array * @param index (optional) The index found. * @private */ _delete: function(s, subs, i) { var when = s._when; if (!subs) { subs = (when === AFTER) ? this._afters : this._subscribers; i = YArray.indexOf(subs, s, 0); } if (s && subs[i] === s) { subs.splice(i, 1); } if (this._kds) { if (when === AFTER) { delete this.afters[s.id]; } else { delete this.subscribers[s.id]; } } if (this.monitored && this.host) { this.host._monitor('detach', this, { ce: this, sub: s }); } if (s) { s.deleted = true; } } }; /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute. * @param {Object} context The value of the keyword 'this' in the listener. * @param {Array} args* 0..n additional arguments to supply the listener. * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args, when) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.stamp(this); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; this._when = when; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ // this.events = null; /** * This listener only reacts to the event once * @property once */ // this.once = false; }; Y.Subscriber.prototype = { constructor: Y.Subscriber, _notify: function(c, args, ce) { if (this.deleted && !this.postponed) { if (this.postponed) { delete this.fn; delete this.context; } else { delete this.postponed; return null; } } var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } if (this.once) { ce._delete(this); } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber. * @param ce {CustomEvent} The custom event that sent the notification. */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config && Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch (e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute. * @param {Object} context optional 'this' keyword for the listener. * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn == fn) && this.context == context); } else { return (this.fn == fn); } }, valueOf : function() { return this.id; } }; /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param {CustomEvent} evt the custom event. * @param {Subscriber} sub the subscriber. */ Y.EventHandle = function(evt, sub) { /** * The custom event * * @property evt * @type CustomEvent */ this.evt = evt; /** * The subscriber object * * @property sub * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { batch: function(f, c) { f.call(c || this, this); if (Y.Lang.isArray(this.evt)) { Y.Array.each(this.evt, function(h) { h.batch.call(c || h, f); }); } }, /** * Detaches this subscriber * @method detach * @return {int} the number of detached listeners */ detach: function() { var evt = this.evt, detached = 0, i; if (evt) { // Y.log('EventHandle.detach: ' + this.sub, 'info', 'Event'); if (Y.Lang.isArray(evt)) { for (i = 0; i < evt.length; i++) { detached += evt[i].detach(); } } else { evt._delete(this.sub); detached = 1; } } return detached; }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('attach', 'detach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { return this.evt.monitor.apply(this.evt, arguments); } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {String} the prefix to apply to non-prefixed event names */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', WILD_TYPE_RE = /(.*?)(:)(.*?)/, _wildType = Y.cached(function(type) { return type.replace(WILD_TYPE_RE, "*$2$3"); }), /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = Y.cached(function(type, pre) { if (!pre || (typeof type !== "string") || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }), /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory| menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); // Y.log(t); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t == '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { // Y.log('EventTarget constructor executed: ' + this._yuid); var o = (L.isObject(opts)) ? opts : {}; this._yuievt = this._yuievt || { id: Y.guid(), events: {}, targets: {}, config: o, chain: ('chain' in o) ? o.chain : Y.config.chain, bubbling: false, defaults: { context: o.context || this, host: this, emitFacade: o.emitFacade, fireOnce: o.fireOnce, queuable: o.queuable, monitored: o.monitored, broadcast: o.broadcast, defaultTargetOnly: o.defaultTargetOnly, bubbles: ('bubbles' in o) ? o.bubbles : true } }; }; ET.prototype = { constructor: ET, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>on</code> except the * listener is immediatelly detached when it is executed. * @method once * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ once: function() { var handle = this.on.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>after</code> except the * listener is immediatelly detached when it is executed. * @method onceAfter * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ onceAfter: function() { var handle = this.after.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Takes the type parameter passed to 'on' and parses out the * various pieces that could be included in the type. If the * event type is passed without a prefix, it will be expanded * to include the prefix one is supplied or the event target * is configured with a default prefix. * @method parseType * @param {String} type the type * @param {String} [pre=this._yuievt.config.prefix] the prefix * @since 3.3.0 * @return {Array} an array containing: * * the detach category, if supplied, * * the prefixed event type, * * whether or not this is an after listener, * * the supplied event type */ parseType: function(type, pre) { return _parseType(type, pre || this._yuievt.config.prefix); }, /** * Subscribe a callback function to a custom event fired by this object or * from an object that bubbles its events to this object. * * Callback functions for events published with `emitFacade = true` will * receive an `EventFacade` as the first argument (typically named "e"). * These callbacks can then call `e.preventDefault()` to disable the * behavior published to that event's `defaultFn`. See the `EventFacade` * API for all available properties and methods. Subscribers to * non-`emitFacade` events will receive the arguments passed to `fire()` * after the event name. * * To subscribe to multiple events at once, pass an object as the first * argument, where the key:value pairs correspond to the eventName:callback, * or pass an array of event names as the first argument to subscribe to * all listed events with the same callback. * * Returning `false` from a callback is supported as an alternative to * calling `e.preventDefault(); e.stopPropagation();`. However, it is * recommended to use the event methods whenever possible. * * @method on * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ on: function(type, fn, context) { var yuievt = this._yuievt, parts = _parseType(type, yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent, isArr; // full name, args, detachcategory, after this._monitor('attach', parts[1], { args: arguments, category: parts[0], after: parts[2] }); if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = nativeSlice.call(arguments, 0); ret = []; if (L.isArray(type)) { isArr = true; } after = type._after; delete type._after; Y.each(type, function(v, k) { if (L.isObject(v)) { f = v.fn || ((L.isFunction(v)) ? v : f); c = v.context || c; } var nv = (after) ? AFTER_PREFIX : ''; args[0] = nv + ((isArr) ? v : k); args[1] = f; args[2] = c; ret.push(this.on.apply(this, args)); }, this); return (yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) { args = nativeSlice.call(arguments, 0); args.splice(2, 0, Node.getDOMNode(this)); // Y.log("Node detected, redirecting with these args: " + args); return Y.on.apply(Y, args); } type = parts[1]; if (Y.instanceOf(this, YUI)) { adapt = Y.Env.evt.plugins[type]; args = nativeSlice.call(arguments, 0); args[0] = shorttype; if (Node) { n = args[2]; if (Y.instanceOf(n, Y.NodeList)) { n = Y.NodeList.getDOMNodes(n); } else if (Y.instanceOf(n, Node)) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { Y.log('Using adaptor for ' + shorttype + ', ' + n, 'info', 'event'); handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? nativeSlice.call(arguments, 3) : null, (after) ? 'after' : true); } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { Y.log('EventTarget subscribe() is deprecated, use on()', 'warn', 'deprecated'); return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node)); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return this; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, adapt, store = Y.Env.evt.handles, detachhost, cat, args, ce, keyDetacher = function(lcat, ltype, host) { var handles = lcat[ltype], ce, i; if (handles) { for (i = handles.length - 1; i >= 0; --i) { ce = handles[i].evt; if (ce.host === host || ce.el === host) { handles[i].detach(); } } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; detachhost = (isNode) ? Y.Node.getDOMNode(this) : this; if (cat) { if (type) { keyDetacher(cat, type, detachhost); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i, detachhost); } } } return this; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { type.detach(); return this; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = nativeSlice.call(arguments, 0); args[2] = Node.getDOMNode(this); Y.detach.apply(Y, args); return this; } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (Y.instanceOf(this, YUI)) { args = nativeSlice.call(arguments, 0); // use the adaptor specific detach code if if (adapt && adapt.detach) { adapt.detach.apply(Y, args); return this; // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; Y.Event.detach.apply(Y.Event, args); return this; } } // ce = evts[type]; ce = evts[parts[1]]; if (ce) { ce.detach(fn, context); } return this; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { Y.log('EventTarget unsubscribe() is deprecated, use detach()', 'warn', 'deprecated'); return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {String} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {String} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { Y.log('EventTarget unsubscribeAll() is deprecated, use detachAll()', 'warn', 'deprecated'); return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {String} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * Events can only bubble if emitFacade is true. * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'async': fireOnce event listeners will fire synchronously if the event has already * fired unless async is true. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * * <li> * 'monitored': specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {CustomEvent} the custom event * */ publish: function(type, opts) { var events, ce, ret, defaults, edata = this._yuievt, pre = edata.config.prefix; if (L.isObject(type)) { ret = {}; Y.each(type, function(v, k) { ret[k] = this.publish(k, v || opts); }, this); return ret; } type = (pre) ? _getType(type, pre) : type; events = edata.events; ce = events[type]; this._monitor('publish', type, { args: arguments }); if (ce) { // ce.log("publish applying new config to published event: '"+type+"' exists", 'info', 'event'); if (opts) { ce.applyConfig(opts, true); } } else { // TODO: Lazy publish goes here. defaults = edata.defaults; // apply defaults ce = new Y.CustomEvent(type, defaults); if (opts) { ce.applyConfig(opts, true); } events[type] = ce; } // make sure we turn the broadcast flag off if this // event was published as a result of bubbling // if (opts instanceof Y.CustomEvent) { // events[type].broadcast = false; // } return events[type]; }, /** * This is the entry point for the event monitoring system. * You can monitor 'attach', 'detach', 'fire', and 'publish'. * When configured, these events generate an event. click -> * click_attach, click_detach, click_publish -- these can * be subscribed to like other events to monitor the event * system. Inividual published events can have monitoring * turned on or off (publish can't be turned off before it * it published) by setting the events 'monitor' config. * * @method _monitor * @param what {String} 'attach', 'detach', 'fire', or 'publish' * @param eventType {String|CustomEvent} The prefixed name of the event being monitored, or the CustomEvent object. * @param o {Object} Information about the event interaction, such as * fire() args, subscription category, publish config * @private */ _monitor: function(what, eventType, o) { var monitorevt, ce, type; if (eventType) { if (typeof eventType === "string") { type = eventType; ce = this.getEvent(eventType, true); } else { ce = eventType; type = eventType.type; } if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { monitorevt = type + '_' + what; o.monitored = what; this.fire.call(this, monitorevt, o); } } }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {EventTarget} the event host */ fire: function(type) { var typeIncluded = L.isString(type), t = (typeIncluded) ? type : (type && type.type), yuievt = this._yuievt, pre = yuievt.config.prefix, ce, ret, ce2, args = (typeIncluded) ? nativeSlice.call(arguments, 1) : arguments; t = (pre) ? _getType(t, pre) : t; ce = this.getEvent(t, true); ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } this._monitor('fire', (ce || t), { args: args }); // this event has not been published or subscribed to if (!ce) { if (yuievt.hasTargets) { return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done ret = true; } else { ce.sibling = ce2; ret = ce.fire.apply(ce, args); } return (yuievt.chain) ? this : ret; }, getSibling: function(type, ce) { var ce2; // delegate to *:type events if there are subscribers if (type.indexOf(PREFIX_DELIMITER) > -1) { type = _wildType(type); // console.log(type); ce2 = this.getEvent(type, true); if (ce2) { // console.log("GOT ONE: " + type); ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; // ret = ce2.fire.apply(ce2, a); } } return ce2; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {String} the type, or name of the event * @param prefixed {String} if true, the type is prefixed already * @return {CustomEvent} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return e[type] || null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * * @method after * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ after: function(type, fn) { var a = nativeSlice.call(arguments, 0); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'array': // YArray.each(a[0], function(v) { // v = AFTER_PREFIX + v; // }); // break; case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype); ET.call(Y, { bubbles: false }); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? /** `Y.on()` can do many things: <ul> <li>Subscribe to custom events `publish`ed and `fire`d from Y</li> <li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and `fire`d from any object in the YUI instance sandbox</li> <li>Subscribe to DOM events</li> <li>Subscribe to the execution of a method on any object, effectively treating that method as an event</li> </ul> For custom event subscriptions, pass the custom event name as the first argument and callback as the second. The `this` object in the callback will be `Y` unless an override is passed as the third argument. Y.on('io:complete', function () { Y.MyApp.updateStatus('Transaction complete'); }); To subscribe to DOM events, pass the name of a DOM event as the first argument and a CSS selector string as the third argument after the callback function. Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`, array, or simply omitted (the default is the `window` object). Y.on('click', function (e) { e.preventDefault(); // proceed with ajax form submission var url = this.get('action'); ... }, '#my-form'); The `this` object in DOM event callbacks will be the `Node` targeted by the CSS selector or other identifier. `on()` subscribers for DOM events or custom events `publish`ed with a `defaultFn` can prevent the default behavior with `e.preventDefault()` from the event object passed as the first parameter to the subscription callback. To subscribe to the execution of an object method, pass arguments corresponding to the call signature for <a href="../classes/Do.html#methods_before">`Y.Do.before(...)`</a>. NOTE: The formal parameter list below is for events, not for function injection. See `Y.Do.before` for that signature. @method on @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @see Do.before @for YUI **/ /** Listen for an event one time. Equivalent to `on()`, except that the listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see on @method once @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Listen for an event one time. Equivalent to `once()`, except, like `after()`, the subscription callback executes after all `on()` subscribers and the event's `defaultFn` (if configured) have executed. Like `after()` if any `on()` phase subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()` subscribers will execute. The listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see once @method onceAfter @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Like `on()`, this method creates a subscription to a custom event or to the execution of a method on an object. For events, `after()` subscribers are executed after the event's `defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber. See the <a href="#methods_on">`on()` method</a> for additional subscription options. NOTE: The subscription signature shown is for events, not for function injection. See <a href="../classes/Do.html#methods_after">`Y.Do.after`</a> for that signature. @see on @see Do.after @method after @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [args*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ }, '@VERSION@', {"requires": ["oop"]}); YUI.add('event-custom-complex', function (Y, NAME) { /** * Adds event facades, preventable default behavior, and bubbling. * events. * @module event-custom * @submodule event-custom-complex */ var FACADE, FACADE_KEYS, key, EMPTY = {}, CEProto = Y.CustomEvent.prototype, ETProto = Y.EventTarget.prototype, mixFacadeProps = function(facade, payload) { var p; for (p in payload) { if (!(FACADE_KEYS.hasOwnProperty(p))) { facade[p] = payload[p]; } } }; /** * Wraps and protects a custom event for use when emitFacade is set to true. * Requires the event-custom-complex module * @class EventFacade * @param e {Event} the custom event * @param currentTarget {HTMLElement} the element the listener was attached to */ Y.EventFacade = function(e, currentTarget) { e = e || EMPTY; this._event = e; /** * The arguments passed to fire * @property details * @type Array */ this.details = e.details; /** * The event type, this can be overridden by the fire() payload * @property type * @type string */ this.type = e.type; /** * The real event type * @property _type * @type string * @private */ this._type = e.type; ////////////////////////////////////////////////////// /** * Node reference for the targeted eventtarget * @property target * @type Node */ this.target = e.target; /** * Node reference for the element that the listener was attached to. * @property currentTarget * @type Node */ this.currentTarget = currentTarget; /** * Node reference to the relatedTarget * @property relatedTarget * @type Node */ this.relatedTarget = e.relatedTarget; }; Y.mix(Y.EventFacade.prototype, { /** * Stops the propagation to the next bubble target * @method stopPropagation */ stopPropagation: function() { this._event.stopPropagation(); this.stopped = 1; }, /** * Stops the propagation to the next bubble target and * prevents any additional listeners from being exectued * on the current target. * @method stopImmediatePropagation */ stopImmediatePropagation: function() { this._event.stopImmediatePropagation(); this.stopped = 2; }, /** * Prevents the event's default behavior * @method preventDefault */ preventDefault: function() { this._event.preventDefault(); this.prevented = 1; }, /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ halt: function(immediate) { this._event.halt(immediate); this.prevented = 1; this.stopped = (immediate) ? 2 : 1; } }); CEProto.fireComplex = function(args) { var es, ef, q, queue, ce, ret, events, subs, postponed, self = this, host = self.host || self, next, oldbubble; if (self.stack) { // queue this event if the current item in the queue bubbles if (self.queuable && self.type != self.stack.next.type) { self.log('queue ' + self.type); self.stack.queue.push([self, args]); return true; } } es = self.stack || { // id of the first event in the stack id: self.id, next: self, silent: self.silent, stopped: 0, prevented: 0, bubbling: null, type: self.type, // defaultFnQueue: new Y.Queue(), afterQueue: new Y.Queue(), defaultTargetOnly: self.defaultTargetOnly, queue: [] }; subs = self.getSubs(); self.stopped = (self.type !== es.type) ? 0 : es.stopped; self.prevented = (self.type !== es.type) ? 0 : es.prevented; self.target = self.target || host; if (self.stoppedFn) { events = new Y.EventTarget({ fireOnce: true, context: host }); self.events = events; events.on('stopped', self.stoppedFn); } self.currentTarget = host; self.details = args.slice(); // original arguments in the details // self.log("Firing " + self + ", " + "args: " + args); self.log("Firing " + self.type); self._facade = null; // kill facade to eliminate stale properties ef = self._getFacade(args); if (Y.Lang.isObject(args[0])) { args[0] = ef; } else { args.unshift(ef); } if (subs[0]) { self._procSubs(subs[0], args, ef); } // bubble if this is hosted in an event target and propagation has not been stopped if (self.bubbles && host.bubble && !self.stopped) { oldbubble = es.bubbling; es.bubbling = self.type; if (es.type != self.type) { es.stopped = 0; es.prevented = 0; } ret = host.bubble(self, args, null, es); self.stopped = Math.max(self.stopped, es.stopped); self.prevented = Math.max(self.prevented, es.prevented); es.bubbling = oldbubble; } if (self.prevented) { if (self.preventedFn) { self.preventedFn.apply(host, args); } } else if (self.defaultFn && ((!self.defaultTargetOnly && !es.defaultTargetOnly) || host === ef.target)) { self.defaultFn.apply(host, args); } // broadcast listeners are fired as discreet events on the // YUI instance and potentially the YUI global. self._broadcast(args); // Queue the after if (subs[1] && !self.prevented && self.stopped < 2) { if (es.id === self.id || self.type != host._yuievt.bubbling) { self._procSubs(subs[1], args, ef); while ((next = es.afterQueue.last())) { next(); } } else { postponed = subs[1]; if (es.execDefaultCnt) { postponed = Y.merge(postponed); Y.each(postponed, function(s) { s.postponed = true; }); } es.afterQueue.add(function() { self._procSubs(postponed, args, ef); }); } } self.target = null; if (es.id === self.id) { queue = es.queue; while (queue.length) { q = queue.pop(); ce = q[0]; // set up stack to allow the next item to be processed es.next = ce; ce.fire.apply(ce, q[1]); } self.stack = null; } ret = !(self.stopped); if (self.type != host._yuievt.bubbling) { es.stopped = 0; es.prevented = 0; self.stopped = 0; self.prevented = 0; } // Kill the cached facade to free up memory. // Otherwise we have the facade from the last fire, sitting around forever. self._facade = null; return ret; }; CEProto._getFacade = function() { var ef = this._facade, o, args = this.details; if (!ef) { ef = new Y.EventFacade(this, this.currentTarget); } // if the first argument is an object literal, apply the // properties to the event facade o = args && args[0]; if (Y.Lang.isObject(o, true)) { // protect the event facade properties mixFacadeProps(ef, o); // Allow the event type to be faked // http://yuilibrary.com/projects/yui3/ticket/2528376 ef.type = o.type || ef.type; } // update the details field with the arguments // ef.type = this.type; ef.details = this.details; // use the original target when the event bubbled to this target ef.target = this.originalTarget || this.target; ef.currentTarget = this.currentTarget; ef.stopped = 0; ef.prevented = 0; this._facade = ef; return this._facade; }; /** * Stop propagation to bubble targets * @for CustomEvent * @method stopPropagation */ CEProto.stopPropagation = function() { this.stopped = 1; if (this.stack) { this.stack.stopped = 1; } if (this.events) { this.events.fire('stopped', this); } }; /** * Stops propagation to bubble targets, and prevents any remaining * subscribers on the current target from executing. * @method stopImmediatePropagation */ CEProto.stopImmediatePropagation = function() { this.stopped = 2; if (this.stack) { this.stack.stopped = 2; } if (this.events) { this.events.fire('stopped', this); } }; /** * Prevents the execution of this event's defaultFn * @method preventDefault */ CEProto.preventDefault = function() { if (this.preventable) { this.prevented = 1; if (this.stack) { this.stack.prevented = 1; } } }; /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ CEProto.halt = function(immediate) { if (immediate) { this.stopImmediatePropagation(); } else { this.stopPropagation(); } this.preventDefault(); }; /** * Registers another EventTarget as a bubble target. Bubble order * is determined by the order registered. Multiple targets can * be specified. * * Events can only bubble if emitFacade is true. * * Included in the event-custom-complex submodule. * * @method addTarget * @param o {EventTarget} the target to add * @for EventTarget */ ETProto.addTarget = function(o) { this._yuievt.targets[Y.stamp(o)] = o; this._yuievt.hasTargets = true; }; /** * Returns an array of bubble targets for this object. * @method getTargets * @return EventTarget[] */ ETProto.getTargets = function() { return Y.Object.values(this._yuievt.targets); }; /** * Removes a bubble target * @method removeTarget * @param o {EventTarget} the target to remove * @for EventTarget */ ETProto.removeTarget = function(o) { delete this._yuievt.targets[Y.stamp(o)]; }; /** * Propagate an event. Requires the event-custom-complex module. * @method bubble * @param evt {CustomEvent} the custom event to propagate * @return {boolean} the aggregated return value from Event.Custom.fire * @for EventTarget */ ETProto.bubble = function(evt, args, target, es) { var targs = this._yuievt.targets, ret = true, t, type = evt && evt.type, ce, i, bc, ce2, originalTarget = target || (evt && evt.target) || this, oldbubble; if (!evt || ((!evt.stopped) && targs)) { // Y.log('Bubbling ' + evt.type); for (i in targs) { if (targs.hasOwnProperty(i)) { t = targs[i]; ce = t.getEvent(type, true); ce2 = t.getSibling(type, ce); if (ce2 && !ce) { ce = t.publish(type); } oldbubble = t._yuievt.bubbling; t._yuievt.bubbling = type; // if this event was not published on the bubble target, // continue propagating the event. if (!ce) { if (t._yuievt.hasTargets) { t.bubble(evt, args, originalTarget, es); } } else { ce.sibling = ce2; // set the original target to that the target payload on the // facade is correct. ce.target = originalTarget; ce.originalTarget = originalTarget; ce.currentTarget = t; bc = ce.broadcast; ce.broadcast = false; // default publish may not have emitFacade true -- that // shouldn't be what the implementer meant to do ce.emitFacade = true; ce.stack = es; ret = ret && ce.fire.apply(ce, args || evt.details || []); ce.broadcast = bc; ce.originalTarget = null; // stopPropagation() was called if (ce.stopped) { break; } } t._yuievt.bubbling = oldbubble; } } } return ret; }; FACADE = new Y.EventFacade(); FACADE_KEYS = {}; // Flatten whitelist for (key in FACADE) { FACADE_KEYS[key] = true; } }, '@VERSION@', {"requires": ["event-custom-base"]}); YUI.add('node-core', function (Y, NAME) { /** * The Node Utility provides a DOM-like interface for interacting with DOM nodes. * @module node * @main node * @submodule node-core */ /** * The Node class provides a wrapper for manipulating DOM Nodes. * Node properties can be accessed via the set/get methods. * Use `Y.one()` to retrieve Node instances. * * <strong>NOTE:</strong> Node properties are accessed using * the <code>set</code> and <code>get</code> methods. * * @class Node * @constructor * @param {DOMNode} node the DOM node to be mapped to the Node instance. * @uses EventTarget */ // "globals" var DOT = '.', NODE_NAME = 'nodeName', NODE_TYPE = 'nodeType', OWNER_DOCUMENT = 'ownerDocument', TAG_NAME = 'tagName', UID = '_yuid', EMPTY_OBJ = {}, _slice = Array.prototype.slice, Y_DOM = Y.DOM, Y_Node = function(node) { if (!this.getDOMNode) { // support optional "new" return new Y_Node(node); } if (typeof node == 'string') { node = Y_Node._fromString(node); if (!node) { return null; // NOTE: return } } var uid = (node.nodeType !== 9) ? node.uniqueID : node[UID]; if (uid && Y_Node._instances[uid] && Y_Node._instances[uid]._node !== node) { node[UID] = null; // unset existing uid to prevent collision (via clone or hack) } uid = uid || Y.stamp(node); if (!uid) { // stamp failed; likely IE non-HTMLElement uid = Y.guid(); } this[UID] = uid; /** * The underlying DOM node bound to the Y.Node instance * @property _node * @type DOMNode * @private */ this._node = node; this._stateProxy = node; // when augmented with Attribute if (this._initPlugins) { // when augmented with Plugin.Host this._initPlugins(); } }, // used with previous/next/ancestor tests _wrapFn = function(fn) { var ret = null; if (fn) { ret = (typeof fn == 'string') ? function(n) { return Y.Selector.test(n, fn); } : function(n) { return fn(Y.one(n)); }; } return ret; }; // end "globals" Y_Node.ATTRS = {}; Y_Node.DOM_EVENTS = {}; Y_Node._fromString = function(node) { if (node) { if (node.indexOf('doc') === 0) { // doc OR document node = Y.config.doc; } else if (node.indexOf('win') === 0) { // win OR window node = Y.config.win; } else { node = Y.Selector.query(node, null, true); } } return node || null; }; /** * The name of the component * @static * @type String * @property NAME */ Y_Node.NAME = 'node'; /* * The pattern used to identify ARIA attributes */ Y_Node.re_aria = /^(?:role$|aria-)/; Y_Node.SHOW_TRANSITION = 'fadeIn'; Y_Node.HIDE_TRANSITION = 'fadeOut'; /** * A list of Node instances that have been created * @private * @type Object * @property _instances * @static * */ Y_Node._instances = {}; /** * Retrieves the DOM node bound to a Node instance * @method getDOMNode * @static * * @param {Node | HTMLNode} node The Node instance or an HTMLNode * @return {HTMLNode} The DOM node bound to the Node instance. If a DOM node is passed * as the node argument, it is simply returned. */ Y_Node.getDOMNode = function(node) { if (node) { return (node.nodeType) ? node : node._node || null; } return null; }; /** * Checks Node return values and wraps DOM Nodes as Y.Node instances * and DOM Collections / Arrays as Y.NodeList instances. * Other return values just pass thru. If undefined is returned (e.g. no return) * then the Node instance is returned for chainability. * @method scrubVal * @static * * @param {any} node The Node instance or an HTMLNode * @return {Node | NodeList | Any} Depends on what is returned from the DOM node. */ Y_Node.scrubVal = function(val, node) { if (val) { // only truthy values are risky if (typeof val == 'object' || typeof val == 'function') { // safari nodeList === function if (NODE_TYPE in val || Y_DOM.isWindow(val)) {// node || window val = Y.one(val); } else if ((val.item && !val._nodes) || // dom collection or Node instance (val[0] && val[0][NODE_TYPE])) { // array of DOM Nodes val = Y.all(val); } } } else if (typeof val === 'undefined') { val = node; // for chaining } else if (val === null) { val = null; // IE: DOM null not the same as null } return val; }; /** * Adds methods to the Y.Node prototype, routing through scrubVal. * @method addMethod * @static * * @param {String} name The name of the method to add * @param {Function} fn The function that becomes the method * @param {Object} context An optional context to call the method with * (defaults to the Node instance) * @return {any} Depends on what is returned from the DOM node. */ Y_Node.addMethod = function(name, fn, context) { if (name && fn && typeof fn == 'function') { Y_Node.prototype[name] = function() { var args = _slice.call(arguments), node = this, ret; if (args[0] && args[0]._node) { args[0] = args[0]._node; } if (args[1] && args[1]._node) { args[1] = args[1]._node; } args.unshift(node._node); ret = fn.apply(node, args); if (ret) { // scrub truthy ret = Y_Node.scrubVal(ret, node); } (typeof ret != 'undefined') || (ret = node); return ret; }; } else { Y.log('unable to add method: ' + name, 'warn', 'Node'); } }; /** * Imports utility methods to be added as Y.Node methods. * @method importMethod * @static * * @param {Object} host The object that contains the method to import. * @param {String} name The name of the method to import * @param {String} altName An optional name to use in place of the host name * @param {Object} context An optional context to call the method with */ Y_Node.importMethod = function(host, name, altName) { if (typeof name == 'string') { altName = altName || name; Y_Node.addMethod(altName, host[name], host); } else { Y.Array.each(name, function(n) { Y_Node.importMethod(host, n); }); } }; /** * Retrieves a NodeList based on the given CSS selector. * @method all * * @param {string} selector The CSS selector to test against. * @return {NodeList} A NodeList instance for the matching HTMLCollection/Array. * @for YUI */ /** * Returns a single Node instance bound to the node or the * first element matching the given selector. Returns null if no match found. * <strong>Note:</strong> For chaining purposes you may want to * use <code>Y.all</code>, which returns a NodeList when no match is found. * @method one * @param {String | HTMLElement} node a node or Selector * @return {Node | null} a Node instance or null if no match found. * @for YUI */ /** * Returns a single Node instance bound to the node or the * first element matching the given selector. Returns null if no match found. * <strong>Note:</strong> For chaining purposes you may want to * use <code>Y.all</code>, which returns a NodeList when no match is found. * @method one * @static * @param {String | HTMLElement} node a node or Selector * @return {Node | null} a Node instance or null if no match found. * @for Node */ Y_Node.one = function(node) { var instance = null, cachedNode, uid; if (node) { if (typeof node == 'string') { node = Y_Node._fromString(node); if (!node) { return null; // NOTE: return } } else if (node.getDOMNode) { return node; // NOTE: return } if (node.nodeType || Y.DOM.isWindow(node)) { // avoid bad input (numbers, boolean, etc) uid = (node.uniqueID && node.nodeType !== 9) ? node.uniqueID : node._yuid; instance = Y_Node._instances[uid]; // reuse exising instances cachedNode = instance ? instance._node : null; if (!instance || (cachedNode && node !== cachedNode)) { // new Node when nodes don't match instance = new Y_Node(node); if (node.nodeType != 11) { // dont cache document fragment Y_Node._instances[instance[UID]] = instance; // cache node } } } } return instance; }; /** * The default setter for DOM properties * Called with instance context (this === the Node instance) * @method DEFAULT_SETTER * @static * @param {String} name The attribute/property being set * @param {any} val The value to be set * @return {any} The value */ Y_Node.DEFAULT_SETTER = function(name, val) { var node = this._stateProxy, strPath; if (name.indexOf(DOT) > -1) { strPath = name; name = name.split(DOT); // only allow when defined on node Y.Object.setValue(node, name, val); } else if (typeof node[name] != 'undefined') { // pass thru DOM properties node[name] = val; } return val; }; /** * The default getter for DOM properties * Called with instance context (this === the Node instance) * @method DEFAULT_GETTER * @static * @param {String} name The attribute/property to look up * @return {any} The current value */ Y_Node.DEFAULT_GETTER = function(name) { var node = this._stateProxy, val; if (name.indexOf && name.indexOf(DOT) > -1) { val = Y.Object.getValue(node, name.split(DOT)); } else if (typeof node[name] != 'undefined') { // pass thru from DOM val = node[name]; } return val; }; Y.mix(Y_Node.prototype, { DATA_PREFIX: 'data-', /** * The method called when outputting Node instances as strings * @method toString * @return {String} A string representation of the Node instance */ toString: function() { var str = this[UID] + ': not bound to a node', node = this._node, attrs, id, className; if (node) { attrs = node.attributes; id = (attrs && attrs.id) ? node.getAttribute('id') : null; className = (attrs && attrs.className) ? node.getAttribute('className') : null; str = node[NODE_NAME]; if (id) { str += '#' + id; } if (className) { str += '.' + className.replace(' ', '.'); } // TODO: add yuid? str += ' ' + this[UID]; } return str; }, /** * Returns an attribute value on the Node instance. * Unless pre-configured (via `Node.ATTRS`), get hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be queried. * @method get * @param {String} attr The attribute * @return {any} The current value of the attribute */ get: function(attr) { var val; if (this._getAttr) { // use Attribute imple val = this._getAttr(attr); } else { val = this._get(attr); } if (val) { val = Y_Node.scrubVal(val, this); } else if (val === null) { val = null; // IE: DOM null is not true null (even though they ===) } return val; }, /** * Helper method for get. * @method _get * @private * @param {String} attr The attribute * @return {any} The current value of the attribute */ _get: function(attr) { var attrConfig = Y_Node.ATTRS[attr], val; if (attrConfig && attrConfig.getter) { val = attrConfig.getter.call(this); } else if (Y_Node.re_aria.test(attr)) { val = this._node.getAttribute(attr, 2); } else { val = Y_Node.DEFAULT_GETTER.apply(this, arguments); } return val; }, /** * Sets an attribute on the Node instance. * Unless pre-configured (via Node.ATTRS), set hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be set. * To set custom attributes use setAttribute. * @method set * @param {String} attr The attribute to be set. * @param {any} val The value to set the attribute to. * @chainable */ set: function(attr, val) { var attrConfig = Y_Node.ATTRS[attr]; if (this._setAttr) { // use Attribute imple this._setAttr.apply(this, arguments); } else { // use setters inline if (attrConfig && attrConfig.setter) { attrConfig.setter.call(this, val, attr); } else if (Y_Node.re_aria.test(attr)) { // special case Aria this._node.setAttribute(attr, val); } else { Y_Node.DEFAULT_SETTER.apply(this, arguments); } } return this; }, /** * Sets multiple attributes. * @method setAttrs * @param {Object} attrMap an object of name/value pairs to set * @chainable */ setAttrs: function(attrMap) { if (this._setAttrs) { // use Attribute imple this._setAttrs(attrMap); } else { // use setters inline Y.Object.each(attrMap, function(v, n) { this.set(n, v); }, this); } return this; }, /** * Returns an object containing the values for the requested attributes. * @method getAttrs * @param {Array} attrs an array of attributes to get values * @return {Object} An object with attribute name/value pairs. */ getAttrs: function(attrs) { var ret = {}; if (this._getAttrs) { // use Attribute imple this._getAttrs(attrs); } else { // use setters inline Y.Array.each(attrs, function(v, n) { ret[v] = this.get(v); }, this); } return ret; }, /** * Compares nodes to determine if they match. * Node instances can be compared to each other and/or HTMLElements. * @method compareTo * @param {HTMLElement | Node} refNode The reference node to compare to the node. * @return {Boolean} True if the nodes match, false if they do not. */ compareTo: function(refNode) { var node = this._node; if (refNode && refNode._node) { refNode = refNode._node; } return node === refNode; }, /** * Determines whether the node is appended to the document. * @method inDoc * @param {Node|HTMLElement} doc optional An optional document to check against. * Defaults to current document. * @return {Boolean} Whether or not this node is appended to the document. */ inDoc: function(doc) { var node = this._node; doc = (doc) ? doc._node || doc : node[OWNER_DOCUMENT]; if (doc.documentElement) { return Y_DOM.contains(doc.documentElement, node); } }, getById: function(id) { var node = this._node, ret = Y_DOM.byId(id, node[OWNER_DOCUMENT]); if (ret && Y_DOM.contains(node, ret)) { ret = Y.one(ret); } else { ret = null; } return ret; }, /** * Returns the nearest ancestor that passes the test applied by supplied boolean method. * @method ancestor * @param {String | Function} fn A selector string or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * If fn is not passed as an argument, the parent node will be returned. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @param {String | Function} stopFn optional A selector string or boolean * method to indicate when the search should stop. The search bails when the function * returns true or the selector matches. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} The matching Node instance or null if not found */ ancestor: function(fn, testSelf, stopFn) { // testSelf is optional, check for stopFn as 2nd arg if (arguments.length === 2 && (typeof testSelf == 'string' || typeof testSelf == 'function')) { stopFn = testSelf; } return Y.one(Y_DOM.ancestor(this._node, _wrapFn(fn), testSelf, _wrapFn(stopFn))); }, /** * Returns the ancestors that pass the test applied by supplied boolean method. * @method ancestors * @param {String | Function} fn A selector string or boolean method for testing elements. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * If a function is used, it receives the current node being tested as the only argument. * @return {NodeList} A NodeList instance containing the matching elements */ ancestors: function(fn, testSelf, stopFn) { if (arguments.length === 2 && (typeof testSelf == 'string' || typeof testSelf == 'function')) { stopFn = testSelf; } return Y.all(Y_DOM.ancestors(this._node, _wrapFn(fn), testSelf, _wrapFn(stopFn))); }, /** * Returns the previous matching sibling. * Returns the nearest element node sibling if no method provided. * @method previous * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} Node instance or null if not found */ previous: function(fn, all) { return Y.one(Y_DOM.elementByAxis(this._node, 'previousSibling', _wrapFn(fn), all)); }, /** * Returns the next matching sibling. * Returns the nearest element node sibling if no method provided. * @method next * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} Node instance or null if not found */ next: function(fn, all) { return Y.one(Y_DOM.elementByAxis(this._node, 'nextSibling', _wrapFn(fn), all)); }, /** * Returns all matching siblings. * Returns all siblings if no method provided. * @method siblings * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {NodeList} NodeList instance bound to found siblings */ siblings: function(fn) { return Y.all(Y_DOM.siblings(this._node, _wrapFn(fn))); }, /** * Retrieves a single Node instance, the first element matching the given * CSS selector. * Returns null if no match found. * @method one * * @param {string} selector The CSS selector to test against. * @return {Node | null} A Node instance for the matching HTMLElement or null * if no match found. */ one: function(selector) { return Y.one(Y.Selector.query(selector, this._node, true)); }, /** * Retrieves a NodeList based on the given CSS selector. * @method all * * @param {string} selector The CSS selector to test against. * @return {NodeList} A NodeList instance for the matching HTMLCollection/Array. */ all: function(selector) { var nodelist = Y.all(Y.Selector.query(selector, this._node)); nodelist._query = selector; nodelist._queryRoot = this._node; return nodelist; }, // TODO: allow fn test /** * Test if the supplied node matches the supplied selector. * @method test * * @param {string} selector The CSS selector to test against. * @return {boolean} Whether or not the node matches the selector. */ test: function(selector) { return Y.Selector.test(this._node, selector); }, /** * Removes the node from its parent. * Shortcut for myNode.get('parentNode').removeChild(myNode); * @method remove * @param {Boolean} destroy whether or not to call destroy() on the node * after removal. * @chainable * */ remove: function(destroy) { var node = this._node; if (node && node.parentNode) { node.parentNode.removeChild(node); } if (destroy) { this.destroy(); } return this; }, /** * Replace the node with the other node. This is a DOM update only * and does not change the node bound to the Node instance. * Shortcut for myNode.get('parentNode').replaceChild(newNode, myNode); * @method replace * @param {Node | HTMLNode} newNode Node to be inserted * @chainable * */ replace: function(newNode) { var node = this._node; if (typeof newNode == 'string') { newNode = Y_Node.create(newNode); } node.parentNode.replaceChild(Y_Node.getDOMNode(newNode), node); return this; }, /** * @method replaceChild * @for Node * @param {String | HTMLElement | Node} node Node to be inserted * @param {HTMLElement | Node} refNode Node to be replaced * @return {Node} The replaced node */ replaceChild: function(node, refNode) { if (typeof node == 'string') { node = Y_DOM.create(node); } return Y.one(this._node.replaceChild(Y_Node.getDOMNode(node), Y_Node.getDOMNode(refNode))); }, /** * Nulls internal node references, removes any plugins and event listeners. * Note that destroy() will not remove the node from its parent or from the DOM. For that * functionality, call remove(true). * @method destroy * @param {Boolean} recursivePurge (optional) Whether or not to remove listeners from the * node's subtree (default is false) * */ destroy: function(recursive) { var UID = Y.config.doc.uniqueID ? 'uniqueID' : '_yuid', instance; this.purge(); // TODO: only remove events add via this Node if (this.unplug) { // may not be a PluginHost this.unplug(); } this.clearData(); if (recursive) { Y.NodeList.each(this.all('*'), function(node) { instance = Y_Node._instances[node[UID]]; if (instance) { instance.destroy(); } else { // purge in case added by other means Y.Event.purgeElement(node); } }); } this._node = null; this._stateProxy = null; delete Y_Node._instances[this._yuid]; }, /** * Invokes a method on the Node instance * @method invoke * @param {String} method The name of the method to invoke * @param {Any} a, b, c, etc. Arguments to invoke the method with. * @return Whatever the underly method returns. * DOM Nodes and Collections return values * are converted to Node/NodeList instances. * */ invoke: function(method, a, b, c, d, e) { var node = this._node, ret; if (a && a._node) { a = a._node; } if (b && b._node) { b = b._node; } ret = node[method](a, b, c, d, e); return Y_Node.scrubVal(ret, this); }, /** * @method swap * @description Swap DOM locations with the given node. * This does not change which DOM node each Node instance refers to. * @param {Node} otherNode The node to swap with * @chainable */ swap: Y.config.doc.documentElement.swapNode ? function(otherNode) { this._node.swapNode(Y_Node.getDOMNode(otherNode)); } : function(otherNode) { otherNode = Y_Node.getDOMNode(otherNode); var node = this._node, parent = otherNode.parentNode, nextSibling = otherNode.nextSibling; if (nextSibling === node) { parent.insertBefore(node, otherNode); } else if (otherNode === node.nextSibling) { parent.insertBefore(otherNode, node); } else { node.parentNode.replaceChild(otherNode, node); Y_DOM.addHTML(parent, node, nextSibling); } return this; }, hasMethod: function(method) { var node = this._node; return !!(node && method in node && typeof node[method] != 'unknown' && (typeof node[method] == 'function' || String(node[method]).indexOf('function') === 1)); // IE reports as object, prepends space }, isFragment: function() { return (this.get('nodeType') === 11); }, /** * Removes and destroys all of the nodes within the node. * @method empty * @chainable */ empty: function() { this.get('childNodes').remove().destroy(true); return this; }, /** * Returns the DOM node bound to the Node instance * @method getDOMNode * @return {DOMNode} */ getDOMNode: function() { return this._node; } }, true); Y.Node = Y_Node; Y.one = Y_Node.one; /** * The NodeList module provides support for managing collections of Nodes. * @module node * @submodule node-core */ /** * The NodeList class provides a wrapper for manipulating DOM NodeLists. * NodeList properties can be accessed via the set/get methods. * Use Y.all() to retrieve NodeList instances. * * @class NodeList * @constructor * @param nodes {String|element|Node|Array} A selector, DOM element, Node, list of DOM elements, or list of Nodes with which to populate this NodeList. */ var NodeList = function(nodes) { var tmp = []; if (nodes) { if (typeof nodes === 'string') { // selector query this._query = nodes; nodes = Y.Selector.query(nodes); } else if (nodes.nodeType || Y_DOM.isWindow(nodes)) { // domNode || window nodes = [nodes]; } else if (nodes._node) { // Y.Node nodes = [nodes._node]; } else if (nodes[0] && nodes[0]._node) { // allow array of Y.Nodes Y.Array.each(nodes, function(node) { if (node._node) { tmp.push(node._node); } }); nodes = tmp; } else { // array of domNodes or domNodeList (no mixed array of Y.Node/domNodes) nodes = Y.Array(nodes, 0, true); } } /** * The underlying array of DOM nodes bound to the Y.NodeList instance * @property _nodes * @private */ this._nodes = nodes || []; }; NodeList.NAME = 'NodeList'; /** * Retrieves the DOM nodes bound to a NodeList instance * @method getDOMNodes * @static * * @param {NodeList} nodelist The NodeList instance * @return {Array} The array of DOM nodes bound to the NodeList */ NodeList.getDOMNodes = function(nodelist) { return (nodelist && nodelist._nodes) ? nodelist._nodes : nodelist; }; NodeList.each = function(instance, fn, context) { var nodes = instance._nodes; if (nodes && nodes.length) { Y.Array.each(nodes, fn, context || instance); } else { Y.log('no nodes bound to ' + this, 'warn', 'NodeList'); } }; NodeList.addMethod = function(name, fn, context) { if (name && fn) { NodeList.prototype[name] = function() { var ret = [], args = arguments; Y.Array.each(this._nodes, function(node) { var UID = (node.uniqueID && node.nodeType !== 9 ) ? 'uniqueID' : '_yuid', instance = Y.Node._instances[node[UID]], ctx, result; if (!instance) { instance = NodeList._getTempNode(node); } ctx = context || instance; result = fn.apply(ctx, args); if (result !== undefined && result !== instance) { ret[ret.length] = result; } }); // TODO: remove tmp pointer return ret.length ? ret : this; }; } else { Y.log('unable to add method: ' + name + ' to NodeList', 'warn', 'node'); } }; NodeList.importMethod = function(host, name, altName) { if (typeof name === 'string') { altName = altName || name; NodeList.addMethod(name, host[name]); } else { Y.Array.each(name, function(n) { NodeList.importMethod(host, n); }); } }; NodeList._getTempNode = function(node) { var tmp = NodeList._tempNode; if (!tmp) { tmp = Y.Node.create('<div></div>'); NodeList._tempNode = tmp; } tmp._node = node; tmp._stateProxy = node; return tmp; }; Y.mix(NodeList.prototype, { _invoke: function(method, args, getter) { var ret = (getter) ? [] : this; this.each(function(node) { var val = node[method].apply(node, args); if (getter) { ret.push(val); } }); return ret; }, /** * Retrieves the Node instance at the given index. * @method item * * @param {Number} index The index of the target Node. * @return {Node} The Node instance at the given index. */ item: function(index) { return Y.one((this._nodes || [])[index]); }, /** * Applies the given function to each Node in the NodeList. * @method each * @param {Function} fn The function to apply. It receives 3 arguments: * the current node instance, the node's index, and the NodeList instance * @param {Object} context optional An optional context to apply the function with * Default context is the current Node instance * @chainable */ each: function(fn, context) { var instance = this; Y.Array.each(this._nodes, function(node, index) { node = Y.one(node); return fn.call(context || node, node, index, instance); }); return instance; }, batch: function(fn, context) { var nodelist = this; Y.Array.each(this._nodes, function(node, index) { var instance = Y.Node._instances[node[UID]]; if (!instance) { instance = NodeList._getTempNode(node); } return fn.call(context || instance, instance, index, nodelist); }); return nodelist; }, /** * Executes the function once for each node until a true value is returned. * @method some * @param {Function} fn The function to apply. It receives 3 arguments: * the current node instance, the node's index, and the NodeList instance * @param {Object} context optional An optional context to execute the function from. * Default context is the current Node instance * @return {Boolean} Whether or not the function returned true for any node. */ some: function(fn, context) { var instance = this; return Y.Array.some(this._nodes, function(node, index) { node = Y.one(node); context = context || node; return fn.call(context, node, index, instance); }); }, /** * Creates a documenFragment from the nodes bound to the NodeList instance * @method toFrag * @return {Node} a Node instance bound to the documentFragment */ toFrag: function() { return Y.one(Y.DOM._nl2frag(this._nodes)); }, /** * Returns the index of the node in the NodeList instance * or -1 if the node isn't found. * @method indexOf * @param {Node | DOMNode} node the node to search for * @return {Int} the index of the node value or -1 if not found */ indexOf: function(node) { return Y.Array.indexOf(this._nodes, Y.Node.getDOMNode(node)); }, /** * Filters the NodeList instance down to only nodes matching the given selector. * @method filter * @param {String} selector The selector to filter against * @return {NodeList} NodeList containing the updated collection * @see Selector */ filter: function(selector) { return Y.all(Y.Selector.filter(this._nodes, selector)); }, /** * Creates a new NodeList containing all nodes at every n indices, where * remainder n % index equals r. * (zero-based index). * @method modulus * @param {Int} n The offset to use (return every nth node) * @param {Int} r An optional remainder to use with the modulus operation (defaults to zero) * @return {NodeList} NodeList containing the updated collection */ modulus: function(n, r) { r = r || 0; var nodes = []; NodeList.each(this, function(node, i) { if (i % n === r) { nodes.push(node); } }); return Y.all(nodes); }, /** * Creates a new NodeList containing all nodes at odd indices * (zero-based index). * @method odd * @return {NodeList} NodeList containing the updated collection */ odd: function() { return this.modulus(2, 1); }, /** * Creates a new NodeList containing all nodes at even indices * (zero-based index), including zero. * @method even * @return {NodeList} NodeList containing the updated collection */ even: function() { return this.modulus(2); }, destructor: function() { }, /** * Reruns the initial query, when created using a selector query * @method refresh * @chainable */ refresh: function() { var doc, nodes = this._nodes, query = this._query, root = this._queryRoot; if (query) { if (!root) { if (nodes && nodes[0] && nodes[0].ownerDocument) { root = nodes[0].ownerDocument; } } this._nodes = Y.Selector.query(query, root); } return this; }, /** * Returns the current number of items in the NodeList. * @method size * @return {Int} The number of items in the NodeList. */ size: function() { return this._nodes.length; }, /** * Determines if the instance is bound to any nodes * @method isEmpty * @return {Boolean} Whether or not the NodeList is bound to any nodes */ isEmpty: function() { return this._nodes.length < 1; }, toString: function() { var str = '', errorMsg = this[UID] + ': not bound to any nodes', nodes = this._nodes, node; if (nodes && nodes[0]) { node = nodes[0]; str += node[NODE_NAME]; if (node.id) { str += '#' + node.id; } if (node.className) { str += '.' + node.className.replace(' ', '.'); } if (nodes.length > 1) { str += '...[' + nodes.length + ' items]'; } } return str || errorMsg; }, /** * Returns the DOM node bound to the Node instance * @method getDOMNodes * @return {Array} */ getDOMNodes: function() { return this._nodes; } }, true); NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance. Nulls internal node references, * removes any plugins and event listeners * @method destroy * @param {Boolean} recursivePurge (optional) Whether or not to * remove listeners from the node's subtree (default is false) * @see Node.destroy */ 'destroy', /** * Called on each Node instance. Removes and destroys all of the nodes * within the node * @method empty * @chainable * @see Node.empty */ 'empty', /** * Called on each Node instance. Removes the node from its parent. * Shortcut for myNode.get('parentNode').removeChild(myNode); * @method remove * @param {Boolean} destroy whether or not to call destroy() on the node * after removal. * @chainable * @see Node.remove */ 'remove', /** * Called on each Node instance. Sets an attribute on the Node instance. * Unless pre-configured (via Node.ATTRS), set hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be set. * To set custom attributes use setAttribute. * @method set * @param {String} attr The attribute to be set. * @param {any} val The value to set the attribute to. * @chainable * @see Node.set */ 'set' ]); // one-off implementation to convert array of Nodes to NodeList // e.g. Y.all('input').get('parentNode'); /** Called on each Node instance * @method get * @see Node */ NodeList.prototype.get = function(attr) { var ret = [], nodes = this._nodes, isNodeList = false, getTemp = NodeList._getTempNode, instance, val; if (nodes[0]) { instance = Y.Node._instances[nodes[0]._yuid] || getTemp(nodes[0]); val = instance._get(attr); if (val && val.nodeType) { isNodeList = true; } } Y.Array.each(nodes, function(node) { instance = Y.Node._instances[node._yuid]; if (!instance) { instance = getTemp(node); } val = instance._get(attr); if (!isNodeList) { // convert array of Nodes to NodeList val = Y.Node.scrubVal(val, instance); } ret.push(val); }); return (isNodeList) ? Y.all(ret) : ret; }; Y.NodeList = NodeList; Y.all = function(nodes) { return new NodeList(nodes); }; Y.Node.all = Y.all; /** * @module node * @submodule node-core */ var Y_NodeList = Y.NodeList, ArrayProto = Array.prototype, ArrayMethods = { /** Returns a new NodeList combining the given NodeList(s) * @for NodeList * @method concat * @param {NodeList | Array} valueN Arrays/NodeLists and/or values to * concatenate to the resulting NodeList * @return {NodeList} A new NodeList comprised of this NodeList joined with the input. */ 'concat': 1, /** Removes the last from the NodeList and returns it. * @for NodeList * @method pop * @return {Node} The last item in the NodeList. */ 'pop': 0, /** Adds the given Node(s) to the end of the NodeList. * @for NodeList * @method push * @param {Node | DOMNode} nodes One or more nodes to add to the end of the NodeList. */ 'push': 0, /** Removes the first item from the NodeList and returns it. * @for NodeList * @method shift * @return {Node} The first item in the NodeList. */ 'shift': 0, /** Returns a new NodeList comprising the Nodes in the given range. * @for NodeList * @method slice * @param {Number} begin Zero-based index at which to begin extraction. As a negative index, start indicates an offset from the end of the sequence. slice(-2) extracts the second-to-last element and the last element in the sequence. * @param {Number} end Zero-based index at which to end extraction. slice extracts up to but not including end. slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3). As a negative index, end indicates an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence. If end is omitted, slice extracts to the end of the sequence. * @return {NodeList} A new NodeList comprised of this NodeList joined with the input. */ 'slice': 1, /** Changes the content of the NodeList, adding new elements while removing old elements. * @for NodeList * @method splice * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end. * @param {Number} howMany An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed. In this case, you should specify at least one new element. If no howMany parameter is specified (second syntax above, which is a SpiderMonkey extension), all elements after index are removed. * {Node | DOMNode| element1, ..., elementN The elements to add to the array. If you don't specify any elements, splice simply removes elements from the array. * @return {NodeList} The element(s) removed. */ 'splice': 1, /** Adds the given Node(s) to the beginning of the NodeList. * @for NodeList * @method unshift * @param {Node | DOMNode} nodes One or more nodes to add to the NodeList. */ 'unshift': 0 }; Y.Object.each(ArrayMethods, function(returnNodeList, name) { Y_NodeList.prototype[name] = function() { var args = [], i = 0, arg, ret; while (typeof (arg = arguments[i++]) != 'undefined') { // use DOM nodes/nodeLists args.push(arg._node || arg._nodes || arg); } ret = ArrayProto[name].apply(this._nodes, args); if (returnNodeList) { ret = Y.all(ret); } else { ret = Y.Node.scrubVal(ret); } return ret; }; }); /** * @module node * @submodule node-core */ Y.Array.each([ /** * Passes through to DOM method. * @for Node * @method removeChild * @param {HTMLElement | Node} node Node to be removed * @return {Node} The removed node */ 'removeChild', /** * Passes through to DOM method. * @method hasChildNodes * @return {Boolean} Whether or not the node has any childNodes */ 'hasChildNodes', /** * Passes through to DOM method. * @method cloneNode * @param {Boolean} deep Whether or not to perform a deep clone, which includes * subtree and attributes * @return {Node} The clone */ 'cloneNode', /** * Passes through to DOM method. * @method hasAttribute * @param {String} attribute The attribute to test for * @return {Boolean} Whether or not the attribute is present */ 'hasAttribute', /** * Passes through to DOM method. * @method scrollIntoView * @chainable */ 'scrollIntoView', /** * Passes through to DOM method. * @method getElementsByTagName * @param {String} tagName The tagName to collect * @return {NodeList} A NodeList representing the HTMLCollection */ 'getElementsByTagName', /** * Passes through to DOM method. * @method focus * @chainable */ 'focus', /** * Passes through to DOM method. * @method blur * @chainable */ 'blur', /** * Passes through to DOM method. * Only valid on FORM elements * @method submit * @chainable */ 'submit', /** * Passes through to DOM method. * Only valid on FORM elements * @method reset * @chainable */ 'reset', /** * Passes through to DOM method. * @method select * @chainable */ 'select', /** * Passes through to DOM method. * Only valid on TABLE elements * @method createCaption * @chainable */ 'createCaption' ], function(method) { Y.log('adding: ' + method, 'info', 'node'); Y.Node.prototype[method] = function(arg1, arg2, arg3) { var ret = this.invoke(method, arg1, arg2, arg3); return ret; }; }); /** * Passes through to DOM method. * @method removeAttribute * @param {String} attribute The attribute to be removed * @chainable */ // one-off implementation due to IE returning boolean, breaking chaining Y.Node.prototype.removeAttribute = function(attr) { var node = this._node; if (node) { node.removeAttribute(attr, 0); // comma zero for IE < 8 to force case-insensitive } return this; }; Y.Node.importMethod(Y.DOM, [ /** * Determines whether the node is an ancestor of another HTML element in the DOM hierarchy. * @method contains * @param {Node | HTMLElement} needle The possible node or descendent * @return {Boolean} Whether or not this node is the needle its ancestor */ 'contains', /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @for Node * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @for Node * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute', /** * Wraps the given HTML around the node. * @method wrap * @param {String} html The markup to wrap around the node. * @chainable * @for Node */ 'wrap', /** * Removes the node's parent node. * @method unwrap * @chainable */ 'unwrap', /** * Applies a unique ID to the node if none exists * @method generateID * @return {String} The existing or generated ID */ 'generateID' ]); Y.NodeList.importMethod(Y.Node.prototype, [ /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @see Node * @for NodeList * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute', /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @see Node * @for NodeList * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows for removing attributes on DOM nodes. * This passes through to the DOM node, allowing for custom attributes. * @method removeAttribute * @see Node * @for NodeList * @param {string} name The attribute to remove */ 'removeAttribute', /** * Removes the parent node from node in the list. * @method unwrap * @chainable */ 'unwrap', /** * Wraps the given HTML around each node. * @method wrap * @param {String} html The markup to wrap around the node. * @chainable */ 'wrap', /** * Applies a unique ID to each node if none exists * @method generateID * @return {String} The existing or generated ID */ 'generateID' ]); }, '@VERSION@', {"requires": ["dom-core", "selector"]}); YUI.add('node-base', function (Y, NAME) { /** * @module node * @submodule node-base */ var methods = [ /** * Determines whether each node has the given className. * @method hasClass * @for Node * @param {String} className the class name to search for * @return {Boolean} Whether or not the element has the specified class */ 'hasClass', /** * Adds a class name to each node. * @method addClass * @param {String} className the class name to add to the node's class attribute * @chainable */ 'addClass', /** * Removes a class name from each node. * @method removeClass * @param {String} className the class name to remove from the node's class attribute * @chainable */ 'removeClass', /** * Replace a class with another class for each node. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name * @chainable */ 'replaceClass', /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @param {String} className the class name to be toggled * @param {Boolean} force Option to force adding or removing the class. * @chainable */ 'toggleClass' ]; Y.Node.importMethod(Y.DOM, methods); /** * Determines whether each node has the given className. * @method hasClass * @see Node.hasClass * @for NodeList * @param {String} className the class name to search for * @return {Array} An array of booleans for each node bound to the NodeList. */ /** * Adds a class name to each node. * @method addClass * @see Node.addClass * @param {String} className the class name to add to the node's class attribute * @chainable */ /** * Removes a class name from each node. * @method removeClass * @see Node.removeClass * @param {String} className the class name to remove from the node's class attribute * @chainable */ /** * Replace a class with another class for each node. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @see Node.replaceClass * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name * @chainable */ /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @see Node.toggleClass * @param {String} className the class name to be toggled * @chainable */ Y.NodeList.importMethod(Y.Node.prototype, methods); /** * @module node * @submodule node-base */ var Y_Node = Y.Node, Y_DOM = Y.DOM; /** * Returns a new dom node using the provided markup string. * @method create * @static * @param {String} html The markup used to create the element * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {HTMLDocument} doc An optional document context * @return {Node} A Node instance bound to a DOM node or fragment * @for Node */ Y_Node.create = function(html, doc) { if (doc && doc._node) { doc = doc._node; } return Y.one(Y_DOM.create(html, doc)); }; Y.mix(Y_Node.prototype, { /** * Creates a new Node using the provided markup string. * @method create * @param {String} html The markup used to create the element. * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {HTMLDocument} doc An optional document context * @return {Node} A Node instance bound to a DOM node or fragment */ create: Y_Node.create, /** * Inserts the content before the reference node. * @method insert * @param {String | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {Int | Node | HTMLElement | String} where The position to insert at. * Possible "where" arguments * <dl> * <dt>Y.Node</dt> * <dd>The Node to insert before</dd> * <dt>HTMLElement</dt> * <dd>The element to insert before</dd> * <dt>Int</dt> * <dd>The index of the child element to insert before</dd> * <dt>"replace"</dt> * <dd>Replaces the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts before the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts content before the node</dd> * <dt>"after"</dt> * <dd>Inserts content after the node</dd> * </dl> * @chainable */ insert: function(content, where) { this._insert(content, where); return this; }, _insert: function(content, where) { var node = this._node, ret = null; if (typeof where == 'number') { // allow index where = this._node.childNodes[where]; } else if (where && where._node) { // Node where = where._node; } if (content && typeof content != 'string') { // allow Node or NodeList/Array instances content = content._node || content._nodes || content; } ret = Y_DOM.addHTML(node, content, where); return ret; }, /** * Inserts the content as the firstChild of the node. * @method prepend * @param {String | Node | HTMLElement} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @chainable */ prepend: function(content) { return this.insert(content, 0); }, /** * Inserts the content as the lastChild of the node. * @method append * @param {String | Node | HTMLElement} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @chainable */ append: function(content) { return this.insert(content, null); }, /** * @method appendChild * @param {String | HTMLElement | Node} node Node to be appended * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @return {Node} The appended node */ appendChild: function(node) { return Y_Node.scrubVal(this._insert(node)); }, /** * @method insertBefore * @param {String | HTMLElement | Node} newNode Node to be appended * @param {HTMLElement | Node} refNode Node to be inserted before * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @return {Node} The inserted node */ insertBefore: function(newNode, refNode) { return Y.Node.scrubVal(this._insert(newNode, refNode)); }, /** * Appends the node to the given node. * @method appendTo * @param {Node | HTMLElement} node The node to append to * @chainable */ appendTo: function(node) { Y.one(node).append(this); return this; }, /** * Replaces the node's current content with the content. * Note that this passes to innerHTML and is not escaped. * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content or `set('text')` to add as text. * @method setContent * @deprecated Use setHTML * @param {String | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * @chainable */ setContent: function(content) { this._insert(content, 'replace'); return this; }, /** * Returns the node's current content (e.g. innerHTML) * @method getContent * @deprecated Use getHTML * @return {String} The current content */ getContent: function(content) { return this.get('innerHTML'); } }); /** * Replaces the node's current html content with the content provided. * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @method setHTML * @param {String | HTML | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * @chainable */ Y.Node.prototype.setHTML = Y.Node.prototype.setContent; /** * Returns the node's current html content (e.g. innerHTML) * @method getHTML * @return {String} The html content */ Y.Node.prototype.getHTML = Y.Node.prototype.getContent; Y.NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance * @for NodeList * @method append * @see Node.append */ 'append', /** * Called on each Node instance * @for NodeList * @method insert * @see Node.insert */ 'insert', /** * Called on each Node instance * @for NodeList * @method appendChild * @see Node.appendChild */ 'appendChild', /** * Called on each Node instance * @for NodeList * @method insertBefore * @see Node.insertBefore */ 'insertBefore', /** * Called on each Node instance * @for NodeList * @method prepend * @see Node.prepend */ 'prepend', /** * Called on each Node instance * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @for NodeList * @method setContent * @deprecated Use setHTML */ 'setContent', /** * Called on each Node instance * @for NodeList * @method getContent * @deprecated Use getHTML */ 'getContent', /** * Called on each Node instance * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @for NodeList * @method setHTML * @see Node.setHTML */ 'setHTML', /** * Called on each Node instance * @for NodeList * @method getHTML * @see Node.getHTML */ 'getHTML' ]); /** * @module node * @submodule node-base */ var Y_Node = Y.Node, Y_DOM = Y.DOM; /** * Static collection of configuration attributes for special handling * @property ATTRS * @static * @type object */ Y_Node.ATTRS = { /** * Allows for getting and setting the text of an element. * Formatting is preserved and special characters are treated literally. * @config text * @type String */ text: { getter: function() { return Y_DOM.getText(this._node); }, setter: function(content) { Y_DOM.setText(this._node, content); return content; } }, /** * Allows for getting and setting the text of an element. * Formatting is preserved and special characters are treated literally. * @config for * @type String */ 'for': { getter: function() { return Y_DOM.getAttribute(this._node, 'for'); }, setter: function(val) { Y_DOM.setAttribute(this._node, 'for', val); return val; } }, 'options': { getter: function() { return this._node.getElementsByTagName('option'); } }, /** * Returns a NodeList instance of all HTMLElement children. * @readOnly * @config children * @type NodeList */ 'children': { getter: function() { var node = this._node, children = node.children, childNodes, i, len; if (!children) { childNodes = node.childNodes; children = []; for (i = 0, len = childNodes.length; i < len; ++i) { if (childNodes[i].tagName) { children[children.length] = childNodes[i]; } } } return Y.all(children); } }, value: { getter: function() { return Y_DOM.getValue(this._node); }, setter: function(val) { Y_DOM.setValue(this._node, val); return val; } } }; Y.Node.importMethod(Y.DOM, [ /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @for Node * @for NodeList * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @for Node * @for NodeList * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute' ]); /** * @module node * @submodule node-base */ var Y_Node = Y.Node; var Y_NodeList = Y.NodeList; /** * List of events that route to DOM events * @static * @property DOM_EVENTS * @for Node */ Y_Node.DOM_EVENTS = { abort: 1, beforeunload: 1, blur: 1, change: 1, click: 1, close: 1, command: 1, contextmenu: 1, dblclick: 1, DOMMouseScroll: 1, drag: 1, dragstart: 1, dragenter: 1, dragover: 1, dragleave: 1, dragend: 1, drop: 1, error: 1, focus: 1, key: 1, keydown: 1, keypress: 1, keyup: 1, load: 1, message: 1, mousedown: 1, mouseenter: 1, mouseleave: 1, mousemove: 1, mousemultiwheel: 1, mouseout: 1, mouseover: 1, mouseup: 1, mousewheel: 1, orientationchange: 1, reset: 1, resize: 1, select: 1, selectstart: 1, submit: 1, scroll: 1, textInput: 1, unload: 1 }; // Add custom event adaptors to this list. This will make it so // that delegate, key, available, contentready, etc all will // be available through Node.on Y.mix(Y_Node.DOM_EVENTS, Y.Env.evt.plugins); Y.augment(Y_Node, Y.EventTarget); Y.mix(Y_Node.prototype, { /** * Removes event listeners from the node and (optionally) its subtree * @method purge * @param {Boolean} recurse (optional) Whether or not to remove listeners from the * node's subtree * @param {String} type (optional) Only remove listeners of the specified type * @chainable * */ purge: function(recurse, type) { Y.Event.purgeElement(this._node, recurse, type); return this; } }); Y.mix(Y.NodeList.prototype, { _prepEvtArgs: function(type, fn, context) { // map to Y.on/after signature (type, fn, nodes, context, arg1, arg2, etc) var args = Y.Array(arguments, 0, true); if (args.length < 2) { // type only (event hash) just add nodes args[2] = this._nodes; } else { args.splice(2, 0, this._nodes); } args[3] = context || this; // default to NodeList instance as context return args; }, /** Subscribe a callback function for each `Node` in the collection to execute in response to a DOM event. NOTE: Generally, the `on()` method should be avoided on `NodeLists`, in favor of using event delegation from a parent Node. See the Event user guide for details. Most DOM events are associated with a preventable default behavior, such as link clicks navigating to a new page. Callbacks are passed a `DOMEventFacade` object as their first argument (usually called `e`) that can be used to prevent this default behavior with `e.preventDefault()`. See the `DOMEventFacade` API for all available properties and methods on the object. By default, the `this` object will be the `NodeList` that the subscription came from, <em>not the `Node` that received the event</em>. Use `e.currentTarget` to refer to the `Node`. Returning `false` from a callback is supported as an alternative to calling `e.preventDefault(); e.stopPropagation();`. However, it is recommended to use the event methods. @example Y.all(".sku").on("keydown", function (e) { if (e.keyCode === 13) { e.preventDefault(); // Use e.currentTarget to refer to the individual Node var item = Y.MyApp.searchInventory( e.currentTarget.get('value') ); // etc ... } }); @method on @param {String} type The name of the event @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching that subscription @for NodeList **/ on: function(type, fn, context) { return Y.on.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an one-time event listener to each Node bound to the NodeList. * @method once * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ once: function(type, fn, context) { return Y.once.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an event listener to each Node bound to the NodeList. * The handler is called only after all on() handlers are called * and the event is not prevented. * @method after * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ after: function(type, fn, context) { return Y.after.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an one-time event listener to each Node bound to the NodeList * that will be called only after all on() handlers are called and the * event is not prevented. * * @method onceAfter * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ onceAfter: function(type, fn, context) { return Y.onceAfter.apply(Y, this._prepEvtArgs.apply(this, arguments)); } }); Y_NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance * @method detach * @see Node.detach * @for NodeList */ 'detach', /** Called on each Node instance * @method detachAll * @see Node.detachAll * @for NodeList */ 'detachAll' ]); /** Subscribe a callback function to execute in response to a DOM event or custom event. Most DOM events are associated with a preventable default behavior such as link clicks navigating to a new page. Callbacks are passed a `DOMEventFacade` object as their first argument (usually called `e`) that can be used to prevent this default behavior with `e.preventDefault()`. See the `DOMEventFacade` API for all available properties and methods on the object. If the event name passed as the first parameter is not a whitelisted DOM event, it will be treated as a custom event subscriptions, allowing `node.fire('customEventName')` later in the code. Refer to the Event user guide for the full DOM event whitelist. By default, the `this` object in the callback will refer to the subscribed `Node`. Returning `false` from a callback is supported as an alternative to calling `e.preventDefault(); e.stopPropagation();`. However, it is recommended to use the event methods. @example Y.one("#my-form").on("submit", function (e) { e.preventDefault(); // proceed with ajax form submission instead... }); @method on @param {String} type The name of the event @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching that subscription @for Node **/ Y.mix(Y.Node.ATTRS, { offsetHeight: { setter: function(h) { Y.DOM.setHeight(this._node, h); return h; }, getter: function() { return this._node.offsetHeight; } }, offsetWidth: { setter: function(w) { Y.DOM.setWidth(this._node, w); return w; }, getter: function() { return this._node.offsetWidth; } } }); Y.mix(Y.Node.prototype, { sizeTo: function(w, h) { var node; if (arguments.length < 2) { node = Y.one(w); w = node.get('offsetWidth'); h = node.get('offsetHeight'); } this.setAttrs({ offsetWidth: w, offsetHeight: h }); } }); /** * @module node * @submodule node-base */ var Y_Node = Y.Node; Y.mix(Y_Node.prototype, { /** * Makes the node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @for Node * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ show: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(true, callback); return this; }, /** * The implementation for showing nodes. * Default is to toggle the style.display property. * @method _show * @protected * @chainable */ _show: function() { this.setStyle('display', ''); }, _isHidden: function() { return Y.DOM.getStyle(this._node, 'display') === 'none'; }, /** * Displays or hides the node. * If the "transition" module is loaded, toggleView optionally * animates the toggling of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method toggleView * @for Node * @param {Boolean} [on] An optional boolean value to force the node to be shown or hidden * @param {Function} [callback] An optional function to run after the transition completes. * @chainable */ toggleView: function(on, callback) { this._toggleView.apply(this, arguments); return this; }, _toggleView: function(on, callback) { callback = arguments[arguments.length - 1]; // base on current state if not forcing if (typeof on != 'boolean') { on = (this._isHidden()) ? 1 : 0; } if (on) { this._show(); } else { this._hide(); } if (typeof callback == 'function') { callback.call(this); } return this; }, /** * Hides the node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ hide: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(false, callback); return this; }, /** * The implementation for hiding nodes. * Default is to toggle the style.display property. * @method _hide * @protected * @chainable */ _hide: function() { this.setStyle('display', 'none'); } }); Y.NodeList.importMethod(Y.Node.prototype, [ /** * Makes each node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @for NodeList * @chainable */ 'show', /** * Hides each node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ 'hide', /** * Displays or hides each node. * If the "transition" module is loaded, toggleView optionally * animates the toggling of the nodes using either the default * transition effect ('fadeIn'), or the given named effect. * @method toggleView * @param {Boolean} [on] An optional boolean value to force the nodes to be shown or hidden * @param {Function} [callback] An optional function to run after the transition completes. * @chainable */ 'toggleView' ]); if (!Y.config.doc.documentElement.hasAttribute) { // IE < 8 Y.Node.prototype.hasAttribute = function(attr) { if (attr === 'value') { if (this.get('value') !== "") { // IE < 8 fails to populate specified when set in HTML return true; } } return !!(this._node.attributes[attr] && this._node.attributes[attr].specified); }; } // IE throws an error when calling focus() on an element that's invisible, not // displayed, or disabled. Y.Node.prototype.focus = function () { try { this._node.focus(); } catch (e) { Y.log('error focusing node: ' + e.toString(), 'error', 'node'); } return this; }; // IE throws error when setting input.type = 'hidden', // input.setAttribute('type', 'hidden') and input.attributes.type.value = 'hidden' Y.Node.ATTRS.type = { setter: function(val) { if (val === 'hidden') { try { this._node.type = 'hidden'; } catch(e) { this.setStyle('display', 'none'); this._inputType = 'hidden'; } } else { try { // IE errors when changing the type from "hidden' this._node.type = val; } catch (e) { Y.log('error setting type: ' + val, 'info', 'node'); } } return val; }, getter: function() { return this._inputType || this._node.type; }, _bypassProxy: true // don't update DOM when using with Attribute }; if (Y.config.doc.createElement('form').elements.nodeType) { // IE: elements collection is also FORM node which trips up scrubVal. Y.Node.ATTRS.elements = { getter: function() { return this.all('input, textarea, button, select'); } }; } /** * Provides methods for managing custom Node data. * * @module node * @main node * @submodule node-data */ Y.mix(Y.Node.prototype, { _initData: function() { if (! ('_data' in this)) { this._data = {}; } }, /** * @method getData * @for Node * @description Retrieves arbitrary data stored on a Node instance. * If no data is associated with the Node, it will attempt to retrieve * a value from the corresponding HTML data attribute. (e.g. node.getData('foo') * will check node.getAttribute('data-foo')). * @param {string} name Optional name of the data field to retrieve. * If no name is given, all data is returned. * @return {any | Object} Whatever is stored at the given field, * or an object hash of all fields. */ getData: function(name) { this._initData(); var data = this._data, ret = data; if (arguments.length) { // single field if (name in data) { ret = data[name]; } else { // initialize from HTML attribute ret = this._getDataAttribute(name); } } else if (typeof data == 'object' && data !== null) { // all fields ret = {}; Y.Object.each(data, function(v, n) { ret[n] = v; }); ret = this._getDataAttributes(ret); } return ret; }, _getDataAttributes: function(ret) { ret = ret || {}; var i = 0, attrs = this._node.attributes, len = attrs.length, prefix = this.DATA_PREFIX, prefixLength = prefix.length, name; while (i < len) { name = attrs[i].name; if (name.indexOf(prefix) === 0) { name = name.substr(prefixLength); if (!(name in ret)) { // only merge if not already stored ret[name] = this._getDataAttribute(name); } } i += 1; } return ret; }, _getDataAttribute: function(name) { name = this.DATA_PREFIX + name; var node = this._node, attrs = node.attributes, data = attrs && attrs[name] && attrs[name].value; return data; }, /** * @method setData * @for Node * @description Stores arbitrary data on a Node instance. * This is not stored with the DOM node. * @param {string} name The name of the field to set. If no val * is given, name is treated as the data and overrides any existing data. * @param {any} val The value to be assigned to the field. * @chainable */ setData: function(name, val) { this._initData(); if (arguments.length > 1) { this._data[name] = val; } else { this._data = name; } return this; }, /** * @method clearData * @for Node * @description Clears internally stored data. * @param {string} name The name of the field to clear. If no name * is given, all data is cleared. * @chainable */ clearData: function(name) { if ('_data' in this) { if (typeof name != 'undefined') { delete this._data[name]; } else { delete this._data; } } return this; } }); Y.mix(Y.NodeList.prototype, { /** * @method getData * @for NodeList * @description Retrieves arbitrary data stored on each Node instance * bound to the NodeList. * @see Node * @param {string} name Optional name of the data field to retrieve. * If no name is given, all data is returned. * @return {Array} An array containing all of the data for each Node instance. * or an object hash of all fields. */ getData: function(name) { var args = (arguments.length) ? [name] : []; return this._invoke('getData', args, true); }, /** * @method setData * @for NodeList * @description Stores arbitrary data on each Node instance bound to the * NodeList. This is not stored with the DOM node. * @param {string} name The name of the field to set. If no name * is given, name is treated as the data and overrides any existing data. * @param {any} val The value to be assigned to the field. * @chainable */ setData: function(name, val) { var args = (arguments.length > 1) ? [name, val] : [name]; return this._invoke('setData', args); }, /** * @method clearData * @for NodeList * @description Clears data on all Node instances bound to the NodeList. * @param {string} name The name of the field to clear. If no name * is given, all data is cleared. * @chainable */ clearData: function(name) { var args = (arguments.length) ? [name] : []; return this._invoke('clearData', [name]); } }); }, '@VERSION@', {"requires": ["event-base", "node-core", "dom-base"]}); (function () { var GLOBAL_ENV = YUI.Env; if (!GLOBAL_ENV._ready) { GLOBAL_ENV._ready = function() { GLOBAL_ENV.DOMReady = true; GLOBAL_ENV.remove(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready); }; GLOBAL_ENV.add(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready); } })(); YUI.add('event-base', function (Y, NAME) { /* * DOM event listener abstraction layer * @module event * @submodule event-base */ /** * The domready event fires at the moment the browser's DOM is * usable. In most cases, this is before images are fully * downloaded, allowing you to provide a more responsive user * interface. * * In YUI 3, domready subscribers will be notified immediately if * that moment has already passed when the subscription is created. * * One exception is if the yui.js file is dynamically injected into * the page. If this is done, you must tell the YUI instance that * you did this in order for DOMReady (and window load events) to * fire normally. That configuration option is 'injected' -- set * it to true if the yui.js script is not included inline. * * This method is part of the 'event-ready' module, which is a * submodule of 'event'. * * @event domready * @for YUI */ Y.publish('domready', { fireOnce: true, async: true }); if (YUI.Env.DOMReady) { Y.fire('domready'); } else { Y.Do.before(function() { Y.fire('domready'); }, YUI.Env, '_ready'); } /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event * @submodule event-base */ /** * Wraps a DOM event, properties requiring browser abstraction are * fixed here. Provids a security layer when required. * @class DOMEventFacade * @param ev {Event} the DOM event * @param currentTarget {HTMLElement} the element the listener was attached to * @param wrapper {Event.Custom} the custom event wrapper for this DOM event */ var ua = Y.UA, EMPTY = {}, /** * webkit key remapping required for Safari < 3.1 * @property webkitKeymap * @private */ webkitKeymap = { 63232: 38, // up 63233: 40, // down 63234: 37, // left 63235: 39, // right 63276: 33, // page up 63277: 34, // page down 25: 9, // SHIFT-TAB (Safari provides a different key code in // this case, even though the shiftKey modifier is set) 63272: 46, // delete 63273: 36, // home 63275: 35 // end }, /** * Returns a wrapped node. Intended to be used on event targets, * so it will return the node's parent if the target is a text * node. * * If accessing a property of the node throws an error, this is * probably the anonymous div wrapper Gecko adds inside text * nodes. This likely will only occur when attempting to access * the relatedTarget. In this case, we now return null because * the anonymous div is completely useless and we do not know * what the related target was because we can't even get to * the element's parent node. * * @method resolve * @private */ resolve = function(n) { if (!n) { return n; } try { if (n && 3 == n.nodeType) { n = n.parentNode; } } catch(e) { return null; } return Y.one(n); }, DOMEventFacade = function(ev, currentTarget, wrapper) { this._event = ev; this._currentTarget = currentTarget; this._wrapper = wrapper || EMPTY; // if not lazy init this.init(); }; Y.extend(DOMEventFacade, Object, { init: function() { var e = this._event, overrides = this._wrapper.overrides, x = e.pageX, y = e.pageY, c, currentTarget = this._currentTarget; this.altKey = e.altKey; this.ctrlKey = e.ctrlKey; this.metaKey = e.metaKey; this.shiftKey = e.shiftKey; this.type = (overrides && overrides.type) || e.type; this.clientX = e.clientX; this.clientY = e.clientY; this.pageX = x; this.pageY = y; // charCode is unknown in keyup, keydown. keyCode is unknown in keypress. // FF 3.6 - 8+? pass 0 for keyCode in keypress events. // Webkit, FF 3.6-8+?, and IE9+? pass 0 for charCode in keydown, keyup. // Webkit and IE9+? duplicate charCode in keyCode. // Opera never sets charCode, always keyCode (though with the charCode). // IE6-8 don't set charCode or which. // All browsers other than IE6-8 set which=keyCode in keydown, keyup, and // which=charCode in keypress. // // Moral of the story: (e.which || e.keyCode) will always return the // known code for that key event phase. e.keyCode is often different in // keypress from keydown and keyup. c = e.keyCode || e.charCode; if (ua.webkit && (c in webkitKeymap)) { c = webkitKeymap[c]; } this.keyCode = c; this.charCode = c; // Fill in e.which for IE - implementers should always use this over // e.keyCode or e.charCode. this.which = e.which || e.charCode || c; // this.button = e.button; this.button = this.which; this.target = resolve(e.target); this.currentTarget = resolve(currentTarget); this.relatedTarget = resolve(e.relatedTarget); if (e.type == "mousewheel" || e.type == "DOMMouseScroll") { this.wheelDelta = (e.detail) ? (e.detail * -1) : Math.round(e.wheelDelta / 80) || ((e.wheelDelta < 0) ? -1 : 1); } if (this._touch) { this._touch(e, currentTarget, this._wrapper); } }, stopPropagation: function() { this._event.stopPropagation(); this._wrapper.stopped = 1; this.stopped = 1; }, stopImmediatePropagation: function() { var e = this._event; if (e.stopImmediatePropagation) { e.stopImmediatePropagation(); } else { this.stopPropagation(); } this._wrapper.stopped = 2; this.stopped = 2; }, preventDefault: function(returnValue) { var e = this._event; e.preventDefault(); e.returnValue = returnValue || false; this._wrapper.prevented = 1; this.prevented = 1; }, halt: function(immediate) { if (immediate) { this.stopImmediatePropagation(); } else { this.stopPropagation(); } this.preventDefault(); } }); DOMEventFacade.resolve = resolve; Y.DOM2EventFacade = DOMEventFacade; Y.DOMEventFacade = DOMEventFacade; /** * The native event * @property _event * @type {Native DOM Event} * @private */ /** The name of the event (e.g. "click") @property type @type {String} **/ /** `true` if the "alt" or "option" key is pressed. @property altKey @type {Boolean} **/ /** `true` if the shift key is pressed. @property shiftKey @type {Boolean} **/ /** `true` if the "Windows" key on a Windows keyboard, "command" key on an Apple keyboard, or "meta" key on other keyboards is pressed. @property metaKey @type {Boolean} **/ /** `true` if the "Ctrl" or "control" key is pressed. @property ctrlKey @type {Boolean} **/ /** * The X location of the event on the page (including scroll) * @property pageX * @type {Number} */ /** * The Y location of the event on the page (including scroll) * @property pageY * @type {Number} */ /** * The X location of the event in the viewport * @property clientX * @type {Number} */ /** * The Y location of the event in the viewport * @property clientY * @type {Number} */ /** * The keyCode for key events. Uses charCode if keyCode is not available * @property keyCode * @type {Number} */ /** * The charCode for key events. Same as keyCode * @property charCode * @type {Number} */ /** * The button that was pushed. 1 for left click, 2 for middle click, 3 for * right click. This is only reliably populated on `mouseup` events. * @property button * @type {Number} */ /** * The button that was pushed. Same as button. * @property which * @type {Number} */ /** * Node reference for the targeted element * @property target * @type {Node} */ /** * Node reference for the element that the listener was attached to. * @property currentTarget * @type {Node} */ /** * Node reference to the relatedTarget * @property relatedTarget * @type {Node} */ /** * Number representing the direction and velocity of the movement of the mousewheel. * Negative is down, the higher the number, the faster. Applies to the mousewheel event. * @property wheelDelta * @type {Number} */ /** * Stops the propagation to the next bubble target * @method stopPropagation */ /** * Stops the propagation to the next bubble target and * prevents any additional listeners from being exectued * on the current target. * @method stopImmediatePropagation */ /** * Prevents the event's default behavior * @method preventDefault * @param returnValue {string} sets the returnValue of the event to this value * (rather than the default false value). This can be used to add a customized * confirmation query to the beforeunload event). */ /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ (function() { /** * The event utility provides functions to add and remove event listeners, * event cleansing. It also tries to automatically remove listeners it * registers during the unload event. * @module event * @main event * @submodule event-base */ /** * The event utility provides functions to add and remove event listeners, * event cleansing. It also tries to automatically remove listeners it * registers during the unload event. * * @class Event * @static */ Y.Env.evt.dom_wrappers = {}; Y.Env.evt.dom_map = {}; var YDOM = Y.DOM, _eventenv = Y.Env.evt, config = Y.config, win = config.win, add = YUI.Env.add, remove = YUI.Env.remove, onLoad = function() { YUI.Env.windowLoaded = true; Y.Event._load(); remove(win, "load", onLoad); }, onUnload = function() { Y.Event._unload(); }, EVENT_READY = 'domready', COMPAT_ARG = '~yui|2|compat~', shouldIterate = function(o) { try { // TODO: See if there's a more performant way to return true early on this, for the common case return (o && typeof o !== "string" && Y.Lang.isNumber(o.length) && !o.tagName && !YDOM.isWindow(o)); } catch(ex) { Y.log("collection check failure", "warn", "event"); return false; } }, // aliases to support DOM event subscription clean up when the last // subscriber is detached. deleteAndClean overrides the DOM event's wrapper // CustomEvent _delete method. _ceProtoDelete = Y.CustomEvent.prototype._delete, _deleteAndClean = function(s) { var ret = _ceProtoDelete.apply(this, arguments); if (!this.hasSubs()) { Y.Event._clean(this); } return ret; }, Event = function() { /** * True after the onload event has fired * @property _loadComplete * @type boolean * @static * @private */ var _loadComplete = false, /** * The number of times to poll after window.onload. This number is * increased if additional late-bound handlers are requested after * the page load. * @property _retryCount * @static * @private */ _retryCount = 0, /** * onAvailable listeners * @property _avail * @static * @private */ _avail = [], /** * Custom event wrappers for DOM events. Key is * 'event:' + Element uid stamp + event type * @property _wrappers * @type Y.Event.Custom * @static * @private */ _wrappers = _eventenv.dom_wrappers, _windowLoadKey = null, /** * Custom event wrapper map DOM events. Key is * Element uid stamp. Each item is a hash of custom event * wrappers as provided in the _wrappers collection. This * provides the infrastructure for getListeners. * @property _el_events * @static * @private */ _el_events = _eventenv.dom_map; return { /** * The number of times we should look for elements that are not * in the DOM at the time the event is requested after the document * has been loaded. The default is 1000@amp;40 ms, so it will poll * for 40 seconds or until all outstanding handlers are bound * (whichever comes first). * @property POLL_RETRYS * @type int * @static * @final */ POLL_RETRYS: 1000, /** * The poll interval in milliseconds * @property POLL_INTERVAL * @type int * @static * @final */ POLL_INTERVAL: 40, /** * addListener/removeListener can throw errors in unexpected scenarios. * These errors are suppressed, the method returns false, and this property * is set * @property lastError * @static * @type Error */ lastError: null, /** * poll handle * @property _interval * @static * @private */ _interval: null, /** * document readystate poll handle * @property _dri * @static * @private */ _dri: null, /** * True when the document is initially usable * @property DOMReady * @type boolean * @static */ DOMReady: false, /** * @method startInterval * @static * @private */ startInterval: function() { if (!Event._interval) { Event._interval = setInterval(Event._poll, Event.POLL_INTERVAL); } }, /** * Executes the supplied callback when the item with the supplied * id is found. This is meant to be used to execute behavior as * soon as possible as the page loads. If you use this after the * initial page load it will poll for a fixed time for the element. * The number of times it will poll and the frequency are * configurable. By default it will poll for 10 seconds. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onAvailable * * @param {string||string[]} id the id of the element, or an array * of ids to look for. * @param {function} fn what to execute when the element is found. * @param {object} p_obj an optional object to be passed back as * a parameter to fn. * @param {boolean|object} p_override If set to true, fn will execute * in the context of p_obj, if set to an object it * will execute in the context of that object * @param checkContent {boolean} check child node readiness (onContentReady) * @static * @deprecated Use Y.on("available") */ // @TODO fix arguments onAvailable: function(id, fn, p_obj, p_override, checkContent, compat) { var a = Y.Array(id), i, availHandle; // Y.log('onAvailable registered for: ' + id); for (i=0; i<a.length; i=i+1) { _avail.push({ id: a[i], fn: fn, obj: p_obj, override: p_override, checkReady: checkContent, compat: compat }); } _retryCount = this.POLL_RETRYS; // We want the first test to be immediate, but async setTimeout(Event._poll, 0); availHandle = new Y.EventHandle({ _delete: function() { // set by the event system for lazy DOM listeners if (availHandle.handle) { availHandle.handle.detach(); return; } var i, j; // otherwise try to remove the onAvailable listener(s) for (i = 0; i < a.length; i++) { for (j = 0; j < _avail.length; j++) { if (a[i] === _avail[j].id) { _avail.splice(j, 1); } } } } }); return availHandle; }, /** * Works the same way as onAvailable, but additionally checks the * state of sibling elements to determine if the content of the * available element is safe to modify. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onContentReady * * @param {string} id the id of the element to look for. * @param {function} fn what to execute when the element is ready. * @param {object} obj an optional object to be passed back as * a parameter to fn. * @param {boolean|object} override If set to true, fn will execute * in the context of p_obj. If an object, fn will * exectute in the context of that object * * @static * @deprecated Use Y.on("contentready") */ // @TODO fix arguments onContentReady: function(id, fn, obj, override, compat) { return Event.onAvailable(id, fn, obj, override, true, compat); }, /** * Adds an event listener * * @method attach * * @param {String} type The type of event to append * @param {Function} fn The method the event invokes * @param {String|HTMLElement|Array|NodeList} el An id, an element * reference, or a collection of ids and/or elements to assign the * listener to. * @param {Object} context optional context object * @param {Boolean|object} args 0..n arguments to pass to the callback * @return {EventHandle} an object to that can be used to detach the listener * * @static */ attach: function(type, fn, el, context) { return Event._attach(Y.Array(arguments, 0, true)); }, _createWrapper: function (el, type, capture, compat, facade) { var cewrapper, ek = Y.stamp(el), key = 'event:' + ek + type; if (false === facade) { key += 'native'; } if (capture) { key += 'capture'; } cewrapper = _wrappers[key]; if (!cewrapper) { // create CE wrapper cewrapper = Y.publish(key, { silent: true, bubbles: false, contextFn: function() { if (compat) { return cewrapper.el; } else { cewrapper.nodeRef = cewrapper.nodeRef || Y.one(cewrapper.el); return cewrapper.nodeRef; } } }); cewrapper.overrides = {}; // for later removeListener calls cewrapper.el = el; cewrapper.key = key; cewrapper.domkey = ek; cewrapper.type = type; cewrapper.fn = function(e) { cewrapper.fire(Event.getEvent(e, el, (compat || (false === facade)))); }; cewrapper.capture = capture; if (el == win && type == "load") { // window load happens once cewrapper.fireOnce = true; _windowLoadKey = key; } cewrapper._delete = _deleteAndClean; _wrappers[key] = cewrapper; _el_events[ek] = _el_events[ek] || {}; _el_events[ek][key] = cewrapper; add(el, type, cewrapper.fn, capture); } return cewrapper; }, _attach: function(args, conf) { var compat, handles, oEl, cewrapper, context, fireNow = false, ret, type = args[0], fn = args[1], el = args[2] || win, facade = conf && conf.facade, capture = conf && conf.capture, overrides = conf && conf.overrides; if (args[args.length-1] === COMPAT_ARG) { compat = true; } if (!fn || !fn.call) { // throw new TypeError(type + " attach call failed, callback undefined"); Y.log(type + " attach call failed, invalid callback", "error", "event"); return false; } // The el argument can be an array of elements or element ids. if (shouldIterate(el)) { handles=[]; Y.each(el, function(v, k) { args[2] = v; handles.push(Event._attach(args.slice(), conf)); }); // return (handles.length === 1) ? handles[0] : handles; return new Y.EventHandle(handles); // If the el argument is a string, we assume it is // actually the id of the element. If the page is loaded // we convert el to the actual element, otherwise we // defer attaching the event until the element is // ready } else if (Y.Lang.isString(el)) { // oEl = (compat) ? Y.DOM.byId(el) : Y.Selector.query(el); if (compat) { oEl = YDOM.byId(el); } else { oEl = Y.Selector.query(el); switch (oEl.length) { case 0: oEl = null; break; case 1: oEl = oEl[0]; break; default: args[2] = oEl; return Event._attach(args, conf); } } if (oEl) { el = oEl; // Not found = defer adding the event until the element is available } else { // Y.log(el + ' not found'); ret = Event.onAvailable(el, function() { // Y.log('lazy attach: ' + args); ret.handle = Event._attach(args, conf); }, Event, true, false, compat); return ret; } } // Element should be an html element or node if (!el) { Y.log("unable to attach event " + type, "warn", "event"); return false; } if (Y.Node && Y.instanceOf(el, Y.Node)) { el = Y.Node.getDOMNode(el); } cewrapper = Event._createWrapper(el, type, capture, compat, facade); if (overrides) { Y.mix(cewrapper.overrides, overrides); } if (el == win && type == "load") { // if the load is complete, fire immediately. // all subscribers, including the current one // will be notified. if (YUI.Env.windowLoaded) { fireNow = true; } } if (compat) { args.pop(); } context = args[3]; // set context to the Node if not specified // ret = cewrapper.on.apply(cewrapper, trimmedArgs); ret = cewrapper._on(fn, context, (args.length > 4) ? args.slice(4) : null); if (fireNow) { cewrapper.fire(); } return ret; }, /** * Removes an event listener. Supports the signature the event was bound * with, but the preferred way to remove listeners is using the handle * that is returned when using Y.on * * @method detach * * @param {String} type the type of event to remove. * @param {Function} fn the method the event invokes. If fn is * undefined, then all event handlers for the type of event are * removed. * @param {String|HTMLElement|Array|NodeList|EventHandle} el An * event handle, an id, an element reference, or a collection * of ids and/or elements to remove the listener from. * @return {boolean} true if the unbind was successful, false otherwise. * @static */ detach: function(type, fn, el, obj) { var args=Y.Array(arguments, 0, true), compat, l, ok, i, id, ce; if (args[args.length-1] === COMPAT_ARG) { compat = true; // args.pop(); } if (type && type.detach) { return type.detach(); } // The el argument can be a string if (typeof el == "string") { // el = (compat) ? Y.DOM.byId(el) : Y.all(el); if (compat) { el = YDOM.byId(el); } else { el = Y.Selector.query(el); l = el.length; if (l < 1) { el = null; } else if (l == 1) { el = el[0]; } } // return Event.detach.apply(Event, args); } if (!el) { return false; } if (el.detach) { args.splice(2, 1); return el.detach.apply(el, args); // The el argument can be an array of elements or element ids. } else if (shouldIterate(el)) { ok = true; for (i=0, l=el.length; i<l; ++i) { args[2] = el[i]; ok = ( Y.Event.detach.apply(Y.Event, args) && ok ); } return ok; } if (!type || !fn || !fn.call) { return Event.purgeElement(el, false, type); } id = 'event:' + Y.stamp(el) + type; ce = _wrappers[id]; if (ce) { return ce.detach(fn); } else { return false; } }, /** * Finds the event in the window object, the caller's arguments, or * in the arguments of another method in the callstack. This is * executed automatically for events registered through the event * manager, so the implementer should not normally need to execute * this function at all. * @method getEvent * @param {Event} e the event parameter from the handler * @param {HTMLElement} el the element the listener was attached to * @return {Event} the event * @static */ getEvent: function(e, el, noFacade) { var ev = e || win.event; return (noFacade) ? ev : new Y.DOMEventFacade(ev, el, _wrappers['event:' + Y.stamp(el) + e.type]); }, /** * Generates an unique ID for the element if it does not already * have one. * @method generateId * @param el the element to create the id for * @return {string} the resulting id of the element * @static */ generateId: function(el) { return YDOM.generateID(el); }, /** * We want to be able to use getElementsByTagName as a collection * to attach a group of events to. Unfortunately, different * browsers return different types of collections. This function * tests to determine if the object is array-like. It will also * fail if the object is an array, but is empty. * @method _isValidCollection * @param o the object to test * @return {boolean} true if the object is array-like and populated * @deprecated was not meant to be used directly * @static * @private */ _isValidCollection: shouldIterate, /** * hook up any deferred listeners * @method _load * @static * @private */ _load: function(e) { if (!_loadComplete) { // Y.log('Load Complete', 'info', 'event'); _loadComplete = true; // Just in case DOMReady did not go off for some reason // E._ready(); if (Y.fire) { Y.fire(EVENT_READY); } // Available elements may not have been detected before the // window load event fires. Try to find them now so that the // the user is more likely to get the onAvailable notifications // before the window load notification Event._poll(); } }, /** * Polling function that runs before the onload event fires, * attempting to attach to DOM Nodes as soon as they are * available * @method _poll * @static * @private */ _poll: function() { if (Event.locked) { return; } if (Y.UA.ie && !YUI.Env.DOMReady) { // Hold off if DOMReady has not fired and check current // readyState to protect against the IE operation aborted // issue. Event.startInterval(); return; } Event.locked = true; // Y.log.debug("poll"); // keep trying until after the page is loaded. We need to // check the page load state prior to trying to bind the // elements so that we can be certain all elements have been // tested appropriately var i, len, item, el, notAvail, executeItem, tryAgain = !_loadComplete; if (!tryAgain) { tryAgain = (_retryCount > 0); } // onAvailable notAvail = []; executeItem = function (el, item) { var context, ov = item.override; try { if (item.compat) { if (item.override) { if (ov === true) { context = item.obj; } else { context = ov; } } else { context = el; } item.fn.call(context, item.obj); } else { context = item.obj || Y.one(el); item.fn.apply(context, (Y.Lang.isArray(ov)) ? ov : []); } } catch (e) { Y.log("Error in available or contentReady callback", 'error', 'event'); } }; // onAvailable for (i=0,len=_avail.length; i<len; ++i) { item = _avail[i]; if (item && !item.checkReady) { // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id); el = (item.compat) ? YDOM.byId(item.id) : Y.Selector.query(item.id, null, true); if (el) { // Y.log('avail: ' + el); executeItem(el, item); _avail[i] = null; } else { // Y.log('NOT avail: ' + el); notAvail.push(item); } } } // onContentReady for (i=0,len=_avail.length; i<len; ++i) { item = _avail[i]; if (item && item.checkReady) { // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id); el = (item.compat) ? YDOM.byId(item.id) : Y.Selector.query(item.id, null, true); if (el) { // The element is available, but not necessarily ready // @todo should we test parentNode.nextSibling? if (_loadComplete || (el.get && el.get('nextSibling')) || el.nextSibling) { executeItem(el, item); _avail[i] = null; } } else { notAvail.push(item); } } } _retryCount = (notAvail.length === 0) ? 0 : _retryCount - 1; if (tryAgain) { // we may need to strip the nulled out items here Event.startInterval(); } else { clearInterval(Event._interval); Event._interval = null; } Event.locked = false; return; }, /** * Removes all listeners attached to the given element via addListener. * Optionally, the node's children can also be purged. * Optionally, you can specify a specific type of event to remove. * @method purgeElement * @param {HTMLElement} el the element to purge * @param {boolean} recurse recursively purge this element's children * as well. Use with caution. * @param {string} type optional type of listener to purge. If * left out, all listeners will be removed * @static */ purgeElement: function(el, recurse, type) { // var oEl = (Y.Lang.isString(el)) ? Y.one(el) : el, var oEl = (Y.Lang.isString(el)) ? Y.Selector.query(el, null, true) : el, lis = Event.getListeners(oEl, type), i, len, children, child; if (recurse && oEl) { lis = lis || []; children = Y.Selector.query('*', oEl); len = children.length; for (i = 0; i < len; ++i) { child = Event.getListeners(children[i], type); if (child) { lis = lis.concat(child); } } } if (lis) { for (i = 0, len = lis.length; i < len; ++i) { lis[i].detachAll(); } } }, /** * Removes all object references and the DOM proxy subscription for * a given event for a DOM node. * * @method _clean * @param wrapper {CustomEvent} Custom event proxy for the DOM * subscription * @private * @static * @since 3.4.0 */ _clean: function (wrapper) { var key = wrapper.key, domkey = wrapper.domkey; remove(wrapper.el, wrapper.type, wrapper.fn, wrapper.capture); delete _wrappers[key]; delete Y._yuievt.events[key]; if (_el_events[domkey]) { delete _el_events[domkey][key]; if (!Y.Object.size(_el_events[domkey])) { delete _el_events[domkey]; } } }, /** * Returns all listeners attached to the given element via addListener. * Optionally, you can specify a specific type of event to return. * @method getListeners * @param el {HTMLElement|string} the element or element id to inspect * @param type {string} optional type of listener to return. If * left out, all listeners will be returned * @return {CustomEvent} the custom event wrapper for the DOM event(s) * @static */ getListeners: function(el, type) { var ek = Y.stamp(el, true), evts = _el_events[ek], results=[] , key = (type) ? 'event:' + ek + type : null, adapters = _eventenv.plugins; if (!evts) { return null; } if (key) { // look for synthetic events if (adapters[type] && adapters[type].eventDef) { key += '_synth'; } if (evts[key]) { results.push(evts[key]); } // get native events as well key += 'native'; if (evts[key]) { results.push(evts[key]); } } else { Y.each(evts, function(v, k) { results.push(v); }); } return (results.length) ? results : null; }, /** * Removes all listeners registered by pe.event. Called * automatically during the unload event. * @method _unload * @static * @private */ _unload: function(e) { Y.each(_wrappers, function(v, k) { if (v.type == 'unload') { v.fire(e); } v.detachAll(); }); remove(win, "unload", onUnload); }, /** * Adds a DOM event directly without the caching, cleanup, context adj, etc * * @method nativeAdd * @param {HTMLElement} el the element to bind the handler to * @param {string} type the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ nativeAdd: add, /** * Basic remove listener * * @method nativeRemove * @param {HTMLElement} el the element to bind the handler to * @param {string} type the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ nativeRemove: remove }; }(); Y.Event = Event; if (config.injected || YUI.Env.windowLoaded) { onLoad(); } else { add(win, "load", onLoad); } // Process onAvailable/onContentReady items when when the DOM is ready in IE if (Y.UA.ie) { Y.on(EVENT_READY, Event._poll); } try { add(win, "unload", onUnload); } catch(e) { Y.log("Registering unload listener failed. This is known to happen in Chrome Packaged Apps and Extensions, which don't support unload, and don't provide a way to test for support", "warn", "event-base"); } Event.Custom = Y.CustomEvent; Event.Subscriber = Y.Subscriber; Event.Target = Y.EventTarget; Event.Handle = Y.EventHandle; Event.Facade = Y.EventFacade; Event._poll(); }()); /** * DOM event listener abstraction layer * @module event * @submodule event-base */ /** * Executes the callback as soon as the specified element * is detected in the DOM. This function expects a selector * string for the element(s) to detect. If you already have * an element reference, you don't need this event. * @event available * @param type {string} 'available' * @param fn {function} the callback function to execute. * @param el {string} an selector for the element(s) to attach * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.Env.evt.plugins.available = { on: function(type, fn, id, o) { var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : null; return Y.Event.onAvailable.call(Y.Event, id, fn, o, a); } }; /** * Executes the callback as soon as the specified element * is detected in the DOM with a nextSibling property * (indicating that the element's children are available). * This function expects a selector * string for the element(s) to detect. If you already have * an element reference, you don't need this event. * @event contentready * @param type {string} 'contentready' * @param fn {function} the callback function to execute. * @param el {string} an selector for the element(s) to attach. * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.Env.evt.plugins.contentready = { on: function(type, fn, id, o) { var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : null; return Y.Event.onContentReady.call(Y.Event, id, fn, o, a); } }; }, '@VERSION@', {"requires": ["event-custom-base"]}); (function() { var stateChangeListener, GLOBAL_ENV = YUI.Env, config = YUI.config, doc = config.doc, docElement = doc && doc.documentElement, EVENT_NAME = 'onreadystatechange', pollInterval = config.pollInterval || 40; if (docElement.doScroll && !GLOBAL_ENV._ieready) { GLOBAL_ENV._ieready = function() { GLOBAL_ENV._ready(); }; /*! DOMReady: based on work by: Dean Edwards/John Resig/Matthias Miller/Diego Perini */ // Internet Explorer: use the doScroll() method on the root element. // This isolates what appears to be a safe moment to manipulate the // DOM prior to when the document's readyState suggests it is safe to do so. if (self !== self.top) { stateChangeListener = function() { if (doc.readyState == 'complete') { GLOBAL_ENV.remove(doc, EVENT_NAME, stateChangeListener); GLOBAL_ENV.ieready(); } }; GLOBAL_ENV.add(doc, EVENT_NAME, stateChangeListener); } else { GLOBAL_ENV._dri = setInterval(function() { try { docElement.doScroll('left'); clearInterval(GLOBAL_ENV._dri); GLOBAL_ENV._dri = null; GLOBAL_ENV._ieready(); } catch (domNotReady) { } }, pollInterval); } } })(); YUI.add('event-base-ie', function (Y, NAME) { /* * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event * @submodule event-base */ function IEEventFacade() { // IEEventFacade.superclass.constructor.apply(this, arguments); Y.DOM2EventFacade.apply(this, arguments); } /* * (intentially left out of API docs) * Alternate Facade implementation that is based on Object.defineProperty, which * is partially supported in IE8. Properties that involve setup work are * deferred to temporary getters using the static _define method. */ function IELazyFacade(e) { var proxy = Y.config.doc.createEventObject(e), proto = IELazyFacade.prototype; // TODO: necessary? proxy.hasOwnProperty = function () { return true; }; proxy.init = proto.init; proxy.halt = proto.halt; proxy.preventDefault = proto.preventDefault; proxy.stopPropagation = proto.stopPropagation; proxy.stopImmediatePropagation = proto.stopImmediatePropagation; Y.DOM2EventFacade.apply(proxy, arguments); return proxy; } var imp = Y.config.doc && Y.config.doc.implementation, useLazyFacade = Y.config.lazyEventFacade, buttonMap = { 0: 1, // left click 4: 2, // middle click 2: 3 // right click }, relatedTargetMap = { mouseout: 'toElement', mouseover: 'fromElement' }, resolve = Y.DOM2EventFacade.resolve, proto = { init: function() { IEEventFacade.superclass.init.apply(this, arguments); var e = this._event, x, y, d, b, de, t; this.target = resolve(e.srcElement); if (('clientX' in e) && (!x) && (0 !== x)) { x = e.clientX; y = e.clientY; d = Y.config.doc; b = d.body; de = d.documentElement; x += (de.scrollLeft || (b && b.scrollLeft) || 0); y += (de.scrollTop || (b && b.scrollTop) || 0); this.pageX = x; this.pageY = y; } if (e.type == "mouseout") { t = e.toElement; } else if (e.type == "mouseover") { t = e.fromElement; } // fallback to t.relatedTarget to support simulated events. // IE doesn't support setting toElement or fromElement on generic // events, so Y.Event.simulate sets relatedTarget instead. this.relatedTarget = resolve(t || e.relatedTarget); // which should contain the unicode key code if this is a key event. // For click events, which is normalized for which mouse button was // clicked. this.which = // chained assignment this.button = e.keyCode || buttonMap[e.button] || e.button; }, stopPropagation: function() { this._event.cancelBubble = true; this._wrapper.stopped = 1; this.stopped = 1; }, stopImmediatePropagation: function() { this.stopPropagation(); this._wrapper.stopped = 2; this.stopped = 2; }, preventDefault: function(returnValue) { this._event.returnValue = returnValue || false; this._wrapper.prevented = 1; this.prevented = 1; } }; Y.extend(IEEventFacade, Y.DOM2EventFacade, proto); Y.extend(IELazyFacade, Y.DOM2EventFacade, proto); IELazyFacade.prototype.init = function () { var e = this._event, overrides = this._wrapper.overrides, define = IELazyFacade._define, lazyProperties = IELazyFacade._lazyProperties, prop; this.altKey = e.altKey; this.ctrlKey = e.ctrlKey; this.metaKey = e.metaKey; this.shiftKey = e.shiftKey; this.type = (overrides && overrides.type) || e.type; this.clientX = e.clientX; this.clientY = e.clientY; this.keyCode = // chained assignment this.charCode = e.keyCode; this.which = // chained assignment this.button = e.keyCode || buttonMap[e.button] || e.button; for (prop in lazyProperties) { if (lazyProperties.hasOwnProperty(prop)) { define(this, prop, lazyProperties[prop]); } } if (this._touch) { this._touch(e, this._currentTarget, this._wrapper); } }; IELazyFacade._lazyProperties = { target: function () { return resolve(this._event.srcElement); }, relatedTarget: function () { var e = this._event, targetProp = relatedTargetMap[e.type] || 'relatedTarget'; // fallback to t.relatedTarget to support simulated events. // IE doesn't support setting toElement or fromElement on generic // events, so Y.Event.simulate sets relatedTarget instead. return resolve(e[targetProp] || e.relatedTarget); }, currentTarget: function () { return resolve(this._currentTarget); }, wheelDelta: function () { var e = this._event; if (e.type === "mousewheel" || e.type === "DOMMouseScroll") { return (e.detail) ? (e.detail * -1) : // wheelDelta between -80 and 80 result in -1 or 1 Math.round(e.wheelDelta / 80) || ((e.wheelDelta < 0) ? -1 : 1); } }, pageX: function () { var e = this._event, val = e.pageX, doc, bodyScroll, docScroll; if (val === undefined) { doc = Y.config.doc; bodyScroll = doc.body && doc.body.scrollLeft; docScroll = doc.documentElement.scrollLeft; val = e.clientX + (docScroll || bodyScroll || 0); } return val; }, pageY: function () { var e = this._event, val = e.pageY, doc, bodyScroll, docScroll; if (val === undefined) { doc = Y.config.doc; bodyScroll = doc.body && doc.body.scrollTop; docScroll = doc.documentElement.scrollTop; val = e.clientY + (docScroll || bodyScroll || 0); } return val; } }; /** * Wrapper function for Object.defineProperty that creates a property whose * value will be calulated only when asked for. After calculating the value, * the getter wll be removed, so it will behave as a normal property beyond that * point. A setter is also assigned so assigning to the property will clear * the getter, so foo.prop = 'a'; foo.prop; won't trigger the getter, * overwriting value 'a'. * * Used only by the DOMEventFacades used by IE8 when the YUI configuration * <code>lazyEventFacade</code> is set to true. * * @method _define * @param o {DOMObject} A DOM object to add the property to * @param prop {String} The name of the new property * @param valueFn {Function} The function that will return the initial, default * value for the property. * @static * @private */ IELazyFacade._define = function (o, prop, valueFn) { function val(v) { var ret = (arguments.length) ? v : valueFn.call(this); delete o[prop]; Object.defineProperty(o, prop, { value: ret, configurable: true, writable: true }); return ret; } Object.defineProperty(o, prop, { get: val, set: val, configurable: true }); }; if (imp && (!imp.hasFeature('Events', '2.0'))) { if (useLazyFacade) { // Make sure we can use the lazy facade logic try { Object.defineProperty(Y.config.doc.createEventObject(), 'z', {}); } catch (e) { useLazyFacade = false; } } Y.DOMEventFacade = (useLazyFacade) ? IELazyFacade : IEEventFacade; } }, '@VERSION@', {"requires": ["node-base"]}); YUI.add('pluginhost-base', function (Y, NAME) { /** * Provides the augmentable PluginHost interface, which can be added to any class. * @module pluginhost */ /** * Provides the augmentable PluginHost interface, which can be added to any class. * @module pluginhost-base */ /** * <p> * An augmentable class, which provides the augmented class with the ability to host plugins. * It adds <a href="#method_plug">plug</a> and <a href="#method_unplug">unplug</a> methods to the augmented class, which can * be used to add or remove plugins from instances of the class. * </p> * * <p>Plugins can also be added through the constructor configuration object passed to the host class' constructor using * the "plugins" property. Supported values for the "plugins" property are those defined by the <a href="#method_plug">plug</a> method. * * For example the following code would add the AnimPlugin and IOPlugin to Overlay (the plugin host): * <xmp> * var o = new Overlay({plugins: [ AnimPlugin, {fn:IOPlugin, cfg:{section:"header"}}]}); * </xmp> * </p> * <p> * Plug.Host's protected <a href="#method_initPlugins">_initPlugins</a> and <a href="#method_destroyPlugins">_destroyPlugins</a> * methods should be invoked by the host class at the appropriate point in the host's lifecyle. * </p> * * @class Plugin.Host */ var L = Y.Lang; function PluginHost() { this._plugins = {}; } PluginHost.prototype = { /** * Adds a plugin to the host object. This will instantiate the * plugin and attach it to the configured namespace on the host object. * * @method plug * @chainable * @param P {Function | Object |Array} Accepts the plugin class, or an * object with a "fn" property specifying the plugin class and * a "cfg" property specifying the configuration for the Plugin. * <p> * Additionally an Array can also be passed in, with the above function or * object values, allowing the user to add multiple plugins in a single call. * </p> * @param config (Optional) If the first argument is the plugin class, the second argument * can be the configuration for the plugin. * @return {Base} A reference to the host object */ plug: function(Plugin, config) { var i, ln, ns; if (L.isArray(Plugin)) { for (i = 0, ln = Plugin.length; i < ln; i++) { this.plug(Plugin[i]); } } else { if (Plugin && !L.isFunction(Plugin)) { config = Plugin.cfg; Plugin = Plugin.fn; } // Plugin should be fn by now if (Plugin && Plugin.NS) { ns = Plugin.NS; config = config || {}; config.host = this; if (this.hasPlugin(ns)) { // Update config if (this[ns].setAttrs) { this[ns].setAttrs(config); } else { Y.log("Attempt to replug an already attached plugin, and we can't setAttrs, because it's not Attribute based: " + ns); } } else { // Create new instance this[ns] = new Plugin(config); this._plugins[ns] = Plugin; } } else { Y.log("Attempt to plug in an invalid plugin. Host:" + this + ", Plugin:" + Plugin); } } return this; }, /** * Removes a plugin from the host object. This will destroy the * plugin instance and delete the namespace from the host object. * * @method unplug * @param {String | Function} plugin The namespace of the plugin, or the plugin class with the static NS namespace property defined. If not provided, * all registered plugins are unplugged. * @return {Base} A reference to the host object * @chainable */ unplug: function(plugin) { var ns = plugin, plugins = this._plugins; if (plugin) { if (L.isFunction(plugin)) { ns = plugin.NS; if (ns && (!plugins[ns] || plugins[ns] !== plugin)) { ns = null; } } if (ns) { if (this[ns]) { if (this[ns].destroy) { this[ns].destroy(); } delete this[ns]; } if (plugins[ns]) { delete plugins[ns]; } } } else { for (ns in this._plugins) { if (this._plugins.hasOwnProperty(ns)) { this.unplug(ns); } } } return this; }, /** * Determines if a plugin has plugged into this host. * * @method hasPlugin * @param {String} ns The plugin's namespace * @return {Plugin} Returns a truthy value (the plugin instance) if present, or undefined if not. */ hasPlugin : function(ns) { return (this._plugins[ns] && this[ns]); }, /** * Initializes static plugins registered on the host (using the * Base.plug static method) and any plugins passed to the * instance through the "plugins" configuration property. * * @method _initPlugins * @param {Config} config The configuration object with property name/value pairs. * @private */ _initPlugins: function(config) { this._plugins = this._plugins || {}; if (this._initConfigPlugins) { this._initConfigPlugins(config); } }, /** * Unplugs and destroys all plugins on the host * @method _destroyPlugins * @private */ _destroyPlugins: function() { this.unplug(); } }; Y.namespace("Plugin").Host = PluginHost; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('pluginhost-config', function (Y, NAME) { /** * Adds pluginhost constructor configuration and static configuration support * @submodule pluginhost-config */ var PluginHost = Y.Plugin.Host, L = Y.Lang; /** * A protected initialization method, used by the host class to initialize * plugin configurations passed the constructor, through the config object. * * Host objects should invoke this method at the appropriate time in their * construction lifecycle. * * @method _initConfigPlugins * @param {Object} config The configuration object passed to the constructor * @protected * @for Plugin.Host */ PluginHost.prototype._initConfigPlugins = function(config) { // Class Configuration var classes = (this._getClasses) ? this._getClasses() : [this.constructor], plug = [], unplug = {}, constructor, i, classPlug, classUnplug, pluginClassName; // TODO: Room for optimization. Can we apply statically/unplug in same pass? for (i = classes.length - 1; i >= 0; i--) { constructor = classes[i]; classUnplug = constructor._UNPLUG; if (classUnplug) { // subclasses over-write Y.mix(unplug, classUnplug, true); } classPlug = constructor._PLUG; if (classPlug) { // subclasses over-write Y.mix(plug, classPlug, true); } } for (pluginClassName in plug) { if (plug.hasOwnProperty(pluginClassName)) { if (!unplug[pluginClassName]) { this.plug(plug[pluginClassName]); } } } // User Configuration if (config && config.plugins) { this.plug(config.plugins); } }; /** * Registers plugins to be instantiated at the class level (plugins * which should be plugged into every instance of the class by default). * * @method plug * @static * * @param {Function} hostClass The host class on which to register the plugins * @param {Function | Array} plugin Either the plugin class, an array of plugin classes or an array of objects (with fn and cfg properties defined) * @param {Object} config (Optional) If plugin is the plugin class, the configuration for the plugin * @for Plugin.Host */ PluginHost.plug = function(hostClass, plugin, config) { // Cannot plug into Base, since Plugins derive from Base [ will cause infinite recurrsion ] var p, i, l, name; if (hostClass !== Y.Base) { hostClass._PLUG = hostClass._PLUG || {}; if (!L.isArray(plugin)) { if (config) { plugin = {fn:plugin, cfg:config}; } plugin = [plugin]; } for (i = 0, l = plugin.length; i < l;i++) { p = plugin[i]; name = p.NAME || p.fn.NAME; hostClass._PLUG[name] = p; } } }; /** * Unregisters any class level plugins which have been registered by the host class, or any * other class in the hierarchy. * * @method unplug * @static * * @param {Function} hostClass The host class from which to unregister the plugins * @param {Function | Array} plugin The plugin class, or an array of plugin classes * @for Plugin.Host */ PluginHost.unplug = function(hostClass, plugin) { var p, i, l, name; if (hostClass !== Y.Base) { hostClass._UNPLUG = hostClass._UNPLUG || {}; if (!L.isArray(plugin)) { plugin = [plugin]; } for (i = 0, l = plugin.length; i < l; i++) { p = plugin[i]; name = p.NAME; if (!hostClass._PLUG[name]) { hostClass._UNPLUG[name] = p; } else { delete hostClass._PLUG[name]; } } } }; }, '@VERSION@', {"requires": ["pluginhost-base"]}); YUI.add('event-delegate', function (Y, NAME) { /** * Adds event delegation support to the library. * * @module event * @submodule event-delegate */ var toArray = Y.Array, YLang = Y.Lang, isString = YLang.isString, isObject = YLang.isObject, isArray = YLang.isArray, selectorTest = Y.Selector.test, detachCategories = Y.Env.evt.handles; /** * <p>Sets up event delegation on a container element. The delegated event * will use a supplied selector or filtering function to test if the event * references at least one node that should trigger the subscription * callback.</p> * * <p>Selector string filters will trigger the callback if the event originated * from a node that matches it or is contained in a node that matches it. * Function filters are called for each Node up the parent axis to the * subscribing container node, and receive at each level the Node and the event * object. The function should return true (or a truthy value) if that Node * should trigger the subscription callback. Note, it is possible for filters * to match multiple Nodes for a single event. In this case, the delegate * callback will be executed for each matching Node.</p> * * <p>For each matching Node, the callback will be executed with its 'this' * object set to the Node matched by the filter (unless a specific context was * provided during subscription), and the provided event's * <code>currentTarget</code> will also be set to the matching Node. The * containing Node from which the subscription was originally made can be * referenced as <code>e.container</code>. * * @method delegate * @param type {String} the event type to delegate * @param fn {Function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param el {String|node} the element that is the delegation container * @param filter {string|Function} a selector that must match the target of the * event or a function to test target and its parents for a match * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @static * @for Event */ function delegate(type, fn, el, filter) { var args = toArray(arguments, 0, true), query = isString(el) ? el : null, typeBits, synth, container, categories, cat, i, len, handles, handle; // Support Y.delegate({ click: fnA, key: fnB }, el, filter, ...); // and Y.delegate(['click', 'key'], fn, el, filter, ...); if (isObject(type)) { handles = []; if (isArray(type)) { for (i = 0, len = type.length; i < len; ++i) { args[0] = type[i]; handles.push(Y.delegate.apply(Y, args)); } } else { // Y.delegate({'click', fn}, el, filter) => // Y.delegate('click', fn, el, filter) args.unshift(null); // one arg becomes two; need to make space for (i in type) { if (type.hasOwnProperty(i)) { args[0] = i; args[1] = type[i]; handles.push(Y.delegate.apply(Y, args)); } } } return new Y.EventHandle(handles); } typeBits = type.split(/\|/); if (typeBits.length > 1) { cat = typeBits.shift(); args[0] = type = typeBits.shift(); } synth = Y.Node.DOM_EVENTS[type]; if (isObject(synth) && synth.delegate) { handle = synth.delegate.apply(synth, arguments); } if (!handle) { if (!type || !fn || !el || !filter) { Y.log("delegate requires type, callback, parent, & filter", "warn"); return; } container = (query) ? Y.Selector.query(query, null, true) : el; if (!container && isString(el)) { handle = Y.on('available', function () { Y.mix(handle, Y.delegate.apply(Y, args), true); }, el); } if (!handle && container) { args.splice(2, 2, container); // remove the filter handle = Y.Event._attach(args, { facade: false }); handle.sub.filter = filter; handle.sub._notify = delegate.notifySub; } } if (handle && cat) { categories = detachCategories[cat] || (detachCategories[cat] = {}); categories = categories[type] || (categories[type] = []); categories.push(handle); } return handle; } /** Overrides the <code>_notify</code> method on the normal DOM subscription to inject the filtering logic and only proceed in the case of a match. This method is hosted as a private property of the `delegate` method (e.g. `Y.delegate.notifySub`) @method notifySub @param thisObj {Object} default 'this' object for the callback @param args {Array} arguments passed to the event's <code>fire()</code> @param ce {CustomEvent} the custom event managing the DOM subscriptions for the subscribed event on the subscribing node. @return {Boolean} false if the event was stopped @private @static @since 3.2.0 **/ delegate.notifySub = function (thisObj, args, ce) { // Preserve args for other subscribers args = args.slice(); if (this.args) { args.push.apply(args, this.args); } // Only notify subs if the event occurred on a targeted element var currentTarget = delegate._applyFilter(this.filter, args, ce), //container = e.currentTarget, e, i, len, ret; if (currentTarget) { // Support multiple matches up the the container subtree currentTarget = toArray(currentTarget); // The second arg is the currentTarget, but we'll be reusing this // facade, replacing the currentTarget for each use, so it doesn't // matter what element we seed it with. e = args[0] = new Y.DOMEventFacade(args[0], ce.el, ce); e.container = Y.one(ce.el); for (i = 0, len = currentTarget.length; i < len && !e.stopped; ++i) { e.currentTarget = Y.one(currentTarget[i]); ret = this.fn.apply(this.context || e.currentTarget, args); if (ret === false) { // stop further notifications break; } } return ret; } }; /** Compiles a selector string into a filter function to identify whether Nodes along the parent axis of an event's target should trigger event notification. This function is memoized, so previously compiled filter functions are returned if the same selector string is provided. This function may be useful when defining synthetic events for delegate handling. Hosted as a property of the `delegate` method (e.g. `Y.delegate.compileFilter`). @method compileFilter @param selector {String} the selector string to base the filtration on @return {Function} @since 3.2.0 @static **/ delegate.compileFilter = Y.cached(function (selector) { return function (target, e) { return selectorTest(target._node, selector, (e.currentTarget === e.target) ? null : e.currentTarget._node); }; }); /** Regex to test for disabled elements during filtering. This is only relevant to IE to normalize behavior with other browsers, which swallow events that occur to disabled elements. IE fires the event from the parent element instead of the original target, though it does preserve `event.srcElement` as the disabled element. IE also supports disabled on `<a>`, but the event still bubbles, so it acts more like `e.preventDefault()` plus styling. That issue is not handled here because other browsers fire the event on the `<a>`, so delegate is supported in both cases. @property _disabledRE @type {RegExp} @protected @since 3.8.1 **/ delegate._disabledRE = /^(?:button|input|select|textarea)$/i; /** Walks up the parent axis of an event's target, and tests each element against a supplied filter function. If any Nodes, including the container, satisfy the filter, the delegated callback will be triggered for each. Hosted as a protected property of the `delegate` method (e.g. `Y.delegate._applyFilter`). @method _applyFilter @param filter {Function} boolean function to test for inclusion in event notification @param args {Array} the arguments that would be passed to subscribers @param ce {CustomEvent} the DOM event wrapper @return {Node|Node[]|undefined} The Node or Nodes that satisfy the filter @protected **/ delegate._applyFilter = function (filter, args, ce) { var e = args[0], container = ce.el, // facadeless events in IE, have no e.currentTarget target = e.target || e.srcElement, match = [], isContainer = false; // Resolve text nodes to their containing element if (target.nodeType === 3) { target = target.parentNode; } // For IE. IE propagates events from the parent element of disabled // elements, where other browsers swallow the event entirely. To normalize // this in IE, filtering for matching elements should abort if the target // is a disabled form control. if (target.disabled && delegate._disabledRE.test(target.nodeName)) { return match; } // passing target as the first arg rather than leaving well enough alone // making 'this' in the filter function refer to the target. This is to // support bound filter functions. args.unshift(target); if (isString(filter)) { while (target) { isContainer = (target === container); if (selectorTest(target, filter, (isContainer ? null: container))) { match.push(target); } if (isContainer) { break; } target = target.parentNode; } } else { // filter functions are implementer code and should receive wrappers args[0] = Y.one(target); args[1] = new Y.DOMEventFacade(e, container, ce); while (target) { // filter(target, e, extra args...) - this === target if (filter.apply(args[0], args)) { match.push(target); } if (target === container) { break; } target = target.parentNode; args[0] = Y.one(target); } args[1] = e; // restore the raw DOM event } if (match.length <= 1) { match = match[0]; // single match or undefined } // remove the target args.shift(); return match; }; /** * Sets up event delegation on a container element. The delegated event * will use a supplied filter to test if the callback should be executed. * This filter can be either a selector string or a function that returns * a Node to use as the currentTarget for the event. * * The event object for the delegated event is supplied to the callback * function. It is modified slightly in order to support all properties * that may be needed for event delegation. 'currentTarget' is set to * the element that matched the selector string filter or the Node returned * from the filter function. 'container' is set to the element that the * listener is delegated from (this normally would be the 'currentTarget'). * * Filter functions will be called with the arguments that would be passed to * the callback function, including the event object as the first parameter. * The function should return false (or a falsey value) if the success criteria * aren't met, and the Node to use as the event's currentTarget and 'this' * object if they are. * * @method delegate * @param type {string} the event type to delegate * @param fn {function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param el {string|node} the element that is the delegation container * @param filter {string|function} a selector that must match the target of the * event or a function that returns a Node or false. * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.delegate = Y.Event.delegate = delegate; }, '@VERSION@', {"requires": ["node-base"]}); YUI.add('node-event-delegate', function (Y, NAME) { /** * Functionality to make the node a delegated event container * @module node * @submodule node-event-delegate */ /** * <p>Sets up a delegation listener for an event occurring inside the Node. * The delegated event will be verified against a supplied selector or * filtering function to test if the event references at least one node that * should trigger the subscription callback.</p> * * <p>Selector string filters will trigger the callback if the event originated * from a node that matches it or is contained in a node that matches it. * Function filters are called for each Node up the parent axis to the * subscribing container node, and receive at each level the Node and the event * object. The function should return true (or a truthy value) if that Node * should trigger the subscription callback. Note, it is possible for filters * to match multiple Nodes for a single event. In this case, the delegate * callback will be executed for each matching Node.</p> * * <p>For each matching Node, the callback will be executed with its 'this' * object set to the Node matched by the filter (unless a specific context was * provided during subscription), and the provided event's * <code>currentTarget</code> will also be set to the matching Node. The * containing Node from which the subscription was originally made can be * referenced as <code>e.container</code>. * * @method delegate * @param type {String} the event type to delegate * @param fn {Function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param spec {String|Function} a selector that must match the target of the * event or a function to test target and its parents for a match * @param context {Object} optional argument that specifies what 'this' refers to. * @param args* {any} 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for Node */ Y.Node.prototype.delegate = function(type) { var args = Y.Array(arguments, 0, true), index = (Y.Lang.isObject(type) && !Y.Lang.isArray(type)) ? 1 : 2; args.splice(index, 0, this._node); return Y.delegate.apply(Y, args); }; }, '@VERSION@', {"requires": ["node-base", "event-delegate"]}); YUI.add('node-pluginhost', function (Y, NAME) { /** * @module node * @submodule node-pluginhost */ /** * Registers plugins to be instantiated at the class level (plugins * which should be plugged into every instance of Node by default). * * @method plug * @static * @for Node * @param {Function | Array} plugin Either the plugin class, an array of plugin classes or an array of objects (with fn and cfg properties defined) * @param {Object} config (Optional) If plugin is the plugin class, the configuration for the plugin */ Y.Node.plug = function() { var args = Y.Array(arguments); args.unshift(Y.Node); Y.Plugin.Host.plug.apply(Y.Base, args); return Y.Node; }; /** * Unregisters any class level plugins which have been registered by the Node * * @method unplug * @static * * @param {Function | Array} plugin The plugin class, or an array of plugin classes */ Y.Node.unplug = function() { var args = Y.Array(arguments); args.unshift(Y.Node); Y.Plugin.Host.unplug.apply(Y.Base, args); return Y.Node; }; Y.mix(Y.Node, Y.Plugin.Host, false, null, 1); // allow batching of plug/unplug via NodeList // doesn't use NodeList.importMethod because we need real Nodes (not tmpNode) /** * Adds a plugin to each node in the NodeList. * This will instantiate the plugin and attach it to the configured namespace on each node * @method plug * @for NodeList * @param P {Function | Object |Array} Accepts the plugin class, or an * object with a "fn" property specifying the plugin class and * a "cfg" property specifying the configuration for the Plugin. * <p> * Additionally an Array can also be passed in, with the above function or * object values, allowing the user to add multiple plugins in a single call. * </p> * @param config (Optional) If the first argument is the plugin class, the second argument * can be the configuration for the plugin. * @chainable */ Y.NodeList.prototype.plug = function() { var args = arguments; Y.NodeList.each(this, function(node) { Y.Node.prototype.plug.apply(Y.one(node), args); }); return this; }; /** * Removes a plugin from all nodes in the NodeList. This will destroy the * plugin instance and delete the namespace each node. * @method unplug * @for NodeList * @param {String | Function} plugin The namespace of the plugin, or the plugin class with the static NS namespace property defined. If not provided, * all registered plugins are unplugged. * @chainable */ Y.NodeList.prototype.unplug = function() { var args = arguments; Y.NodeList.each(this, function(node) { Y.Node.prototype.unplug.apply(Y.one(node), args); }); return this; }; }, '@VERSION@', {"requires": ["node-base", "pluginhost"]}); YUI.add('node-screen', function (Y, NAME) { /** * Extended Node interface for managing regions and screen positioning. * Adds support for positioning elements and normalizes window size and scroll detection. * @module node * @submodule node-screen */ // these are all "safe" returns, no wrapping required Y.each([ /** * Returns the inner width of the viewport (exludes scrollbar). * @config winWidth * @for Node * @type {Int} */ 'winWidth', /** * Returns the inner height of the viewport (exludes scrollbar). * @config winHeight * @type {Int} */ 'winHeight', /** * Document width * @config docWidth * @type {Int} */ 'docWidth', /** * Document height * @config docHeight * @type {Int} */ 'docHeight', /** * Pixel distance the page has been scrolled horizontally * @config docScrollX * @type {Int} */ 'docScrollX', /** * Pixel distance the page has been scrolled vertically * @config docScrollY * @type {Int} */ 'docScrollY' ], function(name) { Y.Node.ATTRS[name] = { getter: function() { var args = Array.prototype.slice.call(arguments); args.unshift(Y.Node.getDOMNode(this)); return Y.DOM[name].apply(this, args); } }; } ); Y.Node.ATTRS.scrollLeft = { getter: function() { var node = Y.Node.getDOMNode(this); return ('scrollLeft' in node) ? node.scrollLeft : Y.DOM.docScrollX(node); }, setter: function(val) { var node = Y.Node.getDOMNode(this); if (node) { if ('scrollLeft' in node) { node.scrollLeft = val; } else if (node.document || node.nodeType === 9) { Y.DOM._getWin(node).scrollTo(val, Y.DOM.docScrollY(node)); // scroll window if win or doc } } else { Y.log('unable to set scrollLeft for ' + node, 'error', 'Node'); } } }; Y.Node.ATTRS.scrollTop = { getter: function() { var node = Y.Node.getDOMNode(this); return ('scrollTop' in node) ? node.scrollTop : Y.DOM.docScrollY(node); }, setter: function(val) { var node = Y.Node.getDOMNode(this); if (node) { if ('scrollTop' in node) { node.scrollTop = val; } else if (node.document || node.nodeType === 9) { Y.DOM._getWin(node).scrollTo(Y.DOM.docScrollX(node), val); // scroll window if win or doc } } else { Y.log('unable to set scrollTop for ' + node, 'error', 'Node'); } } }; Y.Node.importMethod(Y.DOM, [ /** * Gets the current position of the node in page coordinates. * @method getXY * @for Node * @return {Array} The XY position of the node */ 'getXY', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setXY * @param {Array} xy Contains X & Y values for new position (coordinates are page-based) * @chainable */ 'setXY', /** * Gets the current position of the node in page coordinates. * @method getX * @return {Int} The X position of the node */ 'getX', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setX * @param {Int} x X value for new position (coordinates are page-based) * @chainable */ 'setX', /** * Gets the current position of the node in page coordinates. * @method getY * @return {Int} The Y position of the node */ 'getY', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setY * @param {Int} y Y value for new position (coordinates are page-based) * @chainable */ 'setY', /** * Swaps the XY position of this node with another node. * @method swapXY * @param {Node | HTMLElement} otherNode The node to swap with. * @chainable */ 'swapXY' ]); /** * @module node * @submodule node-screen */ /** * Returns a region object for the node * @config region * @for Node * @type Node */ Y.Node.ATTRS.region = { getter: function() { var node = this.getDOMNode(), region; if (node && !node.tagName) { if (node.nodeType === 9) { // document node = node.documentElement; } } if (Y.DOM.isWindow(node)) { region = Y.DOM.viewportRegion(node); } else { region = Y.DOM.region(node); } return region; } }; /** * Returns a region object for the node's viewport * @config viewportRegion * @type Node */ Y.Node.ATTRS.viewportRegion = { getter: function() { return Y.DOM.viewportRegion(Y.Node.getDOMNode(this)); } }; Y.Node.importMethod(Y.DOM, 'inViewportRegion'); // these need special treatment to extract 2nd node arg /** * Compares the intersection of the node with another node or region * @method intersect * @for Node * @param {Node|Object} node2 The node or region to compare with. * @param {Object} altRegion An alternate region to use (rather than this node's). * @return {Object} An object representing the intersection of the regions. */ Y.Node.prototype.intersect = function(node2, altRegion) { var node1 = Y.Node.getDOMNode(this); if (Y.instanceOf(node2, Y.Node)) { // might be a region object node2 = Y.Node.getDOMNode(node2); } return Y.DOM.intersect(node1, node2, altRegion); }; /** * Determines whether or not the node is within the giving region. * @method inRegion * @param {Node|Object} node2 The node or region to compare with. * @param {Boolean} all Whether or not all of the node must be in the region. * @param {Object} altRegion An alternate region to use (rather than this node's). * @return {Object} An object representing the intersection of the regions. */ Y.Node.prototype.inRegion = function(node2, all, altRegion) { var node1 = Y.Node.getDOMNode(this); if (Y.instanceOf(node2, Y.Node)) { // might be a region object node2 = Y.Node.getDOMNode(node2); } return Y.DOM.inRegion(node1, node2, all, altRegion); }; }, '@VERSION@', {"requires": ["dom-screen", "node-base"]}); YUI.add('node-style', function (Y, NAME) { (function(Y) { /** * Extended Node interface for managing node styles. * @module node * @submodule node-style */ Y.mix(Y.Node.prototype, { /** * Sets a style property of the node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyle * @param {String} attr The style attribute to set. * @param {String|Number} val The value. * @chainable */ setStyle: function(attr, val) { Y.DOM.setStyle(this._node, attr, val); return this; }, /** * Sets multiple style properties on the node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyles * @param {Object} hash An object literal of property:value pairs. * @chainable */ setStyles: function(hash) { Y.DOM.setStyles(this._node, hash); return this; }, /** * Returns the style's current value. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getStyle * @for Node * @param {String} attr The style attribute to retrieve. * @return {String} The current value of the style property for the element. */ getStyle: function(attr) { return Y.DOM.getStyle(this._node, attr); }, /** * Returns the computed value for the given style property. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getComputedStyle * @param {String} attr The style attribute to retrieve. * @return {String} The computed value of the style property for the element. */ getComputedStyle: function(attr) { return Y.DOM.getComputedStyle(this._node, attr); } }); /** * Returns an array of values for each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getStyle * @for NodeList * @see Node.getStyle * @param {String} attr The style attribute to retrieve. * @return {Array} The current values of the style property for the element. */ /** * Returns an array of the computed value for each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getComputedStyle * @see Node.getComputedStyle * @param {String} attr The style attribute to retrieve. * @return {Array} The computed values for each node. */ /** * Sets a style property on each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyle * @see Node.setStyle * @param {String} attr The style attribute to set. * @param {String|Number} val The value. * @chainable */ /** * Sets multiple style properties on each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyles * @see Node.setStyles * @param {Object} hash An object literal of property:value pairs. * @chainable */ // These are broken out to handle undefined return (avoid false positive for // chainable) Y.NodeList.importMethod(Y.Node.prototype, ['getStyle', 'getComputedStyle', 'setStyle', 'setStyles']); })(Y); }, '@VERSION@', {"requires": ["dom-style", "node-base"]}); YUI.add('querystring-stringify-simple', function (Y, NAME) { /*global Y */ /** * <p>Provides Y.QueryString.stringify method for converting objects to Query Strings. * This is a subset implementation of the full querystring-stringify.</p> * <p>This module provides the bare minimum functionality (encoding a hash of simple values), * without the additional support for nested data structures. Every key-value pair is * encoded by encodeURIComponent.</p> * <p>This module provides a minimalistic way for io to handle single-level objects * as transaction data.</p> * * @module querystring * @submodule querystring-stringify-simple */ var QueryString = Y.namespace("QueryString"), EUC = encodeURIComponent; QueryString.stringify = function (obj, c) { var qs = [], // Default behavior is false; standard key notation. s = c && c.arrayKey ? true : false, key, i, l; for (key in obj) { if (obj.hasOwnProperty(key)) { if (Y.Lang.isArray(obj[key])) { for (i = 0, l = obj[key].length; i < l; i++) { qs.push(EUC(s ? key + '[]' : key) + '=' + EUC(obj[key][i])); } } else { qs.push(EUC(key) + '=' + EUC(obj[key])); } } } return qs.join('&'); }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('io-base', function (Y, NAME) { /** Base IO functionality. Provides basic XHR transport support. @module io @submodule io-base @for IO **/ var // List of events that comprise the IO event lifecycle. EVENTS = ['start', 'complete', 'end', 'success', 'failure', 'progress'], // Whitelist of used XHR response object properties. XHR_PROPS = ['status', 'statusText', 'responseText', 'responseXML'], win = Y.config.win, uid = 0; /** The IO class is a utility that brokers HTTP requests through a simplified interface. Specifically, it allows JavaScript to make HTTP requests to a resource without a page reload. The underlying transport for making same-domain requests is the XMLHttpRequest object. IO can also use Flash, if specified as a transport, for cross-domain requests. @class IO @constructor @param {Object} config Object of EventTarget's publish method configurations used to configure IO's events. **/ function IO (config) { var io = this; io._uid = 'io:' + uid++; io._init(config); Y.io._map[io._uid] = io; } IO.prototype = { //-------------------------------------- // Properties //-------------------------------------- /** * A counter that increments for each transaction. * * @property _id * @private * @type {Number} */ _id: 0, /** * Object of IO HTTP headers sent with each transaction. * * @property _headers * @private * @type {Object} */ _headers: { 'X-Requested-With' : 'XMLHttpRequest' }, /** * Object that stores timeout values for any transaction with a defined * "timeout" configuration property. * * @property _timeout * @private * @type {Object} */ _timeout: {}, //-------------------------------------- // Methods //-------------------------------------- _init: function(config) { var io = this, i, len; io.cfg = config || {}; Y.augment(io, Y.EventTarget); for (i = 0, len = EVENTS.length; i < len; ++i) { // Publish IO global events with configurations, if any. // IO global events are set to broadcast by default. // These events use the "io:" namespace. io.publish('io:' + EVENTS[i], Y.merge({ broadcast: 1 }, config)); // Publish IO transaction events with configurations, if // any. These events use the "io-trn:" namespace. io.publish('io-trn:' + EVENTS[i], config); } }, /** * Method that creates a unique transaction object for each request. * * @method _create * @private * @param {Object} cfg Configuration object subset to determine if * the transaction is an XDR or file upload, * requiring an alternate transport. * @param {Number} id Transaction id * @return {Object} The transaction object */ _create: function(config, id) { var io = this, transaction = { id : Y.Lang.isNumber(id) ? id : io._id++, uid: io._uid }, alt = config.xdr ? config.xdr.use : null, form = config.form && config.form.upload ? 'iframe' : null, use; if (alt === 'native') { // Non-IE and IE >= 10 can use XHR level 2 and not rely on an // external transport. alt = Y.UA.ie && !SUPPORTS_CORS ? 'xdr' : null; // Prevent "pre-flight" OPTIONS request by removing the // `X-Requested-With` HTTP header from CORS requests. This header // can be added back on a per-request basis, if desired. io.setHeader('X-Requested-With'); } use = alt || form; transaction = use ? Y.merge(Y.IO.customTransport(use), transaction) : Y.merge(Y.IO.defaultTransport(), transaction); if (transaction.notify) { config.notify = function (e, t, c) { io.notify(e, t, c); }; } if (!use) { if (win && win.FormData && config.data instanceof win.FormData) { transaction.c.upload.onprogress = function (e) { io.progress(transaction, e, config); }; transaction.c.onload = function (e) { io.load(transaction, e, config); }; transaction.c.onerror = function (e) { io.error(transaction, e, config); }; transaction.upload = true; } } return transaction; }, _destroy: function(transaction) { if (win && !transaction.notify && !transaction.xdr) { if (XHR && !transaction.upload) { transaction.c.onreadystatechange = null; } else if (transaction.upload) { transaction.c.upload.onprogress = null; transaction.c.onload = null; transaction.c.onerror = null; } else if (Y.UA.ie && !transaction.e) { // IE, when using XMLHttpRequest as an ActiveX Object, will throw // a "Type Mismatch" error if the event handler is set to "null". transaction.c.abort(); } } transaction = transaction.c = null; }, /** * Method for creating and firing events. * * @method _evt * @private * @param {String} eventName Event to be published. * @param {Object} transaction Transaction object. * @param {Object} config Configuration data subset for event subscription. */ _evt: function(eventName, transaction, config) { var io = this, params, args = config['arguments'], emitFacade = io.cfg.emitFacade, globalEvent = "io:" + eventName, trnEvent = "io-trn:" + eventName; // Workaround for #2532107 this.detach(trnEvent); if (transaction.e) { transaction.c = { status: 0, statusText: transaction.e }; } // Fire event with parameters or an Event Facade. params = [ emitFacade ? { id: transaction.id, data: transaction.c, cfg: config, 'arguments': args } : transaction.id ]; if (!emitFacade) { if (eventName === EVENTS[0] || eventName === EVENTS[2]) { if (args) { params.push(args); } } else { if (transaction.evt) { params.push(transaction.evt); } else { params.push(transaction.c); } if (args) { params.push(args); } } } params.unshift(globalEvent); // Fire global events. io.fire.apply(io, params); // Fire transaction events, if receivers are defined. if (config.on) { params[0] = trnEvent; io.once(trnEvent, config.on[eventName], config.context || Y); io.fire.apply(io, params); } }, /** * Fires event "io:start" and creates, fires a transaction-specific * start event, if `config.on.start` is defined. * * @method start * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ start: function(transaction, config) { /** * Signals the start of an IO request. * @event io:start */ this._evt(EVENTS[0], transaction, config); }, /** * Fires event "io:complete" and creates, fires a * transaction-specific "complete" event, if config.on.complete is * defined. * * @method complete * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ complete: function(transaction, config) { /** * Signals the completion of the request-response phase of a * transaction. Response status and data are accessible, if * available, in this event. * @event io:complete */ this._evt(EVENTS[1], transaction, config); }, /** * Fires event "io:end" and creates, fires a transaction-specific "end" * event, if config.on.end is defined. * * @method end * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ end: function(transaction, config) { /** * Signals the end of the transaction lifecycle. * @event io:end */ this._evt(EVENTS[2], transaction, config); this._destroy(transaction); }, /** * Fires event "io:success" and creates, fires a transaction-specific * "success" event, if config.on.success is defined. * * @method success * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ success: function(transaction, config) { /** * Signals an HTTP response with status in the 2xx range. * Fires after io:complete. * @event io:success */ this._evt(EVENTS[3], transaction, config); this.end(transaction, config); }, /** * Fires event "io:failure" and creates, fires a transaction-specific * "failure" event, if config.on.failure is defined. * * @method failure * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ failure: function(transaction, config) { /** * Signals an HTTP response with status outside of the 2xx range. * Fires after io:complete. * @event io:failure */ this._evt(EVENTS[4], transaction, config); this.end(transaction, config); }, /** * Fires event "io:progress" and creates, fires a transaction-specific * "progress" event -- for XMLHttpRequest file upload -- if * config.on.progress is defined. * * @method progress * @param {Object} transaction Transaction object. * @param {Object} progress event. * @param {Object} config Configuration object for the transaction. */ progress: function(transaction, e, config) { /** * Signals the interactive state during a file upload transaction. * This event fires after io:start and before io:complete. * @event io:progress */ transaction.evt = e; this._evt(EVENTS[5], transaction, config); }, /** * Fires event "io:complete" and creates, fires a transaction-specific * "complete" event -- for XMLHttpRequest file upload -- if * config.on.complete is defined. * * @method load * @param {Object} transaction Transaction object. * @param {Object} load event. * @param {Object} config Configuration object for the transaction. */ load: function (transaction, e, config) { transaction.evt = e.target; this._evt(EVENTS[1], transaction, config); }, /** * Fires event "io:failure" and creates, fires a transaction-specific * "failure" event -- for XMLHttpRequest file upload -- if * config.on.failure is defined. * * @method error * @param {Object} transaction Transaction object. * @param {Object} error event. * @param {Object} config Configuration object for the transaction. */ error: function (transaction, e, config) { transaction.evt = e; this._evt(EVENTS[4], transaction, config); }, /** * Retry an XDR transaction, using the Flash tranport, if the native * transport fails. * * @method _retry * @private * @param {Object} transaction Transaction object. * @param {String} uri Qualified path to transaction resource. * @param {Object} config Configuration object for the transaction. */ _retry: function(transaction, uri, config) { this._destroy(transaction); config.xdr.use = 'flash'; return this.send(uri, config, transaction.id); }, /** * Method that concatenates string data for HTTP GET transactions. * * @method _concat * @private * @param {String} uri URI or root data. * @param {String} data Data to be concatenated onto URI. * @return {String} */ _concat: function(uri, data) { uri += (uri.indexOf('?') === -1 ? '?' : '&') + data; return uri; }, /** * Stores default client headers for all transactions. If a label is * passed with no value argument, the header will be deleted. * * @method setHeader * @param {String} name HTTP header * @param {String} value HTTP header value */ setHeader: function(name, value) { if (value) { this._headers[name] = value; } else { delete this._headers[name]; } }, /** * Method that sets all HTTP headers to be sent in a transaction. * * @method _setHeaders * @private * @param {Object} transaction - XHR instance for the specific transaction. * @param {Object} headers - HTTP headers for the specific transaction, as * defined in the configuration object passed to YUI.io(). */ _setHeaders: function(transaction, headers) { headers = Y.merge(this._headers, headers); Y.Object.each(headers, function(value, name) { if (value !== 'disable') { transaction.setRequestHeader(name, headers[name]); } }); }, /** * Starts timeout count if the configuration object has a defined * timeout property. * * @method _startTimeout * @private * @param {Object} transaction Transaction object generated by _create(). * @param {Object} timeout Timeout in milliseconds. */ _startTimeout: function(transaction, timeout) { var io = this; io._timeout[transaction.id] = setTimeout(function() { io._abort(transaction, 'timeout'); }, timeout); }, /** * Clears the timeout interval started by _startTimeout(). * * @method _clearTimeout * @private * @param {Number} id - Transaction id. */ _clearTimeout: function(id) { clearTimeout(this._timeout[id]); delete this._timeout[id]; }, /** * Method that determines if a transaction response qualifies as success * or failure, based on the response HTTP status code, and fires the * appropriate success or failure events. * * @method _result * @private * @static * @param {Object} transaction Transaction object generated by _create(). * @param {Object} config Configuration object passed to io(). */ _result: function(transaction, config) { var status; // Firefox will throw an exception if attempting to access // an XHR object's status property, after a request is aborted. try { status = transaction.c.status; } catch(e) { status = 0; } // IE reports HTTP 204 as HTTP 1223. if (status >= 200 && status < 300 || status === 304 || status === 1223) { this.success(transaction, config); } else { this.failure(transaction, config); } }, /** * Event handler bound to onreadystatechange. * * @method _rS * @private * @param {Object} transaction Transaction object generated by _create(). * @param {Object} config Configuration object passed to YUI.io(). */ _rS: function(transaction, config) { var io = this; if (transaction.c.readyState === 4) { if (config.timeout) { io._clearTimeout(transaction.id); } // Yield in the event of request timeout or abort. setTimeout(function() { io.complete(transaction, config); io._result(transaction, config); }, 0); } }, /** * Terminates a transaction due to an explicit abort or timeout. * * @method _abort * @private * @param {Object} transaction Transaction object generated by _create(). * @param {String} type Identifies timed out or aborted transaction. */ _abort: function(transaction, type) { if (transaction && transaction.c) { transaction.e = type; transaction.c.abort(); } }, /** * Requests a transaction. `send()` is implemented as `Y.io()`. Each * transaction may include a configuration object. Its properties are: * * <dl> * <dt>method</dt> * <dd>HTTP method verb (e.g., GET or POST). If this property is not * not defined, the default value will be GET.</dd> * * <dt>data</dt> * <dd>This is the name-value string that will be sent as the * transaction data. If the request is HTTP GET, the data become * part of querystring. If HTTP POST, the data are sent in the * message body.</dd> * * <dt>xdr</dt> * <dd>Defines the transport to be used for cross-domain requests. * By setting this property, the transaction will use the specified * transport instead of XMLHttpRequest. The properties of the * transport object are: * <dl> * <dt>use</dt> * <dd>The transport to be used: 'flash' or 'native'</dd> * <dt>dataType</dt> * <dd>Set the value to 'XML' if that is the expected response * content type.</dd> * </dl></dd> * * <dt>form</dt> * <dd>Form serialization configuration object. Its properties are: * <dl> * <dt>id</dt> * <dd>Node object or id of HTML form</dd> * <dt>useDisabled</dt> * <dd>`true` to also serialize disabled form field values * (defaults to `false`)</dd> * </dl></dd> * * <dt>on</dt> * <dd>Assigns transaction event subscriptions. Available events are: * <dl> * <dt>start</dt> * <dd>Fires when a request is sent to a resource.</dd> * <dt>complete</dt> * <dd>Fires when the transaction is complete.</dd> * <dt>success</dt> * <dd>Fires when the HTTP response status is within the 2xx * range.</dd> * <dt>failure</dt> * <dd>Fires when the HTTP response status is outside the 2xx * range, if an exception occurs, if the transation is aborted, * or if the transaction exceeds a configured `timeout`.</dd> * <dt>end</dt> * <dd>Fires at the conclusion of the transaction * lifecycle, after `success` or `failure`.</dd> * </dl> * * <p>Callback functions for `start` and `end` receive the id of the * transaction as a first argument. For `complete`, `success`, and * `failure`, callbacks receive the id and the response object * (usually the XMLHttpRequest instance). If the `arguments` * property was included in the configuration object passed to * `Y.io()`, the configured data will be passed to all callbacks as * the last argument.</p> * </dd> * * <dt>sync</dt> * <dd>Pass `true` to make a same-domain transaction synchronous. * <strong>CAVEAT</strong>: This will negatively impact the user * experience. Have a <em>very</em> good reason if you intend to use * this.</dd> * * <dt>context</dt> * <dd>The "`this'" object for all configured event handlers. If a * specific context is needed for individual callbacks, bind the * callback to a context using `Y.bind()`.</dd> * * <dt>headers</dt> * <dd>Object map of transaction headers to send to the server. The * object keys are the header names and the values are the header * values.</dd> * * <dt>timeout</dt> * <dd>Millisecond threshold for the transaction before being * automatically aborted.</dd> * * <dt>arguments</dt> * <dd>User-defined data passed to all registered event handlers. * This value is available as the second argument in the "start" and * "end" event handlers. It is the third argument in the "complete", * "success", and "failure" event handlers. <strong>Be sure to quote * this property name in the transaction configuration as * "arguments" is a reserved word in JavaScript</strong> (e.g. * `Y.io({ ..., "arguments": stuff })`).</dd> * </dl> * * @method send * @public * @param {String} uri Qualified path to transaction resource. * @param {Object} config Configuration object for the transaction. * @param {Number} id Transaction id, if already set. * @return {Object} */ send: function(uri, config, id) { var transaction, method, i, len, sync, data, io = this, u = uri, response = {}; config = config ? Y.Object(config) : {}; transaction = io._create(config, id); method = config.method ? config.method.toUpperCase() : 'GET'; sync = config.sync; data = config.data; // Serialize a map object into a key-value string using // querystring-stringify-simple. if ((Y.Lang.isObject(data) && !data.nodeType) && !transaction.upload) { if (Y.QueryString && Y.QueryString.stringify) { Y.log('Stringifying config.data for request', 'info', 'io'); config.data = data = Y.QueryString.stringify(data); } else { Y.log('Failed to stringify config.data object, likely because `querystring-stringify-simple` is missing.', 'warn', 'io'); } } if (config.form) { if (config.form.upload) { // This is a file upload transaction, calling // upload() in io-upload-iframe. return io.upload(transaction, uri, config); } else { // Serialize HTML form data into a key-value string. data = io._serialize(config.form, data); } } if (data) { switch (method) { case 'GET': case 'HEAD': case 'DELETE': u = io._concat(u, data); data = ''; Y.log('HTTP' + method + ' with data. The querystring is: ' + u, 'info', 'io'); break; case 'POST': case 'PUT': // If Content-Type is defined in the configuration object, or // or as a default header, it will be used instead of // 'application/x-www-form-urlencoded; charset=UTF-8' config.headers = Y.merge({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, config.headers); break; } } if (transaction.xdr) { // Route data to io-xdr module for flash and XDomainRequest. return io.xdr(u, transaction, config); } else if (transaction.notify) { // Route data to custom transport return transaction.c.send(transaction, uri, config); } if (!sync && !transaction.upload) { transaction.c.onreadystatechange = function() { io._rS(transaction, config); }; } try { // Determine if request is to be set as // synchronous or asynchronous. transaction.c.open(method, u, !sync, config.username || null, config.password || null); io._setHeaders(transaction.c, config.headers || {}); io.start(transaction, config); // Will work only in browsers that implement the // Cross-Origin Resource Sharing draft. if (config.xdr && config.xdr.credentials && SUPPORTS_CORS) { transaction.c.withCredentials = true; } // Using "null" with HTTP POST will result in a request // with no Content-Length header defined. transaction.c.send(data); if (sync) { // Create a response object for synchronous transactions, // mixing id and arguments properties with the xhr // properties whitelist. for (i = 0, len = XHR_PROPS.length; i < len; ++i) { response[XHR_PROPS[i]] = transaction.c[XHR_PROPS[i]]; } response.getAllResponseHeaders = function() { return transaction.c.getAllResponseHeaders(); }; response.getResponseHeader = function(name) { return transaction.c.getResponseHeader(name); }; io.complete(transaction, config); io._result(transaction, config); return response; } } catch(e) { if (transaction.xdr) { // This exception is usually thrown by browsers // that do not support XMLHttpRequest Level 2. // Retry the request with the XDR transport set // to 'flash'. If the Flash transport is not // initialized or available, the transaction // will resolve to a transport error. return io._retry(transaction, uri, config); } else { io.complete(transaction, config); io._result(transaction, config); } } // If config.timeout is defined, and the request is standard XHR, // initialize timeout polling. if (config.timeout) { io._startTimeout(transaction, config.timeout); Y.log('Configuration timeout set to: ' + config.timeout, 'info', 'io'); } return { id: transaction.id, abort: function() { return transaction.c ? io._abort(transaction, 'abort') : false; }, isInProgress: function() { return transaction.c ? (transaction.c.readyState % 4) : false; }, io: io }; } }; /** Method for initiating an ajax call. The first argument is the url end point for the call. The second argument is an object to configure the transaction and attach event subscriptions. The configuration object supports the following properties: <dl> <dt>method</dt> <dd>HTTP method verb (e.g., GET or POST). If this property is not not defined, the default value will be GET.</dd> <dt>data</dt> <dd>This is the name-value string that will be sent as the transaction data. If the request is HTTP GET, the data become part of querystring. If HTTP POST, the data are sent in the message body.</dd> <dt>xdr</dt> <dd>Defines the transport to be used for cross-domain requests. By setting this property, the transaction will use the specified transport instead of XMLHttpRequest. The properties of the transport object are: <dl> <dt>use</dt> <dd>The transport to be used: 'flash' or 'native'</dd> <dt>dataType</dt> <dd>Set the value to 'XML' if that is the expected response content type.</dd> </dl></dd> <dt>form</dt> <dd>Form serialization configuration object. Its properties are: <dl> <dt>id</dt> <dd>Node object or id of HTML form</dd> <dt>useDisabled</dt> <dd>`true` to also serialize disabled form field values (defaults to `false`)</dd> </dl></dd> <dt>on</dt> <dd>Assigns transaction event subscriptions. Available events are: <dl> <dt>start</dt> <dd>Fires when a request is sent to a resource.</dd> <dt>complete</dt> <dd>Fires when the transaction is complete.</dd> <dt>success</dt> <dd>Fires when the HTTP response status is within the 2xx range.</dd> <dt>failure</dt> <dd>Fires when the HTTP response status is outside the 2xx range, if an exception occurs, if the transation is aborted, or if the transaction exceeds a configured `timeout`.</dd> <dt>end</dt> <dd>Fires at the conclusion of the transaction lifecycle, after `success` or `failure`.</dd> </dl> <p>Callback functions for `start` and `end` receive the id of the transaction as a first argument. For `complete`, `success`, and `failure`, callbacks receive the id and the response object (usually the XMLHttpRequest instance). If the `arguments` property was included in the configuration object passed to `Y.io()`, the configured data will be passed to all callbacks as the last argument.</p> </dd> <dt>sync</dt> <dd>Pass `true` to make a same-domain transaction synchronous. <strong>CAVEAT</strong>: This will negatively impact the user experience. Have a <em>very</em> good reason if you intend to use this.</dd> <dt>context</dt> <dd>The "`this'" object for all configured event handlers. If a specific context is needed for individual callbacks, bind the callback to a context using `Y.bind()`.</dd> <dt>headers</dt> <dd>Object map of transaction headers to send to the server. The object keys are the header names and the values are the header values.</dd> <dt>timeout</dt> <dd>Millisecond threshold for the transaction before being automatically aborted.</dd> <dt>arguments</dt> <dd>User-defined data passed to all registered event handlers. This value is available as the second argument in the "start" and "end" event handlers. It is the third argument in the "complete", "success", and "failure" event handlers. <strong>Be sure to quote this property name in the transaction configuration as "arguments" is a reserved word in JavaScript</strong> (e.g. `Y.io({ ..., "arguments": stuff })`).</dd> </dl> @method io @static @param {String} url qualified path to transaction resource. @param {Object} config configuration object for the transaction. @return {Object} @for YUI **/ Y.io = function(url, config) { // Calling IO through the static interface will use and reuse // an instance of IO. var transaction = Y.io._map['io:0'] || new IO(); return transaction.send.apply(transaction, [url, config]); }; /** Method for setting and deleting IO HTTP headers to be sent with every request. Hosted as a property on the `io` function (e.g. `Y.io.header`). @method header @param {String} name HTTP header @param {String} value HTTP header value @static **/ Y.io.header = function(name, value) { // Calling IO through the static interface will use and reuse // an instance of IO. var transaction = Y.io._map['io:0'] || new IO(); transaction.setHeader(name, value); }; Y.IO = IO; // Map of all IO instances created. Y.io._map = {}; var XHR = win && win.XMLHttpRequest, XDR = win && win.XDomainRequest, AX = win && win.ActiveXObject, // Checks for the presence of the `withCredentials` in an XHR instance // object, which will be present if the environment supports CORS. SUPPORTS_CORS = XHR && 'withCredentials' in (new XMLHttpRequest()); Y.mix(Y.IO, { /** * The ID of the default IO transport, defaults to `xhr` * @property _default * @type {String} * @static */ _default: 'xhr', /** * * @method defaultTransport * @static * @param {String} [id] The transport to set as the default, if empty a new transport is created. * @return {Object} The transport object with a `send` method */ defaultTransport: function(id) { if (id) { Y.log('Setting default IO to: ' + id, 'info', 'io'); Y.IO._default = id; } else { var o = { c: Y.IO.transports[Y.IO._default](), notify: Y.IO._default === 'xhr' ? false : true }; Y.log('Creating default transport: ' + Y.IO._default, 'info', 'io'); return o; } }, /** * An object hash of custom transports available to IO * @property transports * @type {Object} * @static */ transports: { xhr: function () { return XHR ? new XMLHttpRequest() : AX ? new ActiveXObject('Microsoft.XMLHTTP') : null; }, xdr: function () { return XDR ? new XDomainRequest() : null; }, iframe: function () { return {}; }, flash: null, nodejs: null }, /** * Create a custom transport of type and return it's object * @method customTransport * @param {String} id The id of the transport to create. * @static */ customTransport: function(id) { var o = { c: Y.IO.transports[id]() }; o[(id === 'xdr' || id === 'flash') ? 'xdr' : 'notify'] = true; return o; } }); Y.mix(Y.IO.prototype, { /** * Fired from the notify method of the transport which in turn fires * the event on the IO object. * @method notify * @param {String} event The name of the event * @param {Object} transaction The transaction object * @param {Object} config The configuration object for this transaction */ notify: function(event, transaction, config) { var io = this; switch (event) { case 'timeout': case 'abort': case 'transport error': transaction.c = { status: 0, statusText: event }; event = 'failure'; default: io[event].apply(io, [transaction, config]); } } }); }, '@VERSION@', {"requires": ["event-custom-base", "querystring-stringify-simple"]}); YUI.add('json-parse', function (Y, NAME) { var _JSON = Y.config.global.JSON; Y.namespace('JSON').parse = function () { return _JSON.parse.apply(_JSON, arguments); }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('transition', function (Y, NAME) { /** * Provides the transition method for Node. * Transition has no API of its own, but adds the transition method to Node. * * @module transition * @requires node-style */ var CAMEL_VENDOR_PREFIX = '', VENDOR_PREFIX = '', DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', TRANSITION_CAMEL = 'transition', TRANSITION_PROPERTY_CAMEL = 'transitionProperty', TRANSFORM_CAMEL = 'transform', TRANSITION_PROPERTY, TRANSITION_DURATION, TRANSITION_TIMING_FUNCTION, TRANSITION_DELAY, TRANSITION_END, ON_TRANSITION_END, EMPTY_OBJ = {}, VENDORS = [ 'Webkit', 'Moz' ], VENDOR_TRANSITION_END = { Webkit: 'webkitTransitionEnd' }, /** * A class for constructing transition instances. * Adds the "transition" method to Node. * @class Transition * @constructor */ Transition = function() { this.init.apply(this, arguments); }; Transition._toCamel = function(property) { property = property.replace(/-([a-z])/gi, function(m0, m1) { return m1.toUpperCase(); }); return property; }; Transition._toHyphen = function(property) { property = property.replace(/([A-Z]?)([a-z]+)([A-Z]?)/g, function(m0, m1, m2, m3) { var str = ((m1) ? '-' + m1.toLowerCase() : '') + m2; if (m3) { str += '-' + m3.toLowerCase(); } return str; }); return property; }; Transition.SHOW_TRANSITION = 'fadeIn'; Transition.HIDE_TRANSITION = 'fadeOut'; Transition.useNative = false; if ('transition' in DOCUMENT[DOCUMENT_ELEMENT].style) { Transition.useNative = true; Transition.supported = true; // TODO: remove } else { Y.Array.each(VENDORS, function(val) { // then vendor specific var property = val + 'Transition'; if (property in DOCUMENT[DOCUMENT_ELEMENT].style) { CAMEL_VENDOR_PREFIX = val; VENDOR_PREFIX = Transition._toHyphen(val) + '-'; Transition.useNative = true; Transition.supported = true; // TODO: remove Transition._VENDOR_PREFIX = val; } }); } if (CAMEL_VENDOR_PREFIX) { TRANSITION_CAMEL = CAMEL_VENDOR_PREFIX + 'Transition'; TRANSITION_PROPERTY_CAMEL = CAMEL_VENDOR_PREFIX + 'TransitionProperty'; TRANSFORM_CAMEL = CAMEL_VENDOR_PREFIX + 'Transform'; } TRANSITION_PROPERTY = VENDOR_PREFIX + 'transition-property'; TRANSITION_DURATION = VENDOR_PREFIX + 'transition-duration'; TRANSITION_TIMING_FUNCTION = VENDOR_PREFIX + 'transition-timing-function'; TRANSITION_DELAY = VENDOR_PREFIX + 'transition-delay'; TRANSITION_END = 'transitionend'; ON_TRANSITION_END = 'on' + CAMEL_VENDOR_PREFIX.toLowerCase() + 'transitionend'; TRANSITION_END = VENDOR_TRANSITION_END[CAMEL_VENDOR_PREFIX] || TRANSITION_END; Transition.fx = {}; Transition.toggles = {}; Transition._hasEnd = {}; Transition._reKeywords = /^(?:node|duration|iterations|easing|delay|on|onstart|onend)$/i; Y.Node.DOM_EVENTS[TRANSITION_END] = 1; Transition.NAME = 'transition'; Transition.DEFAULT_EASING = 'ease'; Transition.DEFAULT_DURATION = 0.5; Transition.DEFAULT_DELAY = 0; Transition._nodeAttrs = {}; Transition.prototype = { constructor: Transition, init: function(node, config) { var anim = this; anim._node = node; if (!anim._running && config) { anim._config = config; node._transition = anim; // cache for reuse anim._duration = ('duration' in config) ? config.duration: anim.constructor.DEFAULT_DURATION; anim._delay = ('delay' in config) ? config.delay: anim.constructor.DEFAULT_DELAY; anim._easing = config.easing || anim.constructor.DEFAULT_EASING; anim._count = 0; // track number of animated properties anim._running = false; } return anim; }, addProperty: function(prop, config) { var anim = this, node = this._node, uid = Y.stamp(node), nodeInstance = Y.one(node), attrs = Transition._nodeAttrs[uid], computed, compareVal, dur, attr, val; if (!attrs) { attrs = Transition._nodeAttrs[uid] = {}; } attr = attrs[prop]; // might just be a value if (config && config.value !== undefined) { val = config.value; } else if (config !== undefined) { val = config; config = EMPTY_OBJ; } if (typeof val === 'function') { val = val.call(nodeInstance, nodeInstance); } if (attr && attr.transition) { // take control if another transition owns this property if (attr.transition !== anim) { attr.transition._count--; // remapping attr to this transition } } anim._count++; // properties per transition // make 0 async and fire events dur = ((typeof config.duration !== 'undefined') ? config.duration : anim._duration) || 0.0001; attrs[prop] = { value: val, duration: dur, delay: (typeof config.delay !== 'undefined') ? config.delay : anim._delay, easing: config.easing || anim._easing, transition: anim }; // native end event doesnt fire when setting to same value // supplementing with timer // val may be a string or number (height: 0, etc), but computedStyle is always string computed = Y.DOM.getComputedStyle(node, prop); compareVal = (typeof val === 'string') ? computed : parseFloat(computed); if (Transition.useNative && compareVal === val) { setTimeout(function() { anim._onNativeEnd.call(node, { propertyName: prop, elapsedTime: dur }); }, dur * 1000); } }, removeProperty: function(prop) { var anim = this, attrs = Transition._nodeAttrs[Y.stamp(anim._node)]; if (attrs && attrs[prop]) { delete attrs[prop]; anim._count--; } }, initAttrs: function(config) { var attr, node = this._node; if (config.transform && !config[TRANSFORM_CAMEL]) { config[TRANSFORM_CAMEL] = config.transform; delete config.transform; // TODO: copy } for (attr in config) { if (config.hasOwnProperty(attr) && !Transition._reKeywords.test(attr)) { this.addProperty(attr, config[attr]); // when size is auto or % webkit starts from zero instead of computed // (https://bugs.webkit.org/show_bug.cgi?id=16020) // TODO: selective set if (node.style[attr] === '') { Y.DOM.setStyle(node, attr, Y.DOM.getComputedStyle(node, attr)); } } } }, /** * Starts or an animation. * @method run * @chainable * @private */ run: function(callback) { var anim = this, node = anim._node, config = anim._config, data = { type: 'transition:start', config: config }; if (!anim._running) { anim._running = true; if (config.on && config.on.start) { config.on.start.call(Y.one(node), data); } anim.initAttrs(anim._config); anim._callback = callback; anim._start(); } return anim; }, _start: function() { this._runNative(); }, _prepDur: function(dur) { dur = parseFloat(dur) * 1000; return dur + 'ms'; }, _runNative: function() { var anim = this, node = anim._node, uid = Y.stamp(node), style = node.style, computed = node.ownerDocument.defaultView.getComputedStyle(node), attrs = Transition._nodeAttrs[uid], cssText = '', cssTransition = computed[Transition._toCamel(TRANSITION_PROPERTY)], transitionText = TRANSITION_PROPERTY + ': ', duration = TRANSITION_DURATION + ': ', easing = TRANSITION_TIMING_FUNCTION + ': ', delay = TRANSITION_DELAY + ': ', hyphy, attr, name; // preserve existing transitions if (cssTransition !== 'all') { transitionText += cssTransition + ','; duration += computed[Transition._toCamel(TRANSITION_DURATION)] + ','; easing += computed[Transition._toCamel(TRANSITION_TIMING_FUNCTION)] + ','; delay += computed[Transition._toCamel(TRANSITION_DELAY)] + ','; } // run transitions mapped to this instance for (name in attrs) { hyphy = Transition._toHyphen(name); attr = attrs[name]; if ((attr = attrs[name]) && attr.transition === anim) { if (name in node.style) { // only native styles allowed duration += anim._prepDur(attr.duration) + ','; delay += anim._prepDur(attr.delay) + ','; easing += (attr.easing) + ','; transitionText += hyphy + ','; cssText += hyphy + ': ' + attr.value + '; '; } else { this.removeProperty(name); } } } transitionText = transitionText.replace(/,$/, ';'); duration = duration.replace(/,$/, ';'); easing = easing.replace(/,$/, ';'); delay = delay.replace(/,$/, ';'); // only one native end event per node if (!Transition._hasEnd[uid]) { node.addEventListener(TRANSITION_END, anim._onNativeEnd, ''); Transition._hasEnd[uid] = true; } style.cssText += transitionText + duration + easing + delay + cssText; }, _end: function(elapsed) { var anim = this, node = anim._node, callback = anim._callback, config = anim._config, data = { type: 'transition:end', config: config, elapsedTime: elapsed }, nodeInstance = Y.one(node); anim._running = false; anim._callback = null; if (node) { if (config.on && config.on.end) { setTimeout(function() { // IE: allow previous update to finish config.on.end.call(nodeInstance, data); // nested to ensure proper fire order if (callback) { callback.call(nodeInstance, data); } }, 1); } else if (callback) { setTimeout(function() { // IE: allow previous update to finish callback.call(nodeInstance, data); }, 1); } } }, _endNative: function(name) { var node = this._node, value = node.ownerDocument.defaultView.getComputedStyle(node, '')[Transition._toCamel(TRANSITION_PROPERTY)]; name = Transition._toHyphen(name); if (typeof value === 'string') { value = value.replace(new RegExp('(?:^|,\\s)' + name + ',?'), ','); value = value.replace(/^,|,$/, ''); node.style[TRANSITION_CAMEL] = value; } }, _onNativeEnd: function(e) { var node = this, uid = Y.stamp(node), event = e,//e._event, name = Transition._toCamel(event.propertyName), elapsed = event.elapsedTime, attrs = Transition._nodeAttrs[uid], attr = attrs[name], anim = (attr) ? attr.transition : null, data, config; if (anim) { anim.removeProperty(name); anim._endNative(name); config = anim._config[name]; data = { type: 'propertyEnd', propertyName: name, elapsedTime: elapsed, config: config }; if (config && config.on && config.on.end) { config.on.end.call(Y.one(node), data); } if (anim._count <= 0) { // after propertyEnd fires anim._end(elapsed); node.style[TRANSITION_PROPERTY_CAMEL] = ''; // clean up style } } }, destroy: function() { var anim = this, node = anim._node; if (node) { node.removeEventListener(TRANSITION_END, anim._onNativeEnd, false); anim._node = null; } } }; Y.Transition = Transition; Y.TransitionNative = Transition; // TODO: remove /** * Animate one or more css properties to a given value. Requires the "transition" module. * <pre>example usage: * Y.one('#demo').transition({ * duration: 1, // in seconds, default is 0.5 * easing: 'ease-out', // default is 'ease' * delay: '1', // delay start for 1 second, default is 0 * * height: '10px', * width: '10px', * * opacity: { // per property * value: 0, * duration: 2, * delay: 2, * easing: 'ease-in' * } * }); * </pre> * @for Node * @method transition * @param {Object} config An object containing one or more style properties, a duration and an easing. * @param {Function} callback A function to run after the transition has completed. * @chainable */ Y.Node.prototype.transition = function(name, config, callback) { var transitionAttrs = Transition._nodeAttrs[Y.stamp(this._node)], anim = (transitionAttrs) ? transitionAttrs.transition || null : null, fxConfig, prop; if (typeof name === 'string') { // named effect, pull config from registry if (typeof config === 'function') { callback = config; config = null; } fxConfig = Transition.fx[name]; if (config && typeof config !== 'boolean') { config = Y.clone(config); for (prop in fxConfig) { if (fxConfig.hasOwnProperty(prop)) { if (! (prop in config)) { config[prop] = fxConfig[prop]; } } } } else { config = fxConfig; } } else { // name is a config, config is a callback or undefined callback = config; config = name; } if (anim && !anim._running) { anim.init(this, config); } else { anim = new Transition(this._node, config); } anim.run(callback); return this; }; Y.Node.prototype.show = function(name, config, callback) { this._show(); // show prior to transition if (name && Y.Transition) { if (typeof name !== 'string' && !name.push) { // named effect or array of effects supercedes default if (typeof config === 'function') { callback = config; config = name; } name = Transition.SHOW_TRANSITION; } this.transition(name, config, callback); } else if (name && !Y.Transition) { Y.log('unable to transition show; missing transition module', 'warn', 'node'); } return this; }; var _wrapCallBack = function(anim, fn, callback) { return function() { if (fn) { fn.call(anim); } if (callback) { callback.apply(anim._node, arguments); } }; }; Y.Node.prototype.hide = function(name, config, callback) { if (name && Y.Transition) { if (typeof config === 'function') { callback = config; config = null; } callback = _wrapCallBack(this, this._hide, callback); // wrap with existing callback if (typeof name !== 'string' && !name.push) { // named effect or array of effects supercedes default if (typeof config === 'function') { callback = config; config = name; } name = Transition.HIDE_TRANSITION; } this.transition(name, config, callback); } else if (name && !Y.Transition) { Y.log('unable to transition hide; missing transition module', 'warn', 'node'); } else { this._hide(); } return this; }; /** * Animate one or more css properties to a given value. Requires the "transition" module. * <pre>example usage: * Y.all('.demo').transition({ * duration: 1, // in seconds, default is 0.5 * easing: 'ease-out', // default is 'ease' * delay: '1', // delay start for 1 second, default is 0 * * height: '10px', * width: '10px', * * opacity: { // per property * value: 0, * duration: 2, * delay: 2, * easing: 'ease-in' * } * }); * </pre> * @for NodeList * @method transition * @param {Object} config An object containing one or more style properties, a duration and an easing. * @param {Function} callback A function to run after the transition has completed. The callback fires * once per item in the NodeList. * @chainable */ Y.NodeList.prototype.transition = function(config, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { Y.one(node).transition(config, callback); } return this; }; Y.Node.prototype.toggleView = function(name, on, callback) { this._toggles = this._toggles || []; callback = arguments[arguments.length - 1]; if (typeof name === 'boolean') { // no transition, just toggle on = name; name = null; } name = name || Y.Transition.DEFAULT_TOGGLE; if (typeof on === 'undefined' && name in this._toggles) { // reverse current toggle on = ! this._toggles[name]; } on = (on) ? 1 : 0; if (on) { this._show(); } else { callback = _wrapCallBack(this, this._hide, callback); } this._toggles[name] = on; this.transition(Y.Transition.toggles[name][on], callback); return this; }; Y.NodeList.prototype.toggleView = function(name, on, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { Y.one(node).toggleView(name, on, callback); } return this; }; Y.mix(Transition.fx, { fadeOut: { opacity: 0, duration: 0.5, easing: 'ease-out' }, fadeIn: { opacity: 1, duration: 0.5, easing: 'ease-in' }, sizeOut: { height: 0, width: 0, duration: 0.75, easing: 'ease-out' }, sizeIn: { height: function(node) { return node.get('scrollHeight') + 'px'; }, width: function(node) { return node.get('scrollWidth') + 'px'; }, duration: 0.5, easing: 'ease-in', on: { start: function() { var overflow = this.getStyle('overflow'); if (overflow !== 'hidden') { // enable scrollHeight/Width this.setStyle('overflow', 'hidden'); this._transitionOverflow = overflow; } }, end: function() { if (this._transitionOverflow) { // revert overridden value this.setStyle('overflow', this._transitionOverflow); delete this._transitionOverflow; } } } } }); Y.mix(Transition.toggles, { size: ['sizeOut', 'sizeIn'], fade: ['fadeOut', 'fadeIn'] }); Transition.DEFAULT_TOGGLE = 'fade'; }, '@VERSION@', {"requires": ["node-style"]}); YUI.add('selector-css2', function (Y, NAME) { /** * The selector module provides helper methods allowing CSS2 Selectors to be used with DOM elements. * @module dom * @submodule selector-css2 * @for Selector */ /* * Provides helper methods for collecting and filtering DOM elements. */ var PARENT_NODE = 'parentNode', TAG_NAME = 'tagName', ATTRIBUTES = 'attributes', COMBINATOR = 'combinator', PSEUDOS = 'pseudos', Selector = Y.Selector, SelectorCSS2 = { _reRegExpTokens: /([\^\$\?\[\]\*\+\-\.\(\)\|\\])/, SORT_RESULTS: true, // TODO: better detection, document specific _isXML: (function() { var isXML = (Y.config.doc.createElement('div').tagName !== 'DIV'); return isXML; }()), /** * Mapping of shorthand tokens to corresponding attribute selector * @property shorthand * @type object */ shorthand: { '\\#(-?[_a-z0-9]+[-\\w\\uE000]*)': '[id=$1]', '\\.(-?[_a-z]+[-\\w\\uE000]*)': '[className~=$1]' }, /** * List of operators and corresponding boolean functions. * These functions are passed the attribute and the current node's value of the attribute. * @property operators * @type object */ operators: { '': function(node, attr) { return Y.DOM.getAttribute(node, attr) !== ''; }, // Just test for existence of attribute '~=': '(?:^|\\s+){val}(?:\\s+|$)', // space-delimited '|=': '^{val}-?' // optional hyphen-delimited }, pseudos: { 'first-child': function(node) { return Y.DOM._children(node[PARENT_NODE])[0] === node; } }, _bruteQuery: function(selector, root, firstOnly) { var ret = [], nodes = [], tokens = Selector._tokenize(selector), token = tokens[tokens.length - 1], rootDoc = Y.DOM._getDoc(root), child, id, className, tagName; if (token) { // prefilter nodes id = token.id; className = token.className; tagName = token.tagName || '*'; if (root.getElementsByTagName) { // non-IE lacks DOM api on doc frags // try ID first, unless no root.all && root not in document // (root.all works off document, but not getElementById) if (id && (root.all || (root.nodeType === 9 || Y.DOM.inDoc(root)))) { nodes = Y.DOM.allById(id, root); // try className } else if (className) { nodes = root.getElementsByClassName(className); } else { // default to tagName nodes = root.getElementsByTagName(tagName); } } else { // brute getElementsByTagName() child = root.firstChild; while (child) { // only collect HTMLElements // match tag to supplement missing getElementsByTagName if (child.tagName && (tagName === '*' || child.tagName === tagName)) { nodes.push(child); } child = child.nextSibling || child.firstChild; } } if (nodes.length) { ret = Selector._filterNodes(nodes, tokens, firstOnly); } } return ret; }, _filterNodes: function(nodes, tokens, firstOnly) { var i = 0, j, len = tokens.length, n = len - 1, result = [], node = nodes[0], tmpNode = node, getters = Y.Selector.getters, operator, combinator, token, path, pass, value, tests, test; for (i = 0; (tmpNode = node = nodes[i++]);) { n = len - 1; path = null; testLoop: while (tmpNode && tmpNode.tagName) { token = tokens[n]; tests = token.tests; j = tests.length; if (j && !pass) { while ((test = tests[--j])) { operator = test[1]; if (getters[test[0]]) { value = getters[test[0]](tmpNode, test[0]); } else { value = tmpNode[test[0]]; if (test[0] === 'tagName' && !Selector._isXML) { value = value.toUpperCase(); } if (typeof value != 'string' && value !== undefined && value.toString) { value = value.toString(); // coerce for comparison } else if (value === undefined && tmpNode.getAttribute) { // use getAttribute for non-standard attributes value = tmpNode.getAttribute(test[0], 2); // 2 === force string for IE } } if ((operator === '=' && value !== test[2]) || // fast path for equality (typeof operator !== 'string' && // protect against String.test monkey-patch (Moo) operator.test && !operator.test(value)) || // regex test (!operator.test && // protect against RegExp as function (webkit) typeof operator === 'function' && !operator(tmpNode, test[0], test[2]))) { // function test // skip non element nodes or non-matching tags if ((tmpNode = tmpNode[path])) { while (tmpNode && (!tmpNode.tagName || (token.tagName && token.tagName !== tmpNode.tagName)) ) { tmpNode = tmpNode[path]; } } continue testLoop; } } } n--; // move to next token // now that we've passed the test, move up the tree by combinator if (!pass && (combinator = token.combinator)) { path = combinator.axis; tmpNode = tmpNode[path]; // skip non element nodes while (tmpNode && !tmpNode.tagName) { tmpNode = tmpNode[path]; } if (combinator.direct) { // one pass only path = null; } } else { // success if we made it this far result.push(node); if (firstOnly) { return result; } break; } } } node = tmpNode = null; return result; }, combinators: { ' ': { axis: 'parentNode' }, '>': { axis: 'parentNode', direct: true }, '+': { axis: 'previousSibling', direct: true } }, _parsers: [ { name: ATTRIBUTES, re: /^\uE003(-?[a-z]+[\w\-]*)+([~\|\^\$\*!=]=?)?['"]?([^\uE004'"]*)['"]?\uE004/i, fn: function(match, token) { var operator = match[2] || '', operators = Selector.operators, escVal = (match[3]) ? match[3].replace(/\\/g, '') : '', test; // add prefiltering for ID and CLASS if ((match[1] === 'id' && operator === '=') || (match[1] === 'className' && Y.config.doc.documentElement.getElementsByClassName && (operator === '~=' || operator === '='))) { token.prefilter = match[1]; match[3] = escVal; // escape all but ID for prefilter, which may run through QSA (via Dom.allById) token[match[1]] = (match[1] === 'id') ? match[3] : escVal; } // add tests if (operator in operators) { test = operators[operator]; if (typeof test === 'string') { match[3] = escVal.replace(Selector._reRegExpTokens, '\\$1'); test = new RegExp(test.replace('{val}', match[3])); } match[2] = test; } if (!token.last || token.prefilter !== match[1]) { return match.slice(1); } } }, { name: TAG_NAME, re: /^((?:-?[_a-z]+[\w-]*)|\*)/i, fn: function(match, token) { var tag = match[1]; if (!Selector._isXML) { tag = tag.toUpperCase(); } token.tagName = tag; if (tag !== '*' && (!token.last || token.prefilter)) { return [TAG_NAME, '=', tag]; } if (!token.prefilter) { token.prefilter = 'tagName'; } } }, { name: COMBINATOR, re: /^\s*([>+~]|\s)\s*/, fn: function(match, token) { } }, { name: PSEUDOS, re: /^:([\-\w]+)(?:\uE005['"]?([^\uE005]*)['"]?\uE006)*/i, fn: function(match, token) { var test = Selector[PSEUDOS][match[1]]; if (test) { // reorder match array and unescape special chars for tests if (match[2]) { match[2] = match[2].replace(/\\/g, ''); } return [match[2], test]; } else { // selector token not supported (possibly missing CSS3 module) return false; } } } ], _getToken: function(token) { return { tagName: null, id: null, className: null, attributes: {}, combinator: null, tests: [] }; }, /* Break selector into token units per simple selector. Combinator is attached to the previous token. */ _tokenize: function(selector) { selector = selector || ''; selector = Selector._parseSelector(Y.Lang.trim(selector)); var token = Selector._getToken(), // one token per simple selector (left selector holds combinator) query = selector, // original query for debug report tokens = [], // array of tokens found = false, // whether or not any matches were found this pass match, // the regex match test, i, parser; /* Search for selector patterns, store, and strip them from the selector string until no patterns match (invalid selector) or we run out of chars. Multiple attributes and pseudos are allowed, in any order. for example: 'form:first-child[type=button]:not(button)[lang|=en]' */ outer: do { found = false; // reset after full pass for (i = 0; (parser = Selector._parsers[i++]);) { if ( (match = parser.re.exec(selector)) ) { // note assignment if (parser.name !== COMBINATOR ) { token.selector = selector; } selector = selector.replace(match[0], ''); // strip current match from selector if (!selector.length) { token.last = true; } if (Selector._attrFilters[match[1]]) { // convert class to className, etc. match[1] = Selector._attrFilters[match[1]]; } test = parser.fn(match, token); if (test === false) { // selector not supported found = false; break outer; } else if (test) { token.tests.push(test); } if (!selector.length || parser.name === COMBINATOR) { tokens.push(token); token = Selector._getToken(token); if (parser.name === COMBINATOR) { token.combinator = Y.Selector.combinators[match[1]]; } } found = true; } } } while (found && selector.length); if (!found || selector.length) { // not fully parsed Y.log('query: ' + query + ' contains unsupported token in: ' + selector, 'warn', 'Selector'); tokens = []; } return tokens; }, _replaceMarkers: function(selector) { selector = selector.replace(/\[/g, '\uE003'); selector = selector.replace(/\]/g, '\uE004'); selector = selector.replace(/\(/g, '\uE005'); selector = selector.replace(/\)/g, '\uE006'); return selector; }, _replaceShorthand: function(selector) { var shorthand = Y.Selector.shorthand, re; for (re in shorthand) { if (shorthand.hasOwnProperty(re)) { selector = selector.replace(new RegExp(re, 'gi'), shorthand[re]); } } return selector; }, _parseSelector: function(selector) { var replaced = Y.Selector._replaceSelector(selector), selector = replaced.selector; // replace shorthand (".foo, #bar") after pseudos and attrs // to avoid replacing unescaped chars selector = Y.Selector._replaceShorthand(selector); selector = Y.Selector._restore('attr', selector, replaced.attrs); selector = Y.Selector._restore('pseudo', selector, replaced.pseudos); // replace braces and parens before restoring escaped chars // to avoid replacing ecaped markers selector = Y.Selector._replaceMarkers(selector); selector = Y.Selector._restore('esc', selector, replaced.esc); return selector; }, _attrFilters: { 'class': 'className', 'for': 'htmlFor' }, getters: { href: function(node, attr) { return Y.DOM.getAttribute(node, attr); }, id: function(node, attr) { return Y.DOM.getId(node); } } }; Y.mix(Y.Selector, SelectorCSS2, true); Y.Selector.getters.src = Y.Selector.getters.rel = Y.Selector.getters.href; // IE wants class with native queries if (Y.Selector.useNative && Y.config.doc.querySelector) { Y.Selector.shorthand['\\.(-?[_a-z]+[-\\w]*)'] = '[class~=$1]'; } }, '@VERSION@', {"requires": ["selector-native"]}); YUI.add('selector-css3', function (Y, NAME) { /** * The selector css3 module provides support for css3 selectors. * @module dom * @submodule selector-css3 * @for Selector */ /* an+b = get every _a_th node starting at the _b_th 0n+b = no repeat ("0" and "n" may both be omitted (together) , e.g. "0n+1" or "1", not "0+1"), return only the _b_th element 1n+b = get every element starting from b ("1" may may be omitted, e.g. "1n+0" or "n+0" or "n") an+0 = get every _a_th element, "0" may be omitted */ Y.Selector._reNth = /^(?:([\-]?\d*)(n){1}|(odd|even)$)*([\-+]?\d*)$/; Y.Selector._getNth = function(node, expr, tag, reverse) { Y.Selector._reNth.test(expr); var a = parseInt(RegExp.$1, 10), // include every _a_ elements (zero means no repeat, just first _a_) n = RegExp.$2, // "n" oddeven = RegExp.$3, // "odd" or "even" b = parseInt(RegExp.$4, 10) || 0, // start scan from element _b_ result = [], siblings = Y.DOM._children(node.parentNode, tag), op; if (oddeven) { a = 2; // always every other op = '+'; n = 'n'; b = (oddeven === 'odd') ? 1 : 0; } else if ( isNaN(a) ) { a = (n) ? 1 : 0; // start from the first or no repeat } if (a === 0) { // just the first if (reverse) { b = siblings.length - b + 1; } if (siblings[b - 1] === node) { return true; } else { return false; } } else if (a < 0) { reverse = !!reverse; a = Math.abs(a); } if (!reverse) { for (var i = b - 1, len = siblings.length; i < len; i += a) { if ( i >= 0 && siblings[i] === node ) { return true; } } } else { for (var i = siblings.length - b, len = siblings.length; i >= 0; i -= a) { if ( i < len && siblings[i] === node ) { return true; } } } return false; }; Y.mix(Y.Selector.pseudos, { 'root': function(node) { return node === node.ownerDocument.documentElement; }, 'nth-child': function(node, expr) { return Y.Selector._getNth(node, expr); }, 'nth-last-child': function(node, expr) { return Y.Selector._getNth(node, expr, null, true); }, 'nth-of-type': function(node, expr) { return Y.Selector._getNth(node, expr, node.tagName); }, 'nth-last-of-type': function(node, expr) { return Y.Selector._getNth(node, expr, node.tagName, true); }, 'last-child': function(node) { var children = Y.DOM._children(node.parentNode); return children[children.length - 1] === node; }, 'first-of-type': function(node) { return Y.DOM._children(node.parentNode, node.tagName)[0] === node; }, 'last-of-type': function(node) { var children = Y.DOM._children(node.parentNode, node.tagName); return children[children.length - 1] === node; }, 'only-child': function(node) { var children = Y.DOM._children(node.parentNode); return children.length === 1 && children[0] === node; }, 'only-of-type': function(node) { var children = Y.DOM._children(node.parentNode, node.tagName); return children.length === 1 && children[0] === node; }, 'empty': function(node) { return node.childNodes.length === 0; }, 'not': function(node, expr) { return !Y.Selector.test(node, expr); }, 'contains': function(node, expr) { var text = node.innerText || node.textContent || ''; return text.indexOf(expr) > -1; }, 'checked': function(node) { return (node.checked === true || node.selected === true); }, enabled: function(node) { return (node.disabled !== undefined && !node.disabled); }, disabled: function(node) { return (node.disabled); } }); Y.mix(Y.Selector.operators, { '^=': '^{val}', // Match starts with value '$=': '{val}$', // Match ends with value '*=': '{val}' // Match contains value as substring }); Y.Selector.combinators['~'] = { axis: 'previousSibling' }; }, '@VERSION@', {"requires": ["selector-native", "selector-css2"]}); YUI.add('yui-log', function (Y, NAME) { /** * Provides console log capability and exposes a custom event for * console implementations. This module is a `core` YUI module, * <a href="../classes/YUI.html#method_log">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-log */ var INSTANCE = Y, LOGEVENT = 'yui:log', UNDEFINED = 'undefined', LEVELS = { debug: 1, info: 1, warn: 1, error: 1 }; /** * If the 'debug' config is true, a 'yui:log' event will be * dispatched, which the Console widget and anything else * can consume. If the 'useBrowserConsole' config is true, it will * write to the browser console if available. YUI-specific log * messages will only be present in the -debug versions of the * JS files. The build system is supposed to remove log statements * from the raw and minified versions of the files. * * @method log * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.log = function(msg, cat, src, silent) { var bail, excl, incl, m, f, Y = INSTANCE, c = Y.config, publisher = (Y.fire) ? Y : YUI.Env.globalEvents; // suppress log message if the config is off or the event stack // or the event call stack contains a consumer of the yui:log event if (c.debug) { // apply source filters src = src || ""; if (typeof src !== "undefined") { excl = c.logExclude; incl = c.logInclude; if (incl && !(src in incl)) { bail = 1; } else if (incl && (src in incl)) { bail = !incl[src]; } else if (excl && (src in excl)) { bail = excl[src]; } } if (!bail) { if (c.useBrowserConsole) { m = (src) ? src + ': ' + msg : msg; if (Y.Lang.isFunction(c.logFn)) { c.logFn.call(Y, msg, cat, src); } else if (typeof console !== UNDEFINED && console.log) { f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log'; console[f](m); } else if (typeof opera !== UNDEFINED) { opera.postError(m); } } if (publisher && !silent) { if (publisher === Y && (!publisher.getEvent(LOGEVENT))) { publisher.publish(LOGEVENT, { broadcast: 2 }); } publisher.fire(LOGEVENT, { msg: msg, cat: cat, src: src }); } } } return Y; }; /** * Write a system message. This message will be preserved in the * minified and raw versions of the YUI files, unlike log statements. * @method message * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.message = function() { return INSTANCE.log.apply(INSTANCE, arguments); }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('dump', function (Y, NAME) { /** * Returns a simple string representation of the object or array. * Other types of objects will be returned unprocessed. Arrays * are expected to be indexed. Use object notation for * associative arrays. * * If included, the dump method is added to the YUI instance. * * @module dump */ var L = Y.Lang, OBJ = '{...}', FUN = 'f(){...}', COMMA = ', ', ARROW = ' => ', /** * Returns a simple string representation of the object or array. * Other types of objects will be returned unprocessed. Arrays * are expected to be indexed. * * @method dump * @param {Object} o The object to dump. * @param {Number} d How deep to recurse child objects, default 3. * @return {String} the dump result. * @for YUI */ dump = function(o, d) { var i, len, s = [], type = L.type(o); // Cast non-objects to string // Skip dates because the std toString is what we want // Skip HTMLElement-like objects because trying to dump // an element will cause an unhandled exception in FF 2.x if (!L.isObject(o)) { return o + ''; } else if (type == 'date') { return o; } else if (o.nodeType && o.tagName) { return o.tagName + '#' + o.id; } else if (o.document && o.navigator) { return 'window'; } else if (o.location && o.body) { return 'document'; } else if (type == 'function') { return FUN; } // dig into child objects the depth specifed. Default 3 d = (L.isNumber(d)) ? d : 3; // arrays [1, 2, 3] if (type == 'array') { s.push('['); for (i = 0, len = o.length; i < len; i = i + 1) { if (L.isObject(o[i])) { s.push((d > 0) ? L.dump(o[i], d - 1) : OBJ); } else { s.push(o[i]); } s.push(COMMA); } if (s.length > 1) { s.pop(); } s.push(']'); // regexp /foo/ } else if (type == 'regexp') { s.push(o.toString()); // objects {k1 => v1, k2 => v2} } else { s.push('{'); for (i in o) { if (o.hasOwnProperty(i)) { try { s.push(i + ARROW); if (L.isObject(o[i])) { s.push((d > 0) ? L.dump(o[i], d - 1) : OBJ); } else { s.push(o[i]); } s.push(COMMA); } catch (e) { s.push('Error: ' + e.message); } } } if (s.length > 1) { s.pop(); } s.push('}'); } return s.join(''); }; Y.dump = dump; L.dump = dump; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('transition-timer', function (Y, NAME) { /** * Provides the base Transition class, for animating numeric properties. * * @module transition * @submodule transition-timer */ var Transition = Y.Transition; Y.mix(Transition.prototype, { _start: function() { if (Transition.useNative) { this._runNative(); } else { this._runTimer(); } }, _runTimer: function() { var anim = this; anim._initAttrs(); Transition._running[Y.stamp(anim)] = anim; anim._startTime = new Date(); Transition._startTimer(); }, _endTimer: function() { var anim = this; delete Transition._running[Y.stamp(anim)]; anim._startTime = null; }, _runFrame: function() { var t = new Date() - this._startTime; this._runAttrs(t); }, _runAttrs: function(time) { var anim = this, node = anim._node, config = anim._config, uid = Y.stamp(node), attrs = Transition._nodeAttrs[uid], customAttr = Transition.behaviors, done = false, allDone = false, data, name, attribute, setter, elapsed, delay, d, t, i; for (name in attrs) { if ((attribute = attrs[name]) && attribute.transition === anim) { d = attribute.duration; delay = attribute.delay; elapsed = (time - delay) / 1000; t = time; data = { type: 'propertyEnd', propertyName: name, config: config, elapsedTime: elapsed }; setter = (i in customAttr && 'set' in customAttr[i]) ? customAttr[i].set : Transition.DEFAULT_SETTER; done = (t >= d); if (t > d) { t = d; } if (!delay || time >= delay) { setter(anim, name, attribute.from, attribute.to, t - delay, d - delay, attribute.easing, attribute.unit); if (done) { delete attrs[name]; anim._count--; if (config[name] && config[name].on && config[name].on.end) { config[name].on.end.call(Y.one(node), data); } //node.fire('transition:propertyEnd', data); if (!allDone && anim._count <= 0) { allDone = true; anim._end(elapsed); anim._endTimer(); } } } } } }, _initAttrs: function() { var anim = this, customAttr = Transition.behaviors, uid = Y.stamp(anim._node), attrs = Transition._nodeAttrs[uid], attribute, duration, delay, easing, val, name, mTo, mFrom, unit, begin, end; for (name in attrs) { if ((attribute = attrs[name]) && attribute.transition === anim) { duration = attribute.duration * 1000; delay = attribute.delay * 1000; easing = attribute.easing; val = attribute.value; // only allow supported properties if (name in anim._node.style || name in Y.DOM.CUSTOM_STYLES) { begin = (name in customAttr && 'get' in customAttr[name]) ? customAttr[name].get(anim, name) : Transition.DEFAULT_GETTER(anim, name); mFrom = Transition.RE_UNITS.exec(begin); mTo = Transition.RE_UNITS.exec(val); begin = mFrom ? mFrom[1] : begin; end = mTo ? mTo[1] : val; unit = mTo ? mTo[2] : mFrom ? mFrom[2] : ''; // one might be zero TODO: mixed units if (!unit && Transition.RE_DEFAULT_UNIT.test(name)) { unit = Transition.DEFAULT_UNIT; } if (typeof easing === 'string') { if (easing.indexOf('cubic-bezier') > -1) { easing = easing.substring(13, easing.length - 1).split(','); } else if (Transition.easings[easing]) { easing = Transition.easings[easing]; } } attribute.from = Number(begin); attribute.to = Number(end); attribute.unit = unit; attribute.easing = easing; attribute.duration = duration + delay; attribute.delay = delay; } else { delete attrs[name]; anim._count--; } } } }, destroy: function() { this.detachAll(); this._node = null; } }, true); Y.mix(Y.Transition, { _runtimeAttrs: {}, /* * Regex of properties that should use the default unit. * * @property RE_DEFAULT_UNIT * @static */ RE_DEFAULT_UNIT: /^width|height|top|right|bottom|left|margin.*|padding.*|border.*$/i, /* * The default unit to use with properties that pass the RE_DEFAULT_UNIT test. * * @property DEFAULT_UNIT * @static */ DEFAULT_UNIT: 'px', /* * Time in milliseconds passed to setInterval for frame processing * * @property intervalTime * @default 20 * @static */ intervalTime: 20, /* * Bucket for custom getters and setters * * @property behaviors * @static */ behaviors: { left: { get: function(anim, attr) { return Y.DOM._getAttrOffset(anim._node, attr); } } }, /* * The default setter to use when setting object properties. * * @property DEFAULT_SETTER * @static */ DEFAULT_SETTER: function(anim, att, from, to, elapsed, duration, fn, unit) { from = Number(from); to = Number(to); var node = anim._node, val = Transition.cubicBezier(fn, elapsed / duration); val = from + val[0] * (to - from); if (node) { if (att in node.style || att in Y.DOM.CUSTOM_STYLES) { unit = unit || ''; Y.DOM.setStyle(node, att, val + unit); } } else { anim._end(); } }, /* * The default getter to use when getting object properties. * * @property DEFAULT_GETTER * @static */ DEFAULT_GETTER: function(anim, att) { var node = anim._node, val = ''; if (att in node.style || att in Y.DOM.CUSTOM_STYLES) { val = Y.DOM.getComputedStyle(node, att); } return val; }, _startTimer: function() { if (!Transition._timer) { Transition._timer = setInterval(Transition._runFrame, Transition.intervalTime); } }, _stopTimer: function() { clearInterval(Transition._timer); Transition._timer = null; }, /* * Called per Interval to handle each animation frame. * @method _runFrame * @private * @static */ _runFrame: function() { var done = true, anim; for (anim in Transition._running) { if (Transition._running[anim]._runFrame) { done = false; Transition._running[anim]._runFrame(); } } if (done) { Transition._stopTimer(); } }, cubicBezier: function(p, t) { var x0 = 0, y0 = 0, x1 = p[0], y1 = p[1], x2 = p[2], y2 = p[3], x3 = 1, y3 = 0, A = x3 - 3 * x2 + 3 * x1 - x0, B = 3 * x2 - 6 * x1 + 3 * x0, C = 3 * x1 - 3 * x0, D = x0, E = y3 - 3 * y2 + 3 * y1 - y0, F = 3 * y2 - 6 * y1 + 3 * y0, G = 3 * y1 - 3 * y0, H = y0, x = (((A*t) + B)*t + C)*t + D, y = (((E*t) + F)*t + G)*t + H; return [x, y]; }, easings: { ease: [0.25, 0, 1, 0.25], linear: [0, 0, 1, 1], 'ease-in': [0.42, 0, 1, 1], 'ease-out': [0, 0, 0.58, 1], 'ease-in-out': [0.42, 0, 0.58, 1] }, _running: {}, _timer: null, RE_UNITS: /^(-?\d*\.?\d*){1}(em|ex|px|in|cm|mm|pt|pc|%)*$/ }, true); Transition.behaviors.top = Transition.behaviors.bottom = Transition.behaviors.right = Transition.behaviors.left; Y.Transition = Transition; }, '@VERSION@', {"requires": ["transition"]}); YUI.add('yui', function (Y, NAME) { // empty }, '@VERSION@', { "use": [ "yui", "oop", "dom", "event-custom-base", "event-base", "pluginhost", "node", "event-delegate", "io-base", "json-parse", "transition", "selector-css3", "dom-style-ie", "querystring-stringify-simple" ] }); var Y = YUI().use('*');
schoren/cdnjs
ajax/libs/yui/3.9.0pr1/simpleyui/simpleyui-debug.js
JavaScript
mit
650,803
YUI.add('createlink-base', function (Y, NAME) { /** * Adds prompt style link creation. Adds an override for the * <a href="Plugin.ExecCommand.html#method_COMMANDS.createlink">createlink execCommand</a>. * @class Plugin.CreateLinkBase * @static * @submodule createlink-base * @module editor */ var CreateLinkBase = {}; /** * Strings used by the plugin * @property STRINGS * @static */ CreateLinkBase.STRINGS = { /** * String used for the Prompt * @property PROMPT * @static */ PROMPT: 'Please enter the URL for the link to point to:', /** * String used as the default value of the Prompt * @property DEFAULT * @static */ DEFAULT: 'http://' }; Y.namespace('Plugin'); Y.Plugin.CreateLinkBase = CreateLinkBase; Y.mix(Y.Plugin.ExecCommand.COMMANDS, { /** * Override for the createlink method from the <a href="Plugin.CreateLinkBase.html">CreateLinkBase</a> plugin. * @for Plugin.ExecCommand.COMMANDS * @method createlink * @static * @param {String} cmd The command executed: createlink * @return {Node} Node instance of the item touched by this command. */ createlink: function(cmd) { var inst = this.get('host').getInstance(), out, a, sel, holder, url = prompt(CreateLinkBase.STRINGS.PROMPT, CreateLinkBase.STRINGS.DEFAULT); if (url) { holder = inst.config.doc.createElement('div'); url = url.replace(/"/g, '').replace(/'/g, ''); //Remove single & double quotes url = inst.config.doc.createTextNode(url); holder.appendChild(url); url = holder.innerHTML; this.get('host')._execCommand(cmd, url); sel = new inst.EditorSelection(); out = sel.getSelected(); if (!sel.isCollapsed && out.size()) { //We have a selection a = out.item(0).one('a'); if (a) { out.item(0).replace(a); } if (Y.UA.gecko) { if (a.get('parentNode').test('span')) { if (a.get('parentNode').one('br.yui-cursor')) { a.get('parentNode').insert(a, 'before'); } } } } else { //No selection, insert a new node.. this.get('host').execCommand('inserthtml', '<a href="' + url + '">' + url + '</a>'); } } return a; } }); }, '3.18.0', {"requires": ["editor-base"]});
Rich-Harris/cdnjs
ajax/libs/yui/3.18.0/createlink-base/createlink-base.js
JavaScript
mit
2,901
/****************************************************************************** * evtchn.c * * Driver for receiving and demuxing event-channel signals. * * Copyright (c) 2004-2005, K A Fraser * Multi-process extensions Copyright (c) 2004, Steven Smith * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation; or, when distributed * separately from the Linux kernel or incorporated into other * software packages, subject to the following license: * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this source file (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. */ #define pr_fmt(fmt) "xen:" KBUILD_MODNAME ": " fmt #include <linux/module.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/string.h> #include <linux/errno.h> #include <linux/fs.h> #include <linux/miscdevice.h> #include <linux/major.h> #include <linux/proc_fs.h> #include <linux/stat.h> #include <linux/poll.h> #include <linux/irq.h> #include <linux/init.h> #include <linux/mutex.h> #include <linux/cpu.h> #include <linux/mm.h> #include <linux/vmalloc.h> #include <xen/xen.h> #include <xen/events.h> #include <xen/evtchn.h> #include <xen/xen-ops.h> #include <asm/xen/hypervisor.h> struct per_user_data { struct mutex bind_mutex; /* serialize bind/unbind operations */ struct rb_root evtchns; unsigned int nr_evtchns; /* Notification ring, accessed via /dev/xen/evtchn. */ unsigned int ring_size; evtchn_port_t *ring; unsigned int ring_cons, ring_prod, ring_overflow; struct mutex ring_cons_mutex; /* protect against concurrent readers */ spinlock_t ring_prod_lock; /* product against concurrent interrupts */ /* Processes wait on this queue when ring is empty. */ wait_queue_head_t evtchn_wait; struct fasync_struct *evtchn_async_queue; const char *name; domid_t restrict_domid; }; #define UNRESTRICTED_DOMID ((domid_t)-1) struct user_evtchn { struct rb_node node; struct per_user_data *user; unsigned port; bool enabled; }; static evtchn_port_t *evtchn_alloc_ring(unsigned int size) { evtchn_port_t *ring; size_t s = size * sizeof(*ring); ring = kmalloc(s, GFP_KERNEL); if (!ring) ring = vmalloc(s); return ring; } static void evtchn_free_ring(evtchn_port_t *ring) { kvfree(ring); } static unsigned int evtchn_ring_offset(struct per_user_data *u, unsigned int idx) { return idx & (u->ring_size - 1); } static evtchn_port_t *evtchn_ring_entry(struct per_user_data *u, unsigned int idx) { return u->ring + evtchn_ring_offset(u, idx); } static int add_evtchn(struct per_user_data *u, struct user_evtchn *evtchn) { struct rb_node **new = &(u->evtchns.rb_node), *parent = NULL; u->nr_evtchns++; while (*new) { struct user_evtchn *this; this = container_of(*new, struct user_evtchn, node); parent = *new; if (this->port < evtchn->port) new = &((*new)->rb_left); else if (this->port > evtchn->port) new = &((*new)->rb_right); else return -EEXIST; } /* Add new node and rebalance tree. */ rb_link_node(&evtchn->node, parent, new); rb_insert_color(&evtchn->node, &u->evtchns); return 0; } static void del_evtchn(struct per_user_data *u, struct user_evtchn *evtchn) { u->nr_evtchns--; rb_erase(&evtchn->node, &u->evtchns); kfree(evtchn); } static struct user_evtchn *find_evtchn(struct per_user_data *u, unsigned port) { struct rb_node *node = u->evtchns.rb_node; while (node) { struct user_evtchn *evtchn; evtchn = container_of(node, struct user_evtchn, node); if (evtchn->port < port) node = node->rb_left; else if (evtchn->port > port) node = node->rb_right; else return evtchn; } return NULL; } static irqreturn_t evtchn_interrupt(int irq, void *data) { struct user_evtchn *evtchn = data; struct per_user_data *u = evtchn->user; WARN(!evtchn->enabled, "Interrupt for port %d, but apparently not enabled; per-user %p\n", evtchn->port, u); disable_irq_nosync(irq); evtchn->enabled = false; spin_lock(&u->ring_prod_lock); if ((u->ring_prod - u->ring_cons) < u->ring_size) { *evtchn_ring_entry(u, u->ring_prod) = evtchn->port; wmb(); /* Ensure ring contents visible */ if (u->ring_cons == u->ring_prod++) { wake_up_interruptible(&u->evtchn_wait); kill_fasync(&u->evtchn_async_queue, SIGIO, POLL_IN); } } else u->ring_overflow = 1; spin_unlock(&u->ring_prod_lock); return IRQ_HANDLED; } static ssize_t evtchn_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { int rc; unsigned int c, p, bytes1 = 0, bytes2 = 0; struct per_user_data *u = file->private_data; /* Whole number of ports. */ count &= ~(sizeof(evtchn_port_t)-1); if (count == 0) return 0; if (count > PAGE_SIZE) count = PAGE_SIZE; for (;;) { mutex_lock(&u->ring_cons_mutex); rc = -EFBIG; if (u->ring_overflow) goto unlock_out; c = u->ring_cons; p = u->ring_prod; if (c != p) break; mutex_unlock(&u->ring_cons_mutex); if (file->f_flags & O_NONBLOCK) return -EAGAIN; rc = wait_event_interruptible(u->evtchn_wait, u->ring_cons != u->ring_prod); if (rc) return rc; } /* Byte lengths of two chunks. Chunk split (if any) is at ring wrap. */ if (((c ^ p) & u->ring_size) != 0) { bytes1 = (u->ring_size - evtchn_ring_offset(u, c)) * sizeof(evtchn_port_t); bytes2 = evtchn_ring_offset(u, p) * sizeof(evtchn_port_t); } else { bytes1 = (p - c) * sizeof(evtchn_port_t); bytes2 = 0; } /* Truncate chunks according to caller's maximum byte count. */ if (bytes1 > count) { bytes1 = count; bytes2 = 0; } else if ((bytes1 + bytes2) > count) { bytes2 = count - bytes1; } rc = -EFAULT; rmb(); /* Ensure that we see the port before we copy it. */ if (copy_to_user(buf, evtchn_ring_entry(u, c), bytes1) || ((bytes2 != 0) && copy_to_user(&buf[bytes1], &u->ring[0], bytes2))) goto unlock_out; u->ring_cons += (bytes1 + bytes2) / sizeof(evtchn_port_t); rc = bytes1 + bytes2; unlock_out: mutex_unlock(&u->ring_cons_mutex); return rc; } static ssize_t evtchn_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { int rc, i; evtchn_port_t *kbuf = (evtchn_port_t *)__get_free_page(GFP_KERNEL); struct per_user_data *u = file->private_data; if (kbuf == NULL) return -ENOMEM; /* Whole number of ports. */ count &= ~(sizeof(evtchn_port_t)-1); rc = 0; if (count == 0) goto out; if (count > PAGE_SIZE) count = PAGE_SIZE; rc = -EFAULT; if (copy_from_user(kbuf, buf, count) != 0) goto out; mutex_lock(&u->bind_mutex); for (i = 0; i < (count/sizeof(evtchn_port_t)); i++) { unsigned port = kbuf[i]; struct user_evtchn *evtchn; evtchn = find_evtchn(u, port); if (evtchn && !evtchn->enabled) { evtchn->enabled = true; enable_irq(irq_from_evtchn(port)); } } mutex_unlock(&u->bind_mutex); rc = count; out: free_page((unsigned long)kbuf); return rc; } static int evtchn_resize_ring(struct per_user_data *u) { unsigned int new_size; evtchn_port_t *new_ring, *old_ring; /* * Ensure the ring is large enough to capture all possible * events. i.e., one free slot for each bound event. */ if (u->nr_evtchns <= u->ring_size) return 0; if (u->ring_size == 0) new_size = 64; else new_size = 2 * u->ring_size; new_ring = evtchn_alloc_ring(new_size); if (!new_ring) return -ENOMEM; old_ring = u->ring; /* * Access to the ring contents is serialized by either the * prod /or/ cons lock so take both when resizing. */ mutex_lock(&u->ring_cons_mutex); spin_lock_irq(&u->ring_prod_lock); /* * Copy the old ring contents to the new ring. * * To take care of wrapping, a full ring, and the new index * pointing into the second half, simply copy the old contents * twice. * * +---------+ +------------------+ * |34567 12| -> |34567 1234567 12| * +-----p-c-+ +-------c------p---+ */ memcpy(new_ring, old_ring, u->ring_size * sizeof(*u->ring)); memcpy(new_ring + u->ring_size, old_ring, u->ring_size * sizeof(*u->ring)); u->ring = new_ring; u->ring_size = new_size; spin_unlock_irq(&u->ring_prod_lock); mutex_unlock(&u->ring_cons_mutex); evtchn_free_ring(old_ring); return 0; } static int evtchn_bind_to_user(struct per_user_data *u, int port) { struct user_evtchn *evtchn; struct evtchn_close close; int rc = 0; /* * Ports are never reused, so every caller should pass in a * unique port. * * (Locking not necessary because we haven't registered the * interrupt handler yet, and our caller has already * serialized bind operations.) */ evtchn = kzalloc(sizeof(*evtchn), GFP_KERNEL); if (!evtchn) return -ENOMEM; evtchn->user = u; evtchn->port = port; evtchn->enabled = true; /* start enabled */ rc = add_evtchn(u, evtchn); if (rc < 0) goto err; rc = evtchn_resize_ring(u); if (rc < 0) goto err; rc = bind_evtchn_to_irqhandler(port, evtchn_interrupt, 0, u->name, evtchn); if (rc < 0) goto err; rc = evtchn_make_refcounted(port); return rc; err: /* bind failed, should close the port now */ close.port = port; if (HYPERVISOR_event_channel_op(EVTCHNOP_close, &close) != 0) BUG(); del_evtchn(u, evtchn); return rc; } static void evtchn_unbind_from_user(struct per_user_data *u, struct user_evtchn *evtchn) { int irq = irq_from_evtchn(evtchn->port); BUG_ON(irq < 0); unbind_from_irqhandler(irq, evtchn); del_evtchn(u, evtchn); } static long evtchn_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { int rc; struct per_user_data *u = file->private_data; void __user *uarg = (void __user *) arg; /* Prevent bind from racing with unbind */ mutex_lock(&u->bind_mutex); switch (cmd) { case IOCTL_EVTCHN_BIND_VIRQ: { struct ioctl_evtchn_bind_virq bind; struct evtchn_bind_virq bind_virq; rc = -EACCES; if (u->restrict_domid != UNRESTRICTED_DOMID) break; rc = -EFAULT; if (copy_from_user(&bind, uarg, sizeof(bind))) break; bind_virq.virq = bind.virq; bind_virq.vcpu = xen_vcpu_nr(0); rc = HYPERVISOR_event_channel_op(EVTCHNOP_bind_virq, &bind_virq); if (rc != 0) break; rc = evtchn_bind_to_user(u, bind_virq.port); if (rc == 0) rc = bind_virq.port; break; } case IOCTL_EVTCHN_BIND_INTERDOMAIN: { struct ioctl_evtchn_bind_interdomain bind; struct evtchn_bind_interdomain bind_interdomain; rc = -EFAULT; if (copy_from_user(&bind, uarg, sizeof(bind))) break; rc = -EACCES; if (u->restrict_domid != UNRESTRICTED_DOMID && u->restrict_domid != bind.remote_domain) break; bind_interdomain.remote_dom = bind.remote_domain; bind_interdomain.remote_port = bind.remote_port; rc = HYPERVISOR_event_channel_op(EVTCHNOP_bind_interdomain, &bind_interdomain); if (rc != 0) break; rc = evtchn_bind_to_user(u, bind_interdomain.local_port); if (rc == 0) rc = bind_interdomain.local_port; break; } case IOCTL_EVTCHN_BIND_UNBOUND_PORT: { struct ioctl_evtchn_bind_unbound_port bind; struct evtchn_alloc_unbound alloc_unbound; rc = -EACCES; if (u->restrict_domid != UNRESTRICTED_DOMID) break; rc = -EFAULT; if (copy_from_user(&bind, uarg, sizeof(bind))) break; alloc_unbound.dom = DOMID_SELF; alloc_unbound.remote_dom = bind.remote_domain; rc = HYPERVISOR_event_channel_op(EVTCHNOP_alloc_unbound, &alloc_unbound); if (rc != 0) break; rc = evtchn_bind_to_user(u, alloc_unbound.port); if (rc == 0) rc = alloc_unbound.port; break; } case IOCTL_EVTCHN_UNBIND: { struct ioctl_evtchn_unbind unbind; struct user_evtchn *evtchn; rc = -EFAULT; if (copy_from_user(&unbind, uarg, sizeof(unbind))) break; rc = -EINVAL; if (unbind.port >= xen_evtchn_nr_channels()) break; rc = -ENOTCONN; evtchn = find_evtchn(u, unbind.port); if (!evtchn) break; disable_irq(irq_from_evtchn(unbind.port)); evtchn_unbind_from_user(u, evtchn); rc = 0; break; } case IOCTL_EVTCHN_NOTIFY: { struct ioctl_evtchn_notify notify; struct user_evtchn *evtchn; rc = -EFAULT; if (copy_from_user(&notify, uarg, sizeof(notify))) break; rc = -ENOTCONN; evtchn = find_evtchn(u, notify.port); if (evtchn) { notify_remote_via_evtchn(notify.port); rc = 0; } break; } case IOCTL_EVTCHN_RESET: { /* Initialise the ring to empty. Clear errors. */ mutex_lock(&u->ring_cons_mutex); spin_lock_irq(&u->ring_prod_lock); u->ring_cons = u->ring_prod = u->ring_overflow = 0; spin_unlock_irq(&u->ring_prod_lock); mutex_unlock(&u->ring_cons_mutex); rc = 0; break; } case IOCTL_EVTCHN_RESTRICT_DOMID: { struct ioctl_evtchn_restrict_domid ierd; rc = -EACCES; if (u->restrict_domid != UNRESTRICTED_DOMID) break; rc = -EFAULT; if (copy_from_user(&ierd, uarg, sizeof(ierd))) break; rc = -EINVAL; if (ierd.domid == 0 || ierd.domid >= DOMID_FIRST_RESERVED) break; u->restrict_domid = ierd.domid; rc = 0; break; } default: rc = -ENOSYS; break; } mutex_unlock(&u->bind_mutex); return rc; } static unsigned int evtchn_poll(struct file *file, poll_table *wait) { unsigned int mask = POLLOUT | POLLWRNORM; struct per_user_data *u = file->private_data; poll_wait(file, &u->evtchn_wait, wait); if (u->ring_cons != u->ring_prod) mask |= POLLIN | POLLRDNORM; if (u->ring_overflow) mask = POLLERR; return mask; } static int evtchn_fasync(int fd, struct file *filp, int on) { struct per_user_data *u = filp->private_data; return fasync_helper(fd, filp, on, &u->evtchn_async_queue); } static int evtchn_open(struct inode *inode, struct file *filp) { struct per_user_data *u; u = kzalloc(sizeof(*u), GFP_KERNEL); if (u == NULL) return -ENOMEM; u->name = kasprintf(GFP_KERNEL, "evtchn:%s", current->comm); if (u->name == NULL) { kfree(u); return -ENOMEM; } init_waitqueue_head(&u->evtchn_wait); mutex_init(&u->bind_mutex); mutex_init(&u->ring_cons_mutex); spin_lock_init(&u->ring_prod_lock); u->restrict_domid = UNRESTRICTED_DOMID; filp->private_data = u; return nonseekable_open(inode, filp); } static int evtchn_release(struct inode *inode, struct file *filp) { struct per_user_data *u = filp->private_data; struct rb_node *node; while ((node = u->evtchns.rb_node)) { struct user_evtchn *evtchn; evtchn = rb_entry(node, struct user_evtchn, node); disable_irq(irq_from_evtchn(evtchn->port)); evtchn_unbind_from_user(u, evtchn); } evtchn_free_ring(u->ring); kfree(u->name); kfree(u); return 0; } static const struct file_operations evtchn_fops = { .owner = THIS_MODULE, .read = evtchn_read, .write = evtchn_write, .unlocked_ioctl = evtchn_ioctl, .poll = evtchn_poll, .fasync = evtchn_fasync, .open = evtchn_open, .release = evtchn_release, .llseek = no_llseek, }; static struct miscdevice evtchn_miscdev = { .minor = MISC_DYNAMIC_MINOR, .name = "xen/evtchn", .fops = &evtchn_fops, }; static int __init evtchn_init(void) { int err; if (!xen_domain()) return -ENODEV; /* Create '/dev/xen/evtchn'. */ err = misc_register(&evtchn_miscdev); if (err != 0) { pr_err("Could not register /dev/xen/evtchn\n"); return err; } pr_info("Event-channel device installed\n"); return 0; } static void __exit evtchn_cleanup(void) { misc_deregister(&evtchn_miscdev); } module_init(evtchn_init); module_exit(evtchn_cleanup); MODULE_LICENSE("GPL");
dperezde/little-penguin
linux/drivers/xen/evtchn.c
C
gpl-2.0
16,434
/* Copyright (c) 2011-2012, 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. */ #ifndef _LINUX_SLIMBUS_H #define _LINUX_SLIMBUS_H #include <linux/module.h> #include <linux/device.h> #include <linux/mutex.h> #include <linux/mod_devicetable.h> /* Interfaces between SLIMbus manager drivers and SLIMbus infrastructure. */ extern struct bus_type slimbus_type; /* Standard values per SLIMbus spec needed by controllers and devices */ #define SLIM_CL_PER_SUPERFRAME 6144 #define SLIM_CL_PER_SUPERFRAME_DIV8 (SLIM_CL_PER_SUPERFRAME >> 3) #define SLIM_MAX_CLK_GEAR 10 #define SLIM_MIN_CLK_GEAR 1 #define SLIM_CL_PER_SL 4 #define SLIM_SL_PER_SUPERFRAME (SLIM_CL_PER_SUPERFRAME >> 2) #define SLIM_FRM_SLOTS_PER_SUPERFRAME 16 #define SLIM_GDE_SLOTS_PER_SUPERFRAME 2 /* * SLIMbus message types. Related to interpretation of message code. * Values are defined in Table 32 (slimbus spec 1.01.01) */ #define SLIM_MSG_MT_CORE 0x0 #define SLIM_MSG_MT_DEST_REFERRED_CLASS 0x1 #define SLIM_MSG_MT_DEST_REFERRED_USER 0x2 #define SLIM_MSG_MT_SRC_REFERRED_CLASS 0x5 #define SLIM_MSG_MT_SRC_REFERRED_USER 0x6 /* * SLIMbus core type Message Codes. * Values are defined in Table 65 (slimbus spec 1.01.01) */ /* Device management messages */ #define SLIM_MSG_MC_REPORT_PRESENT 0x1 #define SLIM_MSG_MC_ASSIGN_LOGICAL_ADDRESS 0x2 #define SLIM_MSG_MC_RESET_DEVICE 0x4 #define SLIM_MSG_MC_CHANGE_LOGICAL_ADDRESS 0x8 #define SLIM_MSG_MC_CHANGE_ARBITRATION_PRIORITY 0x9 #define SLIM_MSG_MC_REQUEST_SELF_ANNOUNCEMENT 0xC #define SLIM_MSG_MC_REPORT_ABSENT 0xF /* Data channel management messages */ #define SLIM_MSG_MC_CONNECT_SOURCE 0x10 #define SLIM_MSG_MC_CONNECT_SINK 0x11 #define SLIM_MSG_MC_DISCONNECT_PORT 0x14 #define SLIM_MSG_MC_CHANGE_CONTENT 0x18 /* Information management messages */ #define SLIM_MSG_MC_REQUEST_INFORMATION 0x20 #define SLIM_MSG_MC_REQUEST_CLEAR_INFORMATION 0x21 #define SLIM_MSG_MC_REPLY_INFORMATION 0x24 #define SLIM_MSG_MC_CLEAR_INFORMATION 0x28 #define SLIM_MSG_MC_REPORT_INFORMATION 0x29 /* Reconfiguration messages */ #define SLIM_MSG_MC_BEGIN_RECONFIGURATION 0x40 #define SLIM_MSG_MC_NEXT_ACTIVE_FRAMER 0x44 #define SLIM_MSG_MC_NEXT_SUBFRAME_MODE 0x45 #define SLIM_MSG_MC_NEXT_CLOCK_GEAR 0x46 #define SLIM_MSG_MC_NEXT_ROOT_FREQUENCY 0x47 #define SLIM_MSG_MC_NEXT_PAUSE_CLOCK 0x4A #define SLIM_MSG_MC_NEXT_RESET_BUS 0x4B #define SLIM_MSG_MC_NEXT_SHUTDOWN_BUS 0x4C #define SLIM_MSG_MC_NEXT_DEFINE_CHANNEL 0x50 #define SLIM_MSG_MC_NEXT_DEFINE_CONTENT 0x51 #define SLIM_MSG_MC_NEXT_ACTIVATE_CHANNEL 0x54 #define SLIM_MSG_MC_NEXT_DEACTIVATE_CHANNEL 0x55 #define SLIM_MSG_MC_NEXT_REMOVE_CHANNEL 0x58 #define SLIM_MSG_MC_RECONFIGURE_NOW 0x5F /* * Clock pause flag to indicate that the reconfig message * corresponds to clock pause sequence */ #define SLIM_MSG_CLK_PAUSE_SEQ_FLG (1U << 8) /* Value management messages */ #define SLIM_MSG_MC_REQUEST_VALUE 0x60 #define SLIM_MSG_MC_REQUEST_CHANGE_VALUE 0x61 #define SLIM_MSG_MC_REPLY_VALUE 0x64 #define SLIM_MSG_MC_CHANGE_VALUE 0x68 /* Clock pause values defined in Table 66 (slimbus spec 1.01.01) */ #define SLIM_CLK_FAST 0 #define SLIM_CLK_CONST_PHASE 1 #define SLIM_CLK_UNSPECIFIED 2 struct slim_controller; struct slim_device; /* Destination type Values defined in Table 33 (slimbus spec 1.01.01) */ #define SLIM_MSG_DEST_LOGICALADDR 0 #define SLIM_MSG_DEST_ENUMADDR 1 #define SLIM_MSG_DEST_BROADCAST 3 /* * @start_offset: Specifies starting offset in information/value element map * @num_bytes: Can be 1, 2, 3, 4, 6, 8, 12, 16 per spec. This ensures that the * message will fit in the 40-byte message limit and the slicesize can be * compatible with values in table 21 (slimbus spec 1.01.01) * @comp: Completion to indicate end of message-transfer. Used if client wishes * to use the API asynchronously. */ struct slim_ele_access { u16 start_offset; u8 num_bytes; struct completion *comp; }; /* * struct slim_framer - Represents Slimbus framer. * Every controller may have multiple framers. * Manager is responsible for framer hand-over. * @e_addr: 6 byte Elemental address of the framer. * @rootfreq: Root Frequency at which the framer can run. This is maximum * frequency (clock gear 10 per slimbus spec) at which the bus can operate. * @superfreq: Superframes per root frequency. Every frame is 6144 cells (bits) * per slimbus specification. */ struct slim_framer { u8 e_addr[6]; int rootfreq; int superfreq; }; #define to_slim_framer(d) container_of(d, struct slim_framer, dev); /* * struct slim_addrt: slimbus address used internally by the slimbus framework. * @valid: If the device is still there or if the address can be reused. * @eaddr: 6-bytes-long elemental address */ struct slim_addrt { bool valid; u8 eaddr[6]; }; /* * struct slim_msg_txn: Message to be sent by the controller. * Linux framework uses this structure with drivers implementing controller. * This structure has packet header, payload and buffer to be filled (if any) * For the header information, refer to Table 34-36. * @rl: Header field. remaining length. * @mt: Header field. Message type. * @mc: Header field. LSB is message code for type mt. Framework will set MSB to * SLIM_MSG_CLK_PAUSE_SEQ_FLG in case "mc" in the reconfiguration sequence * is for pausing the clock. * @dt: Header field. Destination type. * @ec: Element size. Used for elemental access APIs. * @len: Length of payload. (excludes ec) * @tid: Transaction ID. Used for messages expecting response. * (e.g. relevant for mc = SLIM_MSG_MC_REQUEST_INFORMATION) * @la: Logical address of the device this message is going to. * (Not used when destination type is broadcast.) * @rbuf: Buffer to be populated by controller when response is received. * @wbuf: Payload of the message. (e.g. channel number for DATA channel APIs) * @comp: Completion structure. Used by controller to notify response. * (Field is relevant when tid is used) */ struct slim_msg_txn { u8 rl; u8 mt; u16 mc; u8 dt; u16 ec; u8 len; u8 tid; u8 la; u8 *rbuf; const u8 *wbuf; struct completion *comp; }; /* Internal port state used by slimbus framework to manage data-ports */ enum slim_port_state { SLIM_P_FREE, SLIM_P_UNCFG, SLIM_P_CFG, }; /* * enum slim_port_req: Request port type by user through APIs to manage ports * User can request default, half-duplex or port to be used in multi-channel * configuration. Default indicates a simplex port. */ enum slim_port_req { SLIM_REQ_DEFAULT, SLIM_REQ_HALF_DUP, SLIM_REQ_MULTI_CH, }; /* * enum slim_port_cfg: Port configuration parameters requested. * User can request no configuration, packed data, or MSB aligned data port */ enum slim_port_cfg { SLIM_CFG_NONE, SLIM_CFG_PACKED, SLIM_CFG_ALIGN_MSB, }; /* enum slim_port_flow: Port flow type (inbound/outbound). */ enum slim_port_flow { SLIM_SRC, SLIM_SINK, }; /* enum slim_port_err: Port errors */ enum slim_port_err { SLIM_P_INPROGRESS, SLIM_P_OVERFLOW, SLIM_P_UNDERFLOW, SLIM_P_DISCONNECT, SLIM_P_NOT_OWNED, }; /* * struct slim_port: Internal structure used by framework to manage ports * @err: Port error if any for this port. Refer to enum above. * @state: Port state. Refer to enum above. * @req: Port request for this port. * @cfg: Port configuration for this port. * @flow: Flow type of this port. * @ch: Channel association of this port. * @xcomp: Completion to indicate error, data transfer done event. * @ctrl: Controller to which this port belongs to. This is useful to associate * port with the SW since port hardware interrupts may only contain port * information. */ struct slim_port { enum slim_port_err err; enum slim_port_state state; enum slim_port_req req; enum slim_port_cfg cfg; enum slim_port_flow flow; struct slim_ch *ch; struct completion *xcomp; struct slim_controller *ctrl; }; /* * enum slim_ch_state: Channel state of a channel. * Channel transition happens from free-to-allocated-to-defined-to-pending- * active-to-active. * Once active, channel can be removed or suspended. Suspended channels are * still scheduled, but data transfer doesn't happen. * Removed channels are not deallocated until dealloc_ch API is used. * Deallocation reset channel state back to free. * Removed channels can be defined with different parameters. */ enum slim_ch_state { SLIM_CH_FREE, SLIM_CH_ALLOCATED, SLIM_CH_DEFINED, SLIM_CH_PENDING_ACTIVE, SLIM_CH_ACTIVE, SLIM_CH_SUSPENDED, SLIM_CH_PENDING_REMOVAL, }; /* * enum slim_ch_proto: Channel protocol used by the channel. * Hard Isochronous channel is not scheduled if current frequency doesn't allow * the channel to be run without flow-control. * Auto isochronous channel will be scheduled as hard-isochronous or push-pull * depending on current bus frequency. * Currently, Push-pull or async or extended channels are not supported. * For more details, refer to slimbus spec */ enum slim_ch_proto { SLIM_HARD_ISO, SLIM_AUTO_ISO, SLIM_PUSH, SLIM_PULL, SLIM_ASYNC_SMPLX, SLIM_ASYNC_HALF_DUP, SLIM_EXT_SMPLX, SLIM_EXT_HALF_DUP, }; /* * enum slim_ch_rate: Most commonly used frequency rate families. * Use 1HZ for push-pull transport. * 4KHz and 11.025KHz are most commonly used in audio applications. * Typically, slimbus runs at frequencies to support channels running at 4KHz * and/or 11.025KHz isochronously. */ enum slim_ch_rate { SLIM_RATE_1HZ, SLIM_RATE_4000HZ, SLIM_RATE_11025HZ, }; /* * enum slim_ch_coeff: Coefficient of a channel used internally by framework. * Coefficient is applicable to channels running isochronously. * Coefficient is calculated based on channel rate multiplier. * (If rate multiplier is power of 2, it's coeff.1 channel. Otherwise it's * coeff.3 channel. */ enum slim_ch_coeff { SLIM_COEFF_1, SLIM_COEFF_3, }; /* * enum slim_ch_control: Channel control. * Activate will schedule channel and/or group of channels in the TDM frame. * Suspend will keep the schedule but data-transfer won't happen. * Remove will remove the channel/group from the TDM frame. */ enum slim_ch_control { SLIM_CH_ACTIVATE, SLIM_CH_SUSPEND, SLIM_CH_REMOVE, }; /* enum slim_ch_dataf: Data format per table 60 from slimbus spec 1.01.01 */ enum slim_ch_dataf { SLIM_CH_DATAF_NOT_DEFINED = 0, SLIM_CH_DATAF_LPCM_AUDIO = 1, SLIM_CH_DATAF_IEC61937_COMP_AUDIO = 2, SLIM_CH_DATAF_PACKED_PDM_AUDIO = 3, }; /* enum slim_ch_auxf: Auxiliary field format per table 59 from slimbus spec */ enum slim_ch_auxf { SLIM_CH_AUXF_NOT_APPLICABLE = 0, SLIM_CH_AUXF_ZCUV_TUNNEL_IEC60958 = 1, SLIM_CH_USER_DEFINED = 0xF, }; /* * struct slim_ch: Channel structure used externally by users of channel APIs. * @prot: Desired slimbus protocol. * @baser: Desired base rate. (Typical isochronous rates are: 4KHz, or 11.025KHz * @dataf: Data format. * @auxf: Auxiliary format. * @ratem: Channel rate multiplier. (e.g. 48KHz channel will have 4KHz base rate * and 12 as rate multiplier. * @sampleszbits: Sample size in bits. */ struct slim_ch { enum slim_ch_proto prot; enum slim_ch_rate baser; enum slim_ch_dataf dataf; enum slim_ch_auxf auxf; u32 ratem; u32 sampleszbits; }; /* * struct slim_ich: Internal channel structure used by slimbus framework. * @prop: structure passed by the client. * @coeff: Coefficient of this channel. * @state: Current state of the channel. * @nextgrp: If this channel is part of group, next channel in this group. * @prrate: Presence rate of this channel (per table 62 of the spec) * @offset: Offset of this channel in the superframe. * @newoff: Used during scheduling to hold temporary new offset until the offset * is accepted/rejected by slimbus reconfiguration. * @interval: Interval of this channel per superframe. * @newintr: Used during scheduling to new interval temporarily. * @seglen: Segment length of this channel. * @rootexp: root exponent of this channel. Rate can be found using rootexp and * coefficient. Used during scheduling. * @srch: Source port used by this channel. * @sinkh: Sink ports used by this channel. * @nsink: number of sink ports used by this channel. * @chan: Channel number sent on hardware lines for this channel. May not be * equal to array-index into chans if client requested to use number beyond * channel-array for the controller. * @ref: Reference number to keep track of how many clients (upto 2) are using * this channel. * @def: Used to keep track of how many times the channel definition is sent * to hardware and this will decide if channel-remove can be sent for the * channel. Channel definition may be sent upto twice (once per producer * and once per consumer). Channel removal should be sent only once to * avoid clients getting underflow/overflow errors. */ struct slim_ich { struct slim_ch prop; enum slim_ch_coeff coeff; enum slim_ch_state state; u16 nextgrp; u32 prrate; u32 offset; u32 newoff; u32 interval; u32 newintr; u32 seglen; u8 rootexp; u32 srch; u32 *sinkh; int nsink; u8 chan; int ref; int def; }; /* * struct slim_sched: Framework uses this structure internally for scheduling. * @chc3: Array of all active coeffient 3 channels. * @num_cc3: Number of active coeffient 3 channels. * @chc1: Array of all active coeffient 1 channels. * @num_cc1: Number of active coeffient 1 channels. * @subfrmcode: Current subframe-code used by TDM. This is decided based on * requested message bandwidth and current channels scheduled. * @usedslots: Slots used by all active channels. * @msgsl: Slots used by message-bandwidth. * @pending_msgsl: Used to store pending request of message bandwidth (in slots) * until the scheduling is accepted by reconfiguration. * @m_reconf: This mutex is held until current reconfiguration (data channel * scheduling, message bandwidth reservation) is done. Message APIs can * use the bus concurrently when this mutex is held since elemental access * messages can be sent on the bus when reconfiguration is in progress. * @slots: Used for debugging purposes to debug/verify current schedule in TDM. */ struct slim_sched { struct slim_ich **chc3; int num_cc3; struct slim_ich **chc1; int num_cc1; u32 subfrmcode; u32 usedslots; u32 msgsl; u32 pending_msgsl; struct mutex m_reconf; u8 *slots; }; /* * enum slim_clk_state: Slimbus controller's clock state used internally for * maintaining current clock state. * @SLIM_CLK_ACTIVE: Slimbus clock is active * @SLIM_CLK_PAUSE_FAILED: Slimbus controlled failed to go in clock pause. * Hardware-wise, this state is same as active but controller will wait on * completion before making transition to SLIM_CLK_ACTIVE in framework * @SLIM_CLK_ENTERING_PAUSE: Slimbus clock pause sequence is being sent on the * bus. If this succeeds, state changes to SLIM_CLK_PAUSED. If the * transition fails, state changes to SLIM_CLK_PAUSE_FAILED * @SLIM_CLK_PAUSED: Slimbus controller clock has paused. */ enum slim_clk_state { SLIM_CLK_ACTIVE, SLIM_CLK_ENTERING_PAUSE, SLIM_CLK_PAUSE_FAILED, SLIM_CLK_PAUSED, }; /* * struct slim_controller: Represents manager for a SlimBUS * (similar to 'master' on I2C) * @dev: Device interface to this driver * @nr: Board-specific number identifier for this controller/bus * @list: Link with other slimbus controllers * @name: Name for this controller * @clkgear: Current clock gear in which this bus is running * @min_cg: Minimum clock gear supported by this controller (default value: 1) * @max_cg: Maximum clock gear supported by this controller (default value: 10) * @clk_state: Controller's clock state from enum slim_clk_state * @pause_comp: Signals completion of clock pause sequence. This is useful when * client tries to call slimbus transaction when controller may be entering * clock pause. * @a_framer: Active framer which is clocking the bus managed by this controller * @m_ctrl: Mutex protecting controller data structures (ports, channels etc) * @addrt: Logical address table * @num_dev: Number of active slimbus slaves on this bus * @txnt: Table of transactions having transaction ID * @last_tid: size of the table txnt (can't grow beyond 256 since TID is 8-bits) * @ports: Ports associated with this controller * @nports: Number of ports supported by the controller * @chans: Channels associated with this controller * @nchans: Number of channels supported * @reserved: Reserved channels that controller wants to use internally * Clients will be assigned channel numbers after this number * @sched: scheduler structure used by the controller * @dev_released: completion used to signal when sysfs has released this * controller so that it can be deleted during shutdown * @xfer_msg: Transfer a message on this controller (this can be a broadcast * control/status message like data channel setup, or a unicast message * like value element read/write. * @set_laddr: Setup logical address at laddr for the slave with elemental * address e_addr. Drivers implementing controller will be expected to * send unicast message to this device with its logical address. * @wakeup: This function pointer implements controller-specific procedure * to wake it up from clock-pause. Framework will call this to bring * the controller out of clock pause. * @config_port: Configure a port and make it ready for data transfer. This is * called by framework after connect_port message is sent successfully. * @framer_handover: If this controller has multiple framers, this API will * be called to switch between framers if controller desires to change * the active framer. * @port_xfer: Called to schedule a transfer on port pn. iobuf is physical * address and the buffer may have to be DMA friendly since data channels * will be using data from this buffers without SW intervention. * @port_xfer_status: Called by framework when client calls get_xfer_status * API. Returns how much buffer is actually processed and the port * errors (e.g. overflow/underflow) if any. */ struct slim_controller { struct device dev; unsigned int nr; struct list_head list; char name[SLIMBUS_NAME_SIZE]; int clkgear; int min_cg; int max_cg; enum slim_clk_state clk_state; struct completion pause_comp; struct slim_framer *a_framer; struct mutex m_ctrl; struct slim_addrt *addrt; u8 num_dev; struct slim_msg_txn **txnt; u8 last_tid; struct slim_port *ports; int nports; struct slim_ich *chans; int nchans; u8 reserved; struct slim_sched sched; struct completion dev_released; int (*xfer_msg)(struct slim_controller *ctrl, struct slim_msg_txn *txn); int (*set_laddr)(struct slim_controller *ctrl, const u8 *ea, u8 elen, u8 laddr); int (*wakeup)(struct slim_controller *ctrl); int (*config_port)(struct slim_controller *ctrl, u8 port); int (*framer_handover)(struct slim_controller *ctrl, struct slim_framer *new_framer); int (*port_xfer)(struct slim_controller *ctrl, u8 pn, u8 *iobuf, u32 len, struct completion *comp); enum slim_port_err (*port_xfer_status)(struct slim_controller *ctr, u8 pn, u8 **done_buf, u32 *done_len); }; #define to_slim_controller(d) container_of(d, struct slim_controller, dev) /* * struct slim_driver: Manage Slimbus generic/slave device driver * @probe: Binds this driver to a slimbus device. * @remove: Unbinds this driver from the slimbus device. * @shutdown: Standard shutdown callback used during powerdown/halt. * @suspend: Standard suspend callback used during system suspend * @resume: Standard resume callback used during system resume * @driver: Slimbus device drivers should initialize name and owner field of * this structure * @id_table: List of slimbus devices supported by this driver */ struct slim_driver { int (*probe)(struct slim_device *sldev); int (*remove)(struct slim_device *sldev); void (*shutdown)(struct slim_device *sldev); int (*suspend)(struct slim_device *sldev, pm_message_t pmesg); int (*resume)(struct slim_device *sldev); struct device_driver driver; const struct slim_device_id *id_table; }; #define to_slim_driver(d) container_of(d, struct slim_driver, driver) /* * struct slim_pending_ch: List of pending channels used by framework. * @chan: Channel number * @pending: list of channels */ struct slim_pending_ch { u8 chan; struct list_head pending; }; /* * Client/device handle (struct slim_device): * ------------------------------------------ * This is the client/device handle returned when a slimbus * device is registered with a controller. This structure can be provided * during register_board_info, or can be allocated using slim_add_device API. * Pointer to this structure is used by client-driver as a handle. * @dev: Driver model representation of the device. * @name: Name of driver to use with this device. * @e_addr: 6-byte elemental address of this device. * @driver: Device's driver. Pointer to access routines. * @ctrl: Slimbus controller managing the bus hosting this device. * @laddr: 1-byte Logical address of this device. * @mark_define: List of channels pending definition/activation. * @mark_suspend: List of channels pending suspend. * @mark_removal: List of channels pending removal. * @sldev_reconf: Mutex to protect the pending data-channel lists. * @pending_msgsl: Message bandwidth reservation request by this client in * slots that's pending reconfiguration. * @cur_msgsl: Message bandwidth reserved by this client in slots. * These 3 lists are managed by framework. Lists are populated when client * calls channel control API without reconfig-flag set and the lists are * emptied when the reconfiguration is done by this client. */ struct slim_device { struct device dev; const char *name; u8 e_addr[6]; struct slim_driver *driver; struct slim_controller *ctrl; u8 laddr; struct list_head mark_define; struct list_head mark_suspend; struct list_head mark_removal; struct mutex sldev_reconf; u32 pending_msgsl; u32 cur_msgsl; }; #define to_slim_device(d) container_of(d, struct slim_device, dev) /* * struct slim_boardinfo: Declare board info for Slimbus device bringup. * @bus_num: Controller number (bus) on which this device will sit. * @slim_slave: Device to be registered with slimbus. */ struct slim_boardinfo { int bus_num; struct slim_device *slim_slave; }; /* * slim_get_logical_addr: Return the logical address of a slimbus device. * @sb: client handle requesting the adddress. * @e_addr: Elemental address of the device. * @e_len: Length of e_addr * @laddr: output buffer to store the address * context: can sleep * -EINVAL is returned in case of invalid parameters, and -ENXIO is returned if * the device with this elemental address is not found. */ extern int slim_get_logical_addr(struct slim_device *sb, const u8 *e_addr, u8 e_len, u8 *laddr); /* Message APIs Unicast message APIs used by slimbus slave drivers */ /* * Message API access routines. * @sb: client handle requesting elemental message reads, writes. * @msg: Input structure for start-offset, number of bytes to read. * @rbuf: data buffer to be filled with values read. * @len: data buffer size * @wbuf: data buffer containing value/information to be written * context: can sleep * Returns: * -EINVAL: Invalid parameters * -ETIMEDOUT: If controller could not complete the request. This may happen if * the bus lines are not clocked, controller is not powered-on, slave with * given address is not enumerated/responding. */ extern int slim_request_val_element(struct slim_device *sb, struct slim_ele_access *msg, u8 *buf, u8 len); extern int slim_request_inf_element(struct slim_device *sb, struct slim_ele_access *msg, u8 *buf, u8 len); extern int slim_change_val_element(struct slim_device *sb, struct slim_ele_access *msg, const u8 *buf, u8 len); extern int slim_clear_inf_element(struct slim_device *sb, struct slim_ele_access *msg, u8 *buf, u8 len); extern int slim_request_change_val_element(struct slim_device *sb, struct slim_ele_access *msg, u8 *rbuf, const u8 *wbuf, u8 len); extern int slim_request_clear_inf_element(struct slim_device *sb, struct slim_ele_access *msg, u8 *rbuf, const u8 *wbuf, u8 len); /* * Broadcast message API: * call this API directly with sbdev = NULL. * For broadcast reads, make sure that buffers are big-enough to incorporate * replies from all logical addresses. * All controllers may not support broadcast */ extern int slim_xfer_msg(struct slim_controller *ctrl, struct slim_device *sbdev, struct slim_ele_access *msg, u16 mc, u8 *rbuf, const u8 *wbuf, u8 len); /* end of message apis */ /* Port management for manager device APIs */ /* * slim_alloc_mgrports: Allocate port on manager side. * @sb: device/client handle. * @req: Port request type. * @nports: Number of ports requested * @rh: output buffer to store the port handles * @hsz: size of buffer storing handles * context: can sleep * This port will be typically used by SW. e.g. client driver wants to receive * some data from audio codec HW using a data channel. * Port allocated using this API will be used to receive the data. * If half-duplex ports are requested, two adjacent ports are allocated for * 1 half-duplex port. So the handle-buffer size should be twice the number * of half-duplex ports to be allocated. * -EDQUOT is returned if all ports are in use. */ extern int slim_alloc_mgrports(struct slim_device *sb, enum slim_port_req req, int nports, u32 *rh, int hsz); /* Deallocate the port(s) allocated using the API above */ extern int slim_dealloc_mgrports(struct slim_device *sb, u32 *hdl, int hsz); /* * slim_port_xfer: Schedule buffer to be transferred/received using port-handle. * @sb: client handle * @ph: port-handle * @iobuf: buffer to be transferred or populated * @len: buffer size. * @comp: completion signal to indicate transfer done or error. * context: can sleep * Returns number of bytes transferred/received if used synchronously. * Will return 0 if used asynchronously. * Client will call slim_port_get_xfer_status to get error and/or number of * bytes transferred if used asynchronously. */ extern int slim_port_xfer(struct slim_device *sb, u32 ph, u8 *iobuf, u32 len, struct completion *comp); /* * slim_port_get_xfer_status: Poll for port transfers, or get transfer status * after completion is done. * @sb: client handle * @ph: port-handle * @done_buf: return pointer (iobuf from slim_port_xfer) which is processed. * @done_len: Number of bytes transferred. * This can be called when port_xfer complition is signalled. * The API will return port transfer error (underflow/overflow/disconnect) * and/or done_len will reflect number of bytes transferred. Note that * done_len may be valid even if port error (overflow/underflow) has happened. * e.g. If the transfer was scheduled with a few bytes to be transferred and * client has not supplied more data to be transferred, done_len will indicate * number of bytes transferred with underflow error. To avoid frequent underflow * errors, multiple transfers can be queued (e.g. ping-pong buffers) so that * channel has data to be transferred even if client is not ready to transfer * data all the time. done_buf will indicate address of the last buffer * processed from the multiple transfers. */ extern enum slim_port_err slim_port_get_xfer_status(struct slim_device *sb, u32 ph, u8 **done_buf, u32 *done_len); /* * slim_connect_src: Connect source port to channel. * @sb: client handle * @srch: source handle to be connected to this channel * @chanh: Channel with which the ports need to be associated with. * Per slimbus specification, a channel may have 1 source port. * Channel specified in chanh needs to be allocated first. * Returns -EALREADY if source is already configured for this channel. * Returns -ENOTCONN if channel is not allocated */ extern int slim_connect_src(struct slim_device *sb, u32 srch, u16 chanh); /* * slim_connect_sink: Connect sink port(s) to channel. * @sb: client handle * @sinkh: sink handle(s) to be connected to this channel * @nsink: number of sinks * @chanh: Channel with which the ports need to be associated with. * Per slimbus specification, a channel may have multiple sink-ports. * Channel specified in chanh needs to be allocated first. * Returns -EALREADY if sink is already configured for this channel. * Returns -ENOTCONN if channel is not allocated */ extern int slim_connect_sink(struct slim_device *sb, u32 *sinkh, int nsink, u16 chanh); /* * slim_disconnect_ports: Disconnect port(s) from channel * @sb: client handle * @ph: ports to be disconnected * @nph: number of ports. * Disconnects ports from a channel. */ extern int slim_disconnect_ports(struct slim_device *sb, u32 *ph, int nph); /* * slim_get_slaveport: Get slave port handle * @la: slave device logical address. * @idx: port index at slave * @rh: return handle * @flw: Flow type (source or destination) * This API only returns a slave port's representation as expected by slimbus * driver. This port is not managed by the slimbus driver. Caller is expected * to have visibility of this port since it's a device-port. */ extern int slim_get_slaveport(u8 la, int idx, u32 *rh, enum slim_port_flow flw); /* Channel functions. */ /* * slim_alloc_ch: Allocate a slimbus channel and return its handle. * @sb: client handle. * @chanh: return channel handle * Slimbus channels are limited to 256 per specification. * -EXFULL is returned if all channels are in use. * Although slimbus specification supports 256 channels, a controller may not * support that many channels. */ extern int slim_alloc_ch(struct slim_device *sb, u16 *chanh); /* * slim_query_ch: Get reference-counted handle for a channel number. Every * channel is reference counted by one as producer and the others as * consumer) * @sb: client handle * @chan: slimbus channel number * @chanh: return channel handle * If request channel number is not in use, it is allocated, and reference * count is set to one. If the channel was was already allocated, this API * will return handle to that channel and reference count is incremented. * -EXFULL is returned if all channels are in use */ extern int slim_query_ch(struct slim_device *sb, u8 chan, u16 *chanh); /* * slim_dealloc_ch: Deallocate channel allocated using the API above * -EISCONN is returned if the channel is tried to be deallocated without * being removed first. * -ENOTCONN is returned if deallocation is tried on a channel that's not * allocated. */ extern int slim_dealloc_ch(struct slim_device *sb, u16 chanh); /* * slim_define_ch: Define a channel.This API defines channel parameters for a * given channel. * @sb: client handle. * @prop: slim_ch structure with channel parameters desired to be used. * @chanh: list of channels to be defined. * @nchan: number of channels in a group (1 if grp is false) * @grp: Are the channels grouped * @grph: return group handle if grouping of channels is desired. * Channels can be grouped if multiple channels use same parameters * (e.g. 5.1 audio has 6 channels with same parameters. They will all be * grouped and given 1 handle for simplicity and avoid repeatedly calling * the API) * -EISCONN is returned if channel is already used with different parameters. * -ENXIO is returned if the channel is not yet allocated. */ extern int slim_define_ch(struct slim_device *sb, struct slim_ch *prop, u16 *chanh, u8 nchan, bool grp, u16 *grph); /* * slim_control_ch: Channel control API. * @sb: client handle * @grpchanh: group or channel handle to be controlled * @chctrl: Control command (activate/suspend/remove) * @commit: flag to indicate whether the control should take effect right-away. * This API activates, removes or suspends a channel (or group of channels) * grpchanh indicates the channel or group handle (returned by the define_ch * API). Reconfiguration may be time-consuming since it can change all other * active channel allocations on the bus, change in clock gear used by the * slimbus, and change in the control space width used for messaging. * commit makes sure that multiple channels can be activated/deactivated before * reconfiguration is started. * -EXFULL is returned if there is no space in TDM to reserve the bandwidth. * -EISCONN/-ENOTCONN is returned if the channel is already connected or not * yet defined. * -EINVAL is returned if individual control of a grouped-channel is attempted. */ extern int slim_control_ch(struct slim_device *sb, u16 grpchanh, enum slim_ch_control chctrl, bool commit); /* * slim_get_ch_state: Channel state. * This API returns the channel's state (active, suspended, inactive etc) */ extern enum slim_ch_state slim_get_ch_state(struct slim_device *sb, u16 chanh); /* * slim_reservemsg_bw: Request to reserve bandwidth for messages. * @sb: client handle * @bw_bps: message bandwidth in bits per second to be requested * @commit: indicates whether the reconfiguration needs to be acted upon. * This API call can be grouped with slim_control_ch API call with only one of * the APIs specifying the commit flag to avoid reconfiguration being called too * frequently. -EXFULL is returned if there is no space in TDM to reserve the * bandwidth. -EBUSY is returned if reconfiguration is requested, but a request * is already in progress. */ extern int slim_reservemsg_bw(struct slim_device *sb, u32 bw_bps, bool commit); /* * slim_reconfigure_now: Request reconfiguration now. * @sb: client handle * This API does what commit flag in other scheduling APIs do. * -EXFULL is returned if there is no space in TDM to reserve the * bandwidth. -EBUSY is returned if reconfiguration request is already in * progress. */ extern int slim_reconfigure_now(struct slim_device *sb); /* * slim_ctrl_clk_pause: Called by slimbus controller to request clock to be * paused or woken up out of clock pause * @ctrl: controller requesting bus to be paused or woken up * @wakeup: Wakeup this controller from clock pause. * @restart: Restart time value per spec used for clock pause. This value * isn't used when controller is to be woken up. * This API executes clock pause reconfiguration sequence if wakeup is false. * If wakeup is true, controller's wakeup is called * Slimbus clock is idle and can be disabled by the controller later. */ extern int slim_ctrl_clk_pause(struct slim_controller *ctrl, bool wakeup, u8 restart); /* * slim_driver_register: Client driver registration with slimbus * @drv:Client driver to be associated with client-device. * This API will register the client driver with the slimbus * It is called from the driver's module-init function. */ extern int slim_driver_register(struct slim_driver *drv); /* * slim_add_numbered_controller: Controller bring-up. * @ctrl: Controller to be registered. * A controller is registered with the framework using this API. ctrl->nr is the * desired number with which slimbus framework registers the controller. * Function will return -EBUSY if the number is in use. */ extern int slim_add_numbered_controller(struct slim_controller *ctrl); /* * slim_del_controller: Controller tear-down. * Controller added with the above API is teared down using this API. */ extern int slim_del_controller(struct slim_controller *ctrl); /* * slim_add_device: Add a new device without register board info. * @ctrl: Controller to which this device is to be added to. * Called when device doesn't have an explicit client-driver to be probed, or * the client-driver is a module installed dynamically. */ extern int slim_add_device(struct slim_controller *ctrl, struct slim_device *sbdev); /* slim_remove_device: Remove the effect of slim_add_device() */ extern void slim_remove_device(struct slim_device *sbdev); /* * slim_assign_laddr: Assign logical address to a device enumerated. * @ctrl: Controller with which device is enumerated. * @e_addr: 6-byte elemental address of the device. * @e_len: buffer length for e_addr * @laddr: Return logical address. * Called by controller in response to REPORT_PRESENT. Framework will assign * a logical address to this enumeration address. * Function returns -EXFULL to indicate that all logical addresses are already * taken. */ extern int slim_assign_laddr(struct slim_controller *ctrl, const u8 *e_addr, u8 e_len, u8 *laddr); /* * slim_msg_response: Deliver Message response received from a device to the * framework. * @ctrl: Controller handle * @reply: Reply received from the device * @len: Length of the reply * @tid: Transaction ID received with which framework can associate reply. * Called by controller to inform framework about the response received. * This helps in making the API asynchronous, and controller-driver doesn't need * to manage 1 more table other than the one managed by framework mapping TID * with buffers */ extern void slim_msg_response(struct slim_controller *ctrl, u8 *reply, u8 tid, u8 len); /* * slim_busnum_to_ctrl: Map bus number to controller * @busnum: Bus number * Returns controller representing this bus number */ extern struct slim_controller *slim_busnum_to_ctrl(u32 busnum); /* * slim_register_board_info: Board-initialization routine. * @info: List of all devices on all controllers present on the board. * @n: number of entries. * API enumerates respective devices on corresponding controller. * Called from board-init function. */ #ifdef CONFIG_SLIMBUS extern int slim_register_board_info(struct slim_boardinfo const *info, unsigned n); #else int slim_register_board_info(struct slim_boardinfo const *info, unsigned n) { return 0; } #endif static inline void *slim_get_ctrldata(const struct slim_controller *dev) { return dev_get_drvdata(&dev->dev); } static inline void slim_set_ctrldata(struct slim_controller *dev, void *data) { dev_set_drvdata(&dev->dev, data); } static inline void *slim_get_devicedata(const struct slim_device *dev) { return dev_get_drvdata(&dev->dev); } static inline void slim_set_clientdata(struct slim_device *dev, void *data) { dev_set_drvdata(&dev->dev, data); } #endif /* _LINUX_SLIMBUS_H */
talnoah/android_kernel_htc_dlx
virt/include/linux/slimbus/slimbus.h
C
gpl-2.0
39,153
/* * Copyright 2016 Advanced Micro Devices, Inc. * * 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 COPYRIGHT HOLDER(S) OR AUTHOR(S) 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. * */ #ifndef __GFX_V9_0_H__ #define __GFX_V9_0_H__ extern const struct amdgpu_ip_block_version gfx_v9_0_ip_block; void gfx_v9_0_select_se_sh(struct amdgpu_device *adev, u32 se_num, u32 sh_num, u32 instance); #endif
GuillaumeSeren/linux
drivers/gpu/drm/amd/amdgpu/gfx_v9_0.h
C
gpl-2.0
1,357
"use strict"; var _ = require('lodash'); var path = require('canonical-path'); /** * @dgProcessor generateIndexPagesProcessor * @description * This processor creates docs that will be rendered as the index page for the app */ module.exports = function generateIndexPagesProcessor() { return { deployments: [], $validate: { deployments: { presence: true } }, $runAfter: ['adding-extra-docs'], $runBefore: ['extra-docs-added'], $process: function(docs) { // Collect up all the areas in the docs var areas = {}; docs.forEach(function(doc) { if ( doc.area ) { areas[doc.area] = doc.area; } }); areas = _.keys(areas); this.deployments.forEach(function(deployment) { var indexDoc = _.defaults({ docType: 'indexPage', areas: areas }, deployment); indexDoc.id = 'index' + (deployment.name === 'default' ? '' : '-' + deployment.name); docs.push(indexDoc); }); } }; };
jmatar-sd/power-glass
theme/styles/TODO/angular.js-master/docs/config/processors/index-page.js
JavaScript
apache-2.0
1,027
<div class="test"></div>
february29/Learning
web/vue/AccountBook-Express/node_modules/pug/test/cases/regression.1794.html
HTML
mit
24
/*! * Qoopido.js library v3.2.2, 2014-0-10 * https://github.com/dlueth/qoopido.js * (c) 2014 Dirk Lueth * Dual licensed under MIT and GPL */ !function(e){window.qoopido.register("support/css/rem",e,["../../support"])}(function(e,t,o,s,r,i){"use strict";var n=e.support;return n.addTest("/css/rem",function(e){var t=n.pool?n.pool.obtain("div"):i.createElement("div");try{t.style.fontSize="3rem"}catch(o){}/rem/.test(t.style.fontSize)?e.resolve():e.reject(),t.dispose&&t.dispose()})});
pcarrier/cdnjs
ajax/libs/qoopido.js/3.2.2/support/css/rem.js
JavaScript
mit
484
/*! * Qoopido.js library v3.4.3, 2014-6-11 * https://github.com/dlueth/qoopido.js * (c) 2014 Dirk Lueth * Dual licensed under MIT and GPL *//*! * Qoopido.js library * * version: 3.4.3 * date: 2014-6-11 * author: Dirk Lueth <[email protected]> * website: https://github.com/dlueth/qoopido.js * * Copyright (c) 2014 Dirk Lueth * * Dual licensed under the MIT and GPL licenses. * - http://www.opensource.org/licenses/mit-license.php * - http://www.gnu.org/copyleft/gpl.html */ !function(e){window.qoopido.register("support/element/svg",e,["../../support"])}(function(e,t,r,n,o,s){"use strict";return e.support.addTest("/element/svg",function(e){s.createElementNS&&s.createElementNS("http://www.w3.org/2000/svg","svg").createSVGRect?e.resolve():e.reject()})});
kartikrao31/cdnjs
ajax/libs/qoopido.js/3.4.3/support/element/svg.js
JavaScript
mit
759
#ifndef __TRID4DWAVE_H #define __TRID4DWAVE_H /* * [email protected] * Fri Feb 19 15:55:28 MST 1999 * Definitions for Trident 4DWave DX/NX chips * * * 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. * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. * */ /* PCI vendor and device ID */ #ifndef PCI_VENDOR_ID_TRIDENT #define PCI_VENDOR_ID_TRIDENT 0x1023 #endif #ifndef PCI_VENDOR_ID_SI #define PCI_VENDOR_ID_SI 0x1039 #endif #ifndef PCI_VENDOR_ID_ALI #define PCI_VENDOR_ID_ALI 0x10b9 #endif #ifndef PCI_DEVICE_ID_TRIDENT_4DWAVE_DX #define PCI_DEVICE_ID_TRIDENT_4DWAVE_DX 0x2000 #endif #ifndef PCI_DEVICE_ID_TRIDENT_4DWAVE_NX #define PCI_DEVICE_ID_TRIDENT_4DWAVE_NX 0x2001 #endif #ifndef PCI_DEVICE_ID_SI_7018 #define PCI_DEVICE_ID_SI_7018 0x7018 #endif #ifndef PCI_DEVICE_ID_ALI_5451 #define PCI_DEVICE_ID_ALI_5451 0x5451 #endif #ifndef PCI_DEVICE_ID_ALI_1533 #define PCI_DEVICE_ID_ALI_1533 0x1533 #endif #define CHANNEL_REGS 5 #define CHANNEL_START 0xe0 // The first bytes of the contiguous register space. #define BANK_A 0 #define BANK_B 1 #define NR_BANKS 2 #define TRIDENT_FMT_STEREO 0x01 #define TRIDENT_FMT_16BIT 0x02 #define TRIDENT_FMT_MASK 0x03 #define DAC_RUNNING 0x01 #define ADC_RUNNING 0x02 /* Register Addresses */ /* operational registers common to DX, NX, 7018 */ enum trident_op_registers { T4D_GAME_CR = 0x30, T4D_GAME_LEG = 0x31, T4D_GAME_AXD = 0x34, T4D_REC_CH = 0x70, T4D_START_A = 0x80, T4D_STOP_A = 0x84, T4D_DLY_A = 0x88, T4D_SIGN_CSO_A = 0x8c, T4D_CSPF_A = 0x90, T4D_CEBC_A = 0x94, T4D_AINT_A = 0x98, T4D_EINT_A = 0x9c, T4D_LFO_GC_CIR = 0xa0, T4D_AINTEN_A = 0xa4, T4D_MUSICVOL_WAVEVOL = 0xa8, T4D_SBDELTA_DELTA_R = 0xac, T4D_MISCINT = 0xb0, T4D_START_B = 0xb4, T4D_STOP_B = 0xb8, T4D_CSPF_B = 0xbc, T4D_SBBL_SBCL = 0xc0, T4D_SBCTRL_SBE2R_SBDD = 0xc4, T4D_STIMER = 0xc8, T4D_LFO_B_I2S_DELTA = 0xcc, T4D_AINT_B = 0xd8, T4D_AINTEN_B = 0xdc, ALI_MPUR2 = 0x22, ALI_GPIO = 0x7c, ALI_EBUF1 = 0xf4, ALI_EBUF2 = 0xf8 }; enum ali_op_registers { ALI_SCTRL = 0x48, ALI_GLOBAL_CONTROL = 0xd4, ALI_STIMER = 0xc8, ALI_SPDIF_CS = 0x70, ALI_SPDIF_CTRL = 0x74 }; enum ali_registers_number { ALI_GLOBAL_REGS = 56, ALI_CHANNEL_REGS = 8, ALI_MIXER_REGS = 20 }; enum ali_sctrl_control_bit { ALI_SPDIF_OUT_ENABLE = 0x20 }; enum ali_global_control_bit { ALI_SPDIF_OUT_SEL_PCM = 0x00000400, ALI_SPDIF_IN_SUPPORT = 0x00000800, ALI_SPDIF_OUT_CH_ENABLE = 0x00008000, ALI_SPDIF_IN_CH_ENABLE = 0x00080000, ALI_PCM_IN_DISABLE = 0x7fffffff, ALI_PCM_IN_ENABLE = 0x80000000, ALI_SPDIF_IN_CH_DISABLE = 0xfff7ffff, ALI_SPDIF_OUT_CH_DISABLE = 0xffff7fff, ALI_SPDIF_OUT_SEL_SPDIF = 0xfffffbff }; enum ali_spdif_control_bit { ALI_SPDIF_IN_FUNC_ENABLE = 0x02, ALI_SPDIF_IN_CH_STATUS = 0x40, ALI_SPDIF_OUT_CH_STATUS = 0xbf }; enum ali_control_all { ALI_DISABLE_ALL_IRQ = 0, ALI_CHANNELS = 32, ALI_STOP_ALL_CHANNELS = 0xffffffff, ALI_MULTI_CHANNELS_START_STOP = 0x07800000 }; enum ali_EMOD_control_bit { ALI_EMOD_DEC = 0x00000000, ALI_EMOD_INC = 0x10000000, ALI_EMOD_Delay = 0x20000000, ALI_EMOD_Still = 0x30000000 }; enum ali_pcm_in_channel_num { ALI_NORMAL_CHANNEL = 0, ALI_SPDIF_OUT_CHANNEL = 15, ALI_SPDIF_IN_CHANNEL = 19, ALI_LEF_CHANNEL = 23, ALI_CENTER_CHANNEL = 24, ALI_SURR_RIGHT_CHANNEL = 25, ALI_SURR_LEFT_CHANNEL = 26, ALI_PCM_IN_CHANNEL = 31 }; enum ali_pcm_out_channel_num { ALI_PCM_OUT_CHANNEL_FIRST = 0, ALI_PCM_OUT_CHANNEL_LAST = 31 }; enum ali_ac97_power_control_bit { ALI_EAPD_POWER_DOWN = 0x8000 }; enum ali_update_ptr_flags { ALI_ADDRESS_INT_UPDATE = 0x01 }; enum ali_revision { ALI_5451_V02 = 0x02 }; enum ali_spdif_out_control { ALI_PCM_TO_SPDIF_OUT = 0, ALI_SPDIF_OUT_TO_SPDIF_OUT = 1, ALI_SPDIF_OUT_PCM = 0, ALI_SPDIF_OUT_NON_PCM = 2 }; /* S/PDIF Operational Registers for 4D-NX */ enum nx_spdif_registers { NX_SPCTRL_SPCSO = 0x24, NX_SPLBA = 0x28, NX_SPESO = 0x2c, NX_SPCSTATUS = 0x64 }; /* OP registers to access each hardware channel */ enum channel_registers { CH_DX_CSO_ALPHA_FMS = 0xe0, CH_DX_ESO_DELTA = 0xe8, CH_DX_FMC_RVOL_CVOL = 0xec, CH_NX_DELTA_CSO = 0xe0, CH_NX_DELTA_ESO = 0xe8, CH_NX_ALPHA_FMS_FMC_RVOL_CVOL = 0xec, CH_LBA = 0xe4, CH_GVSEL_PAN_VOL_CTRL_EC = 0xf0 }; /* registers to read/write/control AC97 codec */ enum dx_ac97_registers { DX_ACR0_AC97_W = 0x40, DX_ACR1_AC97_R = 0x44, DX_ACR2_AC97_COM_STAT = 0x48 }; enum nx_ac97_registers { NX_ACR0_AC97_COM_STAT = 0x40, NX_ACR1_AC97_W = 0x44, NX_ACR2_AC97_R_PRIMARY = 0x48, NX_ACR3_AC97_R_SECONDARY = 0x4c }; enum si_ac97_registers { SI_AC97_WRITE = 0x40, SI_AC97_READ = 0x44, SI_SERIAL_INTF_CTRL = 0x48, SI_AC97_GPIO = 0x4c }; enum ali_ac97_registers { ALI_AC97_WRITE = 0x40, ALI_AC97_READ = 0x44 }; /* Bit mask for operational registers */ #define AC97_REG_ADDR 0x000000ff enum ali_ac97_bits { ALI_AC97_BUSY_WRITE = 0x8000, ALI_AC97_BUSY_READ = 0x8000, ALI_AC97_WRITE_ACTION = 0x8000, ALI_AC97_READ_ACTION = 0x8000, ALI_AC97_AUDIO_BUSY = 0x4000, ALI_AC97_SECONDARY = 0x0080, ALI_AC97_READ_MIXER_REGISTER = 0xfeff, ALI_AC97_WRITE_MIXER_REGISTER = 0x0100 }; enum sis7018_ac97_bits { SI_AC97_BUSY_WRITE = 0x8000, SI_AC97_BUSY_READ = 0x8000, SI_AC97_AUDIO_BUSY = 0x4000, SI_AC97_MODEM_BUSY = 0x2000, SI_AC97_SECONDARY = 0x0080 }; enum trident_dx_ac97_bits { DX_AC97_BUSY_WRITE = 0x8000, DX_AC97_BUSY_READ = 0x8000, DX_AC97_READY = 0x0010, DX_AC97_RECORD = 0x0008, DX_AC97_PLAYBACK = 0x0002 }; enum trident_nx_ac97_bits { /* ACR1-3 */ NX_AC97_BUSY_WRITE = 0x0800, NX_AC97_BUSY_READ = 0x0800, NX_AC97_BUSY_DATA = 0x0400, NX_AC97_WRITE_SECONDARY = 0x0100, /* ACR0 */ NX_AC97_SECONDARY_READY = 0x0040, NX_AC97_SECONDARY_RECORD = 0x0020, NX_AC97_SURROUND_OUTPUT = 0x0010, NX_AC97_PRIMARY_READY = 0x0008, NX_AC97_PRIMARY_RECORD = 0x0004, NX_AC97_PCM_OUTPUT = 0x0002, NX_AC97_WARM_RESET = 0x0001 }; enum serial_intf_ctrl_bits { WARM_REST = 0x00000001, COLD_RESET = 0x00000002, I2S_CLOCK = 0x00000004, PCM_SEC_AC97= 0x00000008, AC97_DBL_RATE = 0x00000010, SPDIF_EN = 0x00000020, I2S_OUTPUT_EN = 0x00000040, I2S_INPUT_EN = 0x00000080, PCMIN = 0x00000100, LINE1IN = 0x00000200, MICIN = 0x00000400, LINE2IN = 0x00000800, HEAD_SET_IN = 0x00001000, GPIOIN = 0x00002000, /* 7018 spec says id = 01 but the demo board routed to 10 SECONDARY_ID= 0x00004000, */ SECONDARY_ID= 0x00004000, PCMOUT = 0x00010000, SURROUT = 0x00020000, CENTEROUT = 0x00040000, LFEOUT = 0x00080000, LINE1OUT = 0x00100000, LINE2OUT = 0x00200000, GPIOOUT = 0x00400000, SI_AC97_PRIMARY_READY = 0x01000000, SI_AC97_SECONDARY_READY = 0x02000000, }; enum global_control_bits { CHANNLE_IDX = 0x0000003f, PB_RESET = 0x00000100, PAUSE_ENG = 0x00000200, OVERRUN_IE = 0x00000400, UNDERRUN_IE = 0x00000800, ENDLP_IE = 0x00001000, MIDLP_IE = 0x00002000, ETOG_IE = 0x00004000, EDROP_IE = 0x00008000, BANK_B_EN = 0x00010000 }; enum channel_control_bits { CHANNEL_LOOP = 0x00001000, CHANNEL_SIGNED = 0x00002000, CHANNEL_STEREO = 0x00004000, CHANNEL_16BITS = 0x00008000, }; enum channel_attribute { /* playback/record select */ CHANNEL_PB = 0x0000, CHANNEL_SPC_PB = 0x4000, CHANNEL_REC = 0x8000, CHANNEL_REC_PB = 0xc000, /* playback destination/record source select */ MODEM_LINE1 = 0x0000, MODEM_LINE2 = 0x0400, PCM_LR = 0x0800, HSET = 0x0c00, I2S_LR = 0x1000, CENTER_LFE = 0x1400, SURR_LR = 0x1800, SPDIF_LR = 0x1c00, MIC = 0x1400, /* mist stuff */ MONO_LEFT = 0x0000, MONO_RIGHT = 0x0100, MONO_MIX = 0x0200, SRC_ENABLE = 0x0080, }; enum miscint_bits { PB_UNDERRUN_IRO = 0x00000001, REC_OVERRUN_IRQ = 0x00000002, SB_IRQ = 0x00000004, MPU401_IRQ = 0x00000008, OPL3_IRQ = 0x00000010, ADDRESS_IRQ = 0x00000020, ENVELOPE_IRQ = 0x00000040, ST_IRQ = 0x00000080, PB_UNDERRUN = 0x00000100, REC_OVERRUN = 0x00000200, MIXER_UNDERFLOW = 0x00000400, MIXER_OVERFLOW = 0x00000800, ST_TARGET_REACHED = 0x00008000, PB_24K_MODE = 0x00010000, ST_IRQ_EN = 0x00800000, ACGPIO_IRQ = 0x01000000 }; #define TRID_REG( trident, x ) ( (trident) -> iobase + (x) ) #define CYBER_PORT_AUDIO 0x3CE #define CYBER_IDX_AUDIO_ENABLE 0x7B #define CYBER_BMSK_AUDIO_INT_ENABLE 0x09 #define CYBER_BMSK_AUENZ 0x01 #define CYBER_BMSK_AUENZ_ENABLE 0x00 #define CYBER_IDX_IRQ_ENABLE 0x12 #define VALIDATE_MAGIC(FOO,MAG) \ ({ \ if (!(FOO) || (FOO)->magic != MAG) { \ printk(invalid_magic,__FUNCTION__); \ return -ENXIO; \ } \ }) #define VALIDATE_STATE(a) VALIDATE_MAGIC(a,TRIDENT_STATE_MAGIC) #define VALIDATE_CARD(a) VALIDATE_MAGIC(a,TRIDENT_CARD_MAGIC) static inline unsigned ld2(unsigned int x) { unsigned r = 0; if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 4) { x >>= 2; r += 2; } if (x >= 2) r++; return r; } #endif /* __TRID4DWAVE_H */
foxsat-hdr/linux-kernel
sound/oss/trident.h
C
gpl-2.0
9,824
/* * arch/arm/mach-omap2/board-blaze-panel.c * * Copyright (C) 2011 Texas Instruments * * 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. * */ #include <linux/delay.h> #include <linux/kernel.h> #include <linux/gpio.h> #include <linux/i2c.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/io.h> #include <linux/leds-omap4430sdp-display.h> #include <linux/platform_device.h> #include <linux/i2c/twl.h> #include <plat/i2c.h> #include "board-blaze.h" #include "mux.h" #define DP_4430_GPIO_59 59 #define LED_SEC_DISP_GPIO 27 #define DSI2_GPIO_59 59 #define LED_PWM2ON 0x03 #define LED_PWM2OFF 0x04 #define LED_TOGGLE3 0x92 static void blaze_init_display_led(void) { twl_i2c_write_u8(TWL_MODULE_PWM, 0xFF, LED_PWM2ON); twl_i2c_write_u8(TWL_MODULE_PWM, 0x7F, LED_PWM2OFF); twl_i2c_write_u8(TWL6030_MODULE_ID1, 0x30, LED_TOGGLE3); } static void blaze_set_primary_brightness(u8 brightness) { if (brightness > 1) { if (brightness == 255) brightness = 0x7f; else brightness = (~(brightness/2)) & 0x7f; twl_i2c_write_u8(TWL6030_MODULE_ID1, 0x30, LED_TOGGLE3); twl_i2c_write_u8(TWL_MODULE_PWM, brightness, LED_PWM2ON); } else if (brightness <= 1) { twl_i2c_write_u8(TWL6030_MODULE_ID1, 0x08, LED_TOGGLE3); twl_i2c_write_u8(TWL6030_MODULE_ID1, 0x38, LED_TOGGLE3); } } static void blaze_set_secondary_brightness(u8 brightness) { if (brightness > 0) brightness = 1; gpio_set_value(LED_SEC_DISP_GPIO, brightness); } static struct omap4430_sdp_disp_led_platform_data blaze_disp_led_data = { .flags = LEDS_CTRL_AS_ONE_DISPLAY, .display_led_init = blaze_init_display_led, .primary_display_set = blaze_set_primary_brightness, .secondary_display_set = blaze_set_secondary_brightness, }; static void __init omap_disp_led_init(void) { /* Seconday backlight control */ gpio_request(DSI2_GPIO_59, "dsi2_bl_gpio"); gpio_direction_output(DSI2_GPIO_59, 0); if (blaze_disp_led_data.flags & LEDS_CTRL_AS_ONE_DISPLAY) { pr_info("%s: Configuring as one display LED\n", __func__); gpio_set_value(DSI2_GPIO_59, 1); } gpio_request(LED_SEC_DISP_GPIO, "dsi1_bl_gpio"); gpio_direction_output(LED_SEC_DISP_GPIO, 1); mdelay(120); gpio_set_value(LED_SEC_DISP_GPIO, 0); } static struct platform_device blaze_disp_led = { .name = "display_led", .id = -1, .dev = { .platform_data = &blaze_disp_led_data, }, }; int __init blaze_panel_init(void) { omap_disp_led_init(); platform_device_register(&blaze_disp_led); return 0; }
MWisBest/android_kernel_amazon_bowser-common
arch/arm/mach-omap2/board-blaze-panel.c
C
gpl-2.0
2,895
<?php /** * Element * * @package Less * @subpackage tree */ class Less_Tree_Element extends Less_Tree{ public $combinator = ''; public $value = ''; public $index; public $currentFileInfo; public $type = 'Element'; public $value_is_object = false; public function __construct($combinator, $value, $index = null, $currentFileInfo = null ){ $this->value = $value; $this->value_is_object = is_object($value); if( $combinator ){ $this->combinator = $combinator; } $this->index = $index; $this->currentFileInfo = $currentFileInfo; } function accept( $visitor ){ if( $this->value_is_object ){ //object or string $this->value = $visitor->visitObj( $this->value ); } } public function compile($env){ if( Less_Environment::$mixin_stack ){ return new Less_Tree_Element($this->combinator, ($this->value_is_object ? $this->value->compile($env) : $this->value), $this->index, $this->currentFileInfo ); } if( $this->value_is_object ){ $this->value = $this->value->compile($env); } return $this; } /** * @see Less_Tree::genCSS */ public function genCSS( $output ){ $output->add( $this->toCSS(), $this->currentFileInfo, $this->index ); } public function toCSS(){ if( $this->value_is_object ){ $value = $this->value->toCSS(); }else{ $value = $this->value; } if( $value === '' && $this->combinator && $this->combinator === '&' ){ return ''; } return Less_Environment::$_outputMap[$this->combinator] . $value; } }
mauricioabisay/loc
wp-content/themes/madison/wp-less/vendor/oyejorge/less.php/lib/Less/Tree/Element.php
PHP
gpl-2.0
1,510
// mkerrors.sh -m32 // Code generated by the command above; see README.md. DO NOT EDIT. //go:build 386 && openbsd // +build 386,openbsd // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs -- -m32 _const.go package unix import "syscall" const ( AF_APPLETALK = 0x10 AF_BLUETOOTH = 0x20 AF_CCITT = 0xa AF_CHAOS = 0x5 AF_CNT = 0x15 AF_COIP = 0x14 AF_DATAKIT = 0x9 AF_DECnet = 0xc AF_DLI = 0xd AF_E164 = 0x1a AF_ECMA = 0x8 AF_ENCAP = 0x1c AF_HYLINK = 0xf AF_IMPLINK = 0x3 AF_INET = 0x2 AF_INET6 = 0x18 AF_IPX = 0x17 AF_ISDN = 0x1a AF_ISO = 0x7 AF_KEY = 0x1e AF_LAT = 0xe AF_LINK = 0x12 AF_LOCAL = 0x1 AF_MAX = 0x24 AF_MPLS = 0x21 AF_NATM = 0x1b AF_NS = 0x6 AF_OSI = 0x7 AF_PUP = 0x4 AF_ROUTE = 0x11 AF_SIP = 0x1d AF_SNA = 0xb AF_UNIX = 0x1 AF_UNSPEC = 0x0 ARPHRD_ETHER = 0x1 ARPHRD_FRELAY = 0xf ARPHRD_IEEE1394 = 0x18 ARPHRD_IEEE802 = 0x6 B0 = 0x0 B110 = 0x6e B115200 = 0x1c200 B1200 = 0x4b0 B134 = 0x86 B14400 = 0x3840 B150 = 0x96 B1800 = 0x708 B19200 = 0x4b00 B200 = 0xc8 B230400 = 0x38400 B2400 = 0x960 B28800 = 0x7080 B300 = 0x12c B38400 = 0x9600 B4800 = 0x12c0 B50 = 0x32 B57600 = 0xe100 B600 = 0x258 B7200 = 0x1c20 B75 = 0x4b B76800 = 0x12c00 B9600 = 0x2580 BIOCFLUSH = 0x20004268 BIOCGBLEN = 0x40044266 BIOCGDIRFILT = 0x4004427c BIOCGDLT = 0x4004426a BIOCGDLTLIST = 0xc008427b BIOCGETIF = 0x4020426b BIOCGFILDROP = 0x40044278 BIOCGHDRCMPLT = 0x40044274 BIOCGRSIG = 0x40044273 BIOCGRTIMEOUT = 0x400c426e BIOCGSTATS = 0x4008426f BIOCIMMEDIATE = 0x80044270 BIOCLOCK = 0x20004276 BIOCPROMISC = 0x20004269 BIOCSBLEN = 0xc0044266 BIOCSDIRFILT = 0x8004427d BIOCSDLT = 0x8004427a BIOCSETF = 0x80084267 BIOCSETIF = 0x8020426c BIOCSETWF = 0x80084277 BIOCSFILDROP = 0x80044279 BIOCSHDRCMPLT = 0x80044275 BIOCSRSIG = 0x80044272 BIOCSRTIMEOUT = 0x800c426d BIOCVERSION = 0x40044271 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALIGNMENT = 0x4 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DIRECTION_IN = 0x1 BPF_DIRECTION_OUT = 0x2 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXBUFSIZE = 0x200000 BPF_MAXINSNS = 0x200 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINBUFSIZE = 0x20 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_OR = 0x40 BPF_RELEASE = 0x30bb6 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BRKINT = 0x2 CFLUSH = 0xf CLOCAL = 0x8000 CPUSTATES = 0x6 CP_IDLE = 0x5 CP_INTR = 0x4 CP_NICE = 0x1 CP_SPIN = 0x3 CP_SYS = 0x2 CP_USER = 0x0 CREAD = 0x800 CRTSCTS = 0x10000 CS5 = 0x0 CS6 = 0x100 CS7 = 0x200 CS8 = 0x300 CSIZE = 0x300 CSTART = 0x11 CSTATUS = 0xff CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a CTL_HW = 0x6 CTL_KERN = 0x1 CTL_MAXNAME = 0xc CTL_NET = 0x4 DIOCOSFPFLUSH = 0x2000444e DLT_ARCNET = 0x7 DLT_ATM_RFC1483 = 0xb DLT_AX25 = 0x3 DLT_CHAOS = 0x5 DLT_C_HDLC = 0x68 DLT_EN10MB = 0x1 DLT_EN3MB = 0x2 DLT_ENC = 0xd DLT_FDDI = 0xa DLT_IEEE802 = 0x6 DLT_IEEE802_11 = 0x69 DLT_IEEE802_11_RADIO = 0x7f DLT_LOOP = 0xc DLT_MPLS = 0xdb DLT_NULL = 0x0 DLT_PFLOG = 0x75 DLT_PFSYNC = 0x12 DLT_PPP = 0x9 DLT_PPP_BSDOS = 0x10 DLT_PPP_ETHER = 0x33 DLT_PPP_SERIAL = 0x32 DLT_PRONET = 0x4 DLT_RAW = 0xe DLT_SLIP = 0x8 DLT_SLIP_BSDOS = 0xf DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 ECHO = 0x8 ECHOCTL = 0x40 ECHOE = 0x2 ECHOK = 0x4 ECHOKE = 0x1 ECHONL = 0x10 ECHOPRT = 0x20 EMT_TAGOVF = 0x1 EMUL_ENABLED = 0x1 EMUL_NATIVE = 0x2 ENDRUNDISC = 0x9 ETHERMIN = 0x2e ETHERMTU = 0x5dc ETHERTYPE_8023 = 0x4 ETHERTYPE_AARP = 0x80f3 ETHERTYPE_ACCTON = 0x8390 ETHERTYPE_AEONIC = 0x8036 ETHERTYPE_ALPHA = 0x814a ETHERTYPE_AMBER = 0x6008 ETHERTYPE_AMOEBA = 0x8145 ETHERTYPE_AOE = 0x88a2 ETHERTYPE_APOLLO = 0x80f7 ETHERTYPE_APOLLODOMAIN = 0x8019 ETHERTYPE_APPLETALK = 0x809b ETHERTYPE_APPLITEK = 0x80c7 ETHERTYPE_ARGONAUT = 0x803a ETHERTYPE_ARP = 0x806 ETHERTYPE_AT = 0x809b ETHERTYPE_ATALK = 0x809b ETHERTYPE_ATOMIC = 0x86df ETHERTYPE_ATT = 0x8069 ETHERTYPE_ATTSTANFORD = 0x8008 ETHERTYPE_AUTOPHON = 0x806a ETHERTYPE_AXIS = 0x8856 ETHERTYPE_BCLOOP = 0x9003 ETHERTYPE_BOFL = 0x8102 ETHERTYPE_CABLETRON = 0x7034 ETHERTYPE_CHAOS = 0x804 ETHERTYPE_COMDESIGN = 0x806c ETHERTYPE_COMPUGRAPHIC = 0x806d ETHERTYPE_COUNTERPOINT = 0x8062 ETHERTYPE_CRONUS = 0x8004 ETHERTYPE_CRONUSVLN = 0x8003 ETHERTYPE_DCA = 0x1234 ETHERTYPE_DDE = 0x807b ETHERTYPE_DEBNI = 0xaaaa ETHERTYPE_DECAM = 0x8048 ETHERTYPE_DECCUST = 0x6006 ETHERTYPE_DECDIAG = 0x6005 ETHERTYPE_DECDNS = 0x803c ETHERTYPE_DECDTS = 0x803e ETHERTYPE_DECEXPER = 0x6000 ETHERTYPE_DECLAST = 0x8041 ETHERTYPE_DECLTM = 0x803f ETHERTYPE_DECMUMPS = 0x6009 ETHERTYPE_DECNETBIOS = 0x8040 ETHERTYPE_DELTACON = 0x86de ETHERTYPE_DIDDLE = 0x4321 ETHERTYPE_DLOG1 = 0x660 ETHERTYPE_DLOG2 = 0x661 ETHERTYPE_DN = 0x6003 ETHERTYPE_DOGFIGHT = 0x1989 ETHERTYPE_DSMD = 0x8039 ETHERTYPE_ECMA = 0x803 ETHERTYPE_ENCRYPT = 0x803d ETHERTYPE_ES = 0x805d ETHERTYPE_EXCELAN = 0x8010 ETHERTYPE_EXPERDATA = 0x8049 ETHERTYPE_FLIP = 0x8146 ETHERTYPE_FLOWCONTROL = 0x8808 ETHERTYPE_FRARP = 0x808 ETHERTYPE_GENDYN = 0x8068 ETHERTYPE_HAYES = 0x8130 ETHERTYPE_HIPPI_FP = 0x8180 ETHERTYPE_HITACHI = 0x8820 ETHERTYPE_HP = 0x8005 ETHERTYPE_IEEEPUP = 0xa00 ETHERTYPE_IEEEPUPAT = 0xa01 ETHERTYPE_IMLBL = 0x4c42 ETHERTYPE_IMLBLDIAG = 0x424c ETHERTYPE_IP = 0x800 ETHERTYPE_IPAS = 0x876c ETHERTYPE_IPV6 = 0x86dd ETHERTYPE_IPX = 0x8137 ETHERTYPE_IPXNEW = 0x8037 ETHERTYPE_KALPANA = 0x8582 ETHERTYPE_LANBRIDGE = 0x8038 ETHERTYPE_LANPROBE = 0x8888 ETHERTYPE_LAT = 0x6004 ETHERTYPE_LBACK = 0x9000 ETHERTYPE_LITTLE = 0x8060 ETHERTYPE_LLDP = 0x88cc ETHERTYPE_LOGICRAFT = 0x8148 ETHERTYPE_LOOPBACK = 0x9000 ETHERTYPE_MATRA = 0x807a ETHERTYPE_MAX = 0xffff ETHERTYPE_MERIT = 0x807c ETHERTYPE_MICP = 0x873a ETHERTYPE_MOPDL = 0x6001 ETHERTYPE_MOPRC = 0x6002 ETHERTYPE_MOTOROLA = 0x818d ETHERTYPE_MPLS = 0x8847 ETHERTYPE_MPLS_MCAST = 0x8848 ETHERTYPE_MUMPS = 0x813f ETHERTYPE_NBPCC = 0x3c04 ETHERTYPE_NBPCLAIM = 0x3c09 ETHERTYPE_NBPCLREQ = 0x3c05 ETHERTYPE_NBPCLRSP = 0x3c06 ETHERTYPE_NBPCREQ = 0x3c02 ETHERTYPE_NBPCRSP = 0x3c03 ETHERTYPE_NBPDG = 0x3c07 ETHERTYPE_NBPDGB = 0x3c08 ETHERTYPE_NBPDLTE = 0x3c0a ETHERTYPE_NBPRAR = 0x3c0c ETHERTYPE_NBPRAS = 0x3c0b ETHERTYPE_NBPRST = 0x3c0d ETHERTYPE_NBPSCD = 0x3c01 ETHERTYPE_NBPVCD = 0x3c00 ETHERTYPE_NBS = 0x802 ETHERTYPE_NCD = 0x8149 ETHERTYPE_NESTAR = 0x8006 ETHERTYPE_NETBEUI = 0x8191 ETHERTYPE_NOVELL = 0x8138 ETHERTYPE_NS = 0x600 ETHERTYPE_NSAT = 0x601 ETHERTYPE_NSCOMPAT = 0x807 ETHERTYPE_NTRAILER = 0x10 ETHERTYPE_OS9 = 0x7007 ETHERTYPE_OS9NET = 0x7009 ETHERTYPE_PACER = 0x80c6 ETHERTYPE_PAE = 0x888e ETHERTYPE_PCS = 0x4242 ETHERTYPE_PLANNING = 0x8044 ETHERTYPE_PPP = 0x880b ETHERTYPE_PPPOE = 0x8864 ETHERTYPE_PPPOEDISC = 0x8863 ETHERTYPE_PRIMENTS = 0x7031 ETHERTYPE_PUP = 0x200 ETHERTYPE_PUPAT = 0x200 ETHERTYPE_QINQ = 0x88a8 ETHERTYPE_RACAL = 0x7030 ETHERTYPE_RATIONAL = 0x8150 ETHERTYPE_RAWFR = 0x6559 ETHERTYPE_RCL = 0x1995 ETHERTYPE_RDP = 0x8739 ETHERTYPE_RETIX = 0x80f2 ETHERTYPE_REVARP = 0x8035 ETHERTYPE_SCA = 0x6007 ETHERTYPE_SECTRA = 0x86db ETHERTYPE_SECUREDATA = 0x876d ETHERTYPE_SGITW = 0x817e ETHERTYPE_SG_BOUNCE = 0x8016 ETHERTYPE_SG_DIAG = 0x8013 ETHERTYPE_SG_NETGAMES = 0x8014 ETHERTYPE_SG_RESV = 0x8015 ETHERTYPE_SIMNET = 0x5208 ETHERTYPE_SLOW = 0x8809 ETHERTYPE_SNA = 0x80d5 ETHERTYPE_SNMP = 0x814c ETHERTYPE_SONIX = 0xfaf5 ETHERTYPE_SPIDER = 0x809f ETHERTYPE_SPRITE = 0x500 ETHERTYPE_STP = 0x8181 ETHERTYPE_TALARIS = 0x812b ETHERTYPE_TALARISMC = 0x852b ETHERTYPE_TCPCOMP = 0x876b ETHERTYPE_TCPSM = 0x9002 ETHERTYPE_TEC = 0x814f ETHERTYPE_TIGAN = 0x802f ETHERTYPE_TRAIL = 0x1000 ETHERTYPE_TRANSETHER = 0x6558 ETHERTYPE_TYMSHARE = 0x802e ETHERTYPE_UBBST = 0x7005 ETHERTYPE_UBDEBUG = 0x900 ETHERTYPE_UBDIAGLOOP = 0x7002 ETHERTYPE_UBDL = 0x7000 ETHERTYPE_UBNIU = 0x7001 ETHERTYPE_UBNMC = 0x7003 ETHERTYPE_VALID = 0x1600 ETHERTYPE_VARIAN = 0x80dd ETHERTYPE_VAXELN = 0x803b ETHERTYPE_VEECO = 0x8067 ETHERTYPE_VEXP = 0x805b ETHERTYPE_VGLAB = 0x8131 ETHERTYPE_VINES = 0xbad ETHERTYPE_VINESECHO = 0xbaf ETHERTYPE_VINESLOOP = 0xbae ETHERTYPE_VITAL = 0xff00 ETHERTYPE_VLAN = 0x8100 ETHERTYPE_VLTLMAN = 0x8080 ETHERTYPE_VPROD = 0x805c ETHERTYPE_VURESERVED = 0x8147 ETHERTYPE_WATERLOO = 0x8130 ETHERTYPE_WELLFLEET = 0x8103 ETHERTYPE_X25 = 0x805 ETHERTYPE_X75 = 0x801 ETHERTYPE_XNSSM = 0x9001 ETHERTYPE_XTP = 0x817d ETHER_ADDR_LEN = 0x6 ETHER_ALIGN = 0x2 ETHER_CRC_LEN = 0x4 ETHER_CRC_POLY_BE = 0x4c11db6 ETHER_CRC_POLY_LE = 0xedb88320 ETHER_HDR_LEN = 0xe ETHER_MAX_DIX_LEN = 0x600 ETHER_MAX_LEN = 0x5ee ETHER_MIN_LEN = 0x40 ETHER_TYPE_LEN = 0x2 ETHER_VLAN_ENCAP_LEN = 0x4 EVFILT_AIO = -0x3 EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0x7 EVFILT_TIMER = -0x7 EVFILT_VNODE = -0x4 EVFILT_WRITE = -0x2 EV_ADD = 0x1 EV_CLEAR = 0x20 EV_DELETE = 0x2 EV_DISABLE = 0x8 EV_ENABLE = 0x4 EV_EOF = 0x8000 EV_ERROR = 0x4000 EV_FLAG1 = 0x2000 EV_ONESHOT = 0x10 EV_SYSFLAGS = 0xf000 EXTA = 0x4b00 EXTB = 0x9600 EXTPROC = 0x800 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FLUSHO = 0x800000 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0xa F_GETFD = 0x1 F_GETFL = 0x3 F_GETLK = 0x7 F_GETOWN = 0x5 F_OK = 0x0 F_RDLCK = 0x1 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLK = 0x8 F_SETLKW = 0x9 F_SETOWN = 0x6 F_UNLCK = 0x2 F_WRLCK = 0x3 HUPCL = 0x4000 HW_MACHINE = 0x1 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 IEXTEN = 0x400 IFAN_ARRIVAL = 0x0 IFAN_DEPARTURE = 0x1 IFA_ROUTE = 0x1 IFF_ALLMULTI = 0x200 IFF_BROADCAST = 0x2 IFF_CANTCHANGE = 0x8e52 IFF_DEBUG = 0x4 IFF_LINK0 = 0x1000 IFF_LINK1 = 0x2000 IFF_LINK2 = 0x4000 IFF_LOOPBACK = 0x8 IFF_MULTICAST = 0x8000 IFF_NOARP = 0x80 IFF_NOTRAILERS = 0x20 IFF_OACTIVE = 0x400 IFF_POINTOPOINT = 0x10 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SIMPLEX = 0x800 IFF_UP = 0x1 IFNAMSIZ = 0x10 IFT_1822 = 0x2 IFT_A12MPPSWITCH = 0x82 IFT_AAL2 = 0xbb IFT_AAL5 = 0x31 IFT_ADSL = 0x5e IFT_AFLANE8023 = 0x3b IFT_AFLANE8025 = 0x3c IFT_ARAP = 0x58 IFT_ARCNET = 0x23 IFT_ARCNETPLUS = 0x24 IFT_ASYNC = 0x54 IFT_ATM = 0x25 IFT_ATMDXI = 0x69 IFT_ATMFUNI = 0x6a IFT_ATMIMA = 0x6b IFT_ATMLOGICAL = 0x50 IFT_ATMRADIO = 0xbd IFT_ATMSUBINTERFACE = 0x86 IFT_ATMVCIENDPT = 0xc2 IFT_ATMVIRTUAL = 0x95 IFT_BGPPOLICYACCOUNTING = 0xa2 IFT_BLUETOOTH = 0xf8 IFT_BRIDGE = 0xd1 IFT_BSC = 0x53 IFT_CARP = 0xf7 IFT_CCTEMUL = 0x3d IFT_CEPT = 0x13 IFT_CES = 0x85 IFT_CHANNEL = 0x46 IFT_CNR = 0x55 IFT_COFFEE = 0x84 IFT_COMPOSITELINK = 0x9b IFT_DCN = 0x8d IFT_DIGITALPOWERLINE = 0x8a IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba IFT_DLSW = 0x4a IFT_DOCSCABLEDOWNSTREAM = 0x80 IFT_DOCSCABLEMACLAYER = 0x7f IFT_DOCSCABLEUPSTREAM = 0x81 IFT_DOCSCABLEUPSTREAMCHANNEL = 0xcd IFT_DS0 = 0x51 IFT_DS0BUNDLE = 0x52 IFT_DS1FDL = 0xaa IFT_DS3 = 0x1e IFT_DTM = 0x8c IFT_DUMMY = 0xf1 IFT_DVBASILN = 0xac IFT_DVBASIOUT = 0xad IFT_DVBRCCDOWNSTREAM = 0x93 IFT_DVBRCCMACLAYER = 0x92 IFT_DVBRCCUPSTREAM = 0x94 IFT_ECONET = 0xce IFT_ENC = 0xf4 IFT_EON = 0x19 IFT_EPLRS = 0x57 IFT_ESCON = 0x49 IFT_ETHER = 0x6 IFT_FAITH = 0xf3 IFT_FAST = 0x7d IFT_FASTETHER = 0x3e IFT_FASTETHERFX = 0x45 IFT_FDDI = 0xf IFT_FIBRECHANNEL = 0x38 IFT_FRAMERELAYINTERCONNECT = 0x3a IFT_FRAMERELAYMPI = 0x5c IFT_FRDLCIENDPT = 0xc1 IFT_FRELAY = 0x20 IFT_FRELAYDCE = 0x2c IFT_FRF16MFRBUNDLE = 0xa3 IFT_FRFORWARD = 0x9e IFT_G703AT2MB = 0x43 IFT_G703AT64K = 0x42 IFT_GIF = 0xf0 IFT_GIGABITETHERNET = 0x75 IFT_GR303IDT = 0xb2 IFT_GR303RDT = 0xb1 IFT_H323GATEKEEPER = 0xa4 IFT_H323PROXY = 0xa5 IFT_HDH1822 = 0x3 IFT_HDLC = 0x76 IFT_HDSL2 = 0xa8 IFT_HIPERLAN2 = 0xb7 IFT_HIPPI = 0x2f IFT_HIPPIINTERFACE = 0x39 IFT_HOSTPAD = 0x5a IFT_HSSI = 0x2e IFT_HY = 0xe IFT_IBM370PARCHAN = 0x48 IFT_IDSL = 0x9a IFT_IEEE1394 = 0x90 IFT_IEEE80211 = 0x47 IFT_IEEE80212 = 0x37 IFT_IEEE8023ADLAG = 0xa1 IFT_IFGSN = 0x91 IFT_IMT = 0xbe IFT_INFINIBAND = 0xc7 IFT_INTERLEAVE = 0x7c IFT_IP = 0x7e IFT_IPFORWARD = 0x8e IFT_IPOVERATM = 0x72 IFT_IPOVERCDLC = 0x6d IFT_IPOVERCLAW = 0x6e IFT_IPSWITCH = 0x4e IFT_ISDN = 0x3f IFT_ISDNBASIC = 0x14 IFT_ISDNPRIMARY = 0x15 IFT_ISDNS = 0x4b IFT_ISDNU = 0x4c IFT_ISO88022LLC = 0x29 IFT_ISO88023 = 0x7 IFT_ISO88024 = 0x8 IFT_ISO88025 = 0x9 IFT_ISO88025CRFPINT = 0x62 IFT_ISO88025DTR = 0x56 IFT_ISO88025FIBER = 0x73 IFT_ISO88026 = 0xa IFT_ISUP = 0xb3 IFT_L2VLAN = 0x87 IFT_L3IPVLAN = 0x88 IFT_L3IPXVLAN = 0x89 IFT_LAPB = 0x10 IFT_LAPD = 0x4d IFT_LAPF = 0x77 IFT_LINEGROUP = 0xd2 IFT_LOCALTALK = 0x2a IFT_LOOP = 0x18 IFT_MEDIAMAILOVERIP = 0x8b IFT_MFSIGLINK = 0xa7 IFT_MIOX25 = 0x26 IFT_MODEM = 0x30 IFT_MPC = 0x71 IFT_MPLS = 0xa6 IFT_MPLSTUNNEL = 0x96 IFT_MSDSL = 0x8f IFT_MVL = 0xbf IFT_MYRINET = 0x63 IFT_NFAS = 0xaf IFT_NSIP = 0x1b IFT_OPTICALCHANNEL = 0xc3 IFT_OPTICALTRANSPORT = 0xc4 IFT_OTHER = 0x1 IFT_P10 = 0xc IFT_P80 = 0xd IFT_PARA = 0x22 IFT_PFLOG = 0xf5 IFT_PFLOW = 0xf9 IFT_PFSYNC = 0xf6 IFT_PLC = 0xae IFT_PON155 = 0xcf IFT_PON622 = 0xd0 IFT_POS = 0xab IFT_PPP = 0x17 IFT_PPPMULTILINKBUNDLE = 0x6c IFT_PROPATM = 0xc5 IFT_PROPBWAP2MP = 0xb8 IFT_PROPCNLS = 0x59 IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5 IFT_PROPDOCSWIRELESSMACLAYER = 0xb4 IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6 IFT_PROPMUX = 0x36 IFT_PROPVIRTUAL = 0x35 IFT_PROPWIRELESSP2P = 0x9d IFT_PTPSERIAL = 0x16 IFT_PVC = 0xf2 IFT_Q2931 = 0xc9 IFT_QLLC = 0x44 IFT_RADIOMAC = 0xbc IFT_RADSL = 0x5f IFT_REACHDSL = 0xc0 IFT_RFC1483 = 0x9f IFT_RS232 = 0x21 IFT_RSRB = 0x4f IFT_SDLC = 0x11 IFT_SDSL = 0x60 IFT_SHDSL = 0xa9 IFT_SIP = 0x1f IFT_SIPSIG = 0xcc IFT_SIPTG = 0xcb IFT_SLIP = 0x1c IFT_SMDSDXI = 0x2b IFT_SMDSICIP = 0x34 IFT_SONET = 0x27 IFT_SONETOVERHEADCHANNEL = 0xb9 IFT_SONETPATH = 0x32 IFT_SONETVT = 0x33 IFT_SRP = 0x97 IFT_SS7SIGLINK = 0x9c IFT_STACKTOSTACK = 0x6f IFT_STARLAN = 0xb IFT_T1 = 0x12 IFT_TDLC = 0x74 IFT_TELINK = 0xc8 IFT_TERMPAD = 0x5b IFT_TR008 = 0xb0 IFT_TRANSPHDLC = 0x7b IFT_TUNNEL = 0x83 IFT_ULTRA = 0x1d IFT_USB = 0xa0 IFT_V11 = 0x40 IFT_V35 = 0x2d IFT_V36 = 0x41 IFT_V37 = 0x78 IFT_VDSL = 0x61 IFT_VIRTUALIPADDRESS = 0x70 IFT_VIRTUALTG = 0xca IFT_VOICEDID = 0xd5 IFT_VOICEEM = 0x64 IFT_VOICEEMFGD = 0xd3 IFT_VOICEENCAP = 0x67 IFT_VOICEFGDEANA = 0xd4 IFT_VOICEFXO = 0x65 IFT_VOICEFXS = 0x66 IFT_VOICEOVERATM = 0x98 IFT_VOICEOVERCABLE = 0xc6 IFT_VOICEOVERFRAMERELAY = 0x99 IFT_VOICEOVERIP = 0x68 IFT_X213 = 0x5d IFT_X25 = 0x5 IFT_X25DDN = 0x4 IFT_X25HUNTGROUP = 0x7a IFT_X25MLP = 0x79 IFT_X25PLE = 0x28 IFT_XETHER = 0x1a IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLASSD_HOST = 0xfffffff IN_CLASSD_NET = 0xf0000000 IN_CLASSD_NSHIFT = 0x1c IN_LOOPBACKNET = 0x7f IN_RFC3021_HOST = 0x1 IN_RFC3021_NET = 0xfffffffe IN_RFC3021_NSHIFT = 0x1f IPPROTO_AH = 0x33 IPPROTO_CARP = 0x70 IPPROTO_DIVERT = 0x102 IPPROTO_DIVERT_INIT = 0x2 IPPROTO_DIVERT_RESP = 0x1 IPPROTO_DONE = 0x101 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_ENCAP = 0x62 IPPROTO_EON = 0x50 IPPROTO_ESP = 0x32 IPPROTO_ETHERIP = 0x61 IPPROTO_FRAGMENT = 0x2c IPPROTO_GGP = 0x3 IPPROTO_GRE = 0x2f IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IGMP = 0x2 IPPROTO_IP = 0x0 IPPROTO_IPCOMP = 0x6c IPPROTO_IPIP = 0x4 IPPROTO_IPV4 = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_MAX = 0x100 IPPROTO_MAXID = 0x103 IPPROTO_MOBILE = 0x37 IPPROTO_MPLS = 0x89 IPPROTO_NONE = 0x3b IPPROTO_PFSYNC = 0xf0 IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPV6_AUTH_LEVEL = 0x35 IPV6_AUTOFLOWLABEL = 0x3b IPV6_CHECKSUM = 0x1a IPV6_DEFAULT_MULTICAST_HOPS = 0x1 IPV6_DEFAULT_MULTICAST_LOOP = 0x1 IPV6_DEFHLIM = 0x40 IPV6_DONTFRAG = 0x3e IPV6_DSTOPTS = 0x32 IPV6_ESP_NETWORK_LEVEL = 0x37 IPV6_ESP_TRANS_LEVEL = 0x36 IPV6_FAITH = 0x1d IPV6_FLOWINFO_MASK = 0xffffff0f IPV6_FLOWLABEL_MASK = 0xffff0f00 IPV6_FRAGTTL = 0x78 IPV6_HLIMDEC = 0x1 IPV6_HOPLIMIT = 0x2f IPV6_HOPOPTS = 0x31 IPV6_IPCOMP_LEVEL = 0x3c IPV6_JOIN_GROUP = 0xc IPV6_LEAVE_GROUP = 0xd IPV6_MAXHLIM = 0xff IPV6_MAXPACKET = 0xffff IPV6_MMTU = 0x500 IPV6_MULTICAST_HOPS = 0xa IPV6_MULTICAST_IF = 0x9 IPV6_MULTICAST_LOOP = 0xb IPV6_NEXTHOP = 0x30 IPV6_OPTIONS = 0x1 IPV6_PATHMTU = 0x2c IPV6_PIPEX = 0x3f IPV6_PKTINFO = 0x2e IPV6_PORTRANGE = 0xe IPV6_PORTRANGE_DEFAULT = 0x0 IPV6_PORTRANGE_HIGH = 0x1 IPV6_PORTRANGE_LOW = 0x2 IPV6_RECVDSTOPTS = 0x28 IPV6_RECVDSTPORT = 0x40 IPV6_RECVHOPLIMIT = 0x25 IPV6_RECVHOPOPTS = 0x27 IPV6_RECVPATHMTU = 0x2b IPV6_RECVPKTINFO = 0x24 IPV6_RECVRTHDR = 0x26 IPV6_RECVTCLASS = 0x39 IPV6_RTABLE = 0x1021 IPV6_RTHDR = 0x33 IPV6_RTHDRDSTOPTS = 0x23 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_SOCKOPT_RESERVED1 = 0x3 IPV6_TCLASS = 0x3d IPV6_UNICAST_HOPS = 0x4 IPV6_USE_MIN_MTU = 0x2a IPV6_V6ONLY = 0x1b IPV6_VERSION = 0x60 IPV6_VERSION_MASK = 0xf0 IP_ADD_MEMBERSHIP = 0xc IP_AUTH_LEVEL = 0x14 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DIVERTFL = 0x1022 IP_DROP_MEMBERSHIP = 0xd IP_ESP_NETWORK_LEVEL = 0x16 IP_ESP_TRANS_LEVEL = 0x15 IP_HDRINCL = 0x2 IP_IPCOMP_LEVEL = 0x1d IP_IPSECFLOWINFO = 0x24 IP_IPSEC_LOCAL_AUTH = 0x1b IP_IPSEC_LOCAL_CRED = 0x19 IP_IPSEC_LOCAL_ID = 0x17 IP_IPSEC_REMOTE_AUTH = 0x1c IP_IPSEC_REMOTE_CRED = 0x1a IP_IPSEC_REMOTE_ID = 0x18 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0xfff IP_MF = 0x2000 IP_MINTTL = 0x20 IP_MIN_MEMBERSHIPS = 0xf IP_MSS = 0x240 IP_MULTICAST_IF = 0x9 IP_MULTICAST_LOOP = 0xb IP_MULTICAST_TTL = 0xa IP_OFFMASK = 0x1fff IP_OPTIONS = 0x1 IP_PIPEX = 0x22 IP_PORTRANGE = 0x13 IP_PORTRANGE_DEFAULT = 0x0 IP_PORTRANGE_HIGH = 0x1 IP_PORTRANGE_LOW = 0x2 IP_RECVDSTADDR = 0x7 IP_RECVDSTPORT = 0x21 IP_RECVIF = 0x1e IP_RECVOPTS = 0x5 IP_RECVRETOPTS = 0x6 IP_RECVRTABLE = 0x23 IP_RECVTTL = 0x1f IP_RETOPTS = 0x8 IP_RF = 0x8000 IP_RTABLE = 0x1021 IP_TOS = 0x3 IP_TTL = 0x4 ISIG = 0x80 ISTRIP = 0x20 IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 KERN_HOSTNAME = 0xa KERN_OSRELEASE = 0x2 KERN_OSTYPE = 0x1 KERN_VERSION = 0x4 LCNT_OVERLOAD_FLUSH = 0x6 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_DONTNEED = 0x4 MADV_FREE = 0x6 MADV_NORMAL = 0x0 MADV_RANDOM = 0x1 MADV_SEQUENTIAL = 0x2 MADV_SPACEAVAIL = 0x5 MADV_WILLNEED = 0x3 MAP_ANON = 0x1000 MAP_ANONYMOUS = 0x1000 MAP_CONCEAL = 0x8000 MAP_COPY = 0x2 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_FLAGMASK = 0xfff7 MAP_HASSEMAPHORE = 0x0 MAP_INHERIT = 0x0 MAP_INHERIT_COPY = 0x1 MAP_INHERIT_NONE = 0x2 MAP_INHERIT_SHARE = 0x0 MAP_NOEXTEND = 0x100 MAP_NORESERVE = 0x40 MAP_PRIVATE = 0x2 MAP_RENAME = 0x20 MAP_SHARED = 0x1 MAP_STACK = 0x4000 MAP_TRYFIXED = 0x0 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MNT_ASYNC = 0x40 MNT_DEFEXPORTED = 0x200 MNT_DELEXPORT = 0x20000 MNT_DOOMED = 0x8000000 MNT_EXPORTANON = 0x400 MNT_EXPORTED = 0x100 MNT_EXRDONLY = 0x80 MNT_FORCE = 0x80000 MNT_LAZY = 0x3 MNT_LOCAL = 0x1000 MNT_NOATIME = 0x8000 MNT_NODEV = 0x10 MNT_NOEXEC = 0x4 MNT_NOSUID = 0x8 MNT_NOWAIT = 0x2 MNT_QUOTA = 0x2000 MNT_RDONLY = 0x1 MNT_RELOAD = 0x40000 MNT_ROOTFS = 0x4000 MNT_SOFTDEP = 0x4000000 MNT_SYNCHRONOUS = 0x2 MNT_UPDATE = 0x10000 MNT_VISFLAGMASK = 0x400ffff MNT_WAIT = 0x1 MNT_WANTRDWR = 0x2000000 MNT_WXALLOWED = 0x800 MSG_BCAST = 0x100 MSG_CTRUNC = 0x20 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x80 MSG_EOR = 0x8 MSG_MCAST = 0x200 MSG_NOSIGNAL = 0x400 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_TRUNC = 0x10 MSG_WAITALL = 0x40 MS_ASYNC = 0x1 MS_INVALIDATE = 0x4 MS_SYNC = 0x2 NAME_MAX = 0xff NET_RT_DUMP = 0x1 NET_RT_FLAGS = 0x2 NET_RT_IFLIST = 0x3 NET_RT_MAXID = 0x6 NET_RT_STATS = 0x4 NET_RT_TABLE = 0x5 NFDBITS = 0x20 NOFLSH = 0x80000000 NOTE_ATTRIB = 0x8 NOTE_CHILD = 0x4 NOTE_DELETE = 0x1 NOTE_EOF = 0x2 NOTE_EXEC = 0x20000000 NOTE_EXIT = 0x80000000 NOTE_EXTEND = 0x4 NOTE_FORK = 0x40000000 NOTE_LINK = 0x10 NOTE_LOWAT = 0x1 NOTE_PCTRLMASK = 0xf0000000 NOTE_PDATAMASK = 0xfffff NOTE_RENAME = 0x20 NOTE_REVOKE = 0x40 NOTE_TRACK = 0x1 NOTE_TRACKERR = 0x2 NOTE_TRUNCATE = 0x80 NOTE_WRITE = 0x2 OCRNL = 0x10 ONLCR = 0x2 ONLRET = 0x80 ONOCR = 0x40 ONOEOT = 0x8 OPOST = 0x1 O_ACCMODE = 0x3 O_APPEND = 0x8 O_ASYNC = 0x40 O_CLOEXEC = 0x10000 O_CREAT = 0x200 O_DIRECTORY = 0x20000 O_DSYNC = 0x80 O_EXCL = 0x800 O_EXLOCK = 0x20 O_FSYNC = 0x80 O_NDELAY = 0x4 O_NOCTTY = 0x8000 O_NOFOLLOW = 0x100 O_NONBLOCK = 0x4 O_RDONLY = 0x0 O_RDWR = 0x2 O_RSYNC = 0x80 O_SHLOCK = 0x10 O_SYNC = 0x80 O_TRUNC = 0x400 O_WRONLY = 0x1 PARENB = 0x1000 PARMRK = 0x8 PARODD = 0x2000 PENDIN = 0x20000000 PF_FLUSH = 0x1 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 PT_MASK = 0x3ff000 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_NOFILE = 0x8 RLIMIT_STACK = 0x3 RLIM_INFINITY = 0x7fffffffffffffff RTAX_AUTHOR = 0x6 RTAX_BRD = 0x7 RTAX_DST = 0x0 RTAX_GATEWAY = 0x1 RTAX_GENMASK = 0x3 RTAX_IFA = 0x5 RTAX_IFP = 0x4 RTAX_LABEL = 0xa RTAX_MAX = 0xb RTAX_NETMASK = 0x2 RTAX_SRC = 0x8 RTAX_SRCMASK = 0x9 RTA_AUTHOR = 0x40 RTA_BRD = 0x80 RTA_DST = 0x1 RTA_GATEWAY = 0x2 RTA_GENMASK = 0x8 RTA_IFA = 0x20 RTA_IFP = 0x10 RTA_LABEL = 0x400 RTA_NETMASK = 0x4 RTA_SRC = 0x100 RTA_SRCMASK = 0x200 RTF_ANNOUNCE = 0x4000 RTF_BLACKHOLE = 0x1000 RTF_CLONED = 0x10000 RTF_CLONING = 0x100 RTF_DONE = 0x40 RTF_DYNAMIC = 0x10 RTF_FMASK = 0x10f808 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_LLINFO = 0x400 RTF_MASK = 0x80 RTF_MODIFIED = 0x20 RTF_MPATH = 0x40000 RTF_MPLS = 0x100000 RTF_PERMANENT_ARP = 0x2000 RTF_PROTO1 = 0x8000 RTF_PROTO2 = 0x4000 RTF_PROTO3 = 0x2000 RTF_REJECT = 0x8 RTF_SOURCE = 0x20000 RTF_STATIC = 0x800 RTF_TUNNEL = 0x100000 RTF_UP = 0x1 RTF_USETRAILERS = 0x8000 RTF_XRESOLVE = 0x200 RTM_ADD = 0x1 RTM_CHANGE = 0x3 RTM_DELADDR = 0xd RTM_DELETE = 0x2 RTM_DESYNC = 0x10 RTM_GET = 0x4 RTM_IFANNOUNCE = 0xf RTM_IFINFO = 0xe RTM_LOCK = 0x8 RTM_LOSING = 0x5 RTM_MAXSIZE = 0x800 RTM_MISS = 0x7 RTM_NEWADDR = 0xc RTM_REDIRECT = 0x6 RTM_RESOLVE = 0xb RTM_RTTUNIT = 0xf4240 RTM_VERSION = 0x5 RTV_EXPIRE = 0x4 RTV_HOPCOUNT = 0x2 RTV_MTU = 0x1 RTV_RPIPE = 0x8 RTV_RTT = 0x40 RTV_RTTVAR = 0x80 RTV_SPIPE = 0x10 RTV_SSTHRESH = 0x20 RT_TABLEID_MAX = 0xff RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x4 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDMULTI = 0x80206931 SIOCAIFADDR = 0x8040691a SIOCAIFGROUP = 0x80246987 SIOCALIFADDR = 0x8218691c SIOCATMARK = 0x40047307 SIOCBRDGADD = 0x8054693c SIOCBRDGADDS = 0x80546941 SIOCBRDGARL = 0x806e694d SIOCBRDGDADDR = 0x81286947 SIOCBRDGDEL = 0x8054693d SIOCBRDGDELS = 0x80546942 SIOCBRDGFLUSH = 0x80546948 SIOCBRDGFRL = 0x806e694e SIOCBRDGGCACHE = 0xc0146941 SIOCBRDGGFD = 0xc0146952 SIOCBRDGGHT = 0xc0146951 SIOCBRDGGIFFLGS = 0xc054693e SIOCBRDGGMA = 0xc0146953 SIOCBRDGGPARAM = 0xc03c6958 SIOCBRDGGPRI = 0xc0146950 SIOCBRDGGRL = 0xc028694f SIOCBRDGGSIFS = 0xc054693c SIOCBRDGGTO = 0xc0146946 SIOCBRDGIFS = 0xc0546942 SIOCBRDGRTS = 0xc0186943 SIOCBRDGSADDR = 0xc1286944 SIOCBRDGSCACHE = 0x80146940 SIOCBRDGSFD = 0x80146952 SIOCBRDGSHT = 0x80146951 SIOCBRDGSIFCOST = 0x80546955 SIOCBRDGSIFFLGS = 0x8054693f SIOCBRDGSIFPRIO = 0x80546954 SIOCBRDGSMA = 0x80146953 SIOCBRDGSPRI = 0x80146950 SIOCBRDGSPROTO = 0x8014695a SIOCBRDGSTO = 0x80146945 SIOCBRDGSTXHC = 0x80146959 SIOCDELMULTI = 0x80206932 SIOCDIFADDR = 0x80206919 SIOCDIFGROUP = 0x80246989 SIOCDIFPHYADDR = 0x80206949 SIOCDLIFADDR = 0x8218691e SIOCGETKALIVE = 0xc01869a4 SIOCGETLABEL = 0x8020699a SIOCGETPFLOW = 0xc02069fe SIOCGETPFSYNC = 0xc02069f8 SIOCGETSGCNT = 0xc0147534 SIOCGETVIFCNT = 0xc0147533 SIOCGETVLAN = 0xc0206990 SIOCGHIWAT = 0x40047301 SIOCGIFADDR = 0xc0206921 SIOCGIFASYNCMAP = 0xc020697c SIOCGIFBRDADDR = 0xc0206923 SIOCGIFCONF = 0xc0086924 SIOCGIFDATA = 0xc020691b SIOCGIFDESCR = 0xc0206981 SIOCGIFDSTADDR = 0xc0206922 SIOCGIFFLAGS = 0xc0206911 SIOCGIFGATTR = 0xc024698b SIOCGIFGENERIC = 0xc020693a SIOCGIFGMEMB = 0xc024698a SIOCGIFGROUP = 0xc0246988 SIOCGIFHARDMTU = 0xc02069a5 SIOCGIFMEDIA = 0xc0286936 SIOCGIFMETRIC = 0xc0206917 SIOCGIFMTU = 0xc020697e SIOCGIFNETMASK = 0xc0206925 SIOCGIFPDSTADDR = 0xc0206948 SIOCGIFPRIORITY = 0xc020699c SIOCGIFPSRCADDR = 0xc0206947 SIOCGIFRDOMAIN = 0xc02069a0 SIOCGIFRTLABEL = 0xc0206983 SIOCGIFTIMESLOT = 0xc0206986 SIOCGIFXFLAGS = 0xc020699e SIOCGLIFADDR = 0xc218691d SIOCGLIFPHYADDR = 0xc218694b SIOCGLIFPHYRTABLE = 0xc02069a2 SIOCGLIFPHYTTL = 0xc02069a9 SIOCGLOWAT = 0x40047303 SIOCGPGRP = 0x40047309 SIOCGSPPPPARAMS = 0xc0206994 SIOCGVH = 0xc02069f6 SIOCGVNETID = 0xc02069a7 SIOCIFCREATE = 0x8020697a SIOCIFDESTROY = 0x80206979 SIOCIFGCLONERS = 0xc00c6978 SIOCSETKALIVE = 0x801869a3 SIOCSETLABEL = 0x80206999 SIOCSETPFLOW = 0x802069fd SIOCSETPFSYNC = 0x802069f7 SIOCSETVLAN = 0x8020698f SIOCSHIWAT = 0x80047300 SIOCSIFADDR = 0x8020690c SIOCSIFASYNCMAP = 0x8020697d SIOCSIFBRDADDR = 0x80206913 SIOCSIFDESCR = 0x80206980 SIOCSIFDSTADDR = 0x8020690e SIOCSIFFLAGS = 0x80206910 SIOCSIFGATTR = 0x8024698c SIOCSIFGENERIC = 0x80206939 SIOCSIFLLADDR = 0x8020691f SIOCSIFMEDIA = 0xc0206935 SIOCSIFMETRIC = 0x80206918 SIOCSIFMTU = 0x8020697f SIOCSIFNETMASK = 0x80206916 SIOCSIFPHYADDR = 0x80406946 SIOCSIFPRIORITY = 0x8020699b SIOCSIFRDOMAIN = 0x8020699f SIOCSIFRTLABEL = 0x80206982 SIOCSIFTIMESLOT = 0x80206985 SIOCSIFXFLAGS = 0x8020699d SIOCSLIFPHYADDR = 0x8218694a SIOCSLIFPHYRTABLE = 0x802069a1 SIOCSLIFPHYTTL = 0x802069a8 SIOCSLOWAT = 0x80047302 SIOCSPGRP = 0x80047308 SIOCSSPPPPARAMS = 0x80206993 SIOCSVH = 0xc02069f5 SIOCSVNETID = 0x802069a6 SOCK_DGRAM = 0x2 SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_SOCKET = 0xffff SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x2 SO_BINDANY = 0x1000 SO_BROADCAST = 0x20 SO_DEBUG = 0x1 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 SO_KEEPALIVE = 0x8 SO_LINGER = 0x80 SO_NETPROC = 0x1020 SO_OOBINLINE = 0x100 SO_PEERCRED = 0x1022 SO_RCVBUF = 0x1002 SO_RCVLOWAT = 0x1004 SO_RCVTIMEO = 0x1006 SO_REUSEADDR = 0x4 SO_REUSEPORT = 0x200 SO_RTABLE = 0x1021 SO_SNDBUF = 0x1001 SO_SNDLOWAT = 0x1003 SO_SNDTIMEO = 0x1005 SO_SPLICE = 0x1023 SO_TIMESTAMP = 0x800 SO_TYPE = 0x1008 SO_USELOOPBACK = 0x40 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFIFO = 0x1000 S_IFLNK = 0xa000 S_IFMT = 0xf000 S_IFREG = 0x8000 S_IFSOCK = 0xc000 S_IREAD = 0x100 S_IRGRP = 0x20 S_IROTH = 0x4 S_IRUSR = 0x100 S_IRWXG = 0x38 S_IRWXO = 0x7 S_IRWXU = 0x1c0 S_ISGID = 0x400 S_ISTXT = 0x200 S_ISUID = 0x800 S_ISVTX = 0x200 S_IWGRP = 0x10 S_IWOTH = 0x2 S_IWRITE = 0x80 S_IWUSR = 0x80 S_IXGRP = 0x8 S_IXOTH = 0x1 S_IXUSR = 0x40 TCIFLUSH = 0x1 TCIOFLUSH = 0x3 TCOFLUSH = 0x2 TCP_MAXBURST = 0x4 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_SACK = 0x3 TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0x4 TCP_MSS = 0x200 TCP_NODELAY = 0x1 TCP_NOPUSH = 0x10 TCP_NSTATES = 0xb TCP_SACK_ENABLE = 0x8 TCSAFLUSH = 0x2 TIOCCBRK = 0x2000747a TIOCCDTR = 0x20007478 TIOCCONS = 0x80047462 TIOCDRAIN = 0x2000745e TIOCEXCL = 0x2000740d TIOCEXT = 0x80047460 TIOCFLAG_CLOCAL = 0x2 TIOCFLAG_CRTSCTS = 0x4 TIOCFLAG_MDMBUF = 0x8 TIOCFLAG_PPS = 0x10 TIOCFLAG_SOFTCAR = 0x1 TIOCFLUSH = 0x80047410 TIOCGETA = 0x402c7413 TIOCGETD = 0x4004741a TIOCGFLAGS = 0x4004745d TIOCGPGRP = 0x40047477 TIOCGSID = 0x40047463 TIOCGTSTAMP = 0x400c745b TIOCGWINSZ = 0x40087468 TIOCMBIC = 0x8004746b TIOCMBIS = 0x8004746c TIOCMGET = 0x4004746a TIOCMODG = 0x4004746a TIOCMODS = 0x8004746d TIOCMSET = 0x8004746d TIOCM_CAR = 0x40 TIOCM_CD = 0x40 TIOCM_CTS = 0x20 TIOCM_DSR = 0x100 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_RI = 0x80 TIOCM_RNG = 0x80 TIOCM_RTS = 0x4 TIOCM_SR = 0x10 TIOCM_ST = 0x8 TIOCNOTTY = 0x20007471 TIOCNXCL = 0x2000740e TIOCOUTQ = 0x40047473 TIOCPKT = 0x80047470 TIOCPKT_DATA = 0x0 TIOCPKT_DOSTOP = 0x20 TIOCPKT_FLUSHREAD = 0x1 TIOCPKT_FLUSHWRITE = 0x2 TIOCPKT_IOCTL = 0x40 TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 TIOCREMOTE = 0x80047469 TIOCSBRK = 0x2000747b TIOCSCTTY = 0x20007461 TIOCSDTR = 0x20007479 TIOCSETA = 0x802c7414 TIOCSETAF = 0x802c7416 TIOCSETAW = 0x802c7415 TIOCSETD = 0x8004741b TIOCSFLAGS = 0x8004745c TIOCSIG = 0x8004745f TIOCSPGRP = 0x80047476 TIOCSTART = 0x2000746e TIOCSTAT = 0x80047465 TIOCSTI = 0x80017472 TIOCSTOP = 0x2000746f TIOCSTSTAMP = 0x8008745a TIOCSWINSZ = 0x80087467 TIOCUCNTL = 0x80047466 TOSTOP = 0x400000 VDISCARD = 0xf VDSUSP = 0xb VEOF = 0x0 VEOL = 0x1 VEOL2 = 0x2 VERASE = 0x3 VINTR = 0x8 VKILL = 0x5 VLNEXT = 0xe VMIN = 0x10 VQUIT = 0x9 VREPRINT = 0x6 VSTART = 0xc VSTATUS = 0x12 VSTOP = 0xd VSUSP = 0xa VTIME = 0x11 VWERASE = 0x4 WALTSIG = 0x4 WCONTINUED = 0x8 WCOREFLAG = 0x80 WNOHANG = 0x1 WSTOPPED = 0x7f WUNTRACED = 0x2 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x30) EADDRNOTAVAIL = syscall.Errno(0x31) EAFNOSUPPORT = syscall.Errno(0x2f) EAGAIN = syscall.Errno(0x23) EALREADY = syscall.Errno(0x25) EAUTH = syscall.Errno(0x50) EBADF = syscall.Errno(0x9) EBADRPC = syscall.Errno(0x48) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x58) ECHILD = syscall.Errno(0xa) ECONNABORTED = syscall.Errno(0x35) ECONNREFUSED = syscall.Errno(0x3d) ECONNRESET = syscall.Errno(0x36) EDEADLK = syscall.Errno(0xb) EDESTADDRREQ = syscall.Errno(0x27) EDOM = syscall.Errno(0x21) EDQUOT = syscall.Errno(0x45) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EFTYPE = syscall.Errno(0x4f) EHOSTDOWN = syscall.Errno(0x40) EHOSTUNREACH = syscall.Errno(0x41) EIDRM = syscall.Errno(0x59) EILSEQ = syscall.Errno(0x54) EINPROGRESS = syscall.Errno(0x24) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EIPSEC = syscall.Errno(0x52) EISCONN = syscall.Errno(0x38) EISDIR = syscall.Errno(0x15) ELAST = syscall.Errno(0x5b) ELOOP = syscall.Errno(0x3e) EMEDIUMTYPE = syscall.Errno(0x56) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x28) ENAMETOOLONG = syscall.Errno(0x3f) ENEEDAUTH = syscall.Errno(0x51) ENETDOWN = syscall.Errno(0x32) ENETRESET = syscall.Errno(0x34) ENETUNREACH = syscall.Errno(0x33) ENFILE = syscall.Errno(0x17) ENOATTR = syscall.Errno(0x53) ENOBUFS = syscall.Errno(0x37) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOLCK = syscall.Errno(0x4d) ENOMEDIUM = syscall.Errno(0x55) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x5a) ENOPROTOOPT = syscall.Errno(0x2a) ENOSPC = syscall.Errno(0x1c) ENOSYS = syscall.Errno(0x4e) ENOTBLK = syscall.Errno(0xf) ENOTCONN = syscall.Errno(0x39) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x42) ENOTSOCK = syscall.Errno(0x26) ENOTSUP = syscall.Errno(0x5b) ENOTTY = syscall.Errno(0x19) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x2d) EOVERFLOW = syscall.Errno(0x57) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x2e) EPIPE = syscall.Errno(0x20) EPROCLIM = syscall.Errno(0x43) EPROCUNAVAIL = syscall.Errno(0x4c) EPROGMISMATCH = syscall.Errno(0x4b) EPROGUNAVAIL = syscall.Errno(0x4a) EPROTONOSUPPORT = syscall.Errno(0x2b) EPROTOTYPE = syscall.Errno(0x29) ERANGE = syscall.Errno(0x22) EREMOTE = syscall.Errno(0x47) EROFS = syscall.Errno(0x1e) ERPCMISMATCH = syscall.Errno(0x49) ESHUTDOWN = syscall.Errno(0x3a) ESOCKTNOSUPPORT = syscall.Errno(0x2c) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESTALE = syscall.Errno(0x46) ETIMEDOUT = syscall.Errno(0x3c) ETOOMANYREFS = syscall.Errno(0x3b) ETXTBSY = syscall.Errno(0x1a) EUSERS = syscall.Errno(0x44) EWOULDBLOCK = syscall.Errno(0x23) EXDEV = syscall.Errno(0x12) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0xa) SIGCHLD = syscall.Signal(0x14) SIGCONT = syscall.Signal(0x13) SIGEMT = syscall.Signal(0x7) SIGFPE = syscall.Signal(0x8) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINFO = syscall.Signal(0x1d) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x17) SIGIOT = syscall.Signal(0x6) SIGKILL = syscall.Signal(0x9) SIGPIPE = syscall.Signal(0xd) SIGPROF = syscall.Signal(0x1b) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTOP = syscall.Signal(0x11) SIGSYS = syscall.Signal(0xc) SIGTERM = syscall.Signal(0xf) SIGTHR = syscall.Signal(0x20) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x12) SIGTTIN = syscall.Signal(0x15) SIGTTOU = syscall.Signal(0x16) SIGURG = syscall.Signal(0x10) SIGUSR1 = syscall.Signal(0x1e) SIGUSR2 = syscall.Signal(0x1f) SIGVTALRM = syscall.Signal(0x1a) SIGWINCH = syscall.Signal(0x1c) SIGXCPU = syscall.Signal(0x18) SIGXFSZ = syscall.Signal(0x19) ) // Error table var errorList = [...]struct { num syscall.Errno name string desc string }{ {1, "EPERM", "operation not permitted"}, {2, "ENOENT", "no such file or directory"}, {3, "ESRCH", "no such process"}, {4, "EINTR", "interrupted system call"}, {5, "EIO", "input/output error"}, {6, "ENXIO", "device not configured"}, {7, "E2BIG", "argument list too long"}, {8, "ENOEXEC", "exec format error"}, {9, "EBADF", "bad file descriptor"}, {10, "ECHILD", "no child processes"}, {11, "EDEADLK", "resource deadlock avoided"}, {12, "ENOMEM", "cannot allocate memory"}, {13, "EACCES", "permission denied"}, {14, "EFAULT", "bad address"}, {15, "ENOTBLK", "block device required"}, {16, "EBUSY", "device busy"}, {17, "EEXIST", "file exists"}, {18, "EXDEV", "cross-device link"}, {19, "ENODEV", "operation not supported by device"}, {20, "ENOTDIR", "not a directory"}, {21, "EISDIR", "is a directory"}, {22, "EINVAL", "invalid argument"}, {23, "ENFILE", "too many open files in system"}, {24, "EMFILE", "too many open files"}, {25, "ENOTTY", "inappropriate ioctl for device"}, {26, "ETXTBSY", "text file busy"}, {27, "EFBIG", "file too large"}, {28, "ENOSPC", "no space left on device"}, {29, "ESPIPE", "illegal seek"}, {30, "EROFS", "read-only file system"}, {31, "EMLINK", "too many links"}, {32, "EPIPE", "broken pipe"}, {33, "EDOM", "numerical argument out of domain"}, {34, "ERANGE", "result too large"}, {35, "EWOULDBLOCK", "resource temporarily unavailable"}, {36, "EINPROGRESS", "operation now in progress"}, {37, "EALREADY", "operation already in progress"}, {38, "ENOTSOCK", "socket operation on non-socket"}, {39, "EDESTADDRREQ", "destination address required"}, {40, "EMSGSIZE", "message too long"}, {41, "EPROTOTYPE", "protocol wrong type for socket"}, {42, "ENOPROTOOPT", "protocol not available"}, {43, "EPROTONOSUPPORT", "protocol not supported"}, {44, "ESOCKTNOSUPPORT", "socket type not supported"}, {45, "EOPNOTSUPP", "operation not supported"}, {46, "EPFNOSUPPORT", "protocol family not supported"}, {47, "EAFNOSUPPORT", "address family not supported by protocol family"}, {48, "EADDRINUSE", "address already in use"}, {49, "EADDRNOTAVAIL", "can't assign requested address"}, {50, "ENETDOWN", "network is down"}, {51, "ENETUNREACH", "network is unreachable"}, {52, "ENETRESET", "network dropped connection on reset"}, {53, "ECONNABORTED", "software caused connection abort"}, {54, "ECONNRESET", "connection reset by peer"}, {55, "ENOBUFS", "no buffer space available"}, {56, "EISCONN", "socket is already connected"}, {57, "ENOTCONN", "socket is not connected"}, {58, "ESHUTDOWN", "can't send after socket shutdown"}, {59, "ETOOMANYREFS", "too many references: can't splice"}, {60, "ETIMEDOUT", "operation timed out"}, {61, "ECONNREFUSED", "connection refused"}, {62, "ELOOP", "too many levels of symbolic links"}, {63, "ENAMETOOLONG", "file name too long"}, {64, "EHOSTDOWN", "host is down"}, {65, "EHOSTUNREACH", "no route to host"}, {66, "ENOTEMPTY", "directory not empty"}, {67, "EPROCLIM", "too many processes"}, {68, "EUSERS", "too many users"}, {69, "EDQUOT", "disk quota exceeded"}, {70, "ESTALE", "stale NFS file handle"}, {71, "EREMOTE", "too many levels of remote in path"}, {72, "EBADRPC", "RPC struct is bad"}, {73, "ERPCMISMATCH", "RPC version wrong"}, {74, "EPROGUNAVAIL", "RPC program not available"}, {75, "EPROGMISMATCH", "program version wrong"}, {76, "EPROCUNAVAIL", "bad procedure for program"}, {77, "ENOLCK", "no locks available"}, {78, "ENOSYS", "function not implemented"}, {79, "EFTYPE", "inappropriate file type or format"}, {80, "EAUTH", "authentication error"}, {81, "ENEEDAUTH", "need authenticator"}, {82, "EIPSEC", "IPsec processing failure"}, {83, "ENOATTR", "attribute not found"}, {84, "EILSEQ", "illegal byte sequence"}, {85, "ENOMEDIUM", "no medium found"}, {86, "EMEDIUMTYPE", "wrong medium type"}, {87, "EOVERFLOW", "value too large to be stored in data type"}, {88, "ECANCELED", "operation canceled"}, {89, "EIDRM", "identifier removed"}, {90, "ENOMSG", "no message of desired type"}, {91, "ELAST", "not supported"}, } // Signal table var signalList = [...]struct { num syscall.Signal name string desc string }{ {1, "SIGHUP", "hangup"}, {2, "SIGINT", "interrupt"}, {3, "SIGQUIT", "quit"}, {4, "SIGILL", "illegal instruction"}, {5, "SIGTRAP", "trace/BPT trap"}, {6, "SIGABRT", "abort trap"}, {7, "SIGEMT", "EMT trap"}, {8, "SIGFPE", "floating point exception"}, {9, "SIGKILL", "killed"}, {10, "SIGBUS", "bus error"}, {11, "SIGSEGV", "segmentation fault"}, {12, "SIGSYS", "bad system call"}, {13, "SIGPIPE", "broken pipe"}, {14, "SIGALRM", "alarm clock"}, {15, "SIGTERM", "terminated"}, {16, "SIGURG", "urgent I/O condition"}, {17, "SIGSTOP", "suspended (signal)"}, {18, "SIGTSTP", "suspended"}, {19, "SIGCONT", "continued"}, {20, "SIGCHLD", "child exited"}, {21, "SIGTTIN", "stopped (tty input)"}, {22, "SIGTTOU", "stopped (tty output)"}, {23, "SIGIO", "I/O possible"}, {24, "SIGXCPU", "cputime limit exceeded"}, {25, "SIGXFSZ", "filesize limit exceeded"}, {26, "SIGVTALRM", "virtual timer expired"}, {27, "SIGPROF", "profiling timer expired"}, {28, "SIGWINCH", "window size changes"}, {29, "SIGINFO", "information request"}, {30, "SIGUSR1", "user defined signal 1"}, {31, "SIGUSR2", "user defined signal 2"}, {32, "SIGTHR", "thread AST"}, }
gravitational/monitoring-app
watcher/vendor/golang.org/x/sys/unix/zerrors_openbsd_386.go
GO
apache-2.0
69,797
/* * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. * * Copyright (C) 2012 Cavium, Inc. * * Copyright (C) 2009 Wind River Systems, * written by Ralf Baechle <[email protected]> */ #include <linux/module.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/interrupt.h> #include <linux/io.h> #include <linux/edac.h> #include "edac_core.h" #include "edac_module.h" #include <asm/octeon/cvmx.h> #include <asm/mipsregs.h> extern int register_co_cache_error_notifier(struct notifier_block *nb); extern int unregister_co_cache_error_notifier(struct notifier_block *nb); extern unsigned long long cache_err_dcache[NR_CPUS]; struct co_cache_error { struct notifier_block notifier; struct edac_device_ctl_info *ed; }; /** * EDAC CPU cache error callback * * @event: non-zero if unrecoverable. */ static int co_cache_error_event(struct notifier_block *this, unsigned long event, void *ptr) { struct co_cache_error *p = container_of(this, struct co_cache_error, notifier); unsigned int core = cvmx_get_core_num(); unsigned int cpu = smp_processor_id(); u64 icache_err = read_octeon_c0_icacheerr(); u64 dcache_err; if (event) { dcache_err = cache_err_dcache[core]; cache_err_dcache[core] = 0; } else { dcache_err = read_octeon_c0_dcacheerr(); } if (icache_err & 1) { edac_device_printk(p->ed, KERN_ERR, "CacheErr (Icache):%llx, core %d/cpu %d, cp0_errorepc == %lx\n", (unsigned long long)icache_err, core, cpu, read_c0_errorepc()); write_octeon_c0_icacheerr(0); edac_device_handle_ce(p->ed, cpu, 1, "icache"); } if (dcache_err & 1) { edac_device_printk(p->ed, KERN_ERR, "CacheErr (Dcache):%llx, core %d/cpu %d, cp0_errorepc == %lx\n", (unsigned long long)dcache_err, core, cpu, read_c0_errorepc()); if (event) edac_device_handle_ue(p->ed, cpu, 0, "dcache"); else edac_device_handle_ce(p->ed, cpu, 0, "dcache"); /* Clear the error indication */ if (OCTEON_IS_OCTEON2()) write_octeon_c0_dcacheerr(1); else write_octeon_c0_dcacheerr(0); } return NOTIFY_STOP; } static int co_cache_error_probe(struct platform_device *pdev) { struct co_cache_error *p = devm_kzalloc(&pdev->dev, sizeof(*p), GFP_KERNEL); if (!p) return -ENOMEM; p->notifier.notifier_call = co_cache_error_event; platform_set_drvdata(pdev, p); p->ed = edac_device_alloc_ctl_info(0, "cpu", num_possible_cpus(), "cache", 2, 0, NULL, 0, edac_device_alloc_index()); if (!p->ed) goto err; p->ed->dev = &pdev->dev; p->ed->dev_name = dev_name(&pdev->dev); p->ed->mod_name = "octeon-cpu"; p->ed->ctl_name = "cache"; if (edac_device_add_device(p->ed)) { pr_err("%s: edac_device_add_device() failed\n", __func__); goto err1; } register_co_cache_error_notifier(&p->notifier); return 0; err1: edac_device_free_ctl_info(p->ed); err: return -ENXIO; } static int co_cache_error_remove(struct platform_device *pdev) { struct co_cache_error *p = platform_get_drvdata(pdev); unregister_co_cache_error_notifier(&p->notifier); edac_device_del_device(&pdev->dev); edac_device_free_ctl_info(p->ed); return 0; } static struct platform_driver co_cache_error_driver = { .probe = co_cache_error_probe, .remove = co_cache_error_remove, .driver = { .name = "octeon_pc_edac", } }; module_platform_driver(co_cache_error_driver); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Ralf Baechle <[email protected]>");
AiJiaZone/linux-4.0
virt/drivers/edac/octeon_edac-pc.c
C
gpl-2.0
3,561
/* * * Copyright 2014, Google 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 Google Inc. nor the names of its * contributors 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. * */ package grpc import ( "bytes" "errors" "io" "sync" "time" "golang.org/x/net/context" "golang.org/x/net/trace" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" "google.golang.org/grpc/transport" ) type streamHandler func(srv interface{}, stream ServerStream) error // StreamDesc represents a streaming RPC service's method specification. type StreamDesc struct { StreamName string Handler streamHandler // At least one of these is true. ServerStreams bool ClientStreams bool } // Stream defines the common interface a client or server stream has to satisfy. type Stream interface { // Context returns the context for this stream. Context() context.Context // SendMsg blocks until it sends m, the stream is done or the stream // breaks. // On error, it aborts the stream and returns an RPC status on client // side. On server side, it simply returns the error to the caller. // SendMsg is called by generated code. SendMsg(m interface{}) error // RecvMsg blocks until it receives a message or the stream is // done. On client side, it returns io.EOF when the stream is done. On // any other error, it aborts the stream and returns an RPC status. On // server side, it simply returns the error to the caller. RecvMsg(m interface{}) error } // ClientStream defines the interface a client stream has to satify. type ClientStream interface { // Header returns the header metedata received from the server if there // is any. It blocks if the metadata is not ready to read. Header() (metadata.MD, error) // Trailer returns the trailer metadata from the server. It must be called // after stream.Recv() returns non-nil error (including io.EOF) for // bi-directional streaming and server streaming or stream.CloseAndRecv() // returns for client streaming in order to receive trailer metadata if // present. Otherwise, it could returns an empty MD even though trailer // is present. Trailer() metadata.MD // CloseSend closes the send direction of the stream. It closes the stream // when non-nil error is met. CloseSend() error Stream } // NewClientStream creates a new Stream for the client side. This is called // by generated code. func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (ClientStream, error) { var ( t transport.ClientTransport err error ) t, err = cc.dopts.picker.Pick(ctx) if err != nil { return nil, toRPCErr(err) } // TODO(zhaoq): CallOption is omitted. Add support when it is needed. callHdr := &transport.CallHdr{ Host: cc.authority, Method: method, Flush: desc.ServerStreams && desc.ClientStreams, } if cc.dopts.cp != nil { callHdr.SendCompress = cc.dopts.cp.Type() } cs := &clientStream{ desc: desc, codec: cc.dopts.codec, cp: cc.dopts.cp, dc: cc.dopts.dc, tracing: EnableTracing, } if cc.dopts.cp != nil { callHdr.SendCompress = cc.dopts.cp.Type() cs.cbuf = new(bytes.Buffer) } if cs.tracing { cs.trInfo.tr = trace.New("grpc.Sent."+methodFamily(method), method) cs.trInfo.firstLine.client = true if deadline, ok := ctx.Deadline(); ok { cs.trInfo.firstLine.deadline = deadline.Sub(time.Now()) } cs.trInfo.tr.LazyLog(&cs.trInfo.firstLine, false) ctx = trace.NewContext(ctx, cs.trInfo.tr) } s, err := t.NewStream(ctx, callHdr) if err != nil { cs.finish(err) return nil, toRPCErr(err) } cs.t = t cs.s = s cs.p = &parser{r: s} // Listen on ctx.Done() to detect cancellation when there is no pending // I/O operations on this stream. go func() { select { case <-t.Error(): // Incur transport error, simply exit. case <-s.Context().Done(): err := s.Context().Err() cs.finish(err) cs.closeTransportStream(transport.ContextErr(err)) } }() return cs, nil } // clientStream implements a client side Stream. type clientStream struct { t transport.ClientTransport s *transport.Stream p *parser desc *StreamDesc codec Codec cp Compressor cbuf *bytes.Buffer dc Decompressor tracing bool // set to EnableTracing when the clientStream is created. mu sync.Mutex closed bool // trInfo.tr is set when the clientStream is created (if EnableTracing is true), // and is set to nil when the clientStream's finish method is called. trInfo traceInfo } func (cs *clientStream) Context() context.Context { return cs.s.Context() } func (cs *clientStream) Header() (metadata.MD, error) { m, err := cs.s.Header() if err != nil { if _, ok := err.(transport.ConnectionError); !ok { cs.closeTransportStream(err) } } return m, err } func (cs *clientStream) Trailer() metadata.MD { return cs.s.Trailer() } func (cs *clientStream) SendMsg(m interface{}) (err error) { if cs.tracing { cs.mu.Lock() if cs.trInfo.tr != nil { cs.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true) } cs.mu.Unlock() } defer func() { if err != nil { cs.finish(err) } if err == nil || err == io.EOF { return } if _, ok := err.(transport.ConnectionError); !ok { cs.closeTransportStream(err) } err = toRPCErr(err) }() out, err := encode(cs.codec, m, cs.cp, cs.cbuf) defer func() { if cs.cbuf != nil { cs.cbuf.Reset() } }() if err != nil { return transport.StreamErrorf(codes.Internal, "grpc: %v", err) } return cs.t.Write(cs.s, out, &transport.Options{Last: false}) } func (cs *clientStream) RecvMsg(m interface{}) (err error) { err = recv(cs.p, cs.codec, cs.s, cs.dc, m) defer func() { // err != nil indicates the termination of the stream. if err != nil { cs.finish(err) } }() if err == nil { if cs.tracing { cs.mu.Lock() if cs.trInfo.tr != nil { cs.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true) } cs.mu.Unlock() } if !cs.desc.ClientStreams || cs.desc.ServerStreams { return } // Special handling for client streaming rpc. err = recv(cs.p, cs.codec, cs.s, cs.dc, m) cs.closeTransportStream(err) if err == nil { return toRPCErr(errors.New("grpc: client streaming protocol violation: get <nil>, want <EOF>")) } if err == io.EOF { if cs.s.StatusCode() == codes.OK { cs.finish(err) return nil } return Errorf(cs.s.StatusCode(), cs.s.StatusDesc()) } return toRPCErr(err) } if _, ok := err.(transport.ConnectionError); !ok { cs.closeTransportStream(err) } if err == io.EOF { if cs.s.StatusCode() == codes.OK { // Returns io.EOF to indicate the end of the stream. return } return Errorf(cs.s.StatusCode(), cs.s.StatusDesc()) } return toRPCErr(err) } func (cs *clientStream) CloseSend() (err error) { err = cs.t.Write(cs.s, nil, &transport.Options{Last: true}) defer func() { if err != nil { cs.finish(err) } }() if err == nil || err == io.EOF { return } if _, ok := err.(transport.ConnectionError); !ok { cs.closeTransportStream(err) } err = toRPCErr(err) return } func (cs *clientStream) closeTransportStream(err error) { cs.mu.Lock() if cs.closed { cs.mu.Unlock() return } cs.closed = true cs.mu.Unlock() cs.t.CloseStream(cs.s, err) } func (cs *clientStream) finish(err error) { if !cs.tracing { return } cs.mu.Lock() defer cs.mu.Unlock() if cs.trInfo.tr != nil { if err == nil || err == io.EOF { cs.trInfo.tr.LazyPrintf("RPC: [OK]") } else { cs.trInfo.tr.LazyPrintf("RPC: [%v]", err) cs.trInfo.tr.SetError() } cs.trInfo.tr.Finish() cs.trInfo.tr = nil } } // ServerStream defines the interface a server stream has to satisfy. type ServerStream interface { // SendHeader sends the header metadata. It should not be called // after SendProto. It fails if called multiple times or if // called after SendProto. SendHeader(metadata.MD) error // SetTrailer sets the trailer metadata which will be sent with the // RPC status. SetTrailer(metadata.MD) Stream } // serverStream implements a server side Stream. type serverStream struct { t transport.ServerTransport s *transport.Stream p *parser codec Codec cp Compressor dc Decompressor cbuf *bytes.Buffer statusCode codes.Code statusDesc string trInfo *traceInfo mu sync.Mutex // protects trInfo.tr after the service handler runs. } func (ss *serverStream) Context() context.Context { return ss.s.Context() } func (ss *serverStream) SendHeader(md metadata.MD) error { return ss.t.WriteHeader(ss.s, md) } func (ss *serverStream) SetTrailer(md metadata.MD) { if md.Len() == 0 { return } ss.s.SetTrailer(md) return } func (ss *serverStream) SendMsg(m interface{}) (err error) { defer func() { if ss.trInfo != nil { ss.mu.Lock() if ss.trInfo.tr != nil { if err == nil { ss.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true) } else { ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true) ss.trInfo.tr.SetError() } } ss.mu.Unlock() } }() out, err := encode(ss.codec, m, ss.cp, ss.cbuf) defer func() { if ss.cbuf != nil { ss.cbuf.Reset() } }() if err != nil { err = transport.StreamErrorf(codes.Internal, "grpc: %v", err) return err } return ss.t.Write(ss.s, out, &transport.Options{Last: false}) } func (ss *serverStream) RecvMsg(m interface{}) (err error) { defer func() { if ss.trInfo != nil { ss.mu.Lock() if ss.trInfo.tr != nil { if err == nil { ss.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true) } else if err != io.EOF { ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true) ss.trInfo.tr.SetError() } } ss.mu.Unlock() } }() return recv(ss.p, ss.codec, ss.s, ss.dc, m) }
dobril-stanga/distribution
vendor/google.golang.org/grpc/stream.go
GO
apache-2.0
11,192
Rainbow.extend("c",[{matches:{2:[{matches:{1:"keyword.define",2:"entity.name"},pattern:/(\w+)\s(\w+)\b/g},{name:"keyword.define",pattern:/endif/g},{matches:{1:"keyword.include",2:"string"},pattern:/(include)\s(.*?)$/g}]},pattern:/(\#)([\S\s]*?)$/gm},{name:"keyword",pattern:/\b(do|goto|continue|break|switch|case|typedef)\b/g},{name:"entity.label",pattern:/\w+:/g},{matches:{1:"storage.type",3:"storage.type",4:"entity.name.function"},pattern:/\b((un)?signed|const)?\s?(void|char|short|int|long|float|double)\*?(\s(\w+)(?=\())?/g},{matches:{2:"entity.name.function"},pattern:/(\w|\*)(\s(\w+)(?=\())?/g},{name:"storage.modifier",pattern:/\b(static|extern|auto|register|volatile|inline)\b/g},{name:"support.type",pattern:/\b(struct|union|enum)\b/g},{name:"variable",pattern:/\b[A-Z0-9_]{2,}\b/g},{matches:{1:"support.function.call"},pattern:/(\w{4,})(?=\()/g}]);
xuminready/baiducdnstatic
libs/rainbow/1.1.8/js/language/c.min.js
JavaScript
mit
860
#ifndef BOOST_PP_IS_ITERATING /*============================================================================= Copyright (c) 2011 Eric Niebler Copyright (c) 2001-2011 Joel de Guzman Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #if !defined(BOOST_FUSION_VECTOR10_FWD_HPP_INCLUDED) #define BOOST_FUSION_VECTOR10_FWD_HPP_INCLUDED #include <boost/fusion/support/config.hpp> #include <boost/preprocessor/cat.hpp> #include <boost/preprocessor/iteration/iterate.hpp> #include <boost/preprocessor/repetition/enum_params.hpp> namespace boost { namespace fusion { template <typename Dummy = void> struct vector0; }} #if !defined(BOOST_FUSION_DONT_USE_PREPROCESSED_FILES) #include <boost/fusion/container/vector/detail/preprocessed/vector10_fwd.hpp> #else #if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES) #pragma wave option(preserve: 2, line: 0, output: "detail/preprocessed/vector10_fwd.hpp") #endif /*============================================================================= Copyright (c) 2011 Eric Niebler Copyright (c) 2001-2011 Joel de Guzman Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) This is an auto-generated file. Do not edit! ==============================================================================*/ #if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES) #pragma wave option(preserve: 1) #endif namespace boost { namespace fusion { // expand vector1 to vector10 #define BOOST_PP_FILENAME_1 <boost/fusion/container/vector/vector10_fwd.hpp> #define BOOST_PP_ITERATION_LIMITS (1, 10) #include BOOST_PP_ITERATE() }} #if defined(__WAVE__) && defined(BOOST_FUSION_CREATE_PREPROCESSED_FILES) #pragma wave option(output: null) #endif #endif // BOOST_FUSION_DONT_USE_PREPROCESSED_FILES #endif #else template <BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), typename T)> struct BOOST_PP_CAT(vector, BOOST_PP_ITERATION()); #endif
edlund/fabl-ng
vendor/builds/boost-1.58/include/boost/fusion/container/vector/vector10_fwd.hpp
C++
gpl-3.0
2,235
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import hr_timesheet import wizard import report # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
diogocs1/comps
web/addons/hr_timesheet/__init__.py
Python
apache-2.0
1,104
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Gdata * @subpackage Health * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * @see Zend_Gdata_Entry */ require_once 'Zend/Gdata/Entry.php'; /** * @see Zend_Gdata_YouTube_Extension_VideoId */ require_once 'Zend/Gdata/YouTube/Extension/VideoId.php'; /** * @see Zend_Gdata_YouTube_Extension_Username */ require_once 'Zend/Gdata/YouTube/Extension/Username.php'; /** * @see Zend_Gdata_YouTube_Extension_Rating */ require_once 'Zend/Gdata/Extension/Rating.php'; /** * A concrete class for working with YouTube user activity entries. * * @link http://code.google.com/apis/youtube/ * * @category Zend * @package Zend_Gdata * @subpackage YouTube * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Gdata_YouTube_ActivityEntry extends Zend_Gdata_Entry { const ACTIVITY_CATEGORY_SCHEME = 'http://gdata.youtube.com/schemas/2007/userevents.cat'; /** * The classname for individual user activity entry elements. * * @var string */ protected $_entryClassName = 'Zend_Gdata_YouTube_ActivityEntry'; /** * The ID of the video that was part of the activity * * @var Zend_Gdata_YouTube_VideoId */ protected $_videoId = null; /** * The username for the user that was part of the activity * * @var Zend_Gdata_YouTube_Username */ protected $_username = null; /** * The rating element that was part of the activity * * @var Zend_Gdata_Extension_Rating */ protected $_rating = null; /** * Constructs a new Zend_Gdata_YouTube_ActivityEntry object. * @param DOMElement $element (optional) The DOMElement on which to * base this object. */ public function __construct($element = null) { $this->registerAllNamespaces(Zend_Gdata_YouTube::$namespaces); parent::__construct($element); } /** * Retrieves a DOMElement which corresponds to this element and all * child properties. This is used to build an entry back into a DOM * and eventually XML text for application storage/persistence. * * @param DOMDocument $doc The DOMDocument used to construct DOMElements * @return DOMElement The DOMElement representing this element and all * child properties. */ public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null) { $element = parent::getDOM($doc, $majorVersion, $minorVersion); if ($this->_videoId !== null) { $element->appendChild($this->_videoId->getDOM( $element->ownerDocument)); } if ($this->_username !== null) { $element->appendChild($this->_username->getDOM( $element->ownerDocument)); } if ($this->_rating !== null) { $element->appendChild($this->_rating->getDOM( $element->ownerDocument)); } return $element; } /** * Creates individual Entry objects of the appropriate type and * stores them as members of this entry based upon DOM data. * * @param DOMNode $child The DOMNode to process */ protected function takeChildFromDOM($child) { $absoluteNodeName = $child->namespaceURI . ':' . $child->localName; switch ($absoluteNodeName) { case $this->lookupNamespace('yt') . ':' . 'videoid': $videoId = new Zend_Gdata_YouTube_Extension_VideoId(); $videoId->transferFromDOM($child); $this->_videoId = $videoId; break; case $this->lookupNamespace('yt') . ':' . 'username': $username = new Zend_Gdata_YouTube_Extension_Username(); $username->transferFromDOM($child); $this->_username = $username; break; case $this->lookupNamespace('gd') . ':' . 'rating': $rating = new Zend_Gdata_Extension_Rating(); $rating->transferFromDOM($child); $this->_rating = $rating; break; default: parent::takeChildFromDOM($child); break; } } /** * Returns the video ID for this activity entry. * * @return null|Zend_Gdata_YouTube_Extension_VideoId */ public function getVideoId() { return $this->_videoId; } /** * Returns the username for this activity entry. * * @return null|Zend_Gdata_YouTube_Extension_Username */ public function getUsername() { return $this->_username; } /** * Returns the rating for this activity entry. * * @return null|Zend_Gdata_YouTube_Extension_Rating */ public function getRating() { return $this->_rating; } /** * Return the value of the rating for this video entry. * * Convenience method to save needless typing. * * @return integer|null The value of the rating that was created, if found. */ public function getRatingValue() { $rating = $this->_rating; if ($rating) { return $rating->getValue(); } return null; } /** * Return the activity type that was performed. * * Convenience method that inspects category where scheme is * http://gdata.youtube.com/schemas/2007/userevents.cat. * * @return string|null The activity category if found. */ public function getActivityType() { $categories = $this->getCategory(); foreach($categories as $category) { if ($category->getScheme() == self::ACTIVITY_CATEGORY_SCHEME) { return $category->getTerm(); } } return null; } /** * Convenience method to quickly get access to the author of the activity * * @return string The author of the activity */ public function getAuthorName() { $authors = $this->getAuthor(); return $authors[0]->getName()->getText(); } }
blackstark/site
www/sugar/Zend/Gdata/YouTube/ActivityEntry.php
PHP
gpl-2.0
6,807
/* * # Semantic - Progress * http://github.com/semantic-org/semantic-ui/ * * * Copyright 2014 Contributor * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ( $, window, document, undefined ) { "use strict"; $.fn.progress = function(parameters) { var $allModules = $(this), moduleSelector = $allModules.selector || '', time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), returnedValue ; $allModules .each(function() { var settings = ( $.isPlainObject(parameters) ) ? $.extend(true, {}, $.fn.progress.settings, parameters) : $.extend({}, $.fn.progress.settings), className = settings.className, metadata = settings.metadata, namespace = settings.namespace, selector = settings.selector, error = settings.error, eventNamespace = '.' + namespace, moduleNamespace = 'module-' + namespace, $module = $(this), $bar = $(this).find(selector.bar), $progress = $(this).find(selector.progress), $label = $(this).find(selector.label), element = this, instance = $module.data(moduleNamespace), module ; module = { initialize: function() { module.debug('Initializing progress', settings); module.read.metadata(); module.set.initials(); module.instantiate(); }, instantiate: function() { module.verbose('Storing instance of progress', module); instance = module; $module .data(moduleNamespace, module) ; }, destroy: function() { module.verbose('Destroying previous progress for', $module); module.remove.state(); $module.removeData(moduleNamespace); instance = undefined; }, reset: function() { module.set.percent(0); }, complete: function() { if(module.percent === undefined || module.percent < 100) { module.set.percent(100); } }, read: { metadata: function() { if( $module.data(metadata.percent) ) { module.verbose('Current percent value set from metadata'); module.percent = $module.data(metadata.percent); } if( $module.data(metadata.total) ) { module.verbose('Total value set from metadata'); module.total = $module.data(metadata.total); } if( $module.data(metadata.value) ) { module.verbose('Current value set from metadata'); module.value = $module.data(metadata.value); } }, currentValue: function() { return (module.value !== undefined) ? module.value : false ; } }, increment: function(incrementValue) { var total = module.total || false, edgeValue, startValue, newValue ; if(total) { startValue = module.value || 0; incrementValue = incrementValue || 1; newValue = startValue + incrementValue; edgeValue = module.total; module.debug('Incrementing value by', incrementValue, startValue, edgeValue); if(newValue > edgeValue ) { module.debug('Value cannot increment above total', edgeValue); newValue = edgeValue; } module.set.progress(newValue); } else { startValue = module.percent || 0; incrementValue = incrementValue || module.get.randomValue(); newValue = startValue + incrementValue; edgeValue = 100; module.debug('Incrementing percentage by', incrementValue, startValue); if(newValue > edgeValue ) { module.debug('Value cannot increment above 100 percent'); newValue = edgeValue; } module.set.progress(newValue); } }, decrement: function(decrementValue) { var total = module.total || false, edgeValue = 0, startValue, newValue ; if(total) { startValue = module.value || 0; decrementValue = decrementValue || 1; newValue = startValue - decrementValue; module.debug('Decrementing value by', decrementValue, startValue); } else { startValue = module.percent || 0; decrementValue = decrementValue || module.get.randomValue(); newValue = startValue - decrementValue; module.debug('Decrementing percentage by', decrementValue, startValue); } if(newValue < edgeValue) { module.debug('Value cannot decrement below 0'); newValue = 0; } module.set.progress(newValue); }, get: { text: function(templateText) { var value = module.value || 0, total = module.total || 0, percent = module.percent || 0 ; templateText = templateText || ''; templateText = templateText .replace('{value}', value) .replace('{total}', total) .replace('{percent}', percent) ; module.debug('Adding variables to progress bar text', templateText); return templateText; }, randomValue: function() { module.debug('Generating random increment percentage'); return Math.floor((Math.random() * settings.random.max) + settings.random.min); }, percent: function() { return module.percent || 0; }, value: function() { return module.value || false; }, total: function() { return module.total || false; } }, is: { success: function() { return $module.hasClass(className.success); }, warning: function() { return $module.hasClass(className.warning); }, error: function() { return $module.hasClass(className.error); } }, remove: { state: function() { module.verbose('Removing stored state'); delete module.total; delete module.percent; delete module.value; }, active: function() { module.verbose('Removing active state'); $module.removeClass(className.active); }, success: function() { module.verbose('Removing success state'); $module.removeClass(className.success); }, warning: function() { module.verbose('Removing warning state'); $module.removeClass(className.warning); }, error: function() { module.verbose('Removing error state'); $module.removeClass(className.error); } }, set: { barWidth: function(value) { if(value > 100) { module.error(error.tooHigh, value); } else if (value < 0) { module.error(error.tooLow, value); } else { $bar .css('width', value + '%') ; $module .attr('data-percent', parseInt(value, 10)) ; } }, initials: function() { if(settings.total !== false) { module.verbose('Current total set in settings', settings.total); module.total = settings.total; } if(settings.value !== false) { module.verbose('Current value set in settings', settings.value); module.value = settings.value; } if(settings.percent !== false) { module.verbose('Current percent set in settings', settings.percent); module.percent = settings.percent; } if(module.percent !== undefined) { module.set.percent(module.percent); } else if(module.value !== undefined) { module.set.progress(module.value); } }, percent: function(percent) { percent = (typeof percent == 'string') ? +(percent.replace('%', '')) : percent ; if(percent > 0 && percent < 1) { module.verbose('Module percentage passed as decimal, converting'); percent = percent * 100; } // round percentage if(settings.precision === 0) { percent = Math.round(percent); } else { percent = Math.round(percent * (10 * settings.precision) / (10 * settings.precision) ); } module.percent = percent; if(module.total) { module.value = Math.round( (percent / 100) * module.total); } if(settings.limitValues) { module.value = (module.value > 100) ? 100 : (module.value < 0) ? 0 : module.value ; } module.set.barWidth(percent); module.set.barLabel(); if(percent === 100) { if(settings.autoSuccess && !(module.is.warning() || module.is.error())) { module.set.success(); module.debug('Automatically triggering success at 100%'); } else { module.remove.active(); } } else if(percent > 0) { module.set.active(); } $.proxy(settings.onChange, element)(percent, module.value, module.total); }, label: function(text) { text = text || ''; if(text) { text = module.get.text(text); module.debug('Setting label to text', text); $label.text(text); } }, barLabel: function(text) { if(text !== undefined) { $progress.text( module.get.text(text) ); } else if(settings.label == 'ratio' && module.total) { module.debug('Adding ratio to bar label'); $progress.text( module.get.text(settings.text.ratio) ); } else if(settings.label == 'percent') { module.debug('Adding percentage to bar label'); $progress.text( module.get.text(settings.text.percent) ); } }, active: function(text) { text = text || settings.text.active; module.debug('Setting active state'); if(settings.showActivity) { $module.addClass(className.active); } module.remove.warning(); module.remove.error(); module.remove.success(); if(text) { module.set.label(text); } $.proxy(settings.onActive, element)(module.value, module.total); }, success : function(text) { text = text || settings.text.success; module.debug('Setting success state'); $module.addClass(className.success); module.remove.active(); module.remove.warning(); module.remove.error(); module.complete(); if(text) { module.set.label(text); } $.proxy(settings.onSuccess, element)(module.total); }, warning : function(text) { text = text || settings.text.warning; module.debug('Setting warning state'); $module.addClass(className.warning); module.remove.active(); module.remove.success(); module.remove.error(); module.complete(); if(text) { module.set.label(text); } $.proxy(settings.onWarning, element)(module.value, module.total); }, error : function(text) { text = text || settings.text.error; module.debug('Setting error state'); $module.addClass(className.error); module.remove.active(); module.remove.success(); module.remove.warning(); module.complete(); if(text) { module.set.label(text); } $.proxy(settings.onError, element)(module.value, module.total); }, total: function(totalValue) { module.total = totalValue; }, progress: function(value) { var numericValue = (typeof value === 'string') ? (value.replace(/[^\d.]/g, '') !== '') ? +(value.replace(/[^\d.]/g, '')) : false : value, percentComplete ; if(numericValue === false) { module.error(error.nonNumeric, value); } if(module.total) { module.value = numericValue; percentComplete = (numericValue / module.total) * 100; module.debug('Calculating percent complete from total', percentComplete); module.set.percent( percentComplete ); } else { percentComplete = numericValue; module.debug('Setting value to exact percentage value', percentComplete); module.set.percent( percentComplete ); } } }, setting: function(name, value) { module.debug('Changing setting', name, value); if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { settings[name] = value; } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 100); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { module.error(error.method, query); return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; if(methodInvoked) { if(instance === undefined) { module.initialize(); } module.invoke(query); } else { if(instance !== undefined) { module.destroy(); } module.initialize(); } }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; $.fn.progress.settings = { name : 'Progress', namespace : 'progress', debug : false, verbose : true, performance : true, random : { min : 2, max : 5 }, autoSuccess : true, showActivity : true, limitValues : true, label : 'percent', precision : 1, percent : false, total : false, value : false, onChange : function(percent, value, total){}, onSuccess : function(total){}, onActive : function(value, total){}, onError : function(value, total){}, onWarning : function(value, total){}, error : { method : 'The method you called is not defined.', nonNumeric : 'Progress value is non numeric', tooHigh : 'Value specified is above 100%', tooLow : 'Value specified is below 0%' }, regExp: { variable: /\{\$*[A-z0-9]+\}/g }, metadata: { percent : 'percent', total : 'total', value : 'value' }, selector : { bar : '> .bar', label : '> .label', progress : '.bar > .progress' }, text : { active : false, error : false, success : false, warning : false, percent : '{percent}%', ratio : '{value} of {total}' }, className : { active : 'active', error : 'error', success : 'success', warning : 'warning' } }; })( jQuery, window , document );
Keystion/Semantic-UI
src/definitions/modules/progress.js
JavaScript
mit
21,539
#ifndef LINUX_MM_DEBUG_H #define LINUX_MM_DEBUG_H 1 #ifdef CONFIG_DEBUG_VM #define VM_BUG_ON(cond) BUG_ON(cond) #else #define VM_BUG_ON(cond) do { (void)(cond); } while (0) #endif #ifdef CONFIG_DEBUG_VIRTUAL #define VIRTUAL_BUG_ON(cond) BUG_ON(cond) #else #define VIRTUAL_BUG_ON(cond) do { } while (0) #endif #endif
talnoah/android_kernel_htc_dlx
virt/include/linux/mmdebug.h
C
gpl-2.0
319
/*! jQuery UI - v1.11.2 - 2014-10-17 * http://jqueryui.com * Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */ (function(e){"function"==typeof define&&define.amd?define(["../datepicker"],e):e(jQuery.datepicker)})(function(e){return e.regional.ta={closeText:"மூடு",prevText:"முன்னையது",nextText:"அடுத்தது",currentText:"இன்று",monthNames:["தை","மாசி","பங்குனி","சித்திரை","வைகாசி","ஆனி","ஆடி","ஆவணி","புரட்டாசி","ஐப்பசி","கார்த்திகை","மார்கழி"],monthNamesShort:["தை","மாசி","பங்","சித்","வைகா","ஆனி","ஆடி","ஆவ","புர","ஐப்","கார்","மார்"],dayNames:["ஞாயிற்றுக்கிழமை","திங்கட்கிழமை","செவ்வாய்க்கிழமை","புதன்கிழமை","வியாழக்கிழமை","வெள்ளிக்கிழமை","சனிக்கிழமை"],dayNamesShort:["ஞாயிறு","திங்கள்","செவ்வாய்","புதன்","வியாழன்","வெள்ளி","சனி"],dayNamesMin:["ஞா","தி","செ","பு","வி","வெ","ச"],weekHeader:"Не",dateFormat:"dd/mm/yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},e.setDefaults(e.regional.ta),e.regional.ta});
Saminu/Minated
www/libs/jquery-ui/ui/minified/i18n/datepicker-ta.min.js
JavaScript
mit
1,499
/* * Squashfs - a compressed read only filesystem for Linux * * Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 * Phillip Lougher <[email protected]> * * 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, * or (at your option) 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, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * zlib_wrapper.c */ #include <linux/mutex.h> #include <linux/buffer_head.h> #include <linux/slab.h> #include <linux/zlib.h> #include <linux/vmalloc.h> #include "squashfs_fs.h" #include "squashfs_fs_sb.h" #include "squashfs.h" #include "decompressor.h" static void *zlib_init(struct squashfs_sb_info *dummy, void *buff, int len) { z_stream *stream = kmalloc(sizeof(z_stream), GFP_KERNEL); if (stream == NULL) goto failed; stream->workspace = vmalloc(zlib_inflate_workspacesize()); if (stream->workspace == NULL) goto failed; return stream; failed: ERROR("Failed to allocate zlib workspace\n"); kfree(stream); return ERR_PTR(-ENOMEM); } static void zlib_free(void *strm) { z_stream *stream = strm; if (stream) vfree(stream->workspace); kfree(stream); } static int zlib_uncompress(struct squashfs_sb_info *msblk, void **buffer, struct buffer_head **bh, int b, int offset, int length, int srclength, int pages) { int zlib_err, zlib_init = 0; int k = 0, page = 0; z_stream *stream = msblk->stream; mutex_lock(&msblk->read_data_mutex); stream->avail_out = 0; stream->avail_in = 0; do { if (stream->avail_in == 0 && k < b) { int avail = min(length, msblk->devblksize - offset); length -= avail; wait_on_buffer(bh[k]); if (!buffer_uptodate(bh[k])) goto release_mutex; stream->next_in = bh[k]->b_data + offset; stream->avail_in = avail; offset = 0; } if (stream->avail_out == 0 && page < pages) { stream->next_out = buffer[page++]; stream->avail_out = PAGE_CACHE_SIZE; } if (!zlib_init) { zlib_err = zlib_inflateInit(stream); if (zlib_err != Z_OK) { ERROR("zlib_inflateInit returned unexpected " "result 0x%x, srclength %d\n", zlib_err, srclength); goto release_mutex; } zlib_init = 1; } zlib_err = zlib_inflate(stream, Z_SYNC_FLUSH); if (stream->avail_in == 0 && k < b) put_bh(bh[k++]); } while (zlib_err == Z_OK); if (zlib_err != Z_STREAM_END) { ERROR("zlib_inflate error, data probably corrupt\n"); goto release_mutex; } zlib_err = zlib_inflateEnd(stream); if (zlib_err != Z_OK) { ERROR("zlib_inflate error, data probably corrupt\n"); goto release_mutex; } if (k < b) { ERROR("zlib_uncompress error, data remaining\n"); goto release_mutex; } length = stream->total_out; mutex_unlock(&msblk->read_data_mutex); return length; release_mutex: mutex_unlock(&msblk->read_data_mutex); for (; k < b; k++) put_bh(bh[k]); return -EIO; } const struct squashfs_decompressor squashfs_zlib_comp_ops = { .init = zlib_init, .free = zlib_free, .decompress = zlib_uncompress, .id = ZLIB_COMPRESSION, .name = "zlib", .supported = 1 };
chaoling/test123
linux-2.6.39/fs/squashfs/zlib_wrapper.c
C
gpl-2.0
3,560
package dns import ( "bytes" "crypto" "crypto/dsa" "crypto/ecdsa" "crypto/elliptic" "crypto/md5" "crypto/rsa" "crypto/sha1" "crypto/sha256" "crypto/sha512" "encoding/hex" "hash" "io" "math/big" "sort" "strings" "time" ) // DNSSEC encryption algorithm codes. const ( _ uint8 = iota RSAMD5 DH DSA _ // Skip 4, RFC 6725, section 2.1 RSASHA1 DSANSEC3SHA1 RSASHA1NSEC3SHA1 RSASHA256 _ // Skip 9, RFC 6725, section 2.1 RSASHA512 _ // Skip 11, RFC 6725, section 2.1 ECCGOST ECDSAP256SHA256 ECDSAP384SHA384 INDIRECT uint8 = 252 PRIVATEDNS uint8 = 253 // Private (experimental keys) PRIVATEOID uint8 = 254 ) // DNSSEC hashing algorithm codes. const ( _ uint8 = iota SHA1 // RFC 4034 SHA256 // RFC 4509 GOST94 // RFC 5933 SHA384 // Experimental SHA512 // Experimental ) // DNSKEY flag values. const ( SEP = 1 REVOKE = 1 << 7 ZONE = 1 << 8 ) // The RRSIG needs to be converted to wireformat with some of // the rdata (the signature) missing. Use this struct to easy // the conversion (and re-use the pack/unpack functions). type rrsigWireFmt struct { TypeCovered uint16 Algorithm uint8 Labels uint8 OrigTtl uint32 Expiration uint32 Inception uint32 KeyTag uint16 SignerName string `dns:"domain-name"` /* No Signature */ } // Used for converting DNSKEY's rdata to wirefmt. type dnskeyWireFmt struct { Flags uint16 Protocol uint8 Algorithm uint8 PublicKey string `dns:"base64"` /* Nothing is left out */ } func divRoundUp(a, b int) int { return (a + b - 1) / b } // KeyTag calculates the keytag (or key-id) of the DNSKEY. func (k *DNSKEY) KeyTag() uint16 { if k == nil { return 0 } var keytag int switch k.Algorithm { case RSAMD5: // Look at the bottom two bytes of the modules, which the last // item in the pubkey. We could do this faster by looking directly // at the base64 values. But I'm lazy. modulus, _ := fromBase64([]byte(k.PublicKey)) if len(modulus) > 1 { x, _ := unpackUint16(modulus, len(modulus)-2) keytag = int(x) } default: keywire := new(dnskeyWireFmt) keywire.Flags = k.Flags keywire.Protocol = k.Protocol keywire.Algorithm = k.Algorithm keywire.PublicKey = k.PublicKey wire := make([]byte, DefaultMsgSize) n, err := PackStruct(keywire, wire, 0) if err != nil { return 0 } wire = wire[:n] for i, v := range wire { if i&1 != 0 { keytag += int(v) // must be larger than uint32 } else { keytag += int(v) << 8 } } keytag += (keytag >> 16) & 0xFFFF keytag &= 0xFFFF } return uint16(keytag) } // ToDS converts a DNSKEY record to a DS record. func (k *DNSKEY) ToDS(h uint8) *DS { if k == nil { return nil } ds := new(DS) ds.Hdr.Name = k.Hdr.Name ds.Hdr.Class = k.Hdr.Class ds.Hdr.Rrtype = TypeDS ds.Hdr.Ttl = k.Hdr.Ttl ds.Algorithm = k.Algorithm ds.DigestType = h ds.KeyTag = k.KeyTag() keywire := new(dnskeyWireFmt) keywire.Flags = k.Flags keywire.Protocol = k.Protocol keywire.Algorithm = k.Algorithm keywire.PublicKey = k.PublicKey wire := make([]byte, DefaultMsgSize) n, err := PackStruct(keywire, wire, 0) if err != nil { return nil } wire = wire[:n] owner := make([]byte, 255) off, err1 := PackDomainName(strings.ToLower(k.Hdr.Name), owner, 0, nil, false) if err1 != nil { return nil } owner = owner[:off] // RFC4034: // digest = digest_algorithm( DNSKEY owner name | DNSKEY RDATA); // "|" denotes concatenation // DNSKEY RDATA = Flags | Protocol | Algorithm | Public Key. // digest buffer digest := append(owner, wire...) // another copy switch h { case SHA1: s := sha1.New() io.WriteString(s, string(digest)) ds.Digest = hex.EncodeToString(s.Sum(nil)) case SHA256: s := sha256.New() io.WriteString(s, string(digest)) ds.Digest = hex.EncodeToString(s.Sum(nil)) case SHA384: s := sha512.New384() io.WriteString(s, string(digest)) ds.Digest = hex.EncodeToString(s.Sum(nil)) case GOST94: /* I have no clue */ default: return nil } return ds } // ToCDNSKEY converts a DNSKEY record to a CDNSKEY record. func (k *DNSKEY) ToCDNSKEY() *CDNSKEY { c := &CDNSKEY{DNSKEY: *k} c.Hdr = *k.Hdr.copyHeader() c.Hdr.Rrtype = TypeCDNSKEY return c } // ToCDS converts a DS record to a CDS record. func (d *DS) ToCDS() *CDS { c := &CDS{DS: *d} c.Hdr = *d.Hdr.copyHeader() c.Hdr.Rrtype = TypeCDS return c } // Sign signs an RRSet. The signature needs to be filled in with // the values: Inception, Expiration, KeyTag, SignerName and Algorithm. // The rest is copied from the RRset. Sign returns true when the signing went OK, // otherwise false. // There is no check if RRSet is a proper (RFC 2181) RRSet. // If OrigTTL is non zero, it is used as-is, otherwise the TTL of the RRset // is used as the OrigTTL. func (rr *RRSIG) Sign(k PrivateKey, rrset []RR) error { if k == nil { return ErrPrivKey } // s.Inception and s.Expiration may be 0 (rollover etc.), the rest must be set if rr.KeyTag == 0 || len(rr.SignerName) == 0 || rr.Algorithm == 0 { return ErrKey } rr.Hdr.Rrtype = TypeRRSIG rr.Hdr.Name = rrset[0].Header().Name rr.Hdr.Class = rrset[0].Header().Class if rr.OrigTtl == 0 { // If set don't override rr.OrigTtl = rrset[0].Header().Ttl } rr.TypeCovered = rrset[0].Header().Rrtype rr.Labels = uint8(CountLabel(rrset[0].Header().Name)) if strings.HasPrefix(rrset[0].Header().Name, "*") { rr.Labels-- // wildcard, remove from label count } sigwire := new(rrsigWireFmt) sigwire.TypeCovered = rr.TypeCovered sigwire.Algorithm = rr.Algorithm sigwire.Labels = rr.Labels sigwire.OrigTtl = rr.OrigTtl sigwire.Expiration = rr.Expiration sigwire.Inception = rr.Inception sigwire.KeyTag = rr.KeyTag // For signing, lowercase this name sigwire.SignerName = strings.ToLower(rr.SignerName) // Create the desired binary blob signdata := make([]byte, DefaultMsgSize) n, err := PackStruct(sigwire, signdata, 0) if err != nil { return err } signdata = signdata[:n] wire, err := rawSignatureData(rrset, rr) if err != nil { return err } signdata = append(signdata, wire...) var h hash.Hash switch rr.Algorithm { case DSA, DSANSEC3SHA1: // TODO: this seems bugged, will panic case RSASHA1, RSASHA1NSEC3SHA1: h = sha1.New() case RSASHA256, ECDSAP256SHA256: h = sha256.New() case ECDSAP384SHA384: h = sha512.New384() case RSASHA512: h = sha512.New() case RSAMD5: fallthrough // Deprecated in RFC 6725 default: return ErrAlg } _, err = h.Write(signdata) if err != nil { return err } sighash := h.Sum(nil) signature, err := k.Sign(sighash, rr.Algorithm) if err != nil { return err } rr.Signature = toBase64(signature) return nil } // Verify validates an RRSet with the signature and key. This is only the // cryptographic test, the signature validity period must be checked separately. // This function copies the rdata of some RRs (to lowercase domain names) for the validation to work. func (rr *RRSIG) Verify(k *DNSKEY, rrset []RR) error { // First the easy checks if len(rrset) == 0 { return ErrRRset } if rr.KeyTag != k.KeyTag() { return ErrKey } if rr.Hdr.Class != k.Hdr.Class { return ErrKey } if rr.Algorithm != k.Algorithm { return ErrKey } if strings.ToLower(rr.SignerName) != strings.ToLower(k.Hdr.Name) { return ErrKey } if k.Protocol != 3 { return ErrKey } for _, r := range rrset { if r.Header().Class != rr.Hdr.Class { return ErrRRset } if r.Header().Rrtype != rr.TypeCovered { return ErrRRset } } // RFC 4035 5.3.2. Reconstructing the Signed Data // Copy the sig, except the rrsig data sigwire := new(rrsigWireFmt) sigwire.TypeCovered = rr.TypeCovered sigwire.Algorithm = rr.Algorithm sigwire.Labels = rr.Labels sigwire.OrigTtl = rr.OrigTtl sigwire.Expiration = rr.Expiration sigwire.Inception = rr.Inception sigwire.KeyTag = rr.KeyTag sigwire.SignerName = strings.ToLower(rr.SignerName) // Create the desired binary blob signeddata := make([]byte, DefaultMsgSize) n, err := PackStruct(sigwire, signeddata, 0) if err != nil { return err } signeddata = signeddata[:n] wire, err := rawSignatureData(rrset, rr) if err != nil { return err } signeddata = append(signeddata, wire...) sigbuf := rr.sigBuf() // Get the binary signature data if rr.Algorithm == PRIVATEDNS { // PRIVATEOID // TODO(mg) // remove the domain name and assume its our } switch rr.Algorithm { case RSASHA1, RSASHA1NSEC3SHA1, RSASHA256, RSASHA512, RSAMD5: // TODO(mg): this can be done quicker, ie. cache the pubkey data somewhere?? pubkey := k.publicKeyRSA() // Get the key if pubkey == nil { return ErrKey } // Setup the hash as defined for this alg. var h hash.Hash var ch crypto.Hash switch rr.Algorithm { case RSAMD5: h = md5.New() ch = crypto.MD5 case RSASHA1, RSASHA1NSEC3SHA1: h = sha1.New() ch = crypto.SHA1 case RSASHA256: h = sha256.New() ch = crypto.SHA256 case RSASHA512: h = sha512.New() ch = crypto.SHA512 } io.WriteString(h, string(signeddata)) sighash := h.Sum(nil) return rsa.VerifyPKCS1v15(pubkey, ch, sighash, sigbuf) case ECDSAP256SHA256, ECDSAP384SHA384: pubkey := k.publicKeyECDSA() if pubkey == nil { return ErrKey } var h hash.Hash switch rr.Algorithm { case ECDSAP256SHA256: h = sha256.New() case ECDSAP384SHA384: h = sha512.New384() } io.WriteString(h, string(signeddata)) sighash := h.Sum(nil) // Split sigbuf into the r and s coordinates r := big.NewInt(0) r.SetBytes(sigbuf[:len(sigbuf)/2]) s := big.NewInt(0) s.SetBytes(sigbuf[len(sigbuf)/2:]) if ecdsa.Verify(pubkey, sighash, r, s) { return nil } return ErrSig } // Unknown alg return ErrAlg } // ValidityPeriod uses RFC1982 serial arithmetic to calculate // if a signature period is valid. If t is the zero time, the // current time is taken other t is. func (rr *RRSIG) ValidityPeriod(t time.Time) bool { var utc int64 if t.IsZero() { utc = time.Now().UTC().Unix() } else { utc = t.UTC().Unix() } modi := (int64(rr.Inception) - utc) / year68 mode := (int64(rr.Expiration) - utc) / year68 ti := int64(rr.Inception) + (modi * year68) te := int64(rr.Expiration) + (mode * year68) return ti <= utc && utc <= te } // Return the signatures base64 encodedig sigdata as a byte slice. func (rr *RRSIG) sigBuf() []byte { sigbuf, err := fromBase64([]byte(rr.Signature)) if err != nil { return nil } return sigbuf } // publicKeyRSA returns the RSA public key from a DNSKEY record. func (k *DNSKEY) publicKeyRSA() *rsa.PublicKey { keybuf, err := fromBase64([]byte(k.PublicKey)) if err != nil { return nil } // RFC 2537/3110, section 2. RSA Public KEY Resource Records // Length is in the 0th byte, unless its zero, then it // it in bytes 1 and 2 and its a 16 bit number explen := uint16(keybuf[0]) keyoff := 1 if explen == 0 { explen = uint16(keybuf[1])<<8 | uint16(keybuf[2]) keyoff = 3 } pubkey := new(rsa.PublicKey) pubkey.N = big.NewInt(0) shift := uint64((explen - 1) * 8) expo := uint64(0) for i := int(explen - 1); i > 0; i-- { expo += uint64(keybuf[keyoff+i]) << shift shift -= 8 } // Remainder expo += uint64(keybuf[keyoff]) if expo > 2<<31 { // Larger expo than supported. // println("dns: F5 primes (or larger) are not supported") return nil } pubkey.E = int(expo) pubkey.N.SetBytes(keybuf[keyoff+int(explen):]) return pubkey } // publicKeyECDSA returns the Curve public key from the DNSKEY record. func (k *DNSKEY) publicKeyECDSA() *ecdsa.PublicKey { keybuf, err := fromBase64([]byte(k.PublicKey)) if err != nil { return nil } pubkey := new(ecdsa.PublicKey) switch k.Algorithm { case ECDSAP256SHA256: pubkey.Curve = elliptic.P256() if len(keybuf) != 64 { // wrongly encoded key return nil } case ECDSAP384SHA384: pubkey.Curve = elliptic.P384() if len(keybuf) != 96 { // Wrongly encoded key return nil } } pubkey.X = big.NewInt(0) pubkey.X.SetBytes(keybuf[:len(keybuf)/2]) pubkey.Y = big.NewInt(0) pubkey.Y.SetBytes(keybuf[len(keybuf)/2:]) return pubkey } func (k *DNSKEY) publicKeyDSA() *dsa.PublicKey { keybuf, err := fromBase64([]byte(k.PublicKey)) if err != nil { return nil } if len(keybuf) < 22 { return nil } t, keybuf := int(keybuf[0]), keybuf[1:] size := 64 + t*8 q, keybuf := keybuf[:20], keybuf[20:] if len(keybuf) != 3*size { return nil } p, keybuf := keybuf[:size], keybuf[size:] g, y := keybuf[:size], keybuf[size:] pubkey := new(dsa.PublicKey) pubkey.Parameters.Q = big.NewInt(0).SetBytes(q) pubkey.Parameters.P = big.NewInt(0).SetBytes(p) pubkey.Parameters.G = big.NewInt(0).SetBytes(g) pubkey.Y = big.NewInt(0).SetBytes(y) return pubkey } type wireSlice [][]byte func (p wireSlice) Len() int { return len(p) } func (p wireSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } func (p wireSlice) Less(i, j int) bool { _, ioff, _ := UnpackDomainName(p[i], 0) _, joff, _ := UnpackDomainName(p[j], 0) return bytes.Compare(p[i][ioff+10:], p[j][joff+10:]) < 0 } // Return the raw signature data. func rawSignatureData(rrset []RR, s *RRSIG) (buf []byte, err error) { wires := make(wireSlice, len(rrset)) for i, r := range rrset { r1 := r.copy() r1.Header().Ttl = s.OrigTtl labels := SplitDomainName(r1.Header().Name) // 6.2. Canonical RR Form. (4) - wildcards if len(labels) > int(s.Labels) { // Wildcard r1.Header().Name = "*." + strings.Join(labels[len(labels)-int(s.Labels):], ".") + "." } // RFC 4034: 6.2. Canonical RR Form. (2) - domain name to lowercase r1.Header().Name = strings.ToLower(r1.Header().Name) // 6.2. Canonical RR Form. (3) - domain rdata to lowercase. // NS, MD, MF, CNAME, SOA, MB, MG, MR, PTR, // HINFO, MINFO, MX, RP, AFSDB, RT, SIG, PX, NXT, NAPTR, KX, // SRV, DNAME, A6 switch x := r1.(type) { case *NS: x.Ns = strings.ToLower(x.Ns) case *CNAME: x.Target = strings.ToLower(x.Target) case *SOA: x.Ns = strings.ToLower(x.Ns) x.Mbox = strings.ToLower(x.Mbox) case *MB: x.Mb = strings.ToLower(x.Mb) case *MG: x.Mg = strings.ToLower(x.Mg) case *MR: x.Mr = strings.ToLower(x.Mr) case *PTR: x.Ptr = strings.ToLower(x.Ptr) case *MINFO: x.Rmail = strings.ToLower(x.Rmail) x.Email = strings.ToLower(x.Email) case *MX: x.Mx = strings.ToLower(x.Mx) case *NAPTR: x.Replacement = strings.ToLower(x.Replacement) case *KX: x.Exchanger = strings.ToLower(x.Exchanger) case *SRV: x.Target = strings.ToLower(x.Target) case *DNAME: x.Target = strings.ToLower(x.Target) } // 6.2. Canonical RR Form. (5) - origTTL wire := make([]byte, r1.len()+1) // +1 to be safe(r) off, err1 := PackRR(r1, wire, 0, nil, false) if err1 != nil { return nil, err1 } wire = wire[:off] wires[i] = wire } sort.Sort(wires) for i, wire := range wires { if i > 0 && bytes.Equal(wire, wires[i-1]) { continue } buf = append(buf, wire...) } return buf, nil } // Map for algorithm names. var AlgorithmToString = map[uint8]string{ RSAMD5: "RSAMD5", DH: "DH", DSA: "DSA", RSASHA1: "RSASHA1", DSANSEC3SHA1: "DSA-NSEC3-SHA1", RSASHA1NSEC3SHA1: "RSASHA1-NSEC3-SHA1", RSASHA256: "RSASHA256", RSASHA512: "RSASHA512", ECCGOST: "ECC-GOST", ECDSAP256SHA256: "ECDSAP256SHA256", ECDSAP384SHA384: "ECDSAP384SHA384", INDIRECT: "INDIRECT", PRIVATEDNS: "PRIVATEDNS", PRIVATEOID: "PRIVATEOID", } // Map of algorithm strings. var StringToAlgorithm = reverseInt8(AlgorithmToString) // Map for hash names. var HashToString = map[uint8]string{ SHA1: "SHA1", SHA256: "SHA256", GOST94: "GOST94", SHA384: "SHA384", SHA512: "SHA512", } // Map of hash strings. var StringToHash = reverseInt8(HashToString)
duzc2/arduino-create-agent
vendor/github.com/miekg/dns/dnssec.go
GO
gpl-2.0
15,785
/* * AGPGART driver frontend * Copyright (C) 2004 Silicon Graphics, Inc. * Copyright (C) 2002-2003 Dave Jones * Copyright (C) 1999 Jeff Hartmann * Copyright (C) 1999 Precision Insight, Inc. * Copyright (C) 1999 Xi Graphics, Inc. * * 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 * JEFF HARTMANN, OR ANY OTHER CONTRIBUTORS 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 <linux/types.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/mman.h> #include <linux/pci.h> #include <linux/miscdevice.h> #include <linux/agp_backend.h> #include <linux/agpgart.h> #include <linux/slab.h> #include <linux/mm.h> #include <linux/fs.h> #include <linux/sched.h> #include <asm/uaccess.h> #include <asm/pgtable.h> #include "agp.h" struct agp_front_data agp_fe; struct agp_memory *agp_find_mem_by_key(int key) { struct agp_memory *curr; if (agp_fe.current_controller == NULL) return NULL; curr = agp_fe.current_controller->pool; while (curr != NULL) { if (curr->key == key) break; curr = curr->next; } DBG("key=%d -> mem=%p", key, curr); return curr; } static void agp_remove_from_pool(struct agp_memory *temp) { struct agp_memory *prev; struct agp_memory *next; /* Check to see if this is even in the memory pool */ DBG("mem=%p", temp); if (agp_find_mem_by_key(temp->key) != NULL) { next = temp->next; prev = temp->prev; if (prev != NULL) { prev->next = next; if (next != NULL) next->prev = prev; } else { /* This is the first item on the list */ if (next != NULL) next->prev = NULL; agp_fe.current_controller->pool = next; } } } /* * Routines for managing each client's segment list - * These routines handle adding and removing segments * to each auth'ed client. */ static struct agp_segment_priv *agp_find_seg_in_client(const struct agp_client *client, unsigned long offset, int size, pgprot_t page_prot) { struct agp_segment_priv *seg; int num_segments, i; off_t pg_start; size_t pg_count; pg_start = offset / 4096; pg_count = size / 4096; seg = *(client->segments); num_segments = client->num_segments; for (i = 0; i < client->num_segments; i++) { if ((seg[i].pg_start == pg_start) && (seg[i].pg_count == pg_count) && (pgprot_val(seg[i].prot) == pgprot_val(page_prot))) { return seg + i; } } return NULL; } static void agp_remove_seg_from_client(struct agp_client *client) { DBG("client=%p", client); if (client->segments != NULL) { if (*(client->segments) != NULL) { DBG("Freeing %p from client %p", *(client->segments), client); kfree(*(client->segments)); } DBG("Freeing %p from client %p", client->segments, client); kfree(client->segments); client->segments = NULL; } } static void agp_add_seg_to_client(struct agp_client *client, struct agp_segment_priv ** seg, int num_segments) { struct agp_segment_priv **prev_seg; prev_seg = client->segments; if (prev_seg != NULL) agp_remove_seg_from_client(client); DBG("Adding seg %p (%d segments) to client %p", seg, num_segments, client); client->num_segments = num_segments; client->segments = seg; } static pgprot_t agp_convert_mmap_flags(int prot) { unsigned long prot_bits; prot_bits = calc_vm_prot_bits(prot) | VM_SHARED; return vm_get_page_prot(prot_bits); } int agp_create_segment(struct agp_client *client, struct agp_region *region) { struct agp_segment_priv **ret_seg; struct agp_segment_priv *seg; struct agp_segment *user_seg; size_t i; seg = kzalloc((sizeof(struct agp_segment_priv) * region->seg_count), GFP_KERNEL); if (seg == NULL) { kfree(region->seg_list); region->seg_list = NULL; return -ENOMEM; } user_seg = region->seg_list; for (i = 0; i < region->seg_count; i++) { seg[i].pg_start = user_seg[i].pg_start; seg[i].pg_count = user_seg[i].pg_count; seg[i].prot = agp_convert_mmap_flags(user_seg[i].prot); } kfree(region->seg_list); region->seg_list = NULL; ret_seg = kmalloc(sizeof(void *), GFP_KERNEL); if (ret_seg == NULL) { kfree(seg); return -ENOMEM; } *ret_seg = seg; agp_add_seg_to_client(client, ret_seg, region->seg_count); return 0; } /* End - Routines for managing each client's segment list */ /* This function must only be called when current_controller != NULL */ static void agp_insert_into_pool(struct agp_memory * temp) { struct agp_memory *prev; prev = agp_fe.current_controller->pool; if (prev != NULL) { prev->prev = temp; temp->next = prev; } agp_fe.current_controller->pool = temp; } /* File private list routines */ struct agp_file_private *agp_find_private(pid_t pid) { struct agp_file_private *curr; curr = agp_fe.file_priv_list; while (curr != NULL) { if (curr->my_pid == pid) return curr; curr = curr->next; } return NULL; } static void agp_insert_file_private(struct agp_file_private * priv) { struct agp_file_private *prev; prev = agp_fe.file_priv_list; if (prev != NULL) prev->prev = priv; priv->next = prev; agp_fe.file_priv_list = priv; } static void agp_remove_file_private(struct agp_file_private * priv) { struct agp_file_private *next; struct agp_file_private *prev; next = priv->next; prev = priv->prev; if (prev != NULL) { prev->next = next; if (next != NULL) next->prev = prev; } else { if (next != NULL) next->prev = NULL; agp_fe.file_priv_list = next; } } /* End - File flag list routines */ /* * Wrappers for agp_free_memory & agp_allocate_memory * These make sure that internal lists are kept updated. */ void agp_free_memory_wrap(struct agp_memory *memory) { agp_remove_from_pool(memory); agp_free_memory(memory); } struct agp_memory *agp_allocate_memory_wrap(size_t pg_count, u32 type) { struct agp_memory *memory; memory = agp_allocate_memory(agp_bridge, pg_count, type); if (memory == NULL) return NULL; agp_insert_into_pool(memory); return memory; } /* Routines for managing the list of controllers - * These routines manage the current controller, and the list of * controllers */ static struct agp_controller *agp_find_controller_by_pid(pid_t id) { struct agp_controller *controller; controller = agp_fe.controllers; while (controller != NULL) { if (controller->pid == id) return controller; controller = controller->next; } return NULL; } static struct agp_controller *agp_create_controller(pid_t id) { struct agp_controller *controller; controller = kzalloc(sizeof(struct agp_controller), GFP_KERNEL); if (controller == NULL) return NULL; controller->pid = id; return controller; } static int agp_insert_controller(struct agp_controller *controller) { struct agp_controller *prev_controller; prev_controller = agp_fe.controllers; controller->next = prev_controller; if (prev_controller != NULL) prev_controller->prev = controller; agp_fe.controllers = controller; return 0; } static void agp_remove_all_clients(struct agp_controller *controller) { struct agp_client *client; struct agp_client *temp; client = controller->clients; while (client) { struct agp_file_private *priv; temp = client; agp_remove_seg_from_client(temp); priv = agp_find_private(temp->pid); if (priv != NULL) { clear_bit(AGP_FF_IS_VALID, &priv->access_flags); clear_bit(AGP_FF_IS_CLIENT, &priv->access_flags); } client = client->next; kfree(temp); } } static void agp_remove_all_memory(struct agp_controller *controller) { struct agp_memory *memory; struct agp_memory *temp; memory = controller->pool; while (memory) { temp = memory; memory = memory->next; agp_free_memory_wrap(temp); } } static int agp_remove_controller(struct agp_controller *controller) { struct agp_controller *prev_controller; struct agp_controller *next_controller; prev_controller = controller->prev; next_controller = controller->next; if (prev_controller != NULL) { prev_controller->next = next_controller; if (next_controller != NULL) next_controller->prev = prev_controller; } else { if (next_controller != NULL) next_controller->prev = NULL; agp_fe.controllers = next_controller; } agp_remove_all_memory(controller); agp_remove_all_clients(controller); if (agp_fe.current_controller == controller) { agp_fe.current_controller = NULL; agp_fe.backend_acquired = false; agp_backend_release(agp_bridge); } kfree(controller); return 0; } static void agp_controller_make_current(struct agp_controller *controller) { struct agp_client *clients; clients = controller->clients; while (clients != NULL) { struct agp_file_private *priv; priv = agp_find_private(clients->pid); if (priv != NULL) { set_bit(AGP_FF_IS_VALID, &priv->access_flags); set_bit(AGP_FF_IS_CLIENT, &priv->access_flags); } clients = clients->next; } agp_fe.current_controller = controller; } static void agp_controller_release_current(struct agp_controller *controller, struct agp_file_private *controller_priv) { struct agp_client *clients; clear_bit(AGP_FF_IS_VALID, &controller_priv->access_flags); clients = controller->clients; while (clients != NULL) { struct agp_file_private *priv; priv = agp_find_private(clients->pid); if (priv != NULL) clear_bit(AGP_FF_IS_VALID, &priv->access_flags); clients = clients->next; } agp_fe.current_controller = NULL; agp_fe.used_by_controller = false; agp_backend_release(agp_bridge); } /* * Routines for managing client lists - * These routines are for managing the list of auth'ed clients. */ static struct agp_client *agp_find_client_in_controller(struct agp_controller *controller, pid_t id) { struct agp_client *client; if (controller == NULL) return NULL; client = controller->clients; while (client != NULL) { if (client->pid == id) return client; client = client->next; } return NULL; } static struct agp_controller *agp_find_controller_for_client(pid_t id) { struct agp_controller *controller; controller = agp_fe.controllers; while (controller != NULL) { if ((agp_find_client_in_controller(controller, id)) != NULL) return controller; controller = controller->next; } return NULL; } struct agp_client *agp_find_client_by_pid(pid_t id) { struct agp_client *temp; if (agp_fe.current_controller == NULL) return NULL; temp = agp_find_client_in_controller(agp_fe.current_controller, id); return temp; } static void agp_insert_client(struct agp_client *client) { struct agp_client *prev_client; prev_client = agp_fe.current_controller->clients; client->next = prev_client; if (prev_client != NULL) prev_client->prev = client; agp_fe.current_controller->clients = client; agp_fe.current_controller->num_clients++; } struct agp_client *agp_create_client(pid_t id) { struct agp_client *new_client; new_client = kzalloc(sizeof(struct agp_client), GFP_KERNEL); if (new_client == NULL) return NULL; new_client->pid = id; agp_insert_client(new_client); return new_client; } int agp_remove_client(pid_t id) { struct agp_client *client; struct agp_client *prev_client; struct agp_client *next_client; struct agp_controller *controller; controller = agp_find_controller_for_client(id); if (controller == NULL) return -EINVAL; client = agp_find_client_in_controller(controller, id); if (client == NULL) return -EINVAL; prev_client = client->prev; next_client = client->next; if (prev_client != NULL) { prev_client->next = next_client; if (next_client != NULL) next_client->prev = prev_client; } else { if (next_client != NULL) next_client->prev = NULL; controller->clients = next_client; } controller->num_clients--; agp_remove_seg_from_client(client); kfree(client); return 0; } /* End - Routines for managing client lists */ /* File Operations */ static int agp_mmap(struct file *file, struct vm_area_struct *vma) { unsigned int size, current_size; unsigned long offset; struct agp_client *client; struct agp_file_private *priv = file->private_data; struct agp_kern_info kerninfo; mutex_lock(&(agp_fe.agp_mutex)); if (agp_fe.backend_acquired != true) goto out_eperm; if (!(test_bit(AGP_FF_IS_VALID, &priv->access_flags))) goto out_eperm; agp_copy_info(agp_bridge, &kerninfo); size = vma->vm_end - vma->vm_start; current_size = kerninfo.aper_size; current_size = current_size * 0x100000; offset = vma->vm_pgoff << PAGE_SHIFT; DBG("%lx:%lx", offset, offset+size); if (test_bit(AGP_FF_IS_CLIENT, &priv->access_flags)) { if ((size + offset) > current_size) goto out_inval; client = agp_find_client_by_pid(current->pid); if (client == NULL) goto out_eperm; if (!agp_find_seg_in_client(client, offset, size, vma->vm_page_prot)) goto out_inval; DBG("client vm_ops=%p", kerninfo.vm_ops); if (kerninfo.vm_ops) { vma->vm_ops = kerninfo.vm_ops; } else if (io_remap_pfn_range(vma, vma->vm_start, (kerninfo.aper_base + offset) >> PAGE_SHIFT, size, pgprot_writecombine(vma->vm_page_prot))) { goto out_again; } mutex_unlock(&(agp_fe.agp_mutex)); return 0; } if (test_bit(AGP_FF_IS_CONTROLLER, &priv->access_flags)) { if (size != current_size) goto out_inval; DBG("controller vm_ops=%p", kerninfo.vm_ops); if (kerninfo.vm_ops) { vma->vm_ops = kerninfo.vm_ops; } else if (io_remap_pfn_range(vma, vma->vm_start, kerninfo.aper_base >> PAGE_SHIFT, size, pgprot_writecombine(vma->vm_page_prot))) { goto out_again; } mutex_unlock(&(agp_fe.agp_mutex)); return 0; } out_eperm: mutex_unlock(&(agp_fe.agp_mutex)); return -EPERM; out_inval: mutex_unlock(&(agp_fe.agp_mutex)); return -EINVAL; out_again: mutex_unlock(&(agp_fe.agp_mutex)); return -EAGAIN; } static int agp_release(struct inode *inode, struct file *file) { struct agp_file_private *priv = file->private_data; mutex_lock(&(agp_fe.agp_mutex)); DBG("priv=%p", priv); if (test_bit(AGP_FF_IS_CONTROLLER, &priv->access_flags)) { struct agp_controller *controller; controller = agp_find_controller_by_pid(priv->my_pid); if (controller != NULL) { if (controller == agp_fe.current_controller) agp_controller_release_current(controller, priv); agp_remove_controller(controller); controller = NULL; } } if (test_bit(AGP_FF_IS_CLIENT, &priv->access_flags)) agp_remove_client(priv->my_pid); agp_remove_file_private(priv); kfree(priv); file->private_data = NULL; mutex_unlock(&(agp_fe.agp_mutex)); return 0; } static int agp_open(struct inode *inode, struct file *file) { int minor = iminor(inode); struct agp_file_private *priv; struct agp_client *client; if (minor != AGPGART_MINOR) return -ENXIO; mutex_lock(&(agp_fe.agp_mutex)); priv = kzalloc(sizeof(struct agp_file_private), GFP_KERNEL); if (priv == NULL) { mutex_unlock(&(agp_fe.agp_mutex)); return -ENOMEM; } set_bit(AGP_FF_ALLOW_CLIENT, &priv->access_flags); priv->my_pid = current->pid; if (capable(CAP_SYS_RAWIO)) /* Root priv, can be controller */ set_bit(AGP_FF_ALLOW_CONTROLLER, &priv->access_flags); client = agp_find_client_by_pid(current->pid); if (client != NULL) { set_bit(AGP_FF_IS_CLIENT, &priv->access_flags); set_bit(AGP_FF_IS_VALID, &priv->access_flags); } file->private_data = (void *) priv; agp_insert_file_private(priv); DBG("private=%p, client=%p", priv, client); mutex_unlock(&(agp_fe.agp_mutex)); return 0; } static int agpioc_info_wrap(struct agp_file_private *priv, void __user *arg) { struct agp_info userinfo; struct agp_kern_info kerninfo; agp_copy_info(agp_bridge, &kerninfo); memset(&userinfo, 0, sizeof(userinfo)); userinfo.version.major = kerninfo.version.major; userinfo.version.minor = kerninfo.version.minor; userinfo.bridge_id = kerninfo.device->vendor | (kerninfo.device->device << 16); userinfo.agp_mode = kerninfo.mode; userinfo.aper_base = kerninfo.aper_base; userinfo.aper_size = kerninfo.aper_size; userinfo.pg_total = userinfo.pg_system = kerninfo.max_memory; userinfo.pg_used = kerninfo.current_memory; if (copy_to_user(arg, &userinfo, sizeof(struct agp_info))) return -EFAULT; return 0; } int agpioc_acquire_wrap(struct agp_file_private *priv) { struct agp_controller *controller; DBG(""); if (!(test_bit(AGP_FF_ALLOW_CONTROLLER, &priv->access_flags))) return -EPERM; if (agp_fe.current_controller != NULL) return -EBUSY; if (!agp_bridge) return -ENODEV; if (atomic_read(&agp_bridge->agp_in_use)) return -EBUSY; atomic_inc(&agp_bridge->agp_in_use); agp_fe.backend_acquired = true; controller = agp_find_controller_by_pid(priv->my_pid); if (controller != NULL) { agp_controller_make_current(controller); } else { controller = agp_create_controller(priv->my_pid); if (controller == NULL) { agp_fe.backend_acquired = false; agp_backend_release(agp_bridge); return -ENOMEM; } agp_insert_controller(controller); agp_controller_make_current(controller); } set_bit(AGP_FF_IS_CONTROLLER, &priv->access_flags); set_bit(AGP_FF_IS_VALID, &priv->access_flags); return 0; } int agpioc_release_wrap(struct agp_file_private *priv) { DBG(""); agp_controller_release_current(agp_fe.current_controller, priv); return 0; } int agpioc_setup_wrap(struct agp_file_private *priv, void __user *arg) { struct agp_setup mode; DBG(""); if (copy_from_user(&mode, arg, sizeof(struct agp_setup))) return -EFAULT; agp_enable(agp_bridge, mode.agp_mode); return 0; } static int agpioc_reserve_wrap(struct agp_file_private *priv, void __user *arg) { struct agp_region reserve; struct agp_client *client; struct agp_file_private *client_priv; DBG(""); if (copy_from_user(&reserve, arg, sizeof(struct agp_region))) return -EFAULT; if ((unsigned) reserve.seg_count >= ~0U/sizeof(struct agp_segment)) return -EFAULT; client = agp_find_client_by_pid(reserve.pid); if (reserve.seg_count == 0) { /* remove a client */ client_priv = agp_find_private(reserve.pid); if (client_priv != NULL) { set_bit(AGP_FF_IS_CLIENT, &client_priv->access_flags); set_bit(AGP_FF_IS_VALID, &client_priv->access_flags); } if (client == NULL) { /* client is already removed */ return 0; } return agp_remove_client(reserve.pid); } else { struct agp_segment *segment; if (reserve.seg_count >= 16384) return -EINVAL; segment = kmalloc((sizeof(struct agp_segment) * reserve.seg_count), GFP_KERNEL); if (segment == NULL) return -ENOMEM; if (copy_from_user(segment, (void __user *) reserve.seg_list, sizeof(struct agp_segment) * reserve.seg_count)) { kfree(segment); return -EFAULT; } reserve.seg_list = segment; if (client == NULL) { /* Create the client and add the segment */ client = agp_create_client(reserve.pid); if (client == NULL) { kfree(segment); return -ENOMEM; } client_priv = agp_find_private(reserve.pid); if (client_priv != NULL) { set_bit(AGP_FF_IS_CLIENT, &client_priv->access_flags); set_bit(AGP_FF_IS_VALID, &client_priv->access_flags); } } return agp_create_segment(client, &reserve); } /* Will never really happen */ return -EINVAL; } int agpioc_protect_wrap(struct agp_file_private *priv) { DBG(""); /* This function is not currently implemented */ return -EINVAL; } static int agpioc_allocate_wrap(struct agp_file_private *priv, void __user *arg) { struct agp_memory *memory; struct agp_allocate alloc; DBG(""); if (copy_from_user(&alloc, arg, sizeof(struct agp_allocate))) return -EFAULT; if (alloc.type >= AGP_USER_TYPES) return -EINVAL; memory = agp_allocate_memory_wrap(alloc.pg_count, alloc.type); if (memory == NULL) return -ENOMEM; alloc.key = memory->key; alloc.physical = memory->physical; if (copy_to_user(arg, &alloc, sizeof(struct agp_allocate))) { agp_free_memory_wrap(memory); return -EFAULT; } return 0; } int agpioc_deallocate_wrap(struct agp_file_private *priv, int arg) { struct agp_memory *memory; DBG(""); memory = agp_find_mem_by_key(arg); if (memory == NULL) return -EINVAL; agp_free_memory_wrap(memory); return 0; } static int agpioc_bind_wrap(struct agp_file_private *priv, void __user *arg) { struct agp_bind bind_info; struct agp_memory *memory; DBG(""); if (copy_from_user(&bind_info, arg, sizeof(struct agp_bind))) return -EFAULT; memory = agp_find_mem_by_key(bind_info.key); if (memory == NULL) return -EINVAL; return agp_bind_memory(memory, bind_info.pg_start); } static int agpioc_unbind_wrap(struct agp_file_private *priv, void __user *arg) { struct agp_memory *memory; struct agp_unbind unbind; DBG(""); if (copy_from_user(&unbind, arg, sizeof(struct agp_unbind))) return -EFAULT; memory = agp_find_mem_by_key(unbind.key); if (memory == NULL) return -EINVAL; return agp_unbind_memory(memory); } static long agp_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct agp_file_private *curr_priv = file->private_data; int ret_val = -ENOTTY; DBG("priv=%p, cmd=%x", curr_priv, cmd); mutex_lock(&(agp_fe.agp_mutex)); if ((agp_fe.current_controller == NULL) && (cmd != AGPIOC_ACQUIRE)) { ret_val = -EINVAL; goto ioctl_out; } if ((agp_fe.backend_acquired != true) && (cmd != AGPIOC_ACQUIRE)) { ret_val = -EBUSY; goto ioctl_out; } if (cmd != AGPIOC_ACQUIRE) { if (!(test_bit(AGP_FF_IS_CONTROLLER, &curr_priv->access_flags))) { ret_val = -EPERM; goto ioctl_out; } /* Use the original pid of the controller, * in case it's threaded */ if (agp_fe.current_controller->pid != curr_priv->my_pid) { ret_val = -EBUSY; goto ioctl_out; } } switch (cmd) { case AGPIOC_INFO: ret_val = agpioc_info_wrap(curr_priv, (void __user *) arg); break; case AGPIOC_ACQUIRE: ret_val = agpioc_acquire_wrap(curr_priv); break; case AGPIOC_RELEASE: ret_val = agpioc_release_wrap(curr_priv); break; case AGPIOC_SETUP: ret_val = agpioc_setup_wrap(curr_priv, (void __user *) arg); break; case AGPIOC_RESERVE: ret_val = agpioc_reserve_wrap(curr_priv, (void __user *) arg); break; case AGPIOC_PROTECT: ret_val = agpioc_protect_wrap(curr_priv); break; case AGPIOC_ALLOCATE: ret_val = agpioc_allocate_wrap(curr_priv, (void __user *) arg); break; case AGPIOC_DEALLOCATE: ret_val = agpioc_deallocate_wrap(curr_priv, (int) arg); break; case AGPIOC_BIND: ret_val = agpioc_bind_wrap(curr_priv, (void __user *) arg); break; case AGPIOC_UNBIND: ret_val = agpioc_unbind_wrap(curr_priv, (void __user *) arg); break; case AGPIOC_CHIPSET_FLUSH: break; } ioctl_out: DBG("ioctl returns %d\n", ret_val); mutex_unlock(&(agp_fe.agp_mutex)); return ret_val; } static const struct file_operations agp_fops = { .owner = THIS_MODULE, .llseek = no_llseek, .unlocked_ioctl = agp_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = compat_agp_ioctl, #endif .mmap = agp_mmap, .open = agp_open, .release = agp_release, }; static struct miscdevice agp_miscdev = { .minor = AGPGART_MINOR, .name = "agpgart", .fops = &agp_fops }; int agp_frontend_initialize(void) { memset(&agp_fe, 0, sizeof(struct agp_front_data)); mutex_init(&(agp_fe.agp_mutex)); if (misc_register(&agp_miscdev)) { printk(KERN_ERR PFX "unable to get minor: %d\n", AGPGART_MINOR); return -EIO; } return 0; } void agp_frontend_cleanup(void) { misc_deregister(&agp_miscdev); }
AiJiaZone/linux-4.0
virt/drivers/char/agp/frontend.c
C
gpl-2.0
24,243
require('./angular-locale_shi-tfng-ma'); module.exports = 'ngLocale';
DamascenoRafael/cos482-qualidade-de-software
www/src/main/webapp/bower_components/angular-i18n/shi-tfng-ma.js
JavaScript
mit
70
/* * Regulators driver for Maxim max8649 * * Copyright (C) 2009-2010 Marvell International Ltd. * Haojian Zhuang <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/err.h> #include <linux/i2c.h> #include <linux/platform_device.h> #include <linux/regulator/driver.h> #include <linux/slab.h> #include <linux/regulator/max8649.h> #include <linux/regmap.h> #define MAX8649_DCDC_VMIN 750000 /* uV */ #define MAX8649_DCDC_VMAX 1380000 /* uV */ #define MAX8649_DCDC_STEP 10000 /* uV */ #define MAX8649_VOL_MASK 0x3f /* Registers */ #define MAX8649_MODE0 0x00 #define MAX8649_MODE1 0x01 #define MAX8649_MODE2 0x02 #define MAX8649_MODE3 0x03 #define MAX8649_CONTROL 0x04 #define MAX8649_SYNC 0x05 #define MAX8649_RAMP 0x06 #define MAX8649_CHIP_ID1 0x08 #define MAX8649_CHIP_ID2 0x09 /* Bits */ #define MAX8649_EN_PD (1 << 7) #define MAX8649_VID0_PD (1 << 6) #define MAX8649_VID1_PD (1 << 5) #define MAX8649_VID_MASK (3 << 5) #define MAX8649_FORCE_PWM (1 << 7) #define MAX8649_SYNC_EXTCLK (1 << 6) #define MAX8649_EXT_MASK (3 << 6) #define MAX8649_RAMP_MASK (7 << 5) #define MAX8649_RAMP_DOWN (1 << 1) struct max8649_regulator_info { struct regulator_dev *regulator; struct device *dev; struct regmap *regmap; unsigned mode:2; /* bit[1:0] = VID1, VID0 */ unsigned extclk_freq:2; unsigned extclk:1; unsigned ramp_timing:3; unsigned ramp_down:1; }; /* EN_PD means pulldown on EN input */ static int max8649_enable(struct regulator_dev *rdev) { struct max8649_regulator_info *info = rdev_get_drvdata(rdev); return regmap_update_bits(info->regmap, MAX8649_CONTROL, MAX8649_EN_PD, 0); } /* * Applied internal pulldown resistor on EN input pin. * If pulldown EN pin outside, it would be better. */ static int max8649_disable(struct regulator_dev *rdev) { struct max8649_regulator_info *info = rdev_get_drvdata(rdev); return regmap_update_bits(info->regmap, MAX8649_CONTROL, MAX8649_EN_PD, MAX8649_EN_PD); } static int max8649_is_enabled(struct regulator_dev *rdev) { struct max8649_regulator_info *info = rdev_get_drvdata(rdev); unsigned int val; int ret; ret = regmap_read(info->regmap, MAX8649_CONTROL, &val); if (ret != 0) return ret; return !((unsigned char)val & MAX8649_EN_PD); } static int max8649_enable_time(struct regulator_dev *rdev) { struct max8649_regulator_info *info = rdev_get_drvdata(rdev); int voltage, rate, ret; unsigned int val; /* get voltage */ ret = regmap_read(info->regmap, rdev->desc->vsel_reg, &val); if (ret != 0) return ret; val &= MAX8649_VOL_MASK; voltage = regulator_list_voltage_linear(rdev, (unsigned char)val); /* get rate */ ret = regmap_read(info->regmap, MAX8649_RAMP, &val); if (ret != 0) return ret; ret = (val & MAX8649_RAMP_MASK) >> 5; rate = (32 * 1000) >> ret; /* uV/uS */ return DIV_ROUND_UP(voltage, rate); } static int max8649_set_mode(struct regulator_dev *rdev, unsigned int mode) { struct max8649_regulator_info *info = rdev_get_drvdata(rdev); switch (mode) { case REGULATOR_MODE_FAST: regmap_update_bits(info->regmap, rdev->desc->vsel_reg, MAX8649_FORCE_PWM, MAX8649_FORCE_PWM); break; case REGULATOR_MODE_NORMAL: regmap_update_bits(info->regmap, rdev->desc->vsel_reg, MAX8649_FORCE_PWM, 0); break; default: return -EINVAL; } return 0; } static unsigned int max8649_get_mode(struct regulator_dev *rdev) { struct max8649_regulator_info *info = rdev_get_drvdata(rdev); unsigned int val; int ret; ret = regmap_read(info->regmap, rdev->desc->vsel_reg, &val); if (ret != 0) return ret; if (val & MAX8649_FORCE_PWM) return REGULATOR_MODE_FAST; return REGULATOR_MODE_NORMAL; } static struct regulator_ops max8649_dcdc_ops = { .set_voltage_sel = regulator_set_voltage_sel_regmap, .get_voltage_sel = regulator_get_voltage_sel_regmap, .list_voltage = regulator_list_voltage_linear, .map_voltage = regulator_map_voltage_linear, .enable = max8649_enable, .disable = max8649_disable, .is_enabled = max8649_is_enabled, .enable_time = max8649_enable_time, .set_mode = max8649_set_mode, .get_mode = max8649_get_mode, }; static struct regulator_desc dcdc_desc = { .name = "max8649", .ops = &max8649_dcdc_ops, .type = REGULATOR_VOLTAGE, .n_voltages = 1 << 6, .owner = THIS_MODULE, .vsel_mask = MAX8649_VOL_MASK, .min_uV = MAX8649_DCDC_VMIN, .uV_step = MAX8649_DCDC_STEP, }; static struct regmap_config max8649_regmap_config = { .reg_bits = 8, .val_bits = 8, }; static int max8649_regulator_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct max8649_platform_data *pdata = client->dev.platform_data; struct max8649_regulator_info *info = NULL; struct regulator_config config = { }; unsigned int val; unsigned char data; int ret; info = devm_kzalloc(&client->dev, sizeof(struct max8649_regulator_info), GFP_KERNEL); if (!info) { dev_err(&client->dev, "No enough memory\n"); return -ENOMEM; } info->regmap = devm_regmap_init_i2c(client, &max8649_regmap_config); if (IS_ERR(info->regmap)) { ret = PTR_ERR(info->regmap); dev_err(&client->dev, "Failed to allocate register map: %d\n", ret); return ret; } info->dev = &client->dev; i2c_set_clientdata(client, info); info->mode = pdata->mode; switch (info->mode) { case 0: dcdc_desc.vsel_reg = MAX8649_MODE0; break; case 1: dcdc_desc.vsel_reg = MAX8649_MODE1; break; case 2: dcdc_desc.vsel_reg = MAX8649_MODE2; break; case 3: dcdc_desc.vsel_reg = MAX8649_MODE3; break; default: break; } ret = regmap_read(info->regmap, MAX8649_CHIP_ID1, &val); if (ret != 0) { dev_err(info->dev, "Failed to detect ID of MAX8649:%d\n", ret); return ret; } dev_info(info->dev, "Detected MAX8649 (ID:%x)\n", val); /* enable VID0 & VID1 */ regmap_update_bits(info->regmap, MAX8649_CONTROL, MAX8649_VID_MASK, 0); /* enable/disable external clock synchronization */ info->extclk = pdata->extclk; data = (info->extclk) ? MAX8649_SYNC_EXTCLK : 0; regmap_update_bits(info->regmap, dcdc_desc.vsel_reg, MAX8649_SYNC_EXTCLK, data); if (info->extclk) { /* set external clock frequency */ info->extclk_freq = pdata->extclk_freq; regmap_update_bits(info->regmap, MAX8649_SYNC, MAX8649_EXT_MASK, info->extclk_freq << 6); } if (pdata->ramp_timing) { info->ramp_timing = pdata->ramp_timing; regmap_update_bits(info->regmap, MAX8649_RAMP, MAX8649_RAMP_MASK, info->ramp_timing << 5); } info->ramp_down = pdata->ramp_down; if (info->ramp_down) { regmap_update_bits(info->regmap, MAX8649_RAMP, MAX8649_RAMP_DOWN, MAX8649_RAMP_DOWN); } config.dev = &client->dev; config.init_data = pdata->regulator; config.driver_data = info; config.regmap = info->regmap; info->regulator = regulator_register(&dcdc_desc, &config); if (IS_ERR(info->regulator)) { dev_err(info->dev, "failed to register regulator %s\n", dcdc_desc.name); return PTR_ERR(info->regulator); } return 0; } static int max8649_regulator_remove(struct i2c_client *client) { struct max8649_regulator_info *info = i2c_get_clientdata(client); if (info) { if (info->regulator) regulator_unregister(info->regulator); } return 0; } static const struct i2c_device_id max8649_id[] = { { "max8649", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, max8649_id); static struct i2c_driver max8649_driver = { .probe = max8649_regulator_probe, .remove = max8649_regulator_remove, .driver = { .name = "max8649", }, .id_table = max8649_id, }; static int __init max8649_init(void) { return i2c_add_driver(&max8649_driver); } subsys_initcall(max8649_init); static void __exit max8649_exit(void) { i2c_del_driver(&max8649_driver); } module_exit(max8649_exit); /* Module information */ MODULE_DESCRIPTION("MAXIM 8649 voltage regulator driver"); MODULE_AUTHOR("Haojian Zhuang <[email protected]>"); MODULE_LICENSE("GPL");
SanDisk-Open-Source/SSD_Dashboard
uefi/linux-source-3.8.0/drivers/regulator/max8649.c
C
gpl-2.0
8,089
#include <math.h> #include "headers/atanh.h" double atanh(double x) { return _atanh(x); }
GarethNelson/Zoidberg
userland/newlib/newlib/libm/machine/spu/w_atanh.c
C
gpl-2.0
93
/* * Cache definitions for the Hexagon architecture * * Copyright (c) 2010-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. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ #ifndef __ASM_CACHE_H #define __ASM_CACHE_H /* Bytes per L1 cache line */ #define L1_CACHE_SHIFT (5) #define L1_CACHE_BYTES (1 << L1_CACHE_SHIFT) #define __cacheline_aligned __aligned(L1_CACHE_BYTES) #define ____cacheline_aligned __aligned(L1_CACHE_BYTES) /* See http://lwn.net/Articles/262554/ */ #define __read_mostly #endif
mericon/Xp_Kernel_LGH850
virt/arch/hexagon/include/asm/cache.h
C
gpl-2.0
1,143
<?php /** * Locale data for 'mn_Mong_CN'. * * This file is automatically generated by yiic cldr command. * * Copyright © 1991-2007 Unicode, Inc. All rights reserved. * Distributed under the Terms of Use in http://www.unicode.org/copyright.html. * * @copyright 2008-2013 Yii Software LLC (http://www.yiiframework.com/license/) */ return array ( 'version' => '4123', 'numberSymbols' => array ( 'alias' => '', 'decimal' => '.', 'group' => ',', 'list' => ';', 'percentSign' => '%', 'plusSign' => '+', 'minusSign' => '-', 'exponential' => 'E', 'perMille' => '‰', 'infinity' => '∞', 'nan' => 'NaN', ), 'decimalFormat' => '#,##0.###', 'scientificFormat' => '#E0', 'percentFormat' => '#,##0%', 'currencyFormat' => '¤ #,##0.00', 'currencySymbols' => array ( 'AUD' => 'AU$', 'BRL' => 'R$', 'CAD' => 'CA$', 'CNY' => 'CN¥', 'EUR' => '€', 'GBP' => '£', 'HKD' => 'HK$', 'ILS' => '₪', 'INR' => '₹', 'JPY' => 'JP¥', 'KRW' => '₩', 'MXN' => 'MX$', 'NZD' => 'NZ$', 'THB' => '฿', 'TWD' => 'NT$', 'USD' => 'US$', 'VND' => '₫', 'XAF' => 'FCFA', 'XCD' => 'EC$', 'XOF' => 'CFA', 'XPF' => 'CFPF', 'MNT' => '₮', ), 'monthNames' => array ( 'wide' => array ( 1 => 'Хулгана', 2 => 'Үхэр', 3 => 'Бар', 4 => 'Туулай', 5 => 'Луу', 6 => 'Могой', 7 => 'Морь', 8 => 'Хонь', 9 => 'Бич', 10 => 'Тахиа', 11 => 'Нохой', 12 => 'Гахай', ), 'abbreviated' => array ( 1 => 'хул', 2 => 'үхэ', 3 => 'бар', 4 => 'туу', 5 => 'луу', 6 => 'мог', 7 => 'мор', 8 => 'хон', 9 => 'бич', 10 => 'тах', 11 => 'нох', 12 => 'гах', ), ), 'monthNamesSA' => array ( 'narrow' => array ( 1 => '1', 2 => '2', 3 => '3', 4 => '4', 5 => '5', 6 => '6', 7 => '7', 8 => '8', 9 => '9', 10 => '10', 11 => '11', 12 => '12', ), ), 'weekDayNames' => array ( 'wide' => array ( 0 => 'ням', 1 => 'даваа', 2 => 'мягмар', 3 => 'лхагва', 4 => 'пүрэв', 5 => 'баасан', 6 => 'бямба', ), 'abbreviated' => array ( 0 => 'Ня', 1 => 'Да', 2 => 'Мя', 3 => 'Лх', 4 => 'Пү', 5 => 'Ба', 6 => 'Бя', ), ), 'weekDayNamesSA' => array ( 'narrow' => array ( 0 => '1', 1 => '2', 2 => '3', 3 => '4', 4 => '5', 5 => '6', 6 => '7', ), ), 'eraNames' => array ( 'abbreviated' => array ( 0 => 'м.э.ө', 1 => 'м.э.', ), 'wide' => array ( 0 => 'манай эриний өмнөх', 1 => 'манай эриний', ), 'narrow' => array ( 0 => 'м.э.ө', 1 => 'м.э.', ), ), 'dateFormats' => array ( 'full' => 'EEEE, y MMMM dd', 'long' => 'y MMMM d', 'medium' => 'y MMM d', 'short' => 'yyyy-MM-dd', ), 'timeFormats' => array ( 'full' => 'HH:mm:ss zzzz', 'long' => 'HH:mm:ss z', 'medium' => 'HH:mm:ss', 'short' => 'HH:mm', ), 'dateTimeFormat' => '{1} {0}', 'amName' => 'AM', 'pmName' => 'PM', 'orientation' => 'ltr', 'languages' => array ( 'af' => 'африк', 'am' => 'амхарик', 'ar' => 'араб', 'as' => 'ассам үндэстэн', 'az' => 'азарбежан', 'be' => 'беларусь', 'bg' => 'болгар', 'bh' => 'бихари хэл', 'bn' => 'бенгаль', 'br' => 'бретон', 'bs' => 'босниа', 'ca' => 'каталан', 'cs' => 'чех', 'cy' => 'уэлс', 'da' => 'дани', 'de' => 'герман', 'el' => 'грек', 'en' => 'англи', 'eo' => 'эсперанто', 'es' => 'испани', 'et' => 'эстони', 'eu' => 'баск', 'fa' => 'перс', 'fi' => 'финлянд', 'fil' => 'тагало', 'fo' => 'фөриэс хэл', 'fr' => 'франц', 'fy' => 'голландын фрисиан хэл', 'ga' => 'ирланд', 'gd' => 'шотланд келт', 'gl' => 'галик', 'gn' => 'гуарани', 'gu' => 'энэтхэгийн гужарати', 'he' => 'кипр', 'hi' => 'хинди', 'hr' => 'хорвати', 'hu' => 'унгар', 'hy' => 'армен', 'ia' => 'интерлингво', 'id' => 'индонези', 'ie' => 'нэгдмэл хэл', 'is' => 'исланд', 'it' => 'итали', 'ja' => 'япон', 'jv' => 'ява', 'ka' => 'гүрж', 'km' => 'камбуч', 'kn' => 'каннада', 'ko' => 'солонгос', 'ku' => 'курд', 'ky' => 'киргиз', 'la' => 'латин', 'ln' => 'лингала', 'lo' => 'лаотиан', 'lt' => 'литви', 'lv' => 'латви', 'mk' => 'македони', 'ml' => 'малайлам', 'mn' => 'монгол', 'mr' => 'энэтхэгийн марати', 'ms' => 'малай', 'mt' => 'малти', 'ne' => 'балба', 'nl' => 'голланд', 'nn' => 'норвеги (нынорск)', 'no' => 'норвеги', 'oc' => 'францын окситан', 'or' => 'ория', 'pa' => 'пенжаби', 'pl' => 'польш', 'ps' => 'афган', 'pt' => 'португали', 'pt_br' => 'португали (бразил)', 'pt_pt' => 'португали (португали)', 'ro' => 'румын', 'ru' => 'орос', 'sa' => 'санскирит', 'sd' => 'синдхи', 'sh' => 'хорватын серб', 'si' => 'шри ланк', 'sk' => 'словак', 'sl' => 'словени', 'so' => 'сомали', 'sq' => 'албани', 'sr' => 'серби', 'st' => 'сесото', 'su' => 'сунданес хэл', 'sv' => 'швед', 'sw' => 'африкийн свахили хэл', 'ta' => 'тамил', 'te' => 'тэлүгү', 'th' => 'тай', 'ti' => 'тикрина', 'tk' => 'туркмен', 'tlh' => 'клингон хэл', 'tr' => 'турк', 'tw' => 'тви', 'ug' => 'уйгур', 'uk' => 'украин', 'ur' => 'пакистаны урду', 'uz' => 'узбек', 'vi' => 'вьетнам', 'xh' => 'хоса', 'yi' => 'иддиш', 'zh' => 'хятад', 'zu' => 'зулу', ), 'territories' => array ( 'br' => 'Бразили', 'de' => 'Герман', 'fr' => 'Франц', 'in' => 'Энэтхэг', 'it' => 'Итали', 'jp' => 'Япон', 'mn' => 'Монгол улс', 'ru' => 'Орос', 'to' => 'Тонга', 'us' => 'Америкийн Нэгдсэн Улс', ), 'pluralRules' => array ( 0 => 'n==1', 1 => 'true', ), );
Wyden971/IpMotors
yiiframework/i18n/data/mn_mong_cn.php
PHP
unlicense
7,180
/********************************************************************* * * Filename: irlap.h * Version: 0.8 * Description: An IrDA LAP driver for Linux * Status: Experimental. * Author: Dag Brattli <[email protected]> * Created at: Mon Aug 4 20:40:53 1997 * Modified at: Fri Dec 10 13:21:17 1999 * Modified by: Dag Brattli <[email protected]> * * Copyright (c) 1998-1999 Dag Brattli <[email protected]>, * All Rights Reserved. * Copyright (c) 2000-2002 Jean Tourrilhes <[email protected]> * * 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. * * Neither Dag Brattli nor University of Tromsø admit liability nor * provide warranty for any of this software. This material is * provided "AS-IS" and at no charge. * ********************************************************************/ #ifndef IRLAP_H #define IRLAP_H #include <linux/types.h> #include <linux/skbuff.h> #include <linux/netdevice.h> #include <linux/timer.h> #include <net/irda/irqueue.h> /* irda_queue_t */ #include <net/irda/qos.h> /* struct qos_info */ #include <net/irda/discovery.h> /* discovery_t */ #include <net/irda/irlap_event.h> /* IRLAP_STATE, ... */ #include <net/irda/irmod.h> /* struct notify_t */ #define CONFIG_IRDA_DYNAMIC_WINDOW 1 #define LAP_RELIABLE 1 #define LAP_UNRELIABLE 0 #define LAP_ADDR_HEADER 1 /* IrLAP Address Header */ #define LAP_CTRL_HEADER 1 /* IrLAP Control Header */ /* May be different when we get VFIR */ #define LAP_MAX_HEADER (LAP_ADDR_HEADER + LAP_CTRL_HEADER) /* Each IrDA device gets a random 32 bits IRLAP device address */ #define LAP_ALEN 4 #define BROADCAST 0xffffffff /* Broadcast device address */ #define CBROADCAST 0xfe /* Connection broadcast address */ #define XID_FORMAT 0x01 /* Discovery XID format */ /* Nobody seems to use this constant. */ #define LAP_WINDOW_SIZE 8 /* We keep the LAP queue very small to minimise the amount of buffering. * this improve latency and reduce resource consumption. * This work only because we have synchronous refilling of IrLAP through * the flow control mechanism (via scheduler and IrTTP). * 2 buffers is the minimum we can work with, one that we send while polling * IrTTP, and another to know that we should not send the pf bit. * Jean II */ #define LAP_HIGH_THRESHOLD 2 /* Some rare non TTP clients don't implement flow control, and * so don't comply with the above limit (and neither with this one). * For IAP and management, it doesn't matter, because they never transmit much. *.For IrLPT, this should be fixed. * - Jean II */ #define LAP_MAX_QUEUE 10 /* Please note that all IrDA management frames (LMP/TTP conn req/disc and * IAS queries) fall in the second category and are sent to LAP even if TTP * is stopped. This means that those frames will wait only a maximum of * two (2) data frames before beeing sent on the "wire", which speed up * new socket setup when the link is saturated. * Same story for two sockets competing for the medium : if one saturates * the LAP, when the other want to transmit it only has to wait for * maximum three (3) packets (2 + one scheduling), which improve performance * of delay sensitive applications. * Jean II */ #define NR_EXPECTED 1 #define NR_UNEXPECTED 0 #define NR_INVALID -1 #define NS_EXPECTED 1 #define NS_UNEXPECTED 0 #define NS_INVALID -1 /* * Meta information passed within the IrLAP state machine */ struct irlap_info { __u8 caddr; /* Connection address */ __u8 control; /* Frame type */ __u8 cmd; __u32 saddr; __u32 daddr; int pf; /* Poll/final bit set */ __u8 nr; /* Sequence number of next frame expected */ __u8 ns; /* Sequence number of frame sent */ int S; /* Number of slots */ int slot; /* Random chosen slot */ int s; /* Current slot */ discovery_t *discovery; /* Discovery information */ }; /* Main structure of IrLAP */ struct irlap_cb { irda_queue_t q; /* Must be first */ magic_t magic; /* Device we are attached to */ struct net_device *netdev; char hw_name[2*IFNAMSIZ + 1]; /* Connection state */ volatile IRLAP_STATE state; /* Current state */ /* Timers used by IrLAP */ struct timer_list query_timer; struct timer_list slot_timer; struct timer_list discovery_timer; struct timer_list final_timer; struct timer_list poll_timer; struct timer_list wd_timer; struct timer_list backoff_timer; /* Media busy stuff */ struct timer_list media_busy_timer; int media_busy; /* Timeouts which will be different with different turn time */ int slot_timeout; int poll_timeout; int final_timeout; int wd_timeout; struct sk_buff_head txq; /* Frames to be transmitted */ struct sk_buff_head txq_ultra; __u8 caddr; /* Connection address */ __u32 saddr; /* Source device address */ __u32 daddr; /* Destination device address */ int retry_count; /* Times tried to establish connection */ int add_wait; /* True if we are waiting for frame */ __u8 connect_pending; __u8 disconnect_pending; /* To send a faster RR if tx queue empty */ #ifdef CONFIG_IRDA_FAST_RR int fast_RR_timeout; int fast_RR; #endif /* CONFIG_IRDA_FAST_RR */ int N1; /* N1 * F-timer = Negitiated link disconnect warning threshold */ int N2; /* N2 * F-timer = Negitiated link disconnect time */ int N3; /* Connection retry count */ int local_busy; int remote_busy; int xmitflag; __u8 vs; /* Next frame to be sent */ __u8 vr; /* Next frame to be received */ __u8 va; /* Last frame acked */ int window; /* Nr of I-frames allowed to send */ int window_size; /* Current negotiated window size */ #ifdef CONFIG_IRDA_DYNAMIC_WINDOW __u32 line_capacity; /* Number of bytes allowed to send */ __u32 bytes_left; /* Number of bytes still allowed to transmit */ #endif /* CONFIG_IRDA_DYNAMIC_WINDOW */ struct sk_buff_head wx_list; __u8 ack_required; /* XID parameters */ __u8 S; /* Number of slots */ __u8 slot; /* Random chosen slot */ __u8 s; /* Current slot */ int frame_sent; /* Have we sent reply? */ hashbin_t *discovery_log; discovery_t *discovery_cmd; __u32 speed; /* Link speed */ struct qos_info qos_tx; /* QoS requested by peer */ struct qos_info qos_rx; /* QoS requested by self */ struct qos_info *qos_dev; /* QoS supported by device */ notify_t notify; /* Callbacks to IrLMP */ int mtt_required; /* Minimum turnaround time required */ int xbofs_delay; /* Nr of XBOF's used to MTT */ int bofs_count; /* Negotiated extra BOFs */ int next_bofs; /* Negotiated extra BOFs after next frame */ int mode; /* IrLAP mode (primary, secondary or monitor) */ }; /* * Function prototypes */ int irlap_init(void); void irlap_cleanup(void); struct irlap_cb *irlap_open(struct net_device *dev, struct qos_info *qos, const char *hw_name); void irlap_close(struct irlap_cb *self); void irlap_connect_request(struct irlap_cb *self, __u32 daddr, struct qos_info *qos, int sniff); void irlap_connect_response(struct irlap_cb *self, struct sk_buff *skb); void irlap_connect_indication(struct irlap_cb *self, struct sk_buff *skb); void irlap_connect_confirm(struct irlap_cb *, struct sk_buff *skb); void irlap_data_indication(struct irlap_cb *, struct sk_buff *, int unreliable); void irlap_data_request(struct irlap_cb *, struct sk_buff *, int unreliable); #ifdef CONFIG_IRDA_ULTRA void irlap_unitdata_request(struct irlap_cb *, struct sk_buff *); void irlap_unitdata_indication(struct irlap_cb *, struct sk_buff *); #endif /* CONFIG_IRDA_ULTRA */ void irlap_disconnect_request(struct irlap_cb *); void irlap_disconnect_indication(struct irlap_cb *, LAP_REASON reason); void irlap_status_indication(struct irlap_cb *, int quality_of_link); void irlap_test_request(__u8 *info, int len); void irlap_discovery_request(struct irlap_cb *, discovery_t *discovery); void irlap_discovery_confirm(struct irlap_cb *, hashbin_t *discovery_log); void irlap_discovery_indication(struct irlap_cb *, discovery_t *discovery); void irlap_reset_indication(struct irlap_cb *self); void irlap_reset_confirm(void); void irlap_update_nr_received(struct irlap_cb *, int nr); int irlap_validate_nr_received(struct irlap_cb *, int nr); int irlap_validate_ns_received(struct irlap_cb *, int ns); int irlap_generate_rand_time_slot(int S, int s); void irlap_initiate_connection_state(struct irlap_cb *); void irlap_flush_all_queues(struct irlap_cb *); void irlap_wait_min_turn_around(struct irlap_cb *, struct qos_info *); void irlap_apply_default_connection_parameters(struct irlap_cb *self); void irlap_apply_connection_parameters(struct irlap_cb *self, int now); #define IRLAP_GET_HEADER_SIZE(self) (LAP_MAX_HEADER) #define IRLAP_GET_TX_QUEUE_LEN(self) skb_queue_len(&self->txq) /* Return TRUE if the node is in primary mode (i.e. master) * - Jean II */ static inline int irlap_is_primary(struct irlap_cb *self) { int ret; switch(self->state) { case LAP_XMIT_P: case LAP_NRM_P: ret = 1; break; case LAP_XMIT_S: case LAP_NRM_S: ret = 0; break; default: ret = -1; } return ret; } /* Clear a pending IrLAP disconnect. - Jean II */ static inline void irlap_clear_disconnect(struct irlap_cb *self) { self->disconnect_pending = FALSE; } /* * Function irlap_next_state (self, state) * * Switches state and provides debug information * */ static inline void irlap_next_state(struct irlap_cb *self, IRLAP_STATE state) { /* if (!self || self->magic != LAP_MAGIC) return; pr_debug("next LAP state = %s\n", irlap_state[state]); */ self->state = state; } #endif
AiJiaZone/linux-4.0
virt/include/net/irda/irlap.h
C
gpl-2.0
10,046
// 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. namespace System.Net.NetworkInformation { internal class LinuxIcmpV4Statistics : IcmpV4Statistics { private readonly Icmpv4StatisticsTable _table; // The table is a fairly large struct (108 bytes), pass it by reference public LinuxIcmpV4Statistics() { _table = StringParsingHelpers.ParseIcmpv4FromSnmpFile(NetworkFiles.SnmpV4StatsFile); } public override long AddressMaskRepliesReceived { get { return _table.InAddrMaskReps; } } public override long AddressMaskRepliesSent { get { return _table.OutAddrMaskReps; } } public override long AddressMaskRequestsReceived { get { return _table.InAddrMasks; } } public override long AddressMaskRequestsSent { get { return _table.OutAddrMasks; } } public override long DestinationUnreachableMessagesReceived { get { return _table.InDestUnreachs; } } public override long DestinationUnreachableMessagesSent { get { return _table.OutDestUnreachs; } } public override long EchoRepliesReceived { get { return _table.InEchoReps; } } public override long EchoRepliesSent { get { return _table.OutEchoReps; } } public override long EchoRequestsReceived { get { return _table.InEchos; } } public override long EchoRequestsSent { get { return _table.OutEchos; } } public override long ErrorsReceived { get { return _table.InErrors; } } public override long ErrorsSent { get { return _table.OutErrors; } } public override long MessagesReceived { get { return _table.InMsgs; } } public override long MessagesSent { get { return _table.OutMsgs; } } public override long ParameterProblemsReceived { get { return _table.InParmProbs; } } public override long ParameterProblemsSent { get { return _table.OutParmProbs; } } public override long RedirectsReceived { get { return _table.InRedirects; } } public override long RedirectsSent { get { return _table.OutRedirects; } } public override long SourceQuenchesReceived { get { return _table.InSrcQuenchs; } } public override long SourceQuenchesSent { get { return _table.OutSrcQuenchs; } } public override long TimeExceededMessagesReceived { get { return _table.InTimeExcds; } } public override long TimeExceededMessagesSent { get { return _table.OutTimeExcds; } } public override long TimestampRepliesReceived { get { return _table.InTimeStampReps; } } public override long TimestampRepliesSent { get { return _table.OutTimestampReps; } } public override long TimestampRequestsReceived { get { return _table.InTimestamps; } } public override long TimestampRequestsSent { get { return _table.OutTimestamps; } } } }
iamjasonp/corefx
src/System.Net.NetworkInformation/src/System/Net/NetworkInformation/LinuxIcmpV4Statistics.cs
C#
mit
2,993
// 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. namespace System.Runtime.InteropServices.ComTypes { [Flags] public enum TYMED { TYMED_HGLOBAL = 1, TYMED_FILE = 2, TYMED_ISTREAM = 4, TYMED_ISTORAGE = 8, TYMED_GDI = 16, TYMED_MFPICT = 32, TYMED_ENHMF = 64, TYMED_NULL = 0 } }
iamjasonp/corefx
src/System.Runtime.InteropServices/src/System/Runtime/InteropServices/ComTypes/tymed.cs
C#
mit
510
/* * ZTE zx296702 SoC reset code * * Copyright (c) 2015 Linaro Ltd. * * Author: Jun Nie <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/delay.h> #include <linux/io.h> #include <linux/module.h> #include <linux/notifier.h> #include <linux/of_address.h> #include <linux/platform_device.h> #include <linux/reboot.h> static void __iomem *base; static void __iomem *pcu_base; static int zx_restart_handler(struct notifier_block *this, unsigned long mode, void *cmd) { writel_relaxed(1, base + 0xb0); writel_relaxed(1, pcu_base + 0x34); mdelay(50); pr_emerg("Unable to restart system\n"); return NOTIFY_DONE; } static struct notifier_block zx_restart_nb = { .notifier_call = zx_restart_handler, .priority = 128, }; static int zx_reboot_probe(struct platform_device *pdev) { struct device_node *np = pdev->dev.of_node; int err; base = of_iomap(np, 0); if (!base) { WARN(1, "failed to map base address"); return -ENODEV; } np = of_find_compatible_node(NULL, NULL, "zte,zx296702-pcu"); pcu_base = of_iomap(np, 0); if (!pcu_base) { iounmap(base); WARN(1, "failed to map pcu_base address"); return -ENODEV; } err = register_restart_handler(&zx_restart_nb); if (err) { iounmap(base); iounmap(pcu_base); dev_err(&pdev->dev, "Register restart handler failed(err=%d)\n", err); } return err; } static const struct of_device_id zx_reboot_of_match[] = { { .compatible = "zte,sysctrl" }, {} }; MODULE_DEVICE_TABLE(of, zx_reboot_of_match); static struct platform_driver zx_reboot_driver = { .probe = zx_reboot_probe, .driver = { .name = "zx-reboot", .of_match_table = zx_reboot_of_match, }, }; module_platform_driver(zx_reboot_driver);
mkvdv/au-linux-kernel-autumn-2017
linux/drivers/power/reset/zx-reboot.c
C
gpl-3.0
1,873
/* Copyright 2017 The Kubernetes 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. */ // +k8s:deepcopy-gen=package // +k8s:protobuf-gen=package // +k8s:openapi-gen=true // +groupName=settings.k8s.io package v1alpha1 // import "k8s.io/api/settings/v1alpha1"
gravitational/monitoring-app
watcher/vendor/k8s.io/api/settings/v1alpha1/doc.go
GO
apache-2.0
744
/* * \file drm_lock.c * IOCTLs for locking * * \author Rickard E. (Rik) Faith <[email protected]> * \author Gareth Hughes <[email protected]> */ /* * Created: Tue Feb 2 08:37:54 1999 by [email protected] * * Copyright 1999 Precision Insight, Inc., Cedar Park, Texas. * Copyright 2000 VA Linux Systems, Inc., Sunnyvale, California. * All Rights Reserved. * * 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 (including the next * paragraph) 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 * VA LINUX SYSTEMS AND/OR ITS SUPPLIERS 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 <linux/export.h> #include <linux/sched/signal.h> #include <drm/drm.h> #include <drm/drm_drv.h> #include <drm/drm_file.h> #include <drm/drm_print.h> #include "drm_internal.h" #include "drm_legacy.h" static int drm_lock_take(struct drm_lock_data *lock_data, unsigned int context); /* * Take the heavyweight lock. * * \param lock lock pointer. * \param context locking context. * \return one if the lock is held, or zero otherwise. * * Attempt to mark the lock as held by the given context, via the \p cmpxchg instruction. */ static int drm_lock_take(struct drm_lock_data *lock_data, unsigned int context) { unsigned int old, new, prev; volatile unsigned int *lock = &lock_data->hw_lock->lock; spin_lock_bh(&lock_data->spinlock); do { old = *lock; if (old & _DRM_LOCK_HELD) new = old | _DRM_LOCK_CONT; else { new = context | _DRM_LOCK_HELD | ((lock_data->user_waiters + lock_data->kernel_waiters > 1) ? _DRM_LOCK_CONT : 0); } prev = cmpxchg(lock, old, new); } while (prev != old); spin_unlock_bh(&lock_data->spinlock); if (_DRM_LOCKING_CONTEXT(old) == context) { if (old & _DRM_LOCK_HELD) { if (context != DRM_KERNEL_CONTEXT) { DRM_ERROR("%d holds heavyweight lock\n", context); } return 0; } } if ((_DRM_LOCKING_CONTEXT(new)) == context && (new & _DRM_LOCK_HELD)) { /* Have lock */ return 1; } return 0; } /* * This takes a lock forcibly and hands it to context. Should ONLY be used * inside *_unlock to give lock to kernel before calling *_dma_schedule. * * \param dev DRM device. * \param lock lock pointer. * \param context locking context. * \return always one. * * Resets the lock file pointer. * Marks the lock as held by the given context, via the \p cmpxchg instruction. */ static int drm_lock_transfer(struct drm_lock_data *lock_data, unsigned int context) { unsigned int old, new, prev; volatile unsigned int *lock = &lock_data->hw_lock->lock; lock_data->file_priv = NULL; do { old = *lock; new = context | _DRM_LOCK_HELD; prev = cmpxchg(lock, old, new); } while (prev != old); return 1; } static int drm_legacy_lock_free(struct drm_lock_data *lock_data, unsigned int context) { unsigned int old, new, prev; volatile unsigned int *lock = &lock_data->hw_lock->lock; spin_lock_bh(&lock_data->spinlock); if (lock_data->kernel_waiters != 0) { drm_lock_transfer(lock_data, 0); lock_data->idle_has_lock = 1; spin_unlock_bh(&lock_data->spinlock); return 1; } spin_unlock_bh(&lock_data->spinlock); do { old = *lock; new = _DRM_LOCKING_CONTEXT(old); prev = cmpxchg(lock, old, new); } while (prev != old); if (_DRM_LOCK_IS_HELD(old) && _DRM_LOCKING_CONTEXT(old) != context) { DRM_ERROR("%d freed heavyweight lock held by %d\n", context, _DRM_LOCKING_CONTEXT(old)); return 1; } wake_up_interruptible(&lock_data->lock_queue); return 0; } /* * Lock ioctl. * * \param inode device inode. * \param file_priv DRM file private. * \param cmd command. * \param arg user argument, pointing to a drm_lock structure. * \return zero on success or negative number on failure. * * Add the current task to the lock wait queue, and attempt to take to lock. */ int drm_legacy_lock(struct drm_device *dev, void *data, struct drm_file *file_priv) { DECLARE_WAITQUEUE(entry, current); struct drm_lock *lock = data; struct drm_master *master = file_priv->master; int ret = 0; if (!drm_core_check_feature(dev, DRIVER_LEGACY)) return -EOPNOTSUPP; ++file_priv->lock_count; if (lock->context == DRM_KERNEL_CONTEXT) { DRM_ERROR("Process %d using kernel context %d\n", task_pid_nr(current), lock->context); return -EINVAL; } DRM_DEBUG("%d (pid %d) requests lock (0x%08x), flags = 0x%08x\n", lock->context, task_pid_nr(current), master->lock.hw_lock ? master->lock.hw_lock->lock : -1, lock->flags); add_wait_queue(&master->lock.lock_queue, &entry); spin_lock_bh(&master->lock.spinlock); master->lock.user_waiters++; spin_unlock_bh(&master->lock.spinlock); for (;;) { __set_current_state(TASK_INTERRUPTIBLE); if (!master->lock.hw_lock) { /* Device has been unregistered */ send_sig(SIGTERM, current, 0); ret = -EINTR; break; } if (drm_lock_take(&master->lock, lock->context)) { master->lock.file_priv = file_priv; master->lock.lock_time = jiffies; break; /* Got lock */ } /* Contention */ mutex_unlock(&drm_global_mutex); schedule(); mutex_lock(&drm_global_mutex); if (signal_pending(current)) { ret = -EINTR; break; } } spin_lock_bh(&master->lock.spinlock); master->lock.user_waiters--; spin_unlock_bh(&master->lock.spinlock); __set_current_state(TASK_RUNNING); remove_wait_queue(&master->lock.lock_queue, &entry); DRM_DEBUG("%d %s\n", lock->context, ret ? "interrupted" : "has lock"); if (ret) return ret; /* don't set the block all signals on the master process for now * really probably not the correct answer but lets us debug xkb * xserver for now */ if (!drm_is_current_master(file_priv)) { dev->sigdata.context = lock->context; dev->sigdata.lock = master->lock.hw_lock; } if (dev->driver->dma_quiescent && (lock->flags & _DRM_LOCK_QUIESCENT)) { if (dev->driver->dma_quiescent(dev)) { DRM_DEBUG("%d waiting for DMA quiescent\n", lock->context); return -EBUSY; } } return 0; } /* * Unlock ioctl. * * \param inode device inode. * \param file_priv DRM file private. * \param cmd command. * \param arg user argument, pointing to a drm_lock structure. * \return zero on success or negative number on failure. * * Transfer and free the lock. */ int drm_legacy_unlock(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct drm_lock *lock = data; struct drm_master *master = file_priv->master; if (!drm_core_check_feature(dev, DRIVER_LEGACY)) return -EOPNOTSUPP; if (lock->context == DRM_KERNEL_CONTEXT) { DRM_ERROR("Process %d using kernel context %d\n", task_pid_nr(current), lock->context); return -EINVAL; } if (drm_legacy_lock_free(&master->lock, lock->context)) { /* FIXME: Should really bail out here. */ } return 0; } /* * This function returns immediately and takes the hw lock * with the kernel context if it is free, otherwise it gets the highest priority when and if * it is eventually released. * * This guarantees that the kernel will _eventually_ have the lock _unless_ it is held * by a blocked process. (In the latter case an explicit wait for the hardware lock would cause * a deadlock, which is why the "idlelock" was invented). * * This should be sufficient to wait for GPU idle without * having to worry about starvation. */ void drm_legacy_idlelock_take(struct drm_lock_data *lock_data) { int ret; spin_lock_bh(&lock_data->spinlock); lock_data->kernel_waiters++; if (!lock_data->idle_has_lock) { spin_unlock_bh(&lock_data->spinlock); ret = drm_lock_take(lock_data, DRM_KERNEL_CONTEXT); spin_lock_bh(&lock_data->spinlock); if (ret == 1) lock_data->idle_has_lock = 1; } spin_unlock_bh(&lock_data->spinlock); } EXPORT_SYMBOL(drm_legacy_idlelock_take); void drm_legacy_idlelock_release(struct drm_lock_data *lock_data) { unsigned int old, prev; volatile unsigned int *lock = &lock_data->hw_lock->lock; spin_lock_bh(&lock_data->spinlock); if (--lock_data->kernel_waiters == 0) { if (lock_data->idle_has_lock) { do { old = *lock; prev = cmpxchg(lock, old, DRM_KERNEL_CONTEXT); } while (prev != old); wake_up_interruptible(&lock_data->lock_queue); lock_data->idle_has_lock = 0; } } spin_unlock_bh(&lock_data->spinlock); } EXPORT_SYMBOL(drm_legacy_idlelock_release); static int drm_legacy_i_have_hw_lock(struct drm_device *dev, struct drm_file *file_priv) { struct drm_master *master = file_priv->master; return (file_priv->lock_count && master->lock.hw_lock && _DRM_LOCK_IS_HELD(master->lock.hw_lock->lock) && master->lock.file_priv == file_priv); } void drm_legacy_lock_release(struct drm_device *dev, struct file *filp) { struct drm_file *file_priv = filp->private_data; /* if the master has gone away we can't do anything with the lock */ if (!dev->master) return; if (drm_legacy_i_have_hw_lock(dev, file_priv)) { DRM_DEBUG("File %p released, freeing lock for context %d\n", filp, _DRM_LOCKING_CONTEXT(file_priv->master->lock.hw_lock->lock)); drm_legacy_lock_free(&file_priv->master->lock, _DRM_LOCKING_CONTEXT(file_priv->master->lock.hw_lock->lock)); } } void drm_legacy_lock_master_cleanup(struct drm_device *dev, struct drm_master *master) { if (!drm_core_check_feature(dev, DRIVER_LEGACY)) return; /* * Since the master is disappearing, so is the * possibility to lock. */ mutex_lock(&dev->struct_mutex); if (master->lock.hw_lock) { if (dev->sigdata.lock == master->lock.hw_lock) dev->sigdata.lock = NULL; master->lock.hw_lock = NULL; master->lock.file_priv = NULL; wake_up_interruptible_all(&master->lock.lock_queue); } mutex_unlock(&dev->struct_mutex); }
rperier/linux-rockchip
drivers/gpu/drm/drm_lock.c
C
gpl-2.0
10,551
/* * Copyright 2012 Red Hat Inc. * * 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 COPYRIGHT HOLDER(S) OR AUTHOR(S) 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. * * Authors: Ben Skeggs */ #include "channv50.h" #include <core/client.h> #include <core/ramht.h> #include <nvif/class.h> #include <nvif/cl506e.h> #include <nvif/unpack.h> static int nv50_fifo_dma_new(struct nvkm_fifo *base, const struct nvkm_oclass *oclass, void *data, u32 size, struct nvkm_object **pobject) { struct nvkm_object *parent = oclass->parent; union { struct nv50_channel_dma_v0 v0; } *args = data; struct nv50_fifo *fifo = nv50_fifo(base); struct nv50_fifo_chan *chan; int ret = -ENOSYS; nvif_ioctl(parent, "create channel dma size %d\n", size); if (!(ret = nvif_unpack(ret, &data, &size, args->v0, 0, 0, false))) { nvif_ioctl(parent, "create channel dma vers %d vm %llx " "pushbuf %llx offset %016llx\n", args->v0.version, args->v0.vm, args->v0.pushbuf, args->v0.offset); if (!args->v0.pushbuf) return -EINVAL; } else return ret; if (!(chan = kzalloc(sizeof(*chan), GFP_KERNEL))) return -ENOMEM; *pobject = &chan->base.object; ret = nv50_fifo_chan_ctor(fifo, args->v0.vm, args->v0.pushbuf, oclass, chan); if (ret) return ret; args->v0.chid = chan->base.chid; nvkm_kmap(chan->ramfc); nvkm_wo32(chan->ramfc, 0x08, lower_32_bits(args->v0.offset)); nvkm_wo32(chan->ramfc, 0x0c, upper_32_bits(args->v0.offset)); nvkm_wo32(chan->ramfc, 0x10, lower_32_bits(args->v0.offset)); nvkm_wo32(chan->ramfc, 0x14, upper_32_bits(args->v0.offset)); nvkm_wo32(chan->ramfc, 0x3c, 0x003f6078); nvkm_wo32(chan->ramfc, 0x44, 0x01003fff); nvkm_wo32(chan->ramfc, 0x48, chan->base.push->node->offset >> 4); nvkm_wo32(chan->ramfc, 0x4c, 0xffffffff); nvkm_wo32(chan->ramfc, 0x60, 0x7fffffff); nvkm_wo32(chan->ramfc, 0x78, 0x00000000); nvkm_wo32(chan->ramfc, 0x7c, 0x30000001); nvkm_wo32(chan->ramfc, 0x80, ((chan->ramht->bits - 9) << 27) | (4 << 24) /* SEARCH_FULL */ | (chan->ramht->gpuobj->node->offset >> 4)); nvkm_done(chan->ramfc); return 0; } const struct nvkm_fifo_chan_oclass nv50_fifo_dma_oclass = { .base.oclass = NV50_CHANNEL_DMA, .base.minver = 0, .base.maxver = 0, .ctor = nv50_fifo_dma_new, };
mikedlowis-prototypes/albase
source/kernel/drivers/gpu/drm/nouveau/nvkm/engine/fifo/dmanv50.c
C
bsd-2-clause
3,217
/* * * Copyright 2008 (c) Intel Corporation * Jesse Barnes <[email protected]> * * 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, sub license, 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 (including the * next paragraph) 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 NON-INFRINGEMENT. * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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 "drmP.h" #include "drm.h" #include "i915_drm.h" #include "intel_drv.h" static bool i915_pipe_enabled(struct drm_device *dev, enum pipe pipe) { struct drm_i915_private *dev_priv = dev->dev_private; u32 dpll_reg; if (HAS_PCH_SPLIT(dev)) dpll_reg = (pipe == PIPE_A) ? _PCH_DPLL_A : _PCH_DPLL_B; else dpll_reg = (pipe == PIPE_A) ? _DPLL_A : _DPLL_B; return (I915_READ(dpll_reg) & DPLL_VCO_ENABLE); } static void i915_save_palette(struct drm_device *dev, enum pipe pipe) { struct drm_i915_private *dev_priv = dev->dev_private; unsigned long reg = (pipe == PIPE_A ? _PALETTE_A : _PALETTE_B); u32 *array; int i; if (!i915_pipe_enabled(dev, pipe)) return; if (HAS_PCH_SPLIT(dev)) reg = (pipe == PIPE_A) ? _LGC_PALETTE_A : _LGC_PALETTE_B; if (pipe == PIPE_A) array = dev_priv->save_palette_a; else array = dev_priv->save_palette_b; for(i = 0; i < 256; i++) array[i] = I915_READ(reg + (i << 2)); } static void i915_restore_palette(struct drm_device *dev, enum pipe pipe) { struct drm_i915_private *dev_priv = dev->dev_private; unsigned long reg = (pipe == PIPE_A ? _PALETTE_A : _PALETTE_B); u32 *array; int i; if (!i915_pipe_enabled(dev, pipe)) return; if (HAS_PCH_SPLIT(dev)) reg = (pipe == PIPE_A) ? _LGC_PALETTE_A : _LGC_PALETTE_B; if (pipe == PIPE_A) array = dev_priv->save_palette_a; else array = dev_priv->save_palette_b; for(i = 0; i < 256; i++) I915_WRITE(reg + (i << 2), array[i]); } static u8 i915_read_indexed(struct drm_device *dev, u16 index_port, u16 data_port, u8 reg) { struct drm_i915_private *dev_priv = dev->dev_private; I915_WRITE8(index_port, reg); return I915_READ8(data_port); } static u8 i915_read_ar(struct drm_device *dev, u16 st01, u8 reg, u16 palette_enable) { struct drm_i915_private *dev_priv = dev->dev_private; I915_READ8(st01); I915_WRITE8(VGA_AR_INDEX, palette_enable | reg); return I915_READ8(VGA_AR_DATA_READ); } static void i915_write_ar(struct drm_device *dev, u16 st01, u8 reg, u8 val, u16 palette_enable) { struct drm_i915_private *dev_priv = dev->dev_private; I915_READ8(st01); I915_WRITE8(VGA_AR_INDEX, palette_enable | reg); I915_WRITE8(VGA_AR_DATA_WRITE, val); } static void i915_write_indexed(struct drm_device *dev, u16 index_port, u16 data_port, u8 reg, u8 val) { struct drm_i915_private *dev_priv = dev->dev_private; I915_WRITE8(index_port, reg); I915_WRITE8(data_port, val); } static void i915_save_vga(struct drm_device *dev) { struct drm_i915_private *dev_priv = dev->dev_private; int i; u16 cr_index, cr_data, st01; /* VGA color palette registers */ dev_priv->saveDACMASK = I915_READ8(VGA_DACMASK); /* MSR bits */ dev_priv->saveMSR = I915_READ8(VGA_MSR_READ); if (dev_priv->saveMSR & VGA_MSR_CGA_MODE) { cr_index = VGA_CR_INDEX_CGA; cr_data = VGA_CR_DATA_CGA; st01 = VGA_ST01_CGA; } else { cr_index = VGA_CR_INDEX_MDA; cr_data = VGA_CR_DATA_MDA; st01 = VGA_ST01_MDA; } /* CRT controller regs */ i915_write_indexed(dev, cr_index, cr_data, 0x11, i915_read_indexed(dev, cr_index, cr_data, 0x11) & (~0x80)); for (i = 0; i <= 0x24; i++) dev_priv->saveCR[i] = i915_read_indexed(dev, cr_index, cr_data, i); /* Make sure we don't turn off CR group 0 writes */ dev_priv->saveCR[0x11] &= ~0x80; /* Attribute controller registers */ I915_READ8(st01); dev_priv->saveAR_INDEX = I915_READ8(VGA_AR_INDEX); for (i = 0; i <= 0x14; i++) dev_priv->saveAR[i] = i915_read_ar(dev, st01, i, 0); I915_READ8(st01); I915_WRITE8(VGA_AR_INDEX, dev_priv->saveAR_INDEX); I915_READ8(st01); /* Graphics controller registers */ for (i = 0; i < 9; i++) dev_priv->saveGR[i] = i915_read_indexed(dev, VGA_GR_INDEX, VGA_GR_DATA, i); dev_priv->saveGR[0x10] = i915_read_indexed(dev, VGA_GR_INDEX, VGA_GR_DATA, 0x10); dev_priv->saveGR[0x11] = i915_read_indexed(dev, VGA_GR_INDEX, VGA_GR_DATA, 0x11); dev_priv->saveGR[0x18] = i915_read_indexed(dev, VGA_GR_INDEX, VGA_GR_DATA, 0x18); /* Sequencer registers */ for (i = 0; i < 8; i++) dev_priv->saveSR[i] = i915_read_indexed(dev, VGA_SR_INDEX, VGA_SR_DATA, i); } static void i915_restore_vga(struct drm_device *dev) { struct drm_i915_private *dev_priv = dev->dev_private; int i; u16 cr_index, cr_data, st01; /* MSR bits */ I915_WRITE8(VGA_MSR_WRITE, dev_priv->saveMSR); if (dev_priv->saveMSR & VGA_MSR_CGA_MODE) { cr_index = VGA_CR_INDEX_CGA; cr_data = VGA_CR_DATA_CGA; st01 = VGA_ST01_CGA; } else { cr_index = VGA_CR_INDEX_MDA; cr_data = VGA_CR_DATA_MDA; st01 = VGA_ST01_MDA; } /* Sequencer registers, don't write SR07 */ for (i = 0; i < 7; i++) i915_write_indexed(dev, VGA_SR_INDEX, VGA_SR_DATA, i, dev_priv->saveSR[i]); /* CRT controller regs */ /* Enable CR group 0 writes */ i915_write_indexed(dev, cr_index, cr_data, 0x11, dev_priv->saveCR[0x11]); for (i = 0; i <= 0x24; i++) i915_write_indexed(dev, cr_index, cr_data, i, dev_priv->saveCR[i]); /* Graphics controller regs */ for (i = 0; i < 9; i++) i915_write_indexed(dev, VGA_GR_INDEX, VGA_GR_DATA, i, dev_priv->saveGR[i]); i915_write_indexed(dev, VGA_GR_INDEX, VGA_GR_DATA, 0x10, dev_priv->saveGR[0x10]); i915_write_indexed(dev, VGA_GR_INDEX, VGA_GR_DATA, 0x11, dev_priv->saveGR[0x11]); i915_write_indexed(dev, VGA_GR_INDEX, VGA_GR_DATA, 0x18, dev_priv->saveGR[0x18]); /* Attribute controller registers */ I915_READ8(st01); /* switch back to index mode */ for (i = 0; i <= 0x14; i++) i915_write_ar(dev, st01, i, dev_priv->saveAR[i], 0); I915_READ8(st01); /* switch back to index mode */ I915_WRITE8(VGA_AR_INDEX, dev_priv->saveAR_INDEX | 0x20); I915_READ8(st01); /* VGA color palette registers */ I915_WRITE8(VGA_DACMASK, dev_priv->saveDACMASK); } static void i915_save_modeset_reg(struct drm_device *dev) { struct drm_i915_private *dev_priv = dev->dev_private; int i; if (drm_core_check_feature(dev, DRIVER_MODESET)) return; /* Cursor state */ dev_priv->saveCURACNTR = I915_READ(_CURACNTR); dev_priv->saveCURAPOS = I915_READ(_CURAPOS); dev_priv->saveCURABASE = I915_READ(_CURABASE); dev_priv->saveCURBCNTR = I915_READ(_CURBCNTR); dev_priv->saveCURBPOS = I915_READ(_CURBPOS); dev_priv->saveCURBBASE = I915_READ(_CURBBASE); if (IS_GEN2(dev)) dev_priv->saveCURSIZE = I915_READ(CURSIZE); if (HAS_PCH_SPLIT(dev)) { dev_priv->savePCH_DREF_CONTROL = I915_READ(PCH_DREF_CONTROL); dev_priv->saveDISP_ARB_CTL = I915_READ(DISP_ARB_CTL); } /* Pipe & plane A info */ dev_priv->savePIPEACONF = I915_READ(_PIPEACONF); dev_priv->savePIPEASRC = I915_READ(_PIPEASRC); if (HAS_PCH_SPLIT(dev)) { dev_priv->saveFPA0 = I915_READ(_PCH_FPA0); dev_priv->saveFPA1 = I915_READ(_PCH_FPA1); dev_priv->saveDPLL_A = I915_READ(_PCH_DPLL_A); } else { dev_priv->saveFPA0 = I915_READ(_FPA0); dev_priv->saveFPA1 = I915_READ(_FPA1); dev_priv->saveDPLL_A = I915_READ(_DPLL_A); } if (INTEL_INFO(dev)->gen >= 4 && !HAS_PCH_SPLIT(dev)) dev_priv->saveDPLL_A_MD = I915_READ(_DPLL_A_MD); dev_priv->saveHTOTAL_A = I915_READ(_HTOTAL_A); dev_priv->saveHBLANK_A = I915_READ(_HBLANK_A); dev_priv->saveHSYNC_A = I915_READ(_HSYNC_A); dev_priv->saveVTOTAL_A = I915_READ(_VTOTAL_A); dev_priv->saveVBLANK_A = I915_READ(_VBLANK_A); dev_priv->saveVSYNC_A = I915_READ(_VSYNC_A); if (!HAS_PCH_SPLIT(dev)) dev_priv->saveBCLRPAT_A = I915_READ(_BCLRPAT_A); if (HAS_PCH_SPLIT(dev)) { dev_priv->savePIPEA_DATA_M1 = I915_READ(_PIPEA_DATA_M1); dev_priv->savePIPEA_DATA_N1 = I915_READ(_PIPEA_DATA_N1); dev_priv->savePIPEA_LINK_M1 = I915_READ(_PIPEA_LINK_M1); dev_priv->savePIPEA_LINK_N1 = I915_READ(_PIPEA_LINK_N1); dev_priv->saveFDI_TXA_CTL = I915_READ(_FDI_TXA_CTL); dev_priv->saveFDI_RXA_CTL = I915_READ(_FDI_RXA_CTL); dev_priv->savePFA_CTL_1 = I915_READ(_PFA_CTL_1); dev_priv->savePFA_WIN_SZ = I915_READ(_PFA_WIN_SZ); dev_priv->savePFA_WIN_POS = I915_READ(_PFA_WIN_POS); dev_priv->saveTRANSACONF = I915_READ(_TRANSACONF); dev_priv->saveTRANS_HTOTAL_A = I915_READ(_TRANS_HTOTAL_A); dev_priv->saveTRANS_HBLANK_A = I915_READ(_TRANS_HBLANK_A); dev_priv->saveTRANS_HSYNC_A = I915_READ(_TRANS_HSYNC_A); dev_priv->saveTRANS_VTOTAL_A = I915_READ(_TRANS_VTOTAL_A); dev_priv->saveTRANS_VBLANK_A = I915_READ(_TRANS_VBLANK_A); dev_priv->saveTRANS_VSYNC_A = I915_READ(_TRANS_VSYNC_A); } dev_priv->saveDSPACNTR = I915_READ(_DSPACNTR); dev_priv->saveDSPASTRIDE = I915_READ(_DSPASTRIDE); dev_priv->saveDSPASIZE = I915_READ(_DSPASIZE); dev_priv->saveDSPAPOS = I915_READ(_DSPAPOS); dev_priv->saveDSPAADDR = I915_READ(_DSPAADDR); if (INTEL_INFO(dev)->gen >= 4) { dev_priv->saveDSPASURF = I915_READ(_DSPASURF); dev_priv->saveDSPATILEOFF = I915_READ(_DSPATILEOFF); } i915_save_palette(dev, PIPE_A); dev_priv->savePIPEASTAT = I915_READ(_PIPEASTAT); /* Pipe & plane B info */ dev_priv->savePIPEBCONF = I915_READ(_PIPEBCONF); dev_priv->savePIPEBSRC = I915_READ(_PIPEBSRC); if (HAS_PCH_SPLIT(dev)) { dev_priv->saveFPB0 = I915_READ(_PCH_FPB0); dev_priv->saveFPB1 = I915_READ(_PCH_FPB1); dev_priv->saveDPLL_B = I915_READ(_PCH_DPLL_B); } else { dev_priv->saveFPB0 = I915_READ(_FPB0); dev_priv->saveFPB1 = I915_READ(_FPB1); dev_priv->saveDPLL_B = I915_READ(_DPLL_B); } if (INTEL_INFO(dev)->gen >= 4 && !HAS_PCH_SPLIT(dev)) dev_priv->saveDPLL_B_MD = I915_READ(_DPLL_B_MD); dev_priv->saveHTOTAL_B = I915_READ(_HTOTAL_B); dev_priv->saveHBLANK_B = I915_READ(_HBLANK_B); dev_priv->saveHSYNC_B = I915_READ(_HSYNC_B); dev_priv->saveVTOTAL_B = I915_READ(_VTOTAL_B); dev_priv->saveVBLANK_B = I915_READ(_VBLANK_B); dev_priv->saveVSYNC_B = I915_READ(_VSYNC_B); if (!HAS_PCH_SPLIT(dev)) dev_priv->saveBCLRPAT_B = I915_READ(_BCLRPAT_B); if (HAS_PCH_SPLIT(dev)) { dev_priv->savePIPEB_DATA_M1 = I915_READ(_PIPEB_DATA_M1); dev_priv->savePIPEB_DATA_N1 = I915_READ(_PIPEB_DATA_N1); dev_priv->savePIPEB_LINK_M1 = I915_READ(_PIPEB_LINK_M1); dev_priv->savePIPEB_LINK_N1 = I915_READ(_PIPEB_LINK_N1); dev_priv->saveFDI_TXB_CTL = I915_READ(_FDI_TXB_CTL); dev_priv->saveFDI_RXB_CTL = I915_READ(_FDI_RXB_CTL); dev_priv->savePFB_CTL_1 = I915_READ(_PFB_CTL_1); dev_priv->savePFB_WIN_SZ = I915_READ(_PFB_WIN_SZ); dev_priv->savePFB_WIN_POS = I915_READ(_PFB_WIN_POS); dev_priv->saveTRANSBCONF = I915_READ(_TRANSBCONF); dev_priv->saveTRANS_HTOTAL_B = I915_READ(_TRANS_HTOTAL_B); dev_priv->saveTRANS_HBLANK_B = I915_READ(_TRANS_HBLANK_B); dev_priv->saveTRANS_HSYNC_B = I915_READ(_TRANS_HSYNC_B); dev_priv->saveTRANS_VTOTAL_B = I915_READ(_TRANS_VTOTAL_B); dev_priv->saveTRANS_VBLANK_B = I915_READ(_TRANS_VBLANK_B); dev_priv->saveTRANS_VSYNC_B = I915_READ(_TRANS_VSYNC_B); } dev_priv->saveDSPBCNTR = I915_READ(_DSPBCNTR); dev_priv->saveDSPBSTRIDE = I915_READ(_DSPBSTRIDE); dev_priv->saveDSPBSIZE = I915_READ(_DSPBSIZE); dev_priv->saveDSPBPOS = I915_READ(_DSPBPOS); dev_priv->saveDSPBADDR = I915_READ(_DSPBADDR); if (INTEL_INFO(dev)->gen >= 4) { dev_priv->saveDSPBSURF = I915_READ(_DSPBSURF); dev_priv->saveDSPBTILEOFF = I915_READ(_DSPBTILEOFF); } i915_save_palette(dev, PIPE_B); dev_priv->savePIPEBSTAT = I915_READ(_PIPEBSTAT); /* Fences */ switch (INTEL_INFO(dev)->gen) { case 7: case 6: for (i = 0; i < 16; i++) dev_priv->saveFENCE[i] = I915_READ64(FENCE_REG_SANDYBRIDGE_0 + (i * 8)); break; case 5: case 4: for (i = 0; i < 16; i++) dev_priv->saveFENCE[i] = I915_READ64(FENCE_REG_965_0 + (i * 8)); break; case 3: if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) for (i = 0; i < 8; i++) dev_priv->saveFENCE[i+8] = I915_READ(FENCE_REG_945_8 + (i * 4)); case 2: for (i = 0; i < 8; i++) dev_priv->saveFENCE[i] = I915_READ(FENCE_REG_830_0 + (i * 4)); break; } return; } static void i915_restore_modeset_reg(struct drm_device *dev) { struct drm_i915_private *dev_priv = dev->dev_private; int dpll_a_reg, fpa0_reg, fpa1_reg; int dpll_b_reg, fpb0_reg, fpb1_reg; int i; if (drm_core_check_feature(dev, DRIVER_MODESET)) return; /* Fences */ switch (INTEL_INFO(dev)->gen) { case 7: case 6: for (i = 0; i < 16; i++) I915_WRITE64(FENCE_REG_SANDYBRIDGE_0 + (i * 8), dev_priv->saveFENCE[i]); break; case 5: case 4: for (i = 0; i < 16; i++) I915_WRITE64(FENCE_REG_965_0 + (i * 8), dev_priv->saveFENCE[i]); break; case 3: case 2: if (IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev)) for (i = 0; i < 8; i++) I915_WRITE(FENCE_REG_945_8 + (i * 4), dev_priv->saveFENCE[i+8]); for (i = 0; i < 8; i++) I915_WRITE(FENCE_REG_830_0 + (i * 4), dev_priv->saveFENCE[i]); break; } if (HAS_PCH_SPLIT(dev)) { dpll_a_reg = _PCH_DPLL_A; dpll_b_reg = _PCH_DPLL_B; fpa0_reg = _PCH_FPA0; fpb0_reg = _PCH_FPB0; fpa1_reg = _PCH_FPA1; fpb1_reg = _PCH_FPB1; } else { dpll_a_reg = _DPLL_A; dpll_b_reg = _DPLL_B; fpa0_reg = _FPA0; fpb0_reg = _FPB0; fpa1_reg = _FPA1; fpb1_reg = _FPB1; } if (HAS_PCH_SPLIT(dev)) { I915_WRITE(PCH_DREF_CONTROL, dev_priv->savePCH_DREF_CONTROL); I915_WRITE(DISP_ARB_CTL, dev_priv->saveDISP_ARB_CTL); } /* Pipe & plane A info */ /* Prime the clock */ if (dev_priv->saveDPLL_A & DPLL_VCO_ENABLE) { I915_WRITE(dpll_a_reg, dev_priv->saveDPLL_A & ~DPLL_VCO_ENABLE); POSTING_READ(dpll_a_reg); udelay(150); } I915_WRITE(fpa0_reg, dev_priv->saveFPA0); I915_WRITE(fpa1_reg, dev_priv->saveFPA1); /* Actually enable it */ I915_WRITE(dpll_a_reg, dev_priv->saveDPLL_A); POSTING_READ(dpll_a_reg); udelay(150); if (INTEL_INFO(dev)->gen >= 4 && !HAS_PCH_SPLIT(dev)) { I915_WRITE(_DPLL_A_MD, dev_priv->saveDPLL_A_MD); POSTING_READ(_DPLL_A_MD); } udelay(150); /* Restore mode */ I915_WRITE(_HTOTAL_A, dev_priv->saveHTOTAL_A); I915_WRITE(_HBLANK_A, dev_priv->saveHBLANK_A); I915_WRITE(_HSYNC_A, dev_priv->saveHSYNC_A); I915_WRITE(_VTOTAL_A, dev_priv->saveVTOTAL_A); I915_WRITE(_VBLANK_A, dev_priv->saveVBLANK_A); I915_WRITE(_VSYNC_A, dev_priv->saveVSYNC_A); if (!HAS_PCH_SPLIT(dev)) I915_WRITE(_BCLRPAT_A, dev_priv->saveBCLRPAT_A); if (HAS_PCH_SPLIT(dev)) { I915_WRITE(_PIPEA_DATA_M1, dev_priv->savePIPEA_DATA_M1); I915_WRITE(_PIPEA_DATA_N1, dev_priv->savePIPEA_DATA_N1); I915_WRITE(_PIPEA_LINK_M1, dev_priv->savePIPEA_LINK_M1); I915_WRITE(_PIPEA_LINK_N1, dev_priv->savePIPEA_LINK_N1); I915_WRITE(_FDI_RXA_CTL, dev_priv->saveFDI_RXA_CTL); I915_WRITE(_FDI_TXA_CTL, dev_priv->saveFDI_TXA_CTL); I915_WRITE(_PFA_CTL_1, dev_priv->savePFA_CTL_1); I915_WRITE(_PFA_WIN_SZ, dev_priv->savePFA_WIN_SZ); I915_WRITE(_PFA_WIN_POS, dev_priv->savePFA_WIN_POS); I915_WRITE(_TRANSACONF, dev_priv->saveTRANSACONF); I915_WRITE(_TRANS_HTOTAL_A, dev_priv->saveTRANS_HTOTAL_A); I915_WRITE(_TRANS_HBLANK_A, dev_priv->saveTRANS_HBLANK_A); I915_WRITE(_TRANS_HSYNC_A, dev_priv->saveTRANS_HSYNC_A); I915_WRITE(_TRANS_VTOTAL_A, dev_priv->saveTRANS_VTOTAL_A); I915_WRITE(_TRANS_VBLANK_A, dev_priv->saveTRANS_VBLANK_A); I915_WRITE(_TRANS_VSYNC_A, dev_priv->saveTRANS_VSYNC_A); } /* Restore plane info */ I915_WRITE(_DSPASIZE, dev_priv->saveDSPASIZE); I915_WRITE(_DSPAPOS, dev_priv->saveDSPAPOS); I915_WRITE(_PIPEASRC, dev_priv->savePIPEASRC); I915_WRITE(_DSPAADDR, dev_priv->saveDSPAADDR); I915_WRITE(_DSPASTRIDE, dev_priv->saveDSPASTRIDE); if (INTEL_INFO(dev)->gen >= 4) { I915_WRITE(_DSPASURF, dev_priv->saveDSPASURF); I915_WRITE(_DSPATILEOFF, dev_priv->saveDSPATILEOFF); } I915_WRITE(_PIPEACONF, dev_priv->savePIPEACONF); i915_restore_palette(dev, PIPE_A); /* Enable the plane */ I915_WRITE(_DSPACNTR, dev_priv->saveDSPACNTR); I915_WRITE(_DSPAADDR, I915_READ(_DSPAADDR)); /* Pipe & plane B info */ if (dev_priv->saveDPLL_B & DPLL_VCO_ENABLE) { I915_WRITE(dpll_b_reg, dev_priv->saveDPLL_B & ~DPLL_VCO_ENABLE); POSTING_READ(dpll_b_reg); udelay(150); } I915_WRITE(fpb0_reg, dev_priv->saveFPB0); I915_WRITE(fpb1_reg, dev_priv->saveFPB1); /* Actually enable it */ I915_WRITE(dpll_b_reg, dev_priv->saveDPLL_B); POSTING_READ(dpll_b_reg); udelay(150); if (INTEL_INFO(dev)->gen >= 4 && !HAS_PCH_SPLIT(dev)) { I915_WRITE(_DPLL_B_MD, dev_priv->saveDPLL_B_MD); POSTING_READ(_DPLL_B_MD); } udelay(150); /* Restore mode */ I915_WRITE(_HTOTAL_B, dev_priv->saveHTOTAL_B); I915_WRITE(_HBLANK_B, dev_priv->saveHBLANK_B); I915_WRITE(_HSYNC_B, dev_priv->saveHSYNC_B); I915_WRITE(_VTOTAL_B, dev_priv->saveVTOTAL_B); I915_WRITE(_VBLANK_B, dev_priv->saveVBLANK_B); I915_WRITE(_VSYNC_B, dev_priv->saveVSYNC_B); if (!HAS_PCH_SPLIT(dev)) I915_WRITE(_BCLRPAT_B, dev_priv->saveBCLRPAT_B); if (HAS_PCH_SPLIT(dev)) { I915_WRITE(_PIPEB_DATA_M1, dev_priv->savePIPEB_DATA_M1); I915_WRITE(_PIPEB_DATA_N1, dev_priv->savePIPEB_DATA_N1); I915_WRITE(_PIPEB_LINK_M1, dev_priv->savePIPEB_LINK_M1); I915_WRITE(_PIPEB_LINK_N1, dev_priv->savePIPEB_LINK_N1); I915_WRITE(_FDI_RXB_CTL, dev_priv->saveFDI_RXB_CTL); I915_WRITE(_FDI_TXB_CTL, dev_priv->saveFDI_TXB_CTL); I915_WRITE(_PFB_CTL_1, dev_priv->savePFB_CTL_1); I915_WRITE(_PFB_WIN_SZ, dev_priv->savePFB_WIN_SZ); I915_WRITE(_PFB_WIN_POS, dev_priv->savePFB_WIN_POS); I915_WRITE(_TRANSBCONF, dev_priv->saveTRANSBCONF); I915_WRITE(_TRANS_HTOTAL_B, dev_priv->saveTRANS_HTOTAL_B); I915_WRITE(_TRANS_HBLANK_B, dev_priv->saveTRANS_HBLANK_B); I915_WRITE(_TRANS_HSYNC_B, dev_priv->saveTRANS_HSYNC_B); I915_WRITE(_TRANS_VTOTAL_B, dev_priv->saveTRANS_VTOTAL_B); I915_WRITE(_TRANS_VBLANK_B, dev_priv->saveTRANS_VBLANK_B); I915_WRITE(_TRANS_VSYNC_B, dev_priv->saveTRANS_VSYNC_B); } /* Restore plane info */ I915_WRITE(_DSPBSIZE, dev_priv->saveDSPBSIZE); I915_WRITE(_DSPBPOS, dev_priv->saveDSPBPOS); I915_WRITE(_PIPEBSRC, dev_priv->savePIPEBSRC); I915_WRITE(_DSPBADDR, dev_priv->saveDSPBADDR); I915_WRITE(_DSPBSTRIDE, dev_priv->saveDSPBSTRIDE); if (INTEL_INFO(dev)->gen >= 4) { I915_WRITE(_DSPBSURF, dev_priv->saveDSPBSURF); I915_WRITE(_DSPBTILEOFF, dev_priv->saveDSPBTILEOFF); } I915_WRITE(_PIPEBCONF, dev_priv->savePIPEBCONF); i915_restore_palette(dev, PIPE_B); /* Enable the plane */ I915_WRITE(_DSPBCNTR, dev_priv->saveDSPBCNTR); I915_WRITE(_DSPBADDR, I915_READ(_DSPBADDR)); /* Cursor state */ I915_WRITE(_CURAPOS, dev_priv->saveCURAPOS); I915_WRITE(_CURACNTR, dev_priv->saveCURACNTR); I915_WRITE(_CURABASE, dev_priv->saveCURABASE); I915_WRITE(_CURBPOS, dev_priv->saveCURBPOS); I915_WRITE(_CURBCNTR, dev_priv->saveCURBCNTR); I915_WRITE(_CURBBASE, dev_priv->saveCURBBASE); if (IS_GEN2(dev)) I915_WRITE(CURSIZE, dev_priv->saveCURSIZE); return; } static void i915_save_display(struct drm_device *dev) { struct drm_i915_private *dev_priv = dev->dev_private; /* Display arbitration control */ dev_priv->saveDSPARB = I915_READ(DSPARB); /* This is only meaningful in non-KMS mode */ /* Don't save them in KMS mode */ i915_save_modeset_reg(dev); /* CRT state */ if (HAS_PCH_SPLIT(dev)) { dev_priv->saveADPA = I915_READ(PCH_ADPA); } else { dev_priv->saveADPA = I915_READ(ADPA); } /* LVDS state */ if (HAS_PCH_SPLIT(dev)) { dev_priv->savePP_CONTROL = I915_READ(PCH_PP_CONTROL); dev_priv->saveBLC_PWM_CTL = I915_READ(BLC_PWM_PCH_CTL1); dev_priv->saveBLC_PWM_CTL2 = I915_READ(BLC_PWM_PCH_CTL2); dev_priv->saveBLC_CPU_PWM_CTL = I915_READ(BLC_PWM_CPU_CTL); dev_priv->saveBLC_CPU_PWM_CTL2 = I915_READ(BLC_PWM_CPU_CTL2); dev_priv->saveLVDS = I915_READ(PCH_LVDS); } else { dev_priv->savePP_CONTROL = I915_READ(PP_CONTROL); dev_priv->savePFIT_PGM_RATIOS = I915_READ(PFIT_PGM_RATIOS); dev_priv->saveBLC_PWM_CTL = I915_READ(BLC_PWM_CTL); dev_priv->saveBLC_HIST_CTL = I915_READ(BLC_HIST_CTL); if (INTEL_INFO(dev)->gen >= 4) dev_priv->saveBLC_PWM_CTL2 = I915_READ(BLC_PWM_CTL2); if (IS_MOBILE(dev) && !IS_I830(dev)) dev_priv->saveLVDS = I915_READ(LVDS); } if (!IS_I830(dev) && !IS_845G(dev) && !HAS_PCH_SPLIT(dev)) dev_priv->savePFIT_CONTROL = I915_READ(PFIT_CONTROL); if (HAS_PCH_SPLIT(dev)) { dev_priv->savePP_ON_DELAYS = I915_READ(PCH_PP_ON_DELAYS); dev_priv->savePP_OFF_DELAYS = I915_READ(PCH_PP_OFF_DELAYS); dev_priv->savePP_DIVISOR = I915_READ(PCH_PP_DIVISOR); } else { dev_priv->savePP_ON_DELAYS = I915_READ(PP_ON_DELAYS); dev_priv->savePP_OFF_DELAYS = I915_READ(PP_OFF_DELAYS); dev_priv->savePP_DIVISOR = I915_READ(PP_DIVISOR); } /* Display Port state */ if (SUPPORTS_INTEGRATED_DP(dev)) { dev_priv->saveDP_B = I915_READ(DP_B); dev_priv->saveDP_C = I915_READ(DP_C); dev_priv->saveDP_D = I915_READ(DP_D); dev_priv->savePIPEA_GMCH_DATA_M = I915_READ(_PIPEA_GMCH_DATA_M); dev_priv->savePIPEB_GMCH_DATA_M = I915_READ(_PIPEB_GMCH_DATA_M); dev_priv->savePIPEA_GMCH_DATA_N = I915_READ(_PIPEA_GMCH_DATA_N); dev_priv->savePIPEB_GMCH_DATA_N = I915_READ(_PIPEB_GMCH_DATA_N); dev_priv->savePIPEA_DP_LINK_M = I915_READ(_PIPEA_DP_LINK_M); dev_priv->savePIPEB_DP_LINK_M = I915_READ(_PIPEB_DP_LINK_M); dev_priv->savePIPEA_DP_LINK_N = I915_READ(_PIPEA_DP_LINK_N); dev_priv->savePIPEB_DP_LINK_N = I915_READ(_PIPEB_DP_LINK_N); } /* FIXME: save TV & SDVO state */ /* Only save FBC state on the platform that supports FBC */ if (I915_HAS_FBC(dev)) { if (HAS_PCH_SPLIT(dev)) { dev_priv->saveDPFC_CB_BASE = I915_READ(ILK_DPFC_CB_BASE); } else if (IS_GM45(dev)) { dev_priv->saveDPFC_CB_BASE = I915_READ(DPFC_CB_BASE); } else { dev_priv->saveFBC_CFB_BASE = I915_READ(FBC_CFB_BASE); dev_priv->saveFBC_LL_BASE = I915_READ(FBC_LL_BASE); dev_priv->saveFBC_CONTROL2 = I915_READ(FBC_CONTROL2); dev_priv->saveFBC_CONTROL = I915_READ(FBC_CONTROL); } } /* VGA state */ dev_priv->saveVGA0 = I915_READ(VGA0); dev_priv->saveVGA1 = I915_READ(VGA1); dev_priv->saveVGA_PD = I915_READ(VGA_PD); if (HAS_PCH_SPLIT(dev)) dev_priv->saveVGACNTRL = I915_READ(CPU_VGACNTRL); else dev_priv->saveVGACNTRL = I915_READ(VGACNTRL); i915_save_vga(dev); } static void i915_restore_display(struct drm_device *dev) { struct drm_i915_private *dev_priv = dev->dev_private; /* Display arbitration */ I915_WRITE(DSPARB, dev_priv->saveDSPARB); /* Display port ratios (must be done before clock is set) */ if (SUPPORTS_INTEGRATED_DP(dev)) { I915_WRITE(_PIPEA_GMCH_DATA_M, dev_priv->savePIPEA_GMCH_DATA_M); I915_WRITE(_PIPEB_GMCH_DATA_M, dev_priv->savePIPEB_GMCH_DATA_M); I915_WRITE(_PIPEA_GMCH_DATA_N, dev_priv->savePIPEA_GMCH_DATA_N); I915_WRITE(_PIPEB_GMCH_DATA_N, dev_priv->savePIPEB_GMCH_DATA_N); I915_WRITE(_PIPEA_DP_LINK_M, dev_priv->savePIPEA_DP_LINK_M); I915_WRITE(_PIPEB_DP_LINK_M, dev_priv->savePIPEB_DP_LINK_M); I915_WRITE(_PIPEA_DP_LINK_N, dev_priv->savePIPEA_DP_LINK_N); I915_WRITE(_PIPEB_DP_LINK_N, dev_priv->savePIPEB_DP_LINK_N); } /* This is only meaningful in non-KMS mode */ /* Don't restore them in KMS mode */ i915_restore_modeset_reg(dev); /* CRT state */ if (HAS_PCH_SPLIT(dev)) I915_WRITE(PCH_ADPA, dev_priv->saveADPA); else I915_WRITE(ADPA, dev_priv->saveADPA); /* LVDS state */ if (INTEL_INFO(dev)->gen >= 4 && !HAS_PCH_SPLIT(dev)) I915_WRITE(BLC_PWM_CTL2, dev_priv->saveBLC_PWM_CTL2); if (HAS_PCH_SPLIT(dev)) { I915_WRITE(PCH_LVDS, dev_priv->saveLVDS); } else if (IS_MOBILE(dev) && !IS_I830(dev)) I915_WRITE(LVDS, dev_priv->saveLVDS); if (!IS_I830(dev) && !IS_845G(dev) && !HAS_PCH_SPLIT(dev)) I915_WRITE(PFIT_CONTROL, dev_priv->savePFIT_CONTROL); if (HAS_PCH_SPLIT(dev)) { I915_WRITE(BLC_PWM_PCH_CTL1, dev_priv->saveBLC_PWM_CTL); I915_WRITE(BLC_PWM_PCH_CTL2, dev_priv->saveBLC_PWM_CTL2); I915_WRITE(BLC_PWM_CPU_CTL, dev_priv->saveBLC_CPU_PWM_CTL); I915_WRITE(BLC_PWM_CPU_CTL2, dev_priv->saveBLC_CPU_PWM_CTL2); I915_WRITE(PCH_PP_ON_DELAYS, dev_priv->savePP_ON_DELAYS); I915_WRITE(PCH_PP_OFF_DELAYS, dev_priv->savePP_OFF_DELAYS); I915_WRITE(PCH_PP_DIVISOR, dev_priv->savePP_DIVISOR); I915_WRITE(PCH_PP_CONTROL, dev_priv->savePP_CONTROL); I915_WRITE(RSTDBYCTL, dev_priv->saveMCHBAR_RENDER_STANDBY); } else { I915_WRITE(PFIT_PGM_RATIOS, dev_priv->savePFIT_PGM_RATIOS); I915_WRITE(BLC_PWM_CTL, dev_priv->saveBLC_PWM_CTL); I915_WRITE(BLC_HIST_CTL, dev_priv->saveBLC_HIST_CTL); I915_WRITE(PP_ON_DELAYS, dev_priv->savePP_ON_DELAYS); I915_WRITE(PP_OFF_DELAYS, dev_priv->savePP_OFF_DELAYS); I915_WRITE(PP_DIVISOR, dev_priv->savePP_DIVISOR); I915_WRITE(PP_CONTROL, dev_priv->savePP_CONTROL); } /* Display Port state */ if (SUPPORTS_INTEGRATED_DP(dev)) { I915_WRITE(DP_B, dev_priv->saveDP_B); I915_WRITE(DP_C, dev_priv->saveDP_C); I915_WRITE(DP_D, dev_priv->saveDP_D); } /* FIXME: restore TV & SDVO state */ /* only restore FBC info on the platform that supports FBC*/ if (I915_HAS_FBC(dev)) { if (HAS_PCH_SPLIT(dev)) { ironlake_disable_fbc(dev); I915_WRITE(ILK_DPFC_CB_BASE, dev_priv->saveDPFC_CB_BASE); } else if (IS_GM45(dev)) { g4x_disable_fbc(dev); I915_WRITE(DPFC_CB_BASE, dev_priv->saveDPFC_CB_BASE); } else { i8xx_disable_fbc(dev); I915_WRITE(FBC_CFB_BASE, dev_priv->saveFBC_CFB_BASE); I915_WRITE(FBC_LL_BASE, dev_priv->saveFBC_LL_BASE); I915_WRITE(FBC_CONTROL2, dev_priv->saveFBC_CONTROL2); I915_WRITE(FBC_CONTROL, dev_priv->saveFBC_CONTROL); } } /* VGA state */ if (HAS_PCH_SPLIT(dev)) I915_WRITE(CPU_VGACNTRL, dev_priv->saveVGACNTRL); else I915_WRITE(VGACNTRL, dev_priv->saveVGACNTRL); I915_WRITE(VGA0, dev_priv->saveVGA0); I915_WRITE(VGA1, dev_priv->saveVGA1); I915_WRITE(VGA_PD, dev_priv->saveVGA_PD); POSTING_READ(VGA_PD); udelay(150); i915_restore_vga(dev); } int i915_save_state(struct drm_device *dev) { struct drm_i915_private *dev_priv = dev->dev_private; int i; pci_read_config_byte(dev->pdev, LBB, &dev_priv->saveLBB); mutex_lock(&dev->struct_mutex); /* Hardware status page */ dev_priv->saveHWS = I915_READ(HWS_PGA); i915_save_display(dev); /* Interrupt state */ if (HAS_PCH_SPLIT(dev)) { dev_priv->saveDEIER = I915_READ(DEIER); dev_priv->saveDEIMR = I915_READ(DEIMR); dev_priv->saveGTIER = I915_READ(GTIER); dev_priv->saveGTIMR = I915_READ(GTIMR); dev_priv->saveFDI_RXA_IMR = I915_READ(_FDI_RXA_IMR); dev_priv->saveFDI_RXB_IMR = I915_READ(_FDI_RXB_IMR); dev_priv->saveMCHBAR_RENDER_STANDBY = I915_READ(RSTDBYCTL); dev_priv->savePCH_PORT_HOTPLUG = I915_READ(PCH_PORT_HOTPLUG); } else { dev_priv->saveIER = I915_READ(IER); dev_priv->saveIMR = I915_READ(IMR); } if (IS_IRONLAKE_M(dev)) ironlake_disable_drps(dev); if (IS_GEN6(dev)) gen6_disable_rps(dev); /* Cache mode state */ dev_priv->saveCACHE_MODE_0 = I915_READ(CACHE_MODE_0); /* Memory Arbitration state */ dev_priv->saveMI_ARB_STATE = I915_READ(MI_ARB_STATE); /* Scratch space */ for (i = 0; i < 16; i++) { dev_priv->saveSWF0[i] = I915_READ(SWF00 + (i << 2)); dev_priv->saveSWF1[i] = I915_READ(SWF10 + (i << 2)); } for (i = 0; i < 3; i++) dev_priv->saveSWF2[i] = I915_READ(SWF30 + (i << 2)); mutex_unlock(&dev->struct_mutex); return 0; } int i915_restore_state(struct drm_device *dev) { struct drm_i915_private *dev_priv = dev->dev_private; int i; pci_write_config_byte(dev->pdev, LBB, dev_priv->saveLBB); mutex_lock(&dev->struct_mutex); /* Hardware status page */ I915_WRITE(HWS_PGA, dev_priv->saveHWS); i915_restore_display(dev); /* Interrupt state */ if (HAS_PCH_SPLIT(dev)) { I915_WRITE(DEIER, dev_priv->saveDEIER); I915_WRITE(DEIMR, dev_priv->saveDEIMR); I915_WRITE(GTIER, dev_priv->saveGTIER); I915_WRITE(GTIMR, dev_priv->saveGTIMR); I915_WRITE(_FDI_RXA_IMR, dev_priv->saveFDI_RXA_IMR); I915_WRITE(_FDI_RXB_IMR, dev_priv->saveFDI_RXB_IMR); I915_WRITE(PCH_PORT_HOTPLUG, dev_priv->savePCH_PORT_HOTPLUG); } else { I915_WRITE(IER, dev_priv->saveIER); I915_WRITE(IMR, dev_priv->saveIMR); } mutex_unlock(&dev->struct_mutex); intel_init_clock_gating(dev); if (IS_IRONLAKE_M(dev)) { ironlake_enable_drps(dev); intel_init_emon(dev); } if (IS_GEN6(dev)) gen6_enable_rps(dev_priv); mutex_lock(&dev->struct_mutex); /* Cache mode state */ I915_WRITE (CACHE_MODE_0, dev_priv->saveCACHE_MODE_0 | 0xffff0000); /* Memory arbitration state */ I915_WRITE (MI_ARB_STATE, dev_priv->saveMI_ARB_STATE | 0xffff0000); for (i = 0; i < 16; i++) { I915_WRITE(SWF00 + (i << 2), dev_priv->saveSWF0[i]); I915_WRITE(SWF10 + (i << 2), dev_priv->saveSWF1[i]); } for (i = 0; i < 3; i++) I915_WRITE(SWF30 + (i << 2), dev_priv->saveSWF2[i]); mutex_unlock(&dev->struct_mutex); intel_i2c_reset(dev); return 0; }
NooNameR/k3_bravo
drivers3/gpu/drm/i915/i915_suspend.c
C
gpl-2.0
29,365
/////////////////////////////////////////////////////////////////////////////// // Name: wx/typeinfo.h // Purpose: wxTypeId implementation // Author: Jaakko Salli // Created: 2009-11-19 // Copyright: (c) wxWidgets Team // Licence: wxWindows licence /////////////////////////////////////////////////////////////////////////////// #ifndef _WX_TYPEINFO_H_ #define _WX_TYPEINFO_H_ // // This file defines wxTypeId macro that should be used internally in // wxWidgets instead of typeid(), for compatibility with builds that do // not implement C++ RTTI. Also, type defining macros in this file are // intended for internal use only at this time and may change in future // versions. // // The reason why we need this simple RTTI system in addition to the older // wxObject-based one is that the latter does not work in template // classes. // #include "wx/defs.h" #ifndef wxNO_RTTI // // Let's trust that Visual C++ versions 9.0 and later implement C++ // RTTI well enough, so we can use it and work around harmless memory // leaks reported by the static run-time libraries. // #if wxCHECK_VISUALC_VERSION(9) #define wxTRUST_CPP_RTTI 1 #else #define wxTRUST_CPP_RTTI 0 #endif #include <typeinfo> #include <string.h> #define _WX_DECLARE_TYPEINFO_CUSTOM(CLS, IDENTFUNC) #define WX_DECLARE_TYPEINFO_INLINE(CLS) #define WX_DECLARE_TYPEINFO(CLS) #define WX_DEFINE_TYPEINFO(CLS) #define WX_DECLARE_ABSTRACT_TYPEINFO(CLS) #if wxTRUST_CPP_RTTI #define wxTypeId typeid #else /* !wxTRUST_CPP_RTTI */ // // For improved type-safety, let's make the check using class name // comparison. Most modern compilers already do this, but we cannot // rely on all supported compilers to work this well. However, in // cases where we'd know that typeid() would be flawless (as such), // wxTypeId could of course simply be defined as typeid. // class wxTypeIdentifier { public: wxTypeIdentifier(const char* className) { m_className = className; } bool operator==(const wxTypeIdentifier& other) { return strcmp(m_className, other.m_className) == 0; } bool operator!=(const wxTypeIdentifier& other) { return strcmp(m_className, other.m_className) != 0; } private: const char* m_className; }; #define wxTypeId(OBJ) wxTypeIdentifier(typeid(OBJ).name()) #endif /* wxTRUST_CPP_RTTI/!wxTRUST_CPP_RTTI */ #else // if !wxNO_RTTI #define wxTRUST_CPP_RTTI 0 // // When C++ RTTI is not available, we will have to make the type comparison // using pointer to a dummy static member function. This will fail if // declared type is used across DLL boundaries, although using // WX_DECLARE_TYPEINFO() and WX_DEFINE_TYPEINFO() pair instead of // WX_DECLARE_TYPEINFO_INLINE() should fix this. However, that approach is // usually not possible when type info needs to be declared for a template // class. // typedef void (*wxTypeIdentifier)(); // Use this macro to declare type info with specified static function // IDENTFUNC used as type identifier. Usually you should only use // WX_DECLARE_TYPEINFO() or WX_DECLARE_TYPEINFO_INLINE() however. #define _WX_DECLARE_TYPEINFO_CUSTOM(CLS, IDENTFUNC) \ public: \ virtual wxTypeIdentifier GetWxTypeId() const \ { \ return reinterpret_cast<wxTypeIdentifier> \ (&IDENTFUNC); \ } // Use this macro to declare type info with externally specified // type identifier, defined with WX_DEFINE_TYPEINFO(). #define WX_DECLARE_TYPEINFO(CLS) \ private: \ static CLS sm_wxClassInfo(); \ _WX_DECLARE_TYPEINFO_CUSTOM(CLS, sm_wxClassInfo) // Use this macro to implement type identifier function required by // WX_DECLARE_TYPEINFO(). // NOTE: CLS is required to have default ctor. If it doesn't // already, you should provide a private dummy one. #define WX_DEFINE_TYPEINFO(CLS) \ CLS CLS::sm_wxClassInfo() { return CLS(); } // Use this macro to declare type info fully inline in class. // NOTE: CLS is required to have default ctor. If it doesn't // already, you should provide a private dummy one. #define WX_DECLARE_TYPEINFO_INLINE(CLS) \ private: \ static CLS sm_wxClassInfo() { return CLS(); } \ _WX_DECLARE_TYPEINFO_CUSTOM(CLS, sm_wxClassInfo) #define wxTypeId(OBJ) (OBJ).GetWxTypeId() // Because abstract classes cannot be instantiated, we use // this macro to define pure virtual type interface for them. #define WX_DECLARE_ABSTRACT_TYPEINFO(CLS) \ public: \ virtual wxTypeIdentifier GetWxTypeId() const = 0; #endif // wxNO_RTTI/!wxNO_RTTI #endif // _WX_TYPEINFO_H_
adouble42/nemesis-current
wxWidgets-3.1.0/include/wx/typeinfo.h
C
bsd-2-clause
4,551
/* Copyright 2015 The Kubernetes 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 api import ( "strings" "k8s.io/kubernetes/pkg/api/meta" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/util/sets" ) // Instantiates a DefaultRESTMapper based on types registered in api.Scheme func NewDefaultRESTMapper(defaultGroupVersions []unversioned.GroupVersion, interfacesFunc meta.VersionInterfacesFunc, importPathPrefix string, ignoredKinds, rootScoped sets.String) *meta.DefaultRESTMapper { return NewDefaultRESTMapperFromScheme(defaultGroupVersions, interfacesFunc, importPathPrefix, ignoredKinds, rootScoped, Scheme) } // Instantiates a DefaultRESTMapper based on types registered in the given scheme. func NewDefaultRESTMapperFromScheme(defaultGroupVersions []unversioned.GroupVersion, interfacesFunc meta.VersionInterfacesFunc, importPathPrefix string, ignoredKinds, rootScoped sets.String, scheme *runtime.Scheme) *meta.DefaultRESTMapper { mapper := meta.NewDefaultRESTMapper(defaultGroupVersions, interfacesFunc) // enumerate all supported versions, get the kinds, and register with the mapper how to address // our resources. for _, gv := range defaultGroupVersions { for kind, oType := range scheme.KnownTypes(gv) { gvk := gv.WithKind(kind) // TODO: Remove import path check. // We check the import path because we currently stuff both "api" and "extensions" objects // into the same group within Scheme since Scheme has no notion of groups yet. if !strings.Contains(oType.PkgPath(), importPathPrefix) || ignoredKinds.Has(kind) { continue } scope := meta.RESTScopeNamespace if rootScoped.Has(kind) { scope = meta.RESTScopeRoot } mapper.Add(gvk, scope) } } return mapper }
TStraub-rms/terraform
vendor/k8s.io/kubernetes/pkg/api/mapper.go
GO
mpl-2.0
2,276
/* Make clicks pass-through */ #nprogress { pointer-events: none; } #nprogress .bar { background: #63890b; position: fixed; z-index: 100; top: 0; left: 0; width: 100%; height: 2px; } /* Fancy blur effect */ #nprogress .peg { display: block; position: absolute; right: 0px; width: 100px; height: 100%; box-shadow: 0 0 10px #63890b, 0 0 5px #63890b; opacity: 1.0; -webkit-transform: rotate(3deg) translate(0px, -4px); -ms-transform: rotate(3deg) translate(0px, -4px); transform: rotate(3deg) translate(0px, -4px); } /* Remove these to get rid of the spinner */ #nprogress .spinner { display: block; position: fixed; z-index: 100; top: 7px; right: 5px; } #nprogress .spinner-icon { width: 18px; height: 18px; box-sizing: border-box; border: solid 2px transparent; border-top-color: #63890b; border-left-color: #63890b; border-radius: 50%; -webkit-animation: nprogress-spinner 400ms linear infinite; animation: nprogress-spinner 400ms linear infinite; } @-webkit-keyframes nprogress-spinner { 0% { -webkit-transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); } } @keyframes nprogress-spinner { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
bigfont/muddlingthru
wwwroot/Modules/Orchard.Lists/Styles/nprogress.css
CSS
mit
1,283
require 'test_helper' class SallieMaeTest < Test::Unit::TestCase def setup @gateway = SallieMaeGateway.new( :login => 'FAKEACCOUNT' ) @credit_card = credit_card @amount = 100 @options = { :order_id => '1', :billing_address => address, :description => 'Store Purchase' } end def test_successful_purchase @gateway.expects(:ssl_post).returns(successful_purchase_response) assert response = @gateway.purchase(@amount, @credit_card, @options) assert_success response end def test_unsuccessful_request @gateway.expects(:ssl_post).returns(failed_purchase_response) assert response = @gateway.purchase(@amount, @credit_card, @options) assert_failure response end def test_non_test_account assert [email protected]? end def test_test_account gateway = SallieMaeGateway.new(:login => "TEST0") assert [email protected]? end private # Place raw successful response from gateway here def successful_purchase_response "Status=Accepted" end # Place raw failed response from gateway here def failed_purchase_response "Status=Declined" end end
impurist/active_merchant
test/unit/gateways/sallie_mae_test.rb
Ruby
mit
1,204
// method.h - Header file for methodID instances. -*- c++ -*- /* Copyright (C) 1999, 2000 Free Software Foundation This file is part of libgcj. This software is copyrighted work licensed under the terms of the Libgcj License. Please consult the file "LIBGCJ_LICENSE" for details. */ #ifndef __GCJ_METHOD_H__ #define __GCJ_METHOD_H__ #include <java/lang/Class.h> #include <java/lang/reflect/Constructor.h> #include <java/lang/reflect/Method.h> extern inline jmethodID _Jv_FromReflectedMethod (java::lang::reflect::Method *method) { return (jmethodID) ((char *) method->declaringClass->methods + method->offset); } extern inline jmethodID _Jv_FromReflectedConstructor (java::lang::reflect::Constructor *constructor) { return (jmethodID) ((char *) constructor->declaringClass->methods + constructor->offset); } extern inline jint JvNumMethods (jclass klass) { return klass->method_count; } extern inline jmethodID JvGetFirstMethod (jclass klass) { return &klass->methods[0]; } #endif /* __GCJ_METHOD_H__ */
SanDisk-Open-Source/SSD_Dashboard
uefi/gcc/gcc-4.6.3/libjava/gcj/method.h
C
gpl-2.0
1,037
/****************************************************************************** * * Copyright(c) 2007 - 2011 Realtek Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License 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. * * 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., * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA * * ******************************************************************************/ #ifndef __USB_OPS_H_ #define __USB_OPS_H_ #include <drv_conf.h> #include <osdep_service.h> #include <drv_types.h> #include <osdep_intf.h> #define REALTEK_USB_VENQT_READ 0xC0 #define REALTEK_USB_VENQT_WRITE 0x40 #define REALTEK_USB_VENQT_CMD_REQ 0x05 #define REALTEK_USB_VENQT_CMD_IDX 0x00 enum{ VENDOR_WRITE = 0x00, VENDOR_READ = 0x01, }; #define ALIGNMENT_UNIT 16 #define MAX_VENDOR_REQ_CMD_SIZE 254 //8188cu SIE Support #define MAX_USB_IO_CTL_SIZE (MAX_VENDOR_REQ_CMD_SIZE +ALIGNMENT_UNIT) #ifdef PLATFORM_LINUX #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,12)) #define rtw_usb_control_msg(dev, pipe, request, requesttype, value, index, data, size, timeout_ms) \ usb_control_msg((dev), (pipe), (request), (requesttype), (value), (index), (data), (size), (timeout_ms)) #define rtw_usb_bulk_msg(usb_dev, pipe, data, len, actual_length, timeout_ms) \ usb_bulk_msg((usb_dev), (pipe), (data), (len), (actual_length), (timeout_ms)) #else #define rtw_usb_control_msg(dev, pipe, request, requesttype, value, index, data, size,timeout_ms) \ usb_control_msg((dev), (pipe), (request), (requesttype), (value), (index), (data), (size), \ ((timeout_ms) == 0) ||((timeout_ms)*HZ/1000>0)?((timeout_ms)*HZ/1000):1) #define rtw_usb_bulk_msg(usb_dev, pipe, data, len, actual_length, timeout_ms) \ usb_bulk_msg((usb_dev), (pipe), (data), (len), (actual_length), \ ((timeout_ms) == 0) ||((timeout_ms)*HZ/1000>0)?((timeout_ms)*HZ/1000):1) #endif #endif //PLATFORM_LINUX #ifdef CONFIG_RTL8192C void rtl8192cu_set_intf_ops(struct _io_ops *pops); void rtl8192cu_recv_tasklet(void *priv); void rtl8192cu_xmit_tasklet(void *priv); #endif #ifdef CONFIG_RTL8192D void rtl8192du_set_intf_ops(struct _io_ops *pops); void rtl8192du_recv_tasklet(void *priv); void rtl8192du_xmit_tasklet(void *priv); #endif /* * Increase and check if the continual_urb_error of this @param dvobjprive is larger than MAX_CONTINUAL_URB_ERR * @return _TRUE: * @return _FALSE: */ static inline int rtw_inc_and_chk_continual_urb_error(struct dvobj_priv *dvobjpriv) { int ret = _FALSE; int value; if( (value=ATOMIC_INC_RETURN(&dvobjpriv->continual_urb_error)) > MAX_CONTINUAL_URB_ERR) { DBG_871X("[dvobjpriv:%p][ERROR] continual_urb_error:%d > %d\n", dvobjpriv, value, MAX_CONTINUAL_URB_ERR); ret = _TRUE; } else { //DBG_871X("[dvobjpriv:%p] continual_urb_error:%d\n", dvobjpriv, value); } return ret; } /* * Set the continual_urb_error of this @param dvobjprive to 0 */ static inline void rtw_reset_continual_urb_error(struct dvobj_priv *dvobjpriv) { ATOMIC_SET(&dvobjpriv->continual_urb_error, 0); } #endif //__USB_OPS_H_
Frontier314/kernel_ut4412
rtl8192cu/include/usb_ops.h
C
gpl-2.0
3,552
describe('omPrefixes', function() { var omPrefixes; var cleanup; before(function(done) { var req = requirejs.config({ context: Math.random().toString().slice(2), baseUrl: '../src', paths: {cleanup: '../test/cleanup'} }); req(['omPrefixes', 'cleanup'], function(_omPrefixes, _cleanup) { omPrefixes = _omPrefixes; cleanup = _cleanup; done(); }); }); it('returns a string', function() { expect(omPrefixes).to.be.a('string'); expect(omPrefixes.length).to.not.be(0); }); after(function() { cleanup(); }); });
CardiacAtlasProject/CAPServer2.0
xpacs/src/main/webapp/bower_components/modernizr/test/browser/src/omPrefixes.js
JavaScript
apache-2.0
589
/* * CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen * THIS FILE MUST NOT BE EDITED BY HAND */ package require import ( assert "github.com/stretchr/testify/assert" http "net/http" url "net/url" time "time" ) // Condition uses a Comparison to assert a complex condition. func Condition(t TestingT, comp assert.Comparison, msgAndArgs ...interface{}) { if !assert.Condition(t, comp, msgAndArgs...) { t.FailNow() } } // Contains asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // // assert.Contains(t, "Hello World", "World", "But 'Hello World' does contain 'World'") // assert.Contains(t, ["Hello", "World"], "World", "But ["Hello", "World"] does contain 'World'") // assert.Contains(t, {"Hello": "World"}, "Hello", "But {'Hello': 'World'} does contain 'Hello'") // // Returns whether the assertion was successful (true) or not (false). func Contains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...interface{}) { if !assert.Contains(t, s, contains, msgAndArgs...) { t.FailNow() } } // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // // assert.Empty(t, obj) // // Returns whether the assertion was successful (true) or not (false). func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) { if !assert.Empty(t, object, msgAndArgs...) { t.FailNow() } } // Equal asserts that two objects are equal. // // assert.Equal(t, 123, 123, "123 and 123 should be equal") // // Returns whether the assertion was successful (true) or not (false). func Equal(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { if !assert.Equal(t, expected, actual, msgAndArgs...) { t.FailNow() } } // EqualError asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // // actualObj, err := SomeFunction() // if assert.Error(t, err, "An error was expected") { // assert.Equal(t, err, expectedError) // } // // Returns whether the assertion was successful (true) or not (false). func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) { if !assert.EqualError(t, theError, errString, msgAndArgs...) { t.FailNow() } } // EqualValues asserts that two objects are equal or convertable to the same types // and equal. // // assert.EqualValues(t, uint32(123), int32(123), "123 and 123 should be equal") // // Returns whether the assertion was successful (true) or not (false). func EqualValues(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { if !assert.EqualValues(t, expected, actual, msgAndArgs...) { t.FailNow() } } // Error asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() // if assert.Error(t, err, "An error was expected") { // assert.Equal(t, err, expectedError) // } // // Returns whether the assertion was successful (true) or not (false). func Error(t TestingT, err error, msgAndArgs ...interface{}) { if !assert.Error(t, err, msgAndArgs...) { t.FailNow() } } // Exactly asserts that two objects are equal is value and type. // // assert.Exactly(t, int32(123), int64(123), "123 and 123 should NOT be equal") // // Returns whether the assertion was successful (true) or not (false). func Exactly(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { if !assert.Exactly(t, expected, actual, msgAndArgs...) { t.FailNow() } } // Fail reports a failure through func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) { if !assert.Fail(t, failureMessage, msgAndArgs...) { t.FailNow() } } // FailNow fails test func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) { if !assert.FailNow(t, failureMessage, msgAndArgs...) { t.FailNow() } } // False asserts that the specified value is false. // // assert.False(t, myBool, "myBool should be false") // // Returns whether the assertion was successful (true) or not (false). func False(t TestingT, value bool, msgAndArgs ...interface{}) { if !assert.False(t, value, msgAndArgs...) { t.FailNow() } } // HTTPBodyContains asserts that a specified handler returns a // body that contains a string. // // assert.HTTPBodyContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) { if !assert.HTTPBodyContains(t, handler, method, url, values, str) { t.FailNow() } } // HTTPBodyNotContains asserts that a specified handler returns a // body that does not contain a string. // // assert.HTTPBodyNotContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) { if !assert.HTTPBodyNotContains(t, handler, method, url, values, str) { t.FailNow() } } // HTTPError asserts that a specified handler returns an error status code. // // assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPError(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values) { if !assert.HTTPError(t, handler, method, url, values) { t.FailNow() } } // HTTPRedirect asserts that a specified handler returns a redirect status code. // // assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPRedirect(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values) { if !assert.HTTPRedirect(t, handler, method, url, values) { t.FailNow() } } // HTTPSuccess asserts that a specified handler returns a success status code. // // assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil) // // Returns whether the assertion was successful (true) or not (false). func HTTPSuccess(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values) { if !assert.HTTPSuccess(t, handler, method, url, values) { t.FailNow() } } // Implements asserts that an object is implemented by the specified interface. // // assert.Implements(t, (*MyInterface)(nil), new(MyObject), "MyObject") func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { if !assert.Implements(t, interfaceObject, object, msgAndArgs...) { t.FailNow() } } // InDelta asserts that the two numerals are within delta of each other. // // assert.InDelta(t, math.Pi, (22 / 7.0), 0.01) // // Returns whether the assertion was successful (true) or not (false). func InDelta(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { if !assert.InDelta(t, expected, actual, delta, msgAndArgs...) { t.FailNow() } } // InDeltaSlice is the same as InDelta, except it compares two slices. func InDeltaSlice(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { if !assert.InDeltaSlice(t, expected, actual, delta, msgAndArgs...) { t.FailNow() } } // InEpsilon asserts that expected and actual have a relative error less than epsilon // // Returns whether the assertion was successful (true) or not (false). func InEpsilon(t TestingT, expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { if !assert.InEpsilon(t, expected, actual, epsilon, msgAndArgs...) { t.FailNow() } } // InEpsilonSlice is the same as InEpsilon, except it compares two slices. func InEpsilonSlice(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { if !assert.InEpsilonSlice(t, expected, actual, delta, msgAndArgs...) { t.FailNow() } } // IsType asserts that the specified objects are of the same type. func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) { if !assert.IsType(t, expectedType, object, msgAndArgs...) { t.FailNow() } } // JSONEq asserts that two JSON strings are equivalent. // // assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) // // Returns whether the assertion was successful (true) or not (false). func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) { if !assert.JSONEq(t, expected, actual, msgAndArgs...) { t.FailNow() } } // Len asserts that the specified object has specific length. // Len also fails if the object has a type that len() not accept. // // assert.Len(t, mySlice, 3, "The size of slice is not 3") // // Returns whether the assertion was successful (true) or not (false). func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) { if !assert.Len(t, object, length, msgAndArgs...) { t.FailNow() } } // Nil asserts that the specified object is nil. // // assert.Nil(t, err, "err should be nothing") // // Returns whether the assertion was successful (true) or not (false). func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) { if !assert.Nil(t, object, msgAndArgs...) { t.FailNow() } } // NoError asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() // if assert.NoError(t, err) { // assert.Equal(t, actualObj, expectedObj) // } // // Returns whether the assertion was successful (true) or not (false). func NoError(t TestingT, err error, msgAndArgs ...interface{}) { if !assert.NoError(t, err, msgAndArgs...) { t.FailNow() } } // NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // // assert.NotContains(t, "Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") // assert.NotContains(t, ["Hello", "World"], "Earth", "But ['Hello', 'World'] does NOT contain 'Earth'") // assert.NotContains(t, {"Hello": "World"}, "Earth", "But {'Hello': 'World'} does NOT contain 'Earth'") // // Returns whether the assertion was successful (true) or not (false). func NotContains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...interface{}) { if !assert.NotContains(t, s, contains, msgAndArgs...) { t.FailNow() } } // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // // if assert.NotEmpty(t, obj) { // assert.Equal(t, "two", obj[1]) // } // // Returns whether the assertion was successful (true) or not (false). func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) { if !assert.NotEmpty(t, object, msgAndArgs...) { t.FailNow() } } // NotEqual asserts that the specified values are NOT equal. // // assert.NotEqual(t, obj1, obj2, "two objects shouldn't be equal") // // Returns whether the assertion was successful (true) or not (false). func NotEqual(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { if !assert.NotEqual(t, expected, actual, msgAndArgs...) { t.FailNow() } } // NotNil asserts that the specified object is not nil. // // assert.NotNil(t, err, "err should be something") // // Returns whether the assertion was successful (true) or not (false). func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) { if !assert.NotNil(t, object, msgAndArgs...) { t.FailNow() } } // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. // // assert.NotPanics(t, func(){ // RemainCalm() // }, "Calling RemainCalm() should NOT panic") // // Returns whether the assertion was successful (true) or not (false). func NotPanics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { if !assert.NotPanics(t, f, msgAndArgs...) { t.FailNow() } } // NotRegexp asserts that a specified regexp does not match a string. // // assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") // assert.NotRegexp(t, "^start", "it's not starting") // // Returns whether the assertion was successful (true) or not (false). func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) { if !assert.NotRegexp(t, rx, str, msgAndArgs...) { t.FailNow() } } // NotZero asserts that i is not the zero value for its type and returns the truth. func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) { if !assert.NotZero(t, i, msgAndArgs...) { t.FailNow() } } // Panics asserts that the code inside the specified PanicTestFunc panics. // // assert.Panics(t, func(){ // GoCrazy() // }, "Calling GoCrazy() should panic") // // Returns whether the assertion was successful (true) or not (false). func Panics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { if !assert.Panics(t, f, msgAndArgs...) { t.FailNow() } } // Regexp asserts that a specified regexp matches a string. // // assert.Regexp(t, regexp.MustCompile("start"), "it's starting") // assert.Regexp(t, "start...$", "it's not starting") // // Returns whether the assertion was successful (true) or not (false). func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) { if !assert.Regexp(t, rx, str, msgAndArgs...) { t.FailNow() } } // True asserts that the specified value is true. // // assert.True(t, myBool, "myBool should be true") // // Returns whether the assertion was successful (true) or not (false). func True(t TestingT, value bool, msgAndArgs ...interface{}) { if !assert.True(t, value, msgAndArgs...) { t.FailNow() } } // WithinDuration asserts that the two times are within duration delta of each other. // // assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") // // Returns whether the assertion was successful (true) or not (false). func WithinDuration(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) { if !assert.WithinDuration(t, expected, actual, delta, msgAndArgs...) { t.FailNow() } } // Zero asserts that i is the zero value for its type and returns the truth. func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) { if !assert.Zero(t, i, msgAndArgs...) { t.FailNow() } }
tiagofernandez/boobot
vendor/src/github.com/stretchr/testify/require/require.go
GO
unlicense
14,886
var test = require('../../../'); test(function (t) { t.plan(2); t.equal(1+1, 2); t.ok(true); }); test('wheee', function (t) { t.ok(true); t.end(); });
marcusfaccion/unnamed_app
vendor/bower/mapbox-directions.js/node_modules/tape/example/stream/test/y.js
JavaScript
gpl-3.0
172
/* * drivers/base/power/wakeup.c - System wakeup events framework * * Copyright (c) 2010 Rafael J. Wysocki <[email protected]>, Novell Inc. * * This file is released under the GPLv2. */ #define REALLY_WANT_DEBUGFS #include <linux/device.h> #include <linux/slab.h> #include <linux/sched.h> #include <linux/capability.h> #include <linux/export.h> #include <linux/suspend.h> #include <linux/seq_file.h> #include <linux/debugfs.h> #include <trace/events/power.h> #include "power.h" /* * If set, the suspend/hibernate code will abort transitions to a sleep state * if wakeup events are registered during or immediately before the transition. */ bool events_check_enabled __read_mostly; /* * Combined counters of registered wakeup events and wakeup events in progress. * They need to be modified together atomically, so it's better to use one * atomic variable to hold them both. */ static atomic_t combined_event_count = ATOMIC_INIT(0); #define IN_PROGRESS_BITS (sizeof(int) * 4) #define MAX_IN_PROGRESS ((1 << IN_PROGRESS_BITS) - 1) static void split_counters(unsigned int *cnt, unsigned int *inpr) { unsigned int comb = atomic_read(&combined_event_count); *cnt = (comb >> IN_PROGRESS_BITS); *inpr = comb & MAX_IN_PROGRESS; } /* A preserved old value of the events counter. */ static unsigned int saved_count; static DEFINE_SPINLOCK(events_lock); static void pm_wakeup_timer_fn(unsigned long data); static LIST_HEAD(wakeup_sources); static DECLARE_WAIT_QUEUE_HEAD(wakeup_count_wait_queue); /** * wakeup_source_prepare - Prepare a new wakeup source for initialization. * @ws: Wakeup source to prepare. * @name: Pointer to the name of the new wakeup source. * * Callers must ensure that the @name string won't be freed when @ws is still in * use. */ void wakeup_source_prepare(struct wakeup_source *ws, const char *name) { if (ws) { memset(ws, 0, sizeof(*ws)); ws->name = name; } } EXPORT_SYMBOL_GPL(wakeup_source_prepare); /** * wakeup_source_create - Create a struct wakeup_source object. * @name: Name of the new wakeup source. */ struct wakeup_source *wakeup_source_create(const char *name) { struct wakeup_source *ws; ws = kmalloc(sizeof(*ws), GFP_KERNEL); if (!ws) return NULL; wakeup_source_prepare(ws, name ? kstrdup(name, GFP_KERNEL) : NULL); return ws; } EXPORT_SYMBOL_GPL(wakeup_source_create); /** * wakeup_source_drop - Prepare a struct wakeup_source object for destruction. * @ws: Wakeup source to prepare for destruction. * * Callers must ensure that __pm_stay_awake() or __pm_wakeup_event() will never * be run in parallel with this function for the same wakeup source object. */ void wakeup_source_drop(struct wakeup_source *ws) { if (!ws) return; del_timer_sync(&ws->timer); __pm_relax(ws); } EXPORT_SYMBOL_GPL(wakeup_source_drop); /** * wakeup_source_destroy - Destroy a struct wakeup_source object. * @ws: Wakeup source to destroy. * * Use only for wakeup source objects created with wakeup_source_create(). */ void wakeup_source_destroy(struct wakeup_source *ws) { if (!ws) return; wakeup_source_drop(ws); kfree(ws->name); kfree(ws); } EXPORT_SYMBOL_GPL(wakeup_source_destroy); /** * wakeup_source_add - Add given object to the list of wakeup sources. * @ws: Wakeup source object to add to the list. */ void wakeup_source_add(struct wakeup_source *ws) { if (WARN_ON(!ws)) return; spin_lock_init(&ws->lock); setup_timer(&ws->timer, pm_wakeup_timer_fn, (unsigned long)ws); ws->active = false; ws->last_time = ktime_get(); spin_lock_irq(&events_lock); list_add_rcu(&ws->entry, &wakeup_sources); spin_unlock_irq(&events_lock); } EXPORT_SYMBOL_GPL(wakeup_source_add); /** * wakeup_source_remove - Remove given object from the wakeup sources list. * @ws: Wakeup source object to remove from the list. */ void wakeup_source_remove(struct wakeup_source *ws) { if (WARN_ON(!ws)) return; spin_lock_irq(&events_lock); list_del_rcu(&ws->entry); spin_unlock_irq(&events_lock); synchronize_rcu(); } EXPORT_SYMBOL_GPL(wakeup_source_remove); /** * wakeup_source_register - Create wakeup source and add it to the list. * @name: Name of the wakeup source to register. */ struct wakeup_source *wakeup_source_register(const char *name) { struct wakeup_source *ws; ws = wakeup_source_create(name); if (ws) wakeup_source_add(ws); return ws; } EXPORT_SYMBOL_GPL(wakeup_source_register); /** * wakeup_source_unregister - Remove wakeup source from the list and remove it. * @ws: Wakeup source object to unregister. */ void wakeup_source_unregister(struct wakeup_source *ws) { if (ws) { wakeup_source_remove(ws); wakeup_source_destroy(ws); } } EXPORT_SYMBOL_GPL(wakeup_source_unregister); /** * device_wakeup_attach - Attach a wakeup source object to a device object. * @dev: Device to handle. * @ws: Wakeup source object to attach to @dev. * * This causes @dev to be treated as a wakeup device. */ static int device_wakeup_attach(struct device *dev, struct wakeup_source *ws) { spin_lock_irq(&dev->power.lock); if (dev->power.wakeup) { spin_unlock_irq(&dev->power.lock); return -EEXIST; } dev->power.wakeup = ws; spin_unlock_irq(&dev->power.lock); return 0; } /** * device_wakeup_enable - Enable given device to be a wakeup source. * @dev: Device to handle. * * Create a wakeup source object, register it and attach it to @dev. */ int device_wakeup_enable(struct device *dev) { struct wakeup_source *ws; int ret; if (!dev || !dev->power.can_wakeup) return -EINVAL; ws = wakeup_source_register(dev_name(dev)); if (!ws) return -ENOMEM; ret = device_wakeup_attach(dev, ws); if (ret) wakeup_source_unregister(ws); return ret; } EXPORT_SYMBOL_GPL(device_wakeup_enable); /** * device_wakeup_detach - Detach a device's wakeup source object from it. * @dev: Device to detach the wakeup source object from. * * After it returns, @dev will not be treated as a wakeup device any more. */ static struct wakeup_source *device_wakeup_detach(struct device *dev) { struct wakeup_source *ws; spin_lock_irq(&dev->power.lock); ws = dev->power.wakeup; dev->power.wakeup = NULL; spin_unlock_irq(&dev->power.lock); return ws; } /** * device_wakeup_disable - Do not regard a device as a wakeup source any more. * @dev: Device to handle. * * Detach the @dev's wakeup source object from it, unregister this wakeup source * object and destroy it. */ int device_wakeup_disable(struct device *dev) { struct wakeup_source *ws; if (!dev || !dev->power.can_wakeup) return -EINVAL; ws = device_wakeup_detach(dev); if (ws) wakeup_source_unregister(ws); return 0; } EXPORT_SYMBOL_GPL(device_wakeup_disable); /** * device_set_wakeup_capable - Set/reset device wakeup capability flag. * @dev: Device to handle. * @capable: Whether or not @dev is capable of waking up the system from sleep. * * If @capable is set, set the @dev's power.can_wakeup flag and add its * wakeup-related attributes to sysfs. Otherwise, unset the @dev's * power.can_wakeup flag and remove its wakeup-related attributes from sysfs. * * This function may sleep and it can't be called from any context where * sleeping is not allowed. */ void device_set_wakeup_capable(struct device *dev, bool capable) { if (!!dev->power.can_wakeup == !!capable) return; if (device_is_registered(dev) && !list_empty(&dev->power.entry)) { if (capable) { if (wakeup_sysfs_add(dev)) return; } else { wakeup_sysfs_remove(dev); } } dev->power.can_wakeup = capable; } EXPORT_SYMBOL_GPL(device_set_wakeup_capable); /** * device_init_wakeup - Device wakeup initialization. * @dev: Device to handle. * @enable: Whether or not to enable @dev as a wakeup device. * * By default, most devices should leave wakeup disabled. The exceptions are * devices that everyone expects to be wakeup sources: keyboards, power buttons, * possibly network interfaces, etc. Also, devices that don't generate their * own wakeup requests but merely forward requests from one bus to another * (like PCI bridges) should have wakeup enabled by default. */ int device_init_wakeup(struct device *dev, bool enable) { int ret = 0; if (enable) { device_set_wakeup_capable(dev, true); ret = device_wakeup_enable(dev); } else { device_set_wakeup_capable(dev, false); } return ret; } EXPORT_SYMBOL_GPL(device_init_wakeup); /** * device_set_wakeup_enable - Enable or disable a device to wake up the system. * @dev: Device to handle. */ int device_set_wakeup_enable(struct device *dev, bool enable) { if (!dev || !dev->power.can_wakeup) return -EINVAL; return enable ? device_wakeup_enable(dev) : device_wakeup_disable(dev); } EXPORT_SYMBOL_GPL(device_set_wakeup_enable); /* * The functions below use the observation that each wakeup event starts a * period in which the system should not be suspended. The moment this period * will end depends on how the wakeup event is going to be processed after being * detected and all of the possible cases can be divided into two distinct * groups. * * First, a wakeup event may be detected by the same functional unit that will * carry out the entire processing of it and possibly will pass it to user space * for further processing. In that case the functional unit that has detected * the event may later "close" the "no suspend" period associated with it * directly as soon as it has been dealt with. The pair of pm_stay_awake() and * pm_relax(), balanced with each other, is supposed to be used in such * situations. * * Second, a wakeup event may be detected by one functional unit and processed * by another one. In that case the unit that has detected it cannot really * "close" the "no suspend" period associated with it, unless it knows in * advance what's going to happen to the event during processing. This * knowledge, however, may not be available to it, so it can simply specify time * to wait before the system can be suspended and pass it as the second * argument of pm_wakeup_event(). * * It is valid to call pm_relax() after pm_wakeup_event(), in which case the * "no suspend" period will be ended either by the pm_relax(), or by the timer * function executed when the timer expires, whichever comes first. */ /** * wakup_source_activate - Mark given wakeup source as active. * @ws: Wakeup source to handle. * * Update the @ws' statistics and, if @ws has just been activated, notify the PM * core of the event by incrementing the counter of of wakeup events being * processed. */ static void wakeup_source_activate(struct wakeup_source *ws) { unsigned int cec; ws->active = true; ws->active_count++; ws->last_time = ktime_get(); if (ws->autosleep_enabled) ws->start_prevent_time = ws->last_time; /* Increment the counter of events in progress. */ cec = atomic_inc_return(&combined_event_count); trace_wakeup_source_activate(ws->name, cec); } /** * wakeup_source_report_event - Report wakeup event using the given source. * @ws: Wakeup source to report the event for. */ static void wakeup_source_report_event(struct wakeup_source *ws) { ws->event_count++; /* This is racy, but the counter is approximate anyway. */ if (events_check_enabled) ws->wakeup_count++; if (!ws->active) wakeup_source_activate(ws); } /** * __pm_stay_awake - Notify the PM core of a wakeup event. * @ws: Wakeup source object associated with the source of the event. * * It is safe to call this function from interrupt context. */ void __pm_stay_awake(struct wakeup_source *ws) { unsigned long flags; if (!ws) return; spin_lock_irqsave(&ws->lock, flags); wakeup_source_report_event(ws); del_timer(&ws->timer); ws->timer_expires = 0; spin_unlock_irqrestore(&ws->lock, flags); } EXPORT_SYMBOL_GPL(__pm_stay_awake); /** * pm_stay_awake - Notify the PM core that a wakeup event is being processed. * @dev: Device the wakeup event is related to. * * Notify the PM core of a wakeup event (signaled by @dev) by calling * __pm_stay_awake for the @dev's wakeup source object. * * Call this function after detecting of a wakeup event if pm_relax() is going * to be called directly after processing the event (and possibly passing it to * user space for further processing). */ void pm_stay_awake(struct device *dev) { unsigned long flags; if (!dev) return; spin_lock_irqsave(&dev->power.lock, flags); __pm_stay_awake(dev->power.wakeup); spin_unlock_irqrestore(&dev->power.lock, flags); } EXPORT_SYMBOL_GPL(pm_stay_awake); #ifdef CONFIG_PM_AUTOSLEEP static void update_prevent_sleep_time(struct wakeup_source *ws, ktime_t now) { ktime_t delta = ktime_sub(now, ws->start_prevent_time); ws->prevent_sleep_time = ktime_add(ws->prevent_sleep_time, delta); } #else static inline void update_prevent_sleep_time(struct wakeup_source *ws, ktime_t now) {} #endif /** * wakup_source_deactivate - Mark given wakeup source as inactive. * @ws: Wakeup source to handle. * * Update the @ws' statistics and notify the PM core that the wakeup source has * become inactive by decrementing the counter of wakeup events being processed * and incrementing the counter of registered wakeup events. */ static void wakeup_source_deactivate(struct wakeup_source *ws) { unsigned int cnt, inpr, cec; ktime_t duration; ktime_t now; ws->relax_count++; /* * __pm_relax() may be called directly or from a timer function. * If it is called directly right after the timer function has been * started, but before the timer function calls __pm_relax(), it is * possible that __pm_stay_awake() will be called in the meantime and * will set ws->active. Then, ws->active may be cleared immediately * by the __pm_relax() called from the timer function, but in such a * case ws->relax_count will be different from ws->active_count. */ if (ws->relax_count != ws->active_count) { ws->relax_count--; return; } ws->active = false; now = ktime_get(); duration = ktime_sub(now, ws->last_time); ws->total_time = ktime_add(ws->total_time, duration); if (ktime_to_ns(duration) > ktime_to_ns(ws->max_time)) ws->max_time = duration; ws->last_time = now; del_timer(&ws->timer); ws->timer_expires = 0; if (ws->autosleep_enabled) update_prevent_sleep_time(ws, now); /* * Increment the counter of registered wakeup events and decrement the * couter of wakeup events in progress simultaneously. */ cec = atomic_add_return(MAX_IN_PROGRESS, &combined_event_count); trace_wakeup_source_deactivate(ws->name, cec); split_counters(&cnt, &inpr); if (!inpr && waitqueue_active(&wakeup_count_wait_queue)) wake_up(&wakeup_count_wait_queue); } /** * __pm_relax - Notify the PM core that processing of a wakeup event has ended. * @ws: Wakeup source object associated with the source of the event. * * Call this function for wakeup events whose processing started with calling * __pm_stay_awake(). * * It is safe to call it from interrupt context. */ void __pm_relax(struct wakeup_source *ws) { unsigned long flags; if (!ws) return; spin_lock_irqsave(&ws->lock, flags); if (ws->active) wakeup_source_deactivate(ws); spin_unlock_irqrestore(&ws->lock, flags); } EXPORT_SYMBOL_GPL(__pm_relax); /** * pm_relax - Notify the PM core that processing of a wakeup event has ended. * @dev: Device that signaled the event. * * Execute __pm_relax() for the @dev's wakeup source object. */ void pm_relax(struct device *dev) { unsigned long flags; if (!dev) return; spin_lock_irqsave(&dev->power.lock, flags); __pm_relax(dev->power.wakeup); spin_unlock_irqrestore(&dev->power.lock, flags); } EXPORT_SYMBOL_GPL(pm_relax); /** * pm_wakeup_timer_fn - Delayed finalization of a wakeup event. * @data: Address of the wakeup source object associated with the event source. * * Call wakeup_source_deactivate() for the wakeup source whose address is stored * in @data if it is currently active and its timer has not been canceled and * the expiration time of the timer is not in future. */ static void pm_wakeup_timer_fn(unsigned long data) { struct wakeup_source *ws = (struct wakeup_source *)data; unsigned long flags; spin_lock_irqsave(&ws->lock, flags); if (ws->active && ws->timer_expires && time_after_eq(jiffies, ws->timer_expires)) { wakeup_source_deactivate(ws); ws->expire_count++; } spin_unlock_irqrestore(&ws->lock, flags); } /** * __pm_wakeup_event - Notify the PM core of a wakeup event. * @ws: Wakeup source object associated with the event source. * @msec: Anticipated event processing time (in milliseconds). * * Notify the PM core of a wakeup event whose source is @ws that will take * approximately @msec milliseconds to be processed by the kernel. If @ws is * not active, activate it. If @msec is nonzero, set up the @ws' timer to * execute pm_wakeup_timer_fn() in future. * * It is safe to call this function from interrupt context. */ void __pm_wakeup_event(struct wakeup_source *ws, unsigned int msec) { unsigned long flags; unsigned long expires; if (!ws) return; spin_lock_irqsave(&ws->lock, flags); wakeup_source_report_event(ws); if (!msec) { wakeup_source_deactivate(ws); goto unlock; } expires = jiffies + msecs_to_jiffies(msec); if (!expires) expires = 1; if (!ws->timer_expires || time_after(expires, ws->timer_expires)) { mod_timer(&ws->timer, expires); ws->timer_expires = expires; } unlock: spin_unlock_irqrestore(&ws->lock, flags); } EXPORT_SYMBOL_GPL(__pm_wakeup_event); /** * pm_wakeup_event - Notify the PM core of a wakeup event. * @dev: Device the wakeup event is related to. * @msec: Anticipated event processing time (in milliseconds). * * Call __pm_wakeup_event() for the @dev's wakeup source object. */ void pm_wakeup_event(struct device *dev, unsigned int msec) { unsigned long flags; if (!dev) return; spin_lock_irqsave(&dev->power.lock, flags); __pm_wakeup_event(dev->power.wakeup, msec); spin_unlock_irqrestore(&dev->power.lock, flags); } EXPORT_SYMBOL_GPL(pm_wakeup_event); /** * print_active_wakeup_source_stats - Print active wakeup source statistics * information. Caller must acquire the list_lock spinlock. * @ws: Wakeup source object to print the statistics for. */ static void print_active_wakeup_source_stats(struct wakeup_source *ws) { unsigned long flags; ktime_t total_time; ktime_t max_time; unsigned long active_count; ktime_t active_time; ktime_t prevent_sleep_time; bool need_print = false; spin_lock_irqsave(&ws->lock, flags); total_time = ws->total_time; max_time = ws->max_time; prevent_sleep_time = ws->prevent_sleep_time; active_count = ws->active_count; if (ws->active) { ktime_t now = ktime_get(); active_time = ktime_sub(now, ws->last_time); total_time = ktime_add(total_time, active_time); if (active_time.tv64 > max_time.tv64) max_time = active_time; if (ws->autosleep_enabled) prevent_sleep_time = ktime_add(prevent_sleep_time, ktime_sub(now, ws->start_prevent_time)); need_print = true; } spin_unlock_irqrestore(&ws->lock, flags); if (need_print) pr_info("%s %lld %lld %lld %lld\n", ws->name, ktime_to_ms(active_time), ktime_to_ms(total_time), ktime_to_ms(max_time), ktime_to_ms(prevent_sleep_time)); return; } /** * active_wakeup_sources_stats_show - Print active wakeup sources statistics * information. */ void active_wakeup_sources_stats_show(void) { struct wakeup_source *ws; pr_info("name active(ms) total(ms) max_time(ms) prevent_suspend(ms)"); rcu_read_lock(); list_for_each_entry_rcu(ws, &wakeup_sources, entry) print_active_wakeup_source_stats(ws); rcu_read_unlock(); return; } EXPORT_SYMBOL_GPL(active_wakeup_sources_stats_show); /** * pm_wakeup_pending - Check if power transition in progress should be aborted. * * Compare the current number of registered wakeup events with its preserved * value from the past and return true if new wakeup events have been registered * since the old value was stored. Also return true if the current number of * wakeup events being processed is different from zero. */ bool pm_wakeup_pending(void) { unsigned long flags; bool ret = false; spin_lock_irqsave(&events_lock, flags); if (events_check_enabled) { unsigned int cnt, inpr; split_counters(&cnt, &inpr); ret = (cnt != saved_count || inpr > 0); events_check_enabled = !ret; } spin_unlock_irqrestore(&events_lock, flags); return ret; } /** * pm_get_wakeup_count - Read the number of registered wakeup events. * @count: Address to store the value at. * @block: Whether or not to block. * * Store the number of registered wakeup events at the address in @count. If * @block is set, block until the current number of wakeup events being * processed is zero. * * Return 'false' if the current number of wakeup events being processed is * nonzero. Otherwise return 'true'. */ bool pm_get_wakeup_count(unsigned int *count, bool block) { unsigned int cnt, inpr; if (block) { DEFINE_WAIT(wait); for (;;) { prepare_to_wait(&wakeup_count_wait_queue, &wait, TASK_INTERRUPTIBLE); split_counters(&cnt, &inpr); if (inpr == 0 || signal_pending(current)) break; schedule(); } finish_wait(&wakeup_count_wait_queue, &wait); } split_counters(&cnt, &inpr); *count = cnt; return !inpr; } /** * pm_save_wakeup_count - Save the current number of registered wakeup events. * @count: Value to compare with the current number of registered wakeup events. * * If @count is equal to the current number of registered wakeup events and the * current number of wakeup events being processed is zero, store @count as the * old number of registered wakeup events for pm_check_wakeup_events(), enable * wakeup events detection and return 'true'. Otherwise disable wakeup events * detection and return 'false'. */ bool pm_save_wakeup_count(unsigned int count) { unsigned int cnt, inpr; events_check_enabled = false; spin_lock_irq(&events_lock); split_counters(&cnt, &inpr); if (cnt == count && inpr == 0) { saved_count = count; events_check_enabled = true; } spin_unlock_irq(&events_lock); return events_check_enabled; } #ifdef CONFIG_PM_AUTOSLEEP /** * pm_wakep_autosleep_enabled - Modify autosleep_enabled for all wakeup sources. * @enabled: Whether to set or to clear the autosleep_enabled flags. */ void pm_wakep_autosleep_enabled(bool set) { struct wakeup_source *ws; ktime_t now = ktime_get(); rcu_read_lock(); list_for_each_entry_rcu(ws, &wakeup_sources, entry) { spin_lock_irq(&ws->lock); if (ws->autosleep_enabled != set) { ws->autosleep_enabled = set; if (ws->active) { if (set) ws->start_prevent_time = now; else update_prevent_sleep_time(ws, now); } } spin_unlock_irq(&ws->lock); } rcu_read_unlock(); } #endif /* CONFIG_PM_AUTOSLEEP */ static struct dentry *wakeup_sources_stats_dentry; /** * print_wakeup_source_stats - Print wakeup source statistics information. * @m: seq_file to print the statistics into. * @ws: Wakeup source object to print the statistics for. */ static int print_wakeup_source_stats(struct seq_file *m, struct wakeup_source *ws) { unsigned long flags; ktime_t total_time; ktime_t max_time; unsigned long active_count; ktime_t active_time; ktime_t prevent_sleep_time; int ret; spin_lock_irqsave(&ws->lock, flags); total_time = ws->total_time; max_time = ws->max_time; prevent_sleep_time = ws->prevent_sleep_time; active_count = ws->active_count; if (ws->active) { ktime_t now = ktime_get(); active_time = ktime_sub(now, ws->last_time); total_time = ktime_add(total_time, active_time); if (active_time.tv64 > max_time.tv64) max_time = active_time; if (ws->autosleep_enabled) prevent_sleep_time = ktime_add(prevent_sleep_time, ktime_sub(now, ws->start_prevent_time)); } else { active_time = ktime_set(0, 0); } ret = seq_printf(m, "%-12s\t%lu\t\t%lu\t\t%lu\t\t%lu\t\t" "%lld\t\t%lld\t\t%lld\t\t%lld\t\t%lld\n", ws->name, active_count, ws->event_count, ws->wakeup_count, ws->expire_count, ktime_to_ms(active_time), ktime_to_ms(total_time), ktime_to_ms(max_time), ktime_to_ms(ws->last_time), ktime_to_ms(prevent_sleep_time)); spin_unlock_irqrestore(&ws->lock, flags); return ret; } /** * wakeup_sources_stats_show - Print wakeup sources statistics information. * @m: seq_file to print the statistics into. */ static int wakeup_sources_stats_show(struct seq_file *m, void *unused) { struct wakeup_source *ws; seq_puts(m, "name\t\tactive_count\tevent_count\twakeup_count\t" "expire_count\tactive_since\ttotal_time\tmax_time\t" "last_change\tprevent_suspend_time\n"); rcu_read_lock(); list_for_each_entry_rcu(ws, &wakeup_sources, entry) print_wakeup_source_stats(m, ws); rcu_read_unlock(); return 0; } static int wakeup_sources_stats_open(struct inode *inode, struct file *file) { return single_open(file, wakeup_sources_stats_show, NULL); } static const struct file_operations wakeup_sources_stats_fops = { .owner = THIS_MODULE, .open = wakeup_sources_stats_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static int __init wakeup_sources_debugfs_init(void) { wakeup_sources_stats_dentry = debugfs_create_file("wakeup_sources", S_IRUGO, NULL, NULL, &wakeup_sources_stats_fops); return 0; } postcore_initcall(wakeup_sources_debugfs_init);
arnavgosain/moto_msm8226
drivers/base/power/wakeup.c
C
gpl-2.0
25,361
def flatMap[A,B](ma: F[A])(f: A => F[B]): F[B] = compose((_:Unit) => ma, f)(())
ud3sh/coursework
functional-programming-in-scala-textbook/answerkey/monads/08.answer.scala
Scala
unlicense
81
/** * The examples provided by Facebook are for non-commercial testing and * evaluation purposes only. * * Facebook reserves all rights not expressly granted. * * 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 NON INFRINGEMENT. IN NO EVENT SHALL * FACEBOOK 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. * * @flow */ 'use strict'; var React = require('react-native'); var { StyleSheet, PanResponder, View, } = React; var CIRCLE_SIZE = 80; var CIRCLE_COLOR = 'blue'; var CIRCLE_HIGHLIGHT_COLOR = 'green'; var PanResponderExample = React.createClass({ statics: { title: 'PanResponder Sample', description: 'Basic gesture handling example', }, _panResponder: {}, _previousLeft: 0, _previousTop: 0, _circleStyles: {}, circle: (null : ?{ setNativeProps(props: Object): void }), componentWillMount: function() { this._panResponder = PanResponder.create({ onStartShouldSetPanResponder: this._handleStartShouldSetPanResponder, onMoveShouldSetPanResponder: this._handleMoveShouldSetPanResponder, onPanResponderGrant: this._handlePanResponderGrant, onPanResponderMove: this._handlePanResponderMove, onPanResponderRelease: this._handlePanResponderEnd, onPanResponderTerminate: this._handlePanResponderEnd, }); this._previousLeft = 20; this._previousTop = 84; this._circleStyles = { left: this._previousLeft, top: this._previousTop, }; }, componentDidMount: function() { this._updatePosition(); }, render: function() { return ( <View style={styles.container}> <View ref={(circle) => { this.circle = circle; }} style={styles.circle} {...this._panResponder.panHandlers} /> </View> ); }, _highlight: function() { this.circle && this.circle.setNativeProps({ backgroundColor: CIRCLE_HIGHLIGHT_COLOR }); }, _unHighlight: function() { this.circle && this.circle.setNativeProps({ backgroundColor: CIRCLE_COLOR }); }, _updatePosition: function() { this.circle && this.circle.setNativeProps(this._circleStyles); }, _handleStartShouldSetPanResponder: function(e: Object, gestureState: Object): boolean { // Should we become active when the user presses down on the circle? return true; }, _handleMoveShouldSetPanResponder: function(e: Object, gestureState: Object): boolean { // Should we become active when the user moves a touch over the circle? return true; }, _handlePanResponderGrant: function(e: Object, gestureState: Object) { this._highlight(); }, _handlePanResponderMove: function(e: Object, gestureState: Object) { this._circleStyles.left = this._previousLeft + gestureState.dx; this._circleStyles.top = this._previousTop + gestureState.dy; this._updatePosition(); }, _handlePanResponderEnd: function(e: Object, gestureState: Object) { this._unHighlight(); this._previousLeft += gestureState.dx; this._previousTop += gestureState.dy; }, }); var styles = StyleSheet.create({ circle: { width: CIRCLE_SIZE, height: CIRCLE_SIZE, borderRadius: CIRCLE_SIZE / 2, backgroundColor: CIRCLE_COLOR, position: 'absolute', left: 0, top: 0, }, container: { flex: 1, paddingTop: 64, }, }); module.exports = PanResponderExample;
harrykiselev/react-native
Examples/UIExplorer/PanResponderExample.js
JavaScript
bsd-3-clause
3,701
! { dg-do compile } ! { dg-options "-std=f2008" } ! PR fortran/44709 ! Check that the resolving of loop names in parent namespaces introduced to ! handle intermediate BLOCK's does not go too far and other sanity checks. ! Contributed by Daniel Kraft, [email protected]. PROGRAM main IMPLICIT NONE EXIT ! { dg-error "is not within a construct" } EXIT foobar ! { dg-error "is unknown" } EXIT main ! { dg-error "is not a construct name" } mainLoop: DO CALL test () END DO mainLoop otherLoop: DO EXIT mainLoop ! { dg-error "is not within construct 'mainloop'" } END DO otherLoop CONTAINS SUBROUTINE test () EXIT mainLoop ! { dg-error "is unknown" } END SUBROUTINE test END PROGRAM main
SanDisk-Open-Source/SSD_Dashboard
uefi/gcc/gcc-4.6.3/gcc/testsuite/gfortran.dg/exit_2.f08
FORTRAN
gpl-2.0
718
#include <linux/module.h> #include <linux/string.h> #include <linux/uaccess.h> #include <linux/delay.h> #include <linux/mm.h> #include <asm/checksum.h> #include <asm/sections.h> EXPORT_SYMBOL(memchr); EXPORT_SYMBOL(memcpy); EXPORT_SYMBOL(memset); EXPORT_SYMBOL(memmove); EXPORT_SYMBOL(__copy_user); EXPORT_SYMBOL(__udelay); EXPORT_SYMBOL(__ndelay); EXPORT_SYMBOL(__const_udelay); EXPORT_SYMBOL(strlen); EXPORT_SYMBOL(csum_partial); EXPORT_SYMBOL(csum_partial_copy_generic); EXPORT_SYMBOL(copy_page); EXPORT_SYMBOL(__clear_user); EXPORT_SYMBOL(empty_zero_page); #define DECLARE_EXPORT(name) \ extern void name(void);EXPORT_SYMBOL(name) DECLARE_EXPORT(__udivsi3); DECLARE_EXPORT(__sdivsi3); DECLARE_EXPORT(__lshrsi3); DECLARE_EXPORT(__ashrsi3); DECLARE_EXPORT(__ashlsi3); DECLARE_EXPORT(__ashiftrt_r4_6); DECLARE_EXPORT(__ashiftrt_r4_7); DECLARE_EXPORT(__ashiftrt_r4_8); DECLARE_EXPORT(__ashiftrt_r4_9); DECLARE_EXPORT(__ashiftrt_r4_10); DECLARE_EXPORT(__ashiftrt_r4_11); DECLARE_EXPORT(__ashiftrt_r4_12); DECLARE_EXPORT(__ashiftrt_r4_13); DECLARE_EXPORT(__ashiftrt_r4_14); DECLARE_EXPORT(__ashiftrt_r4_15); DECLARE_EXPORT(__ashiftrt_r4_20); DECLARE_EXPORT(__ashiftrt_r4_21); DECLARE_EXPORT(__ashiftrt_r4_22); DECLARE_EXPORT(__ashiftrt_r4_23); DECLARE_EXPORT(__ashiftrt_r4_24); DECLARE_EXPORT(__ashiftrt_r4_27); DECLARE_EXPORT(__ashiftrt_r4_30); DECLARE_EXPORT(__movstr); DECLARE_EXPORT(__movstrSI8); DECLARE_EXPORT(__movstrSI12); DECLARE_EXPORT(__movstrSI16); DECLARE_EXPORT(__movstrSI20); DECLARE_EXPORT(__movstrSI24); DECLARE_EXPORT(__movstrSI28); DECLARE_EXPORT(__movstrSI32); DECLARE_EXPORT(__movstrSI36); DECLARE_EXPORT(__movstrSI40); DECLARE_EXPORT(__movstrSI44); DECLARE_EXPORT(__movstrSI48); DECLARE_EXPORT(__movstrSI52); DECLARE_EXPORT(__movstrSI56); DECLARE_EXPORT(__movstrSI60); DECLARE_EXPORT(__movstr_i4_even); DECLARE_EXPORT(__movstr_i4_odd); DECLARE_EXPORT(__movstrSI12_i4); DECLARE_EXPORT(__movmem); DECLARE_EXPORT(__movmemSI8); DECLARE_EXPORT(__movmemSI12); DECLARE_EXPORT(__movmemSI16); DECLARE_EXPORT(__movmemSI20); DECLARE_EXPORT(__movmemSI24); DECLARE_EXPORT(__movmemSI28); DECLARE_EXPORT(__movmemSI32); DECLARE_EXPORT(__movmemSI36); DECLARE_EXPORT(__movmemSI40); DECLARE_EXPORT(__movmemSI44); DECLARE_EXPORT(__movmemSI48); DECLARE_EXPORT(__movmemSI52); DECLARE_EXPORT(__movmemSI56); DECLARE_EXPORT(__movmemSI60); DECLARE_EXPORT(__movmem_i4_even); DECLARE_EXPORT(__movmem_i4_odd); DECLARE_EXPORT(__movmemSI12_i4); DECLARE_EXPORT(__udiv_qrnnd_16); DECLARE_EXPORT(__sdivsi3_i4); DECLARE_EXPORT(__udivsi3_i4); DECLARE_EXPORT(__sdivsi3_i4i); DECLARE_EXPORT(__udivsi3_i4i); #ifdef CONFIG_MCOUNT DECLARE_EXPORT(mcount); #endif
SanDisk-Open-Source/SSD_Dashboard
uefi/linux-source-3.8.0/arch/sh/kernel/sh_ksyms_32.c
C
gpl-2.0
2,646
/* * This is a module which is used for rejecting packets. */ /* (C) 1999-2001 Paul `Rusty' Russell * (C) 2002-2004 Netfilter Core Team <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #include <linux/skbuff.h> #include <linux/slab.h> #include <linux/ip.h> #include <linux/udp.h> #include <linux/icmp.h> #include <net/icmp.h> #include <linux/netfilter/x_tables.h> #include <linux/netfilter_ipv4/ip_tables.h> #include <linux/netfilter_ipv4/ipt_REJECT.h> #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER) #include <linux/netfilter_bridge.h> #endif #include <net/netfilter/ipv4/nf_reject.h> MODULE_LICENSE("GPL"); MODULE_AUTHOR("Netfilter Core Team <[email protected]>"); MODULE_DESCRIPTION("Xtables: packet \"rejection\" target for IPv4"); static unsigned int reject_tg(struct sk_buff *skb, const struct xt_action_param *par) { const struct ipt_reject_info *reject = par->targinfo; int hook = xt_hooknum(par); switch (reject->with) { case IPT_ICMP_NET_UNREACHABLE: nf_send_unreach(skb, ICMP_NET_UNREACH, hook); break; case IPT_ICMP_HOST_UNREACHABLE: nf_send_unreach(skb, ICMP_HOST_UNREACH, hook); break; case IPT_ICMP_PROT_UNREACHABLE: nf_send_unreach(skb, ICMP_PROT_UNREACH, hook); break; case IPT_ICMP_PORT_UNREACHABLE: nf_send_unreach(skb, ICMP_PORT_UNREACH, hook); break; case IPT_ICMP_NET_PROHIBITED: nf_send_unreach(skb, ICMP_NET_ANO, hook); break; case IPT_ICMP_HOST_PROHIBITED: nf_send_unreach(skb, ICMP_HOST_ANO, hook); break; case IPT_ICMP_ADMIN_PROHIBITED: nf_send_unreach(skb, ICMP_PKT_FILTERED, hook); break; case IPT_TCP_RESET: nf_send_reset(xt_net(par), skb, hook); case IPT_ICMP_ECHOREPLY: /* Doesn't happen. */ break; } return NF_DROP; } static int reject_tg_check(const struct xt_tgchk_param *par) { const struct ipt_reject_info *rejinfo = par->targinfo; const struct ipt_entry *e = par->entryinfo; if (rejinfo->with == IPT_ICMP_ECHOREPLY) { pr_info("ECHOREPLY no longer supported.\n"); return -EINVAL; } else if (rejinfo->with == IPT_TCP_RESET) { /* Must specify that it's a TCP packet */ if (e->ip.proto != IPPROTO_TCP || (e->ip.invflags & XT_INV_PROTO)) { pr_info("TCP_RESET invalid for non-tcp\n"); return -EINVAL; } } return 0; } static struct xt_target reject_tg_reg __read_mostly = { .name = "REJECT", .family = NFPROTO_IPV4, .target = reject_tg, .targetsize = sizeof(struct ipt_reject_info), .table = "filter", .hooks = (1 << NF_INET_LOCAL_IN) | (1 << NF_INET_FORWARD) | (1 << NF_INET_LOCAL_OUT), .checkentry = reject_tg_check, .me = THIS_MODULE, }; static int __init reject_tg_init(void) { return xt_register_target(&reject_tg_reg); } static void __exit reject_tg_exit(void) { xt_unregister_target(&reject_tg_reg); } module_init(reject_tg_init); module_exit(reject_tg_exit);
uoaerg/linux-dccp
net/ipv4/netfilter/ipt_REJECT.c
C
gpl-2.0
3,047
/* * linux/arch/arm/kernel/ptrace.c * * By Ross Biro 1/23/92 * edited by Linus Torvalds * ARM modifications Copyright (C) 2000 Russell King * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/kernel.h> #include <linux/sched.h> #include <linux/mm.h> #include <linux/elf.h> #include <linux/smp.h> #include <linux/ptrace.h> #include <linux/user.h> #include <linux/security.h> #include <linux/init.h> #include <linux/signal.h> #include <linux/uaccess.h> #include <linux/perf_event.h> #include <linux/hw_breakpoint.h> #include <linux/regset.h> #include <linux/audit.h> #include <linux/tracehook.h> #include <linux/unistd.h> #include <asm/pgtable.h> #include <asm/traps.h> #define CREATE_TRACE_POINTS #include <trace/events/syscalls.h> #define REG_PC 15 #define REG_PSR 16 /* * does not yet catch signals sent when the child dies. * in exit.c or in signal.c. */ #if 0 /* * Breakpoint SWI instruction: SWI &9F0001 */ #define BREAKINST_ARM 0xef9f0001 #define BREAKINST_THUMB 0xdf00 /* fill this in later */ #else /* * New breakpoints - use an undefined instruction. The ARM architecture * reference manual guarantees that the following instruction space * will produce an undefined instruction exception on all CPUs: * * ARM: xxxx 0111 1111 xxxx xxxx xxxx 1111 xxxx * Thumb: 1101 1110 xxxx xxxx */ #define BREAKINST_ARM 0xe7f001f0 #define BREAKINST_THUMB 0xde01 #endif struct pt_regs_offset { const char *name; int offset; }; #define REG_OFFSET_NAME(r) \ {.name = #r, .offset = offsetof(struct pt_regs, ARM_##r)} #define REG_OFFSET_END {.name = NULL, .offset = 0} static const struct pt_regs_offset regoffset_table[] = { REG_OFFSET_NAME(r0), REG_OFFSET_NAME(r1), REG_OFFSET_NAME(r2), REG_OFFSET_NAME(r3), REG_OFFSET_NAME(r4), REG_OFFSET_NAME(r5), REG_OFFSET_NAME(r6), REG_OFFSET_NAME(r7), REG_OFFSET_NAME(r8), REG_OFFSET_NAME(r9), REG_OFFSET_NAME(r10), REG_OFFSET_NAME(fp), REG_OFFSET_NAME(ip), REG_OFFSET_NAME(sp), REG_OFFSET_NAME(lr), REG_OFFSET_NAME(pc), REG_OFFSET_NAME(cpsr), REG_OFFSET_NAME(ORIG_r0), REG_OFFSET_END, }; /** * regs_query_register_offset() - query register offset from its name * @name: the name of a register * * regs_query_register_offset() returns the offset of a register in struct * pt_regs from its name. If the name is invalid, this returns -EINVAL; */ int regs_query_register_offset(const char *name) { const struct pt_regs_offset *roff; for (roff = regoffset_table; roff->name != NULL; roff++) if (!strcmp(roff->name, name)) return roff->offset; return -EINVAL; } /** * regs_query_register_name() - query register name from its offset * @offset: the offset of a register in struct pt_regs. * * regs_query_register_name() returns the name of a register from its * offset in struct pt_regs. If the @offset is invalid, this returns NULL; */ const char *regs_query_register_name(unsigned int offset) { const struct pt_regs_offset *roff; for (roff = regoffset_table; roff->name != NULL; roff++) if (roff->offset == offset) return roff->name; return NULL; } /** * regs_within_kernel_stack() - check the address in the stack * @regs: pt_regs which contains kernel stack pointer. * @addr: address which is checked. * * regs_within_kernel_stack() checks @addr is within the kernel stack page(s). * If @addr is within the kernel stack, it returns true. If not, returns false. */ bool regs_within_kernel_stack(struct pt_regs *regs, unsigned long addr) { return ((addr & ~(THREAD_SIZE - 1)) == (kernel_stack_pointer(regs) & ~(THREAD_SIZE - 1))); } /** * regs_get_kernel_stack_nth() - get Nth entry of the stack * @regs: pt_regs which contains kernel stack pointer. * @n: stack entry number. * * regs_get_kernel_stack_nth() returns @n th entry of the kernel stack which * is specified by @regs. If the @n th entry is NOT in the kernel stack, * this returns 0. */ unsigned long regs_get_kernel_stack_nth(struct pt_regs *regs, unsigned int n) { unsigned long *addr = (unsigned long *)kernel_stack_pointer(regs); addr += n; if (regs_within_kernel_stack(regs, (unsigned long)addr)) return *addr; else return 0; } /* * this routine will get a word off of the processes privileged stack. * the offset is how far from the base addr as stored in the THREAD. * this routine assumes that all the privileged stacks are in our * data space. */ static inline long get_user_reg(struct task_struct *task, int offset) { return task_pt_regs(task)->uregs[offset]; } /* * this routine will put a word on the processes privileged stack. * the offset is how far from the base addr as stored in the THREAD. * this routine assumes that all the privileged stacks are in our * data space. */ static inline int put_user_reg(struct task_struct *task, int offset, long data) { struct pt_regs newregs, *regs = task_pt_regs(task); int ret = -EINVAL; newregs = *regs; newregs.uregs[offset] = data; if (valid_user_regs(&newregs)) { regs->uregs[offset] = data; ret = 0; } return ret; } /* * Called by kernel/ptrace.c when detaching.. */ void ptrace_disable(struct task_struct *child) { /* Nothing to do. */ } /* * Handle hitting a breakpoint. */ void ptrace_break(struct task_struct *tsk, struct pt_regs *regs) { siginfo_t info; info.si_signo = SIGTRAP; info.si_errno = 0; info.si_code = TRAP_BRKPT; info.si_addr = (void __user *)instruction_pointer(regs); force_sig_info(SIGTRAP, &info, tsk); } static int break_trap(struct pt_regs *regs, unsigned int instr) { ptrace_break(current, regs); return 0; } static struct undef_hook arm_break_hook = { .instr_mask = 0x0fffffff, .instr_val = 0x07f001f0, .cpsr_mask = PSR_T_BIT, .cpsr_val = 0, .fn = break_trap, }; static struct undef_hook thumb_break_hook = { .instr_mask = 0xffff, .instr_val = 0xde01, .cpsr_mask = PSR_T_BIT, .cpsr_val = PSR_T_BIT, .fn = break_trap, }; static struct undef_hook thumb2_break_hook = { .instr_mask = 0xffffffff, .instr_val = 0xf7f0a000, .cpsr_mask = PSR_T_BIT, .cpsr_val = PSR_T_BIT, .fn = break_trap, }; static int __init ptrace_break_init(void) { register_undef_hook(&arm_break_hook); register_undef_hook(&thumb_break_hook); register_undef_hook(&thumb2_break_hook); return 0; } core_initcall(ptrace_break_init); /* * Read the word at offset "off" into the "struct user". We * actually access the pt_regs stored on the kernel stack. */ static int ptrace_read_user(struct task_struct *tsk, unsigned long off, unsigned long __user *ret) { unsigned long tmp; if (off & 3) return -EIO; tmp = 0; if (off == PT_TEXT_ADDR) tmp = tsk->mm->start_code; else if (off == PT_DATA_ADDR) tmp = tsk->mm->start_data; else if (off == PT_TEXT_END_ADDR) tmp = tsk->mm->end_code; else if (off < sizeof(struct pt_regs)) tmp = get_user_reg(tsk, off >> 2); else if (off >= sizeof(struct user)) return -EIO; return put_user(tmp, ret); } /* * Write the word at offset "off" into "struct user". We * actually access the pt_regs stored on the kernel stack. */ static int ptrace_write_user(struct task_struct *tsk, unsigned long off, unsigned long val) { if (off & 3 || off >= sizeof(struct user)) return -EIO; if (off >= sizeof(struct pt_regs)) return 0; return put_user_reg(tsk, off >> 2, val); } #ifdef CONFIG_IWMMXT /* * Get the child iWMMXt state. */ static int ptrace_getwmmxregs(struct task_struct *tsk, void __user *ufp) { struct thread_info *thread = task_thread_info(tsk); if (!test_ti_thread_flag(thread, TIF_USING_IWMMXT)) return -ENODATA; iwmmxt_task_disable(thread); /* force it to ram */ return copy_to_user(ufp, &thread->fpstate.iwmmxt, IWMMXT_SIZE) ? -EFAULT : 0; } /* * Set the child iWMMXt state. */ static int ptrace_setwmmxregs(struct task_struct *tsk, void __user *ufp) { struct thread_info *thread = task_thread_info(tsk); if (!test_ti_thread_flag(thread, TIF_USING_IWMMXT)) return -EACCES; iwmmxt_task_release(thread); /* force a reload */ return copy_from_user(&thread->fpstate.iwmmxt, ufp, IWMMXT_SIZE) ? -EFAULT : 0; } #endif #ifdef CONFIG_CRUNCH /* * Get the child Crunch state. */ static int ptrace_getcrunchregs(struct task_struct *tsk, void __user *ufp) { struct thread_info *thread = task_thread_info(tsk); crunch_task_disable(thread); /* force it to ram */ return copy_to_user(ufp, &thread->crunchstate, CRUNCH_SIZE) ? -EFAULT : 0; } /* * Set the child Crunch state. */ static int ptrace_setcrunchregs(struct task_struct *tsk, void __user *ufp) { struct thread_info *thread = task_thread_info(tsk); crunch_task_release(thread); /* force a reload */ return copy_from_user(&thread->crunchstate, ufp, CRUNCH_SIZE) ? -EFAULT : 0; } #endif #ifdef CONFIG_HAVE_HW_BREAKPOINT /* * Convert a virtual register number into an index for a thread_info * breakpoint array. Breakpoints are identified using positive numbers * whilst watchpoints are negative. The registers are laid out as pairs * of (address, control), each pair mapping to a unique hw_breakpoint struct. * Register 0 is reserved for describing resource information. */ static int ptrace_hbp_num_to_idx(long num) { if (num < 0) num = (ARM_MAX_BRP << 1) - num; return (num - 1) >> 1; } /* * Returns the virtual register number for the address of the * breakpoint at index idx. */ static long ptrace_hbp_idx_to_num(int idx) { long mid = ARM_MAX_BRP << 1; long num = (idx << 1) + 1; return num > mid ? mid - num : num; } /* * Handle hitting a HW-breakpoint. */ static void ptrace_hbptriggered(struct perf_event *bp, struct perf_sample_data *data, struct pt_regs *regs) { struct arch_hw_breakpoint *bkpt = counter_arch_bp(bp); long num; int i; siginfo_t info; for (i = 0; i < ARM_MAX_HBP_SLOTS; ++i) if (current->thread.debug.hbp[i] == bp) break; num = (i == ARM_MAX_HBP_SLOTS) ? 0 : ptrace_hbp_idx_to_num(i); info.si_signo = SIGTRAP; info.si_errno = (int)num; info.si_code = TRAP_HWBKPT; info.si_addr = (void __user *)(bkpt->trigger); force_sig_info(SIGTRAP, &info, current); } /* * Set ptrace breakpoint pointers to zero for this task. * This is required in order to prevent child processes from unregistering * breakpoints held by their parent. */ void clear_ptrace_hw_breakpoint(struct task_struct *tsk) { memset(tsk->thread.debug.hbp, 0, sizeof(tsk->thread.debug.hbp)); } /* * Unregister breakpoints from this task and reset the pointers in * the thread_struct. */ void flush_ptrace_hw_breakpoint(struct task_struct *tsk) { int i; struct thread_struct *t = &tsk->thread; for (i = 0; i < ARM_MAX_HBP_SLOTS; i++) { if (t->debug.hbp[i]) { unregister_hw_breakpoint(t->debug.hbp[i]); t->debug.hbp[i] = NULL; } } } static u32 ptrace_get_hbp_resource_info(void) { u8 num_brps, num_wrps, debug_arch, wp_len; u32 reg = 0; num_brps = hw_breakpoint_slots(TYPE_INST); num_wrps = hw_breakpoint_slots(TYPE_DATA); debug_arch = arch_get_debug_arch(); wp_len = arch_get_max_wp_len(); reg |= debug_arch; reg <<= 8; reg |= wp_len; reg <<= 8; reg |= num_wrps; reg <<= 8; reg |= num_brps; return reg; } static struct perf_event *ptrace_hbp_create(struct task_struct *tsk, int type) { struct perf_event_attr attr; ptrace_breakpoint_init(&attr); /* Initialise fields to sane defaults. */ attr.bp_addr = 0; attr.bp_len = HW_BREAKPOINT_LEN_4; attr.bp_type = type; attr.disabled = 1; return register_user_hw_breakpoint(&attr, ptrace_hbptriggered, NULL, tsk); } static int ptrace_gethbpregs(struct task_struct *tsk, long num, unsigned long __user *data) { u32 reg; int idx, ret = 0; struct perf_event *bp; struct arch_hw_breakpoint_ctrl arch_ctrl; if (num == 0) { reg = ptrace_get_hbp_resource_info(); } else { idx = ptrace_hbp_num_to_idx(num); if (idx < 0 || idx >= ARM_MAX_HBP_SLOTS) { ret = -EINVAL; goto out; } bp = tsk->thread.debug.hbp[idx]; if (!bp) { reg = 0; goto put; } arch_ctrl = counter_arch_bp(bp)->ctrl; /* * Fix up the len because we may have adjusted it * to compensate for an unaligned address. */ while (!(arch_ctrl.len & 0x1)) arch_ctrl.len >>= 1; if (num & 0x1) reg = bp->attr.bp_addr; else reg = encode_ctrl_reg(arch_ctrl); } put: if (put_user(reg, data)) ret = -EFAULT; out: return ret; } static int ptrace_sethbpregs(struct task_struct *tsk, long num, unsigned long __user *data) { int idx, gen_len, gen_type, implied_type, ret = 0; u32 user_val; struct perf_event *bp; struct arch_hw_breakpoint_ctrl ctrl; struct perf_event_attr attr; if (num == 0) goto out; else if (num < 0) implied_type = HW_BREAKPOINT_RW; else implied_type = HW_BREAKPOINT_X; idx = ptrace_hbp_num_to_idx(num); if (idx < 0 || idx >= ARM_MAX_HBP_SLOTS) { ret = -EINVAL; goto out; } if (get_user(user_val, data)) { ret = -EFAULT; goto out; } bp = tsk->thread.debug.hbp[idx]; if (!bp) { bp = ptrace_hbp_create(tsk, implied_type); if (IS_ERR(bp)) { ret = PTR_ERR(bp); goto out; } tsk->thread.debug.hbp[idx] = bp; } attr = bp->attr; if (num & 0x1) { /* Address */ attr.bp_addr = user_val; } else { /* Control */ decode_ctrl_reg(user_val, &ctrl); ret = arch_bp_generic_fields(ctrl, &gen_len, &gen_type); if (ret) goto out; if ((gen_type & implied_type) != gen_type) { ret = -EINVAL; goto out; } attr.bp_len = gen_len; attr.bp_type = gen_type; attr.disabled = !ctrl.enabled; } ret = modify_user_hw_breakpoint(bp, &attr); out: return ret; } #endif /* regset get/set implementations */ static int gpr_get(struct task_struct *target, const struct user_regset *regset, unsigned int pos, unsigned int count, void *kbuf, void __user *ubuf) { struct pt_regs *regs = task_pt_regs(target); return user_regset_copyout(&pos, &count, &kbuf, &ubuf, regs, 0, sizeof(*regs)); } static int gpr_set(struct task_struct *target, const struct user_regset *regset, unsigned int pos, unsigned int count, const void *kbuf, const void __user *ubuf) { int ret; struct pt_regs newregs; ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, &newregs, 0, sizeof(newregs)); if (ret) return ret; if (!valid_user_regs(&newregs)) return -EINVAL; *task_pt_regs(target) = newregs; return 0; } static int fpa_get(struct task_struct *target, const struct user_regset *regset, unsigned int pos, unsigned int count, void *kbuf, void __user *ubuf) { return user_regset_copyout(&pos, &count, &kbuf, &ubuf, &task_thread_info(target)->fpstate, 0, sizeof(struct user_fp)); } static int fpa_set(struct task_struct *target, const struct user_regset *regset, unsigned int pos, unsigned int count, const void *kbuf, const void __user *ubuf) { struct thread_info *thread = task_thread_info(target); thread->used_cp[1] = thread->used_cp[2] = 1; return user_regset_copyin(&pos, &count, &kbuf, &ubuf, &thread->fpstate, 0, sizeof(struct user_fp)); } #ifdef CONFIG_VFP /* * VFP register get/set implementations. * * With respect to the kernel, struct user_fp is divided into three chunks: * 16 or 32 real VFP registers (d0-d15 or d0-31) * These are transferred to/from the real registers in the task's * vfp_hard_struct. The number of registers depends on the kernel * configuration. * * 16 or 0 fake VFP registers (d16-d31 or empty) * i.e., the user_vfp structure has space for 32 registers even if * the kernel doesn't have them all. * * vfp_get() reads this chunk as zero where applicable * vfp_set() ignores this chunk * * 1 word for the FPSCR * * The bounds-checking logic built into user_regset_copyout and friends * means that we can make a simple sequence of calls to map the relevant data * to/from the specified slice of the user regset structure. */ static int vfp_get(struct task_struct *target, const struct user_regset *regset, unsigned int pos, unsigned int count, void *kbuf, void __user *ubuf) { int ret; struct thread_info *thread = task_thread_info(target); struct vfp_hard_struct const *vfp = &thread->vfpstate.hard; const size_t user_fpregs_offset = offsetof(struct user_vfp, fpregs); const size_t user_fpscr_offset = offsetof(struct user_vfp, fpscr); vfp_sync_hwstate(thread); ret = user_regset_copyout(&pos, &count, &kbuf, &ubuf, &vfp->fpregs, user_fpregs_offset, user_fpregs_offset + sizeof(vfp->fpregs)); if (ret) return ret; ret = user_regset_copyout_zero(&pos, &count, &kbuf, &ubuf, user_fpregs_offset + sizeof(vfp->fpregs), user_fpscr_offset); if (ret) return ret; return user_regset_copyout(&pos, &count, &kbuf, &ubuf, &vfp->fpscr, user_fpscr_offset, user_fpscr_offset + sizeof(vfp->fpscr)); } /* * For vfp_set() a read-modify-write is done on the VFP registers, * in order to avoid writing back a half-modified set of registers on * failure. */ static int vfp_set(struct task_struct *target, const struct user_regset *regset, unsigned int pos, unsigned int count, const void *kbuf, const void __user *ubuf) { int ret; struct thread_info *thread = task_thread_info(target); struct vfp_hard_struct new_vfp; const size_t user_fpregs_offset = offsetof(struct user_vfp, fpregs); const size_t user_fpscr_offset = offsetof(struct user_vfp, fpscr); vfp_sync_hwstate(thread); new_vfp = thread->vfpstate.hard; ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, &new_vfp.fpregs, user_fpregs_offset, user_fpregs_offset + sizeof(new_vfp.fpregs)); if (ret) return ret; ret = user_regset_copyin_ignore(&pos, &count, &kbuf, &ubuf, user_fpregs_offset + sizeof(new_vfp.fpregs), user_fpscr_offset); if (ret) return ret; ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, &new_vfp.fpscr, user_fpscr_offset, user_fpscr_offset + sizeof(new_vfp.fpscr)); if (ret) return ret; vfp_flush_hwstate(thread); thread->vfpstate.hard = new_vfp; return 0; } #endif /* CONFIG_VFP */ enum arm_regset { REGSET_GPR, REGSET_FPR, #ifdef CONFIG_VFP REGSET_VFP, #endif }; static const struct user_regset arm_regsets[] = { [REGSET_GPR] = { .core_note_type = NT_PRSTATUS, .n = ELF_NGREG, .size = sizeof(u32), .align = sizeof(u32), .get = gpr_get, .set = gpr_set }, [REGSET_FPR] = { /* * For the FPA regs in fpstate, the real fields are a mixture * of sizes, so pretend that the registers are word-sized: */ .core_note_type = NT_PRFPREG, .n = sizeof(struct user_fp) / sizeof(u32), .size = sizeof(u32), .align = sizeof(u32), .get = fpa_get, .set = fpa_set }, #ifdef CONFIG_VFP [REGSET_VFP] = { /* * Pretend that the VFP regs are word-sized, since the FPSCR is * a single word dangling at the end of struct user_vfp: */ .core_note_type = NT_ARM_VFP, .n = ARM_VFPREGS_SIZE / sizeof(u32), .size = sizeof(u32), .align = sizeof(u32), .get = vfp_get, .set = vfp_set }, #endif /* CONFIG_VFP */ }; static const struct user_regset_view user_arm_view = { .name = "arm", .e_machine = ELF_ARCH, .ei_osabi = ELF_OSABI, .regsets = arm_regsets, .n = ARRAY_SIZE(arm_regsets) }; const struct user_regset_view *task_user_regset_view(struct task_struct *task) { return &user_arm_view; } long arch_ptrace(struct task_struct *child, long request, unsigned long addr, unsigned long data) { int ret; unsigned long __user *datap = (unsigned long __user *) data; switch (request) { case PTRACE_PEEKUSR: ret = ptrace_read_user(child, addr, datap); break; case PTRACE_POKEUSR: ret = ptrace_write_user(child, addr, data); break; case PTRACE_GETREGS: ret = copy_regset_to_user(child, &user_arm_view, REGSET_GPR, 0, sizeof(struct pt_regs), datap); break; case PTRACE_SETREGS: ret = copy_regset_from_user(child, &user_arm_view, REGSET_GPR, 0, sizeof(struct pt_regs), datap); break; case PTRACE_GETFPREGS: ret = copy_regset_to_user(child, &user_arm_view, REGSET_FPR, 0, sizeof(union fp_state), datap); break; case PTRACE_SETFPREGS: ret = copy_regset_from_user(child, &user_arm_view, REGSET_FPR, 0, sizeof(union fp_state), datap); break; #ifdef CONFIG_IWMMXT case PTRACE_GETWMMXREGS: ret = ptrace_getwmmxregs(child, datap); break; case PTRACE_SETWMMXREGS: ret = ptrace_setwmmxregs(child, datap); break; #endif case PTRACE_GET_THREAD_AREA: ret = put_user(task_thread_info(child)->tp_value, datap); break; case PTRACE_SET_SYSCALL: task_thread_info(child)->syscall = data; ret = 0; break; #ifdef CONFIG_CRUNCH case PTRACE_GETCRUNCHREGS: ret = ptrace_getcrunchregs(child, datap); break; case PTRACE_SETCRUNCHREGS: ret = ptrace_setcrunchregs(child, datap); break; #endif #ifdef CONFIG_VFP case PTRACE_GETVFPREGS: ret = copy_regset_to_user(child, &user_arm_view, REGSET_VFP, 0, ARM_VFPREGS_SIZE, datap); break; case PTRACE_SETVFPREGS: ret = copy_regset_from_user(child, &user_arm_view, REGSET_VFP, 0, ARM_VFPREGS_SIZE, datap); break; #endif #ifdef CONFIG_HAVE_HW_BREAKPOINT case PTRACE_GETHBPREGS: if (ptrace_get_breakpoints(child) < 0) return -ESRCH; ret = ptrace_gethbpregs(child, addr, (unsigned long __user *)data); ptrace_put_breakpoints(child); break; case PTRACE_SETHBPREGS: if (ptrace_get_breakpoints(child) < 0) return -ESRCH; ret = ptrace_sethbpregs(child, addr, (unsigned long __user *)data); ptrace_put_breakpoints(child); break; #endif default: ret = ptrace_request(child, request, addr, data); break; } return ret; } enum ptrace_syscall_dir { PTRACE_SYSCALL_ENTER = 0, PTRACE_SYSCALL_EXIT, }; static int tracehook_report_syscall(struct pt_regs *regs, enum ptrace_syscall_dir dir) { unsigned long ip; /* * IP is used to denote syscall entry/exit: * IP = 0 -> entry, =1 -> exit */ ip = regs->ARM_ip; regs->ARM_ip = dir; if (dir == PTRACE_SYSCALL_EXIT) tracehook_report_syscall_exit(regs, 0); else if (tracehook_report_syscall_entry(regs)) current_thread_info()->syscall = -1; regs->ARM_ip = ip; return current_thread_info()->syscall; } asmlinkage int syscall_trace_enter(struct pt_regs *regs, int scno) { current_thread_info()->syscall = scno; /* Do the secure computing check first; failures should be fast. */ if (secure_computing(scno) == -1) return -1; if (test_thread_flag(TIF_SYSCALL_TRACE)) scno = tracehook_report_syscall(regs, PTRACE_SYSCALL_ENTER); if (test_thread_flag(TIF_SYSCALL_TRACEPOINT)) trace_sys_enter(regs, scno); audit_syscall_entry(AUDIT_ARCH_ARM, scno, regs->ARM_r0, regs->ARM_r1, regs->ARM_r2, regs->ARM_r3); return scno; } asmlinkage void syscall_trace_exit(struct pt_regs *regs) { /* * Audit the syscall before anything else, as a debugger may * come in and change the current registers. */ audit_syscall_exit(regs); /* * Note that we haven't updated the ->syscall field for the * current thread. This isn't a problem because it will have * been set on syscall entry and there hasn't been an opportunity * for a PTRACE_SET_SYSCALL since then. */ if (test_thread_flag(TIF_SYSCALL_TRACEPOINT)) trace_sys_exit(regs, regs_return_value(regs)); if (test_thread_flag(TIF_SYSCALL_TRACE)) tracehook_report_syscall(regs, PTRACE_SYSCALL_EXIT); }
prasidh09/cse506
unionfs-3.10.y/arch/arm/kernel/ptrace.c
C
gpl-2.0
23,682
# encoding: utf-8 module Mongoid module Relations # This is the superclass for builders that are in charge of handling # creation, deletion, and updates of documents through that ever so lovely # #accepts_nested_attributes_for. class NestedBuilder attr_accessor :attributes, :existing, :metadata, :options # Determines if destroys are allowed for this document. # # @example Do we allow a destroy? # builder.allow_destroy? # # @return [ true, false ] True if the allow destroy option was set. # # @since 2.0.0.rc.1 def allow_destroy? options[:allow_destroy] || false end # Returns the reject if option defined with the macro. # # @example Is there a reject proc? # builder.reject? # # @param The parent document of the relation # @param [ Hash ] attrs The attributes to check for rejection. # # @return [ true, false ] True and call proc or method if rejectable, false if not. # # @since 2.0.0.rc.1 def reject?(document, attrs) case callback = options[:reject_if] when Symbol document.method(callback).arity == 0 ? document.send(callback) : document.send(callback, attrs) when Proc callback.call(attrs) else false end end # Determines if only updates can occur. Only valid for one-to-one # relations. # # @example Is this update only? # builder.update_only? # # @return [ true, false ] True if the update_only option was set. # # @since 2.0.0.rc.1 def update_only? options[:update_only] || false end # Convert an id to its appropriate type. # # @example Convert the id. # builder.convert_id(Person, "4d371b444835d98b8b000010") # # @param [ Class ] klass The class we're trying to convert for. # @param [ String ] id The id, usually coming from the form. # # @return [ BSON::ObjectId, String, Object ] The converted id. # # @since 2.0.0.rc.6 def convert_id(klass, id) klass.using_object_ids? ? BSON::ObjectId.mongoize(id) : id end end end end
hashrocketeer/mongoid
lib/mongoid/relations/nested_builder.rb
Ruby
mit
2,260
/* crypto/evp/m_wp.c */ #include <stdio.h> #include "cryptlib.h" #ifndef OPENSSL_NO_WHIRLPOOL # include <openssl/evp.h> # include <openssl/objects.h> # include <openssl/x509.h> # include <openssl/whrlpool.h> # include "evp_locl.h" static int init(EVP_MD_CTX *ctx) { return WHIRLPOOL_Init(ctx->md_data); } static int update(EVP_MD_CTX *ctx, const void *data, size_t count) { return WHIRLPOOL_Update(ctx->md_data, data, count); } static int final(EVP_MD_CTX *ctx, unsigned char *md) { return WHIRLPOOL_Final(md, ctx->md_data); } static const EVP_MD whirlpool_md = { NID_whirlpool, 0, WHIRLPOOL_DIGEST_LENGTH, 0, init, update, final, NULL, NULL, EVP_PKEY_NULL_method, WHIRLPOOL_BBLOCK / 8, sizeof(EVP_MD *) + sizeof(WHIRLPOOL_CTX), }; const EVP_MD *EVP_whirlpool(void) { return (&whirlpool_md); } #endif
jdgarcia/nodegit
vendor/openssl/openssl/crypto/evp/m_wp.c
C
mit
873
/* { dg-do compile } */ /* { dg-options "-O2 -msse2" } */ typedef int __v4si __attribute__ ((__vector_size__ (16))); typedef float __v4sf __attribute__ ((__vector_size__ (16))); int fooSI_1(__v4si *val) { return __builtin_ia32_vec_ext_v4si(*val, 1); } /* { dg-final { scan-assembler-not "pshufd" } } */ int fooSI_2(__v4si *val) { return __builtin_ia32_vec_ext_v4si(*val, 2); } /* { dg-final { scan-assembler-not "punpckhdq" } } */ float fooSF_2(__v4sf *val) { return __builtin_ia32_vec_ext_v4sf(*val, 2); } /* { dg-final { scan-assembler-not "unpckhps" } } */ float fooSF_3(__v4sf *val) { return __builtin_ia32_vec_ext_v4sf(*val, 3); } /* { dg-final { scan-assembler-not "shufps" } } */
SanDisk-Open-Source/SSD_Dashboard
uefi/gcc/gcc-4.6.3/gcc/testsuite/gcc.target/i386/pr32661.c
C
gpl-2.0
700
<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> <title>Configuration Changing...</title> </head> <body> <p> Orchard is temporarily unavailable as a change in configuration requires a restart. A simple page refresh usually solves this issue.</p> <script type="text/javascript"> window.location.reload(); </script> </body> </html>
bigfont/muddlingthru
wwwroot/Refresh.html
HTML
mit
427
/** * Project: dubbo.registry.server-1.1.0-SNAPSHOT * * File Created at 2009-12-27 * $Id: MemoryStatusChecker.java 181192 2012-06-21 05:05:47Z tony.chenl $ * * Copyright 2008 Alibaba.com Croporation Limited. * All rights reserved. * * This software is the confidential and proprietary information of * Alibaba Company. ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered into * with Alibaba.com. */ package com.alibaba.dubbo.governance.status; import com.alibaba.dubbo.common.status.Status; import com.alibaba.dubbo.common.status.StatusChecker; /** * MemoryStatus * * @author william.liangf */ public class MemoryStatusChecker implements StatusChecker { public Status check() { Runtime runtime = Runtime.getRuntime(); long freeMemory = runtime.freeMemory(); long totalMemory = runtime.totalMemory(); long maxMemory = runtime.maxMemory(); boolean ok = (maxMemory - (totalMemory - freeMemory) > 2048); // 剩余空间小于2M报警 String msg = "Max:" + (maxMemory / 1024 / 1024) + "M, Total:" + (totalMemory / 1024 / 1024) + "M, Free:" + (freeMemory / 1024 / 1024) + "M, Use:" + ((totalMemory / 1024 / 1024) - (freeMemory / 1024 / 1024)) + "M"; return new Status(ok ? Status.Level.OK : Status.Level.WARN, msg); } }
zhushuchen/Ocean
项目源码/dubbo/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/status/MemoryStatusChecker.java
Java
agpl-3.0
1,445
// { dg-do assemble } template <class T> struct S { template <class U = T> friend class S; void f(T); }; template struct S<int>; void g() { S<> s; s.f(3); }
SanDisk-Open-Source/SSD_Dashboard
uefi/gcc/gcc-4.6.3/gcc/testsuite/g++.old-deja/g++.pt/friend24.C
C++
gpl-2.0
172
/* * Copyright (C) 2016 Maxime Ripard * Maxime Ripard <[email protected]> * * 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/clk-provider.h> #include "ccu_gate.h" void ccu_gate_helper_disable(struct ccu_common *common, u32 gate) { unsigned long flags; u32 reg; if (!gate) return; spin_lock_irqsave(common->lock, flags); reg = readl(common->base + common->reg); writel(reg & ~gate, common->base + common->reg); spin_unlock_irqrestore(common->lock, flags); } static void ccu_gate_disable(struct clk_hw *hw) { struct ccu_gate *cg = hw_to_ccu_gate(hw); return ccu_gate_helper_disable(&cg->common, cg->enable); } int ccu_gate_helper_enable(struct ccu_common *common, u32 gate) { unsigned long flags; u32 reg; if (!gate) return 0; spin_lock_irqsave(common->lock, flags); reg = readl(common->base + common->reg); writel(reg | gate, common->base + common->reg); spin_unlock_irqrestore(common->lock, flags); return 0; } static int ccu_gate_enable(struct clk_hw *hw) { struct ccu_gate *cg = hw_to_ccu_gate(hw); return ccu_gate_helper_enable(&cg->common, cg->enable); } int ccu_gate_helper_is_enabled(struct ccu_common *common, u32 gate) { if (!gate) return 1; return readl(common->base + common->reg) & gate; } static int ccu_gate_is_enabled(struct clk_hw *hw) { struct ccu_gate *cg = hw_to_ccu_gate(hw); return ccu_gate_helper_is_enabled(&cg->common, cg->enable); } const struct clk_ops ccu_gate_ops = { .disable = ccu_gate_disable, .enable = ccu_gate_enable, .is_enabled = ccu_gate_is_enabled, };
codebam/linux
drivers/clk/sunxi-ng/ccu_gate.c
C
gpl-2.0
1,785
/*! * # Semantic UI 1.12.3 - Label * http://github.com/semantic-org/semantic-ui/ * * * Copyright 2014 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ /******************************* Label *******************************/ .ui.label { display: inline-block; vertical-align: baseline; line-height: 1; margin: 0em 0.125em; background-color: #e8e8e8; border-color: #e8e8e8; background-image: none; padding: 0.6em 0.8em; color: rgba(0, 0, 0, 0.6); text-transform: none; font-weight: bold; border-radius: 0.2857rem; box-sizing: border-box; -webkit-transition: background 0.2s ease; transition: background 0.2s ease; } .ui.label:first-child { margin-left: 0em; } .ui.label:last-child { margin-right: 0em; } /* Link */ a.ui.label { cursor: pointer; } /* Inside Link */ .ui.label a { cursor: pointer; color: inherit; opacity: 0.8; -webkit-transition: 0.2s opacity ease; transition: 0.2s opacity ease; } .ui.label a:hover { opacity: 1; } /* Icon */ .ui.label .icon { width: auto; margin: 0em 0.75em 0em 0em; } /* Detail */ .ui.label .detail { display: inline-block; vertical-align: top; font-weight: bold; margin-left: 1em; opacity: 0.8; } .ui.label .detail .icon { margin: 0em 0.25em 0em 0em; } /* Removable label */ .ui.label .close.icon, .ui.label .delete.icon { cursor: pointer; margin-right: 0em; margin-left: 0.5em; opacity: 0.8; -webkit-transition: background 0.2s ease; transition: background 0.2s ease; } .ui.label .delete.icon:hover { opacity: 1; } /*------------------- Group --------------------*/ .ui.labels .label { margin: 0em 0.5em 0.75em 0em; } /*------------------- Coupling --------------------*/ /* Remove border radius on attached segment */ .ui.attached.segment > .ui.top.left.attached.label, .ui.bottom.attached.segment > .ui.top.left.attached.label { border-top-left-radius: 0; } .ui.attached.segment > .ui.top.right.attached.label, .ui.bottom.attached.segment > .ui.top.right.attached.label { border-top-right-radius: 0; } .ui.top.attached.segment > .ui.bottom.left.attached.label { border-bottom-left-radius: 0; } .ui.top.attached.segment > .ui.bottom.right.attached.label { border-bottom-right-radius: 0; } /* Padding on next content after a label */ .ui.top.attached.label:first-child + :not(.attached) { margin-top: 2rem !important; } .ui.bottom.attached.label:first-child ~ :last-child:not(.attached) { margin-top: 0em; margin-bottom: 2rem !important; } /******************************* Types *******************************/ .ui.image.label { width: auto !important; margin-top: 0em; margin-bottom: 0em; max-width: 9999px; vertical-align: baseline; text-transform: none; background: #e8e8e8; padding: 0.6em 0.8em 0.6em 0.5em; border-radius: 0.2857rem; box-shadow: none; } .ui.image.label img { display: inline-block; vertical-align: top; height: 2.2em; margin: -0.6em 0.5em -0.6em -0.5em; border-radius: 0.2857rem; } .ui.image.label .detail { background: rgba(0, 0, 0, 0.1); margin: -0.6em -0.8em -0.6em 0.5em; padding: 0.6em 0.8em; border-radius: 0em 0.2857rem 0.2857rem 0em; } /*------------------- Tag --------------------*/ .ui.tag.labels .label, .ui.tag.label { margin-left: 1em; position: relative; padding-left: 1.5em; padding-right: 1.5em; border-radius: 0em 0.2857rem 0.2857rem 0em; } .ui.tag.labels .label:before, .ui.tag.label:before { position: absolute; -webkit-transform: translateY(-50%) translateX(50%) rotate(-45deg); -ms-transform: translateY(-50%) translateX(50%) rotate(-45deg); transform: translateY(-50%) translateX(50%) rotate(-45deg); top: 50%; right: 100%; content: ''; background-color: #e8e8e8; background-image: none; width: 1.56em; height: 1.56em; -webkit-transition: background 0.2s ease; transition: background 0.2s ease; } .ui.tag.labels .label:after, .ui.tag.label:after { position: absolute; content: ''; top: 50%; left: -0.25em; margin-top: -0.25em; background-color: #ffffff !important; width: 0.5em; height: 0.5em; box-shadow: 0 -1px 1px 0 rgba(0, 0, 0, 0.3); border-radius: 500rem; } /*------------------- Corner Label --------------------*/ .ui.corner.label { position: absolute; top: 0em; right: 0em; margin: 0em; padding: 0em; text-align: center; width: 3.25em; height: 3.25em; z-index: 1; -webkit-transition: border-color 0.2s ease; transition: border-color 0.2s ease; } /* Icon Label */ .ui.corner.label { background-color: transparent !important; } .ui.corner.label:after { position: absolute; content: ""; right: 0em; top: 0em; z-index: -1; width: 0em; height: 0em; background-color: transparent !important; border-top: 0em solid transparent; border-right: 3.25em solid transparent; border-bottom: 3.25em solid transparent; border-left: 0em solid transparent; border-right-color: inherit; -webkit-transition: border-color 0.2s ease; transition: border-color 0.2s ease; } .ui.corner.label .icon { position: relative; top: 0.4em; left: 0.75em; font-size: 1em; margin: 0em; } /* Left Corner */ .ui.left.corner.label, .ui.left.corner.label:after { right: auto; left: 0em; } .ui.left.corner.label:after { border-top: 3.25em solid transparent; border-right: 3.25em solid transparent; border-bottom: 0em solid transparent; border-left: 0em solid transparent; border-top-color: inherit; } .ui.left.corner.label .icon { left: -0.75em; } /* Segment */ .ui.segment > .ui.corner.label { top: -1px; right: -1px; } .ui.segment > .ui.left.corner.label { right: auto; left: -1px; } /* Input */ .ui.input > .ui.corner.label { top: 1px; right: 1px; } .ui.input > .ui.right.corner.label { right: auto; left: 1px; } /*------------------- Ribbon --------------------*/ .ui.ribbon.label { position: relative; margin: 0em; min-width: -webkit-max-content; min-width: -moz-max-content; min-width: max-content; border-radius: 0em 0.2857rem 0.2857rem 0em; border-color: rgba(0, 0, 0, 0.15); } .ui.ribbon.label:after { position: absolute; content: ''; top: 100%; left: 0%; background-color: transparent !important; border-style: solid; border-width: 0em 1.2em 1.2em 0em; border-color: transparent; border-right-color: inherit; width: 0em; height: 0em; } /* Right Ribbon */ .ui[class*="right ribbon"].label { text-align: left; -webkit-transform: translateX(-100%); -ms-transform: translateX(-100%); transform: translateX(-100%); border-radius: 0.2857rem 0em 0em 0.2857rem; padding-left: 0.8em; } .ui[class*="right ribbon"].label:after { left: auto; right: 0%; border-style: solid; border-width: 1.2em 1.2em 0em 0em; border-color: transparent; border-top-color: inherit; } /* Positioning */ .ui.ribbon.label { left: -webkit-calc( -1rem - 1.2em ); left: calc( -1rem - 1.2em ); margin-right: -1.2em; padding-left: -webkit-calc( 1rem + 1.2em ); padding-left: calc( 1rem + 1.2em ); } .ui[class*="right ribbon"].label { left: -webkit-calc(100% + 1rem + 1.2em ); left: calc(100% + 1rem + 1.2em ); padding-right: -webkit-calc( 1rem + 1.2em ); padding-right: calc( 1rem + 1.2em ); } /* Inside Image */ .ui.image > .ribbon.label, .ui.card .image > .ribbon.label { position: absolute; top: 1rem; } .ui.card .image > .ui.ribbon.label, .ui.image > .ui.ribbon.label { left: -webkit-calc( 0.05rem - 1.2em ); left: calc( 0.05rem - 1.2em ); padding-left: -webkit-calc( -0.05rem + 1.2em ); padding-left: calc( -0.05rem + 1.2em ); } .ui.card .image > .ui[class*="right ribbon"].label, .ui.image > .ui[class*="right ribbon"].label { left: -webkit-calc(100% + -0.05rem + 1.2em ); left: calc(100% + -0.05rem + 1.2em ); padding-left: 0.8em; padding-right: -webkit-calc( -0.05rem + 1.2em ); padding-right: calc( -0.05rem + 1.2em ); } /*------------------- Attached --------------------*/ .ui.top.attached.label, .ui.attached.label { width: 100%; position: absolute; margin: 0em; top: 0em; left: 0em; padding: 0.75em 1em; border-radius: 0.2857rem 0.2857rem 0em 0em; } .ui.bottom.attached.label { top: auto; bottom: 0em; border-radius: 0em 0em 0.2857rem 0.2857rem; } .ui.top.left.attached.label { width: auto; margin-top: 0em !important; border-radius: 0.2857rem 0em 0.2857rem 0em; } .ui.top.right.attached.label { width: auto; left: auto; right: 0em; border-radius: 0em 0.2857rem 0em 0.2857rem; } .ui.bottom.left.attached.label { width: auto; top: auto; bottom: 0em; border-radius: 0em 0.2857rem 0em 0.2857rem; } .ui.bottom.right.attached.label { top: auto; bottom: 0em; left: auto; right: 0em; width: auto; border-radius: 0.2857rem 0em 0.2857rem 0em; } /******************************* States *******************************/ /*------------------- Disabled --------------------*/ .ui.label.disabled { opacity: 0.5; } /*------------------- Hover --------------------*/ a.ui.labels .label:hover, a.ui.label:hover { background-color: #e0e0e0; border-color: #e0e0e0; background-image: none; color: rgba(0, 0, 0, 0.8); } .ui.labels a.label:hover:before, a.ui.label:hover:before { background-color: #e0e0e0; background-image: none; color: rgba(0, 0, 0, 0.8); } /*------------------- Visible --------------------*/ .ui.labels.visible .label, .ui.label.visible { display: inline-block !important; } /*------------------- Hidden --------------------*/ .ui.labels.hidden .label, .ui.label.hidden { display: none !important; } /******************************* Variations *******************************/ /*------------------- Colors --------------------*/ /*--- Black ---*/ .ui.black.labels .label, .ui.black.label { background-color: #1b1c1d !important; border-color: #1b1c1d !important; color: #ffffff !important; } .ui.labels .black.label:before, .ui.black.labels .label:before, .ui.black.label:before { background-color: #1b1c1d !important; } a.ui.black.labels .label:hover, a.ui.black.label:hover { background-color: #1b1c1d !important; border-color: #1b1c1d !important; } .ui.labels a.black.label:hover:before, .ui.black.labels a.label:hover:before, a.ui.black.label:hover:before { background-color: #1b1c1d !important; } .ui.black.corner.label, .ui.black.corner.label:hover { background-color: transparent !important; } .ui.black.ribbon.label { border-color: #020203 !important; } /*--- Blue ---*/ .ui.blue.labels .label, .ui.blue.label { background-color: #3b83c0 !important; border-color: #3b83c0 !important; color: #ffffff !important; } .ui.labels .blue.label:before, .ui.blue.labels .label:before, .ui.blue.label:before { background-color: #3b83c0 !important; } a.ui.blue.labels .label:hover, .ui.blue.labels a.label:hover, a.ui.blue.label:hover { background-color: #458ac6 !important; border-color: #458ac6 !important; color: #ffffff !important; } .ui.labels a.blue.label:hover:before, .ui.blue.labels a.label:hover:before, a.ui.blue.label:hover:before { background-color: #458ac6 !important; } .ui.blue.corner.label, .ui.blue.corner.label:hover { background-color: transparent !important; } .ui.blue.ribbon.label { border-color: #2f6899 !important; } /*--- Green ---*/ .ui.green.labels .label, .ui.green.label { background-color: #5bbd72 !important; border-color: #5bbd72 !important; color: #ffffff !important; } .ui.labels .green.label:before, .ui.green.labels .label:before, .ui.green.label:before { background-color: #5bbd72 !important; } a.ui.green.labels .label:hover, a.ui.green.label:hover { background-color: #66c17b !important; border-color: #66c17b !important; } .ui.labels a.green.label:hover:before, .ui.green.labels a.label:hover:before, a.ui.green.label:hover:before { background-color: #66c17b !important; } .ui.green.corner.label, .ui.green.corner.label:hover { background-color: transparent !important; } .ui.green.ribbon.label { border-color: #42a359 !important; } /*--- Orange ---*/ .ui.orange.labels .label, .ui.orange.label { background-color: #e07b53 !important; border-color: #e07b53 !important; color: #ffffff !important; } .ui.labels .orange.label:before, .ui.orange.labels .label:before, .ui.orange.label:before { background-color: #e07b53 !important; } a.ui.orange.labels .label:hover, .ui.orange.labels a.label:hover, a.ui.orange.label:hover { background-color: #e28560 !important; border-color: #e28560 !important; color: #ffffff !important; } .ui.labels a.orange.label:hover:before, .ui.orange.labels a.label:hover:before, a.ui.orange.label:hover:before { background-color: #e28560 !important; } .ui.orange.corner.label, .ui.orange.corner.label:hover { background-color: transparent !important; } .ui.orange.ribbon.label { border-color: #d85a28 !important; } /*--- Pink ---*/ .ui.pink.labels .label, .ui.pink.label { background-color: #d9499a !important; border-color: #d9499a !important; color: #ffffff !important; } .ui.labels .pink.label:before, .ui.pink.labels .label:before, .ui.pink.label:before { background-color: #d9499a !important; } a.ui.pink.labels .label:hover, .ui.pink.labels a.label:hover, a.ui.pink.label:hover { background-color: #dc56a1 !important; border-color: #dc56a1 !important; color: #ffffff !important; } .ui.labels a.pink.label:hover:before, .ui.pink.labels a.label:hover:before, a.ui.pink.label:hover:before { background-color: #dc56a1 !important; } .ui.pink.corner.label, .ui.pink.corner.label:hover { background-color: transparent !important; } .ui.pink.ribbon.label { border-color: #c62981 !important; } /*--- Purple ---*/ .ui.purple.labels .label, .ui.purple.label { background-color: #564f8a !important; border-color: #564f8a !important; color: #ffffff !important; } .ui.labels .purple.label:before, .ui.purple.labels .label:before, .ui.purple.label:before { background-color: #564f8a !important; } a.ui.purple.labels .label:hover, .ui.purple.labels a.label:hover, a.ui.purple.label:hover { background-color: #5c5594 !important; border-color: #5c5594 !important; color: #ffffff !important; } .ui.labels a.purple.label:hover:before, .ui.purple.labels a.label:hover:before, a.ui.purple.label:hover:before { background-color: #5c5594 !important; } .ui.purple.corner.label, .ui.purple.corner.label:hover { background-color: transparent !important; } .ui.purple.ribbon.label { border-color: #423c6a !important; } /*--- Red ---*/ .ui.red.labels .label, .ui.red.label { background-color: #d95c5c !important; border-color: #d95c5c !important; color: #ffffff !important; } .ui.labels .red.label:before, .ui.red.labels .label:before, .ui.red.label:before { background-color: #d95c5c !important; } .ui.red.corner.label, .ui.red.corner.label:hover { background-color: transparent !important; } a.ui.red.labels .label:hover, a.ui.red.label:hover { background-color: #dc6868 !important; border-color: #dc6868 !important; color: #ffffff !important; } .ui.labels a.red.label:hover:before, .ui.red.labels a.label:hover:before, a.ui.red.label:hover:before { background-color: #dc6868 !important; } .ui.red.ribbon.label { border-color: #cf3333 !important; } /*--- Teal ---*/ .ui.teal.labels .label, .ui.teal.label { background-color: #00b5ad !important; border-color: #00b5ad !important; color: #ffffff !important; } .ui.labels .teal.label:before, .ui.teal.labels .label:before, .ui.teal.label:before { background-color: #00b5ad !important; } a.ui.teal.labels .label:hover, .ui.teal.labels a.label:hover, a.ui.teal.label:hover { background-color: #00c4bc !important; border-color: #00c4bc !important; color: #ffffff !important; } .ui.labels a.teal.label:hover:before, .ui.teal.labels a.label:hover:before, a.ui.teal.label:hover:before { background-color: #00c4bc !important; } .ui.teal.corner.label, .ui.teal.corner.label:hover { background-color: transparent !important; } .ui.teal.ribbon.label { border-color: #00827c !important; } /*--- Yellow ---*/ .ui.yellow.labels .label, .ui.yellow.label { background-color: #f2c61f !important; border-color: #f2c61f !important; color: #ffffff !important; } .ui.labels .yellow.label:before, .ui.yellow.labels .label:before, .ui.yellow.label:before { background-color: #f2c61f !important; } a.ui.yellow.labels .label:hover, .ui.yellow.labels a.label:hover, a.ui.yellow.label:hover { background-color: #f3ca2d !important; border-color: #f3ca2d !important; color: #ffffff !important; } .ui.labels a.yellow.label:hover:before, .ui.yellow.labels a.label:hover:before, a.ui.yellow.label:hover:before { background-color: #f3ca2d !important; } .ui.yellow.corner.label, .ui.yellow.corner.label:hover { background-color: transparent !important; } .ui.yellow.ribbon.label { border-color: #d2a90c !important; } /*------------------- Fluid --------------------*/ .ui.label.fluid, .ui.fluid.labels > .label { width: 100%; box-sizing: border-box; } /*------------------- Inverted --------------------*/ .ui.inverted.labels .label, .ui.inverted.label { color: #ffffff !important; } /*------------------- Horizontal --------------------*/ .ui.horizontal.labels .label, .ui.horizontal.label { margin: 0em 0.5em 0em 0em; padding: 0.4em 0.8em; min-width: 3em; text-align: center; } /*------------------- Circular --------------------*/ .ui.circular.labels .label, .ui.circular.label { min-width: 2em; min-height: 2em; padding: 0.5em !important; line-height: 1em; text-align: center; border-radius: 500rem; } .ui.empty.circular.labels .label, .ui.empty.circular.label { min-width: 0em; min-height: 0em; overflow: hidden; width: 0.5em; height: 0.5em; vertical-align: baseline; } /*------------------- Pointing --------------------*/ .ui.pointing.label { position: relative; } .ui.attached.pointing.label { position: absolute; } .ui.pointing.label:before { position: absolute; content: ''; -webkit-transform: rotate(45deg); -ms-transform: rotate(45deg); transform: rotate(45deg); background-image: none; z-index: 2; width: 0.6em; height: 0.6em; -webkit-transition: background 0.2s ease; transition: background 0.2s ease; } /*--- Above ---*/ .ui.pointing.label:before { background-color: #e8e8e8; background-image: none; } .ui.pointing.label, .ui.pointing.above.label { margin-top: 1em; } .ui.pointing.label:before, .ui.pointing.above.label:before { margin-left: -0.3em; top: -0.3em; left: 50%; } /*--- Below ---*/ .ui.pointing.bottom.label, .ui.pointing.below.label { margin-top: 0em; margin-bottom: 1em; } .ui.pointing.bottom.label:before, .ui.pointing.below.label:before { margin-left: -0.3em; top: auto; right: auto; bottom: -0.3em; left: 50%; } /*--- Left ---*/ .ui.pointing.left.label { margin-top: 0em; margin-left: 0.6em; } .ui.pointing.left.label:before { margin-top: -0.3em; bottom: auto; right: auto; top: 50%; left: 0em; } /*--- Right ---*/ .ui.pointing.right.label { margin-top: 0em; margin-right: 0.6em; } .ui.pointing.right.label:before { margin-top: -0.3em; right: -0.3em; top: 50%; bottom: auto; left: auto; } /*------------------ Floating Label -------------------*/ .ui.floating.label { position: absolute; z-index: 100; top: -1em; left: 100%; margin: 0em 0em 0em -1.5em !important; } /*------------------- Sizes --------------------*/ .ui.mini.labels .label, .ui.mini.label { font-size: 0.6428rem; } .ui.tiny.labels .label, .ui.tiny.label { font-size: 0.7142rem; } .ui.small.labels .label, .ui.small.label { font-size: 0.7857rem; } .ui.labels .label, .ui.label { font-size: 0.8571rem; } .ui.large.labels .label, .ui.large.label { font-size: 1rem; } .ui.big.labels .label, .ui.big.label { font-size: 1.1428rem; } .ui.huge.labels .label, .ui.huge.label { font-size: 1.2857rem; } .ui.massive.labels .label, .ui.massive.label { font-size: 1.4285rem; } /******************************* Theme Overrides *******************************/ /******************************* Site Overrides *******************************/
codeforchiba/chiba_bicyclemap_ionic
www/lib/semantic-ui/dist/components/label.css
CSS
apache-2.0
20,440
/* * idprom.c: Routines to load the idprom into kernel addresses and * interpret the data contained within. * * Copyright (C) 1995 David S. Miller ([email protected]) * Sun3/3x models added by David Monro ([email protected]) */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/types.h> #include <linux/init.h> #include <linux/string.h> #include <asm/oplib.h> #include <asm/idprom.h> #include <asm/machines.h> /* Fun with Sun released architectures. */ struct idprom *idprom; EXPORT_SYMBOL(idprom); static struct idprom idprom_buffer; /* Here is the master table of Sun machines which use some implementation * of the Sparc CPU and have a meaningful IDPROM machtype value that we * know about. See asm-sparc/machines.h for empirical constants. */ static struct Sun_Machine_Models Sun_Machines[NUM_SUN_MACHINES] = { /* First, Sun3's */ { .name = "Sun 3/160 Series", .id_machtype = (SM_SUN3 | SM_3_160) }, { .name = "Sun 3/50", .id_machtype = (SM_SUN3 | SM_3_50) }, { .name = "Sun 3/260 Series", .id_machtype = (SM_SUN3 | SM_3_260) }, { .name = "Sun 3/110 Series", .id_machtype = (SM_SUN3 | SM_3_110) }, { .name = "Sun 3/60", .id_machtype = (SM_SUN3 | SM_3_60) }, { .name = "Sun 3/E", .id_machtype = (SM_SUN3 | SM_3_E) }, /* Now, Sun3x's */ { .name = "Sun 3/460 Series", .id_machtype = (SM_SUN3X | SM_3_460) }, { .name = "Sun 3/80", .id_machtype = (SM_SUN3X | SM_3_80) }, /* Then, Sun4's */ // { .name = "Sun 4/100 Series", .id_machtype = (SM_SUN4 | SM_4_110) }, // { .name = "Sun 4/200 Series", .id_machtype = (SM_SUN4 | SM_4_260) }, // { .name = "Sun 4/300 Series", .id_machtype = (SM_SUN4 | SM_4_330) }, // { .name = "Sun 4/400 Series", .id_machtype = (SM_SUN4 | SM_4_470) }, /* And now, Sun4c's */ // { .name = "Sun4c SparcStation 1", .id_machtype = (SM_SUN4C | SM_4C_SS1) }, // { .name = "Sun4c SparcStation IPC", .id_machtype = (SM_SUN4C | SM_4C_IPC) }, // { .name = "Sun4c SparcStation 1+", .id_machtype = (SM_SUN4C | SM_4C_SS1PLUS) }, // { .name = "Sun4c SparcStation SLC", .id_machtype = (SM_SUN4C | SM_4C_SLC) }, // { .name = "Sun4c SparcStation 2", .id_machtype = (SM_SUN4C | SM_4C_SS2) }, // { .name = "Sun4c SparcStation ELC", .id_machtype = (SM_SUN4C | SM_4C_ELC) }, // { .name = "Sun4c SparcStation IPX", .id_machtype = (SM_SUN4C | SM_4C_IPX) }, /* Finally, early Sun4m's */ // { .name = "Sun4m SparcSystem600", .id_machtype = (SM_SUN4M | SM_4M_SS60) }, // { .name = "Sun4m SparcStation10/20", .id_machtype = (SM_SUN4M | SM_4M_SS50) }, // { .name = "Sun4m SparcStation5", .id_machtype = (SM_SUN4M | SM_4M_SS40) }, /* One entry for the OBP arch's which are sun4d, sun4e, and newer sun4m's */ // { .name = "Sun4M OBP based system", .id_machtype = (SM_SUN4M_OBP | 0x0) } }; static void __init display_system_type(unsigned char machtype) { register int i; for (i = 0; i < NUM_SUN_MACHINES; i++) { if(Sun_Machines[i].id_machtype == machtype) { if (machtype != (SM_SUN4M_OBP | 0x00)) printk("TYPE: %s\n", Sun_Machines[i].name); else { #if 0 prom_getproperty(prom_root_node, "banner-name", sysname, sizeof(sysname)); printk("TYPE: %s\n", sysname); #endif } return; } } prom_printf("IDPROM: Bogus id_machtype value, 0x%x\n", machtype); prom_halt(); } void sun3_get_model(unsigned char* model) { register int i; for (i = 0; i < NUM_SUN_MACHINES; i++) { if(Sun_Machines[i].id_machtype == idprom->id_machtype) { strcpy(model, Sun_Machines[i].name); return; } } } /* Calculate the IDPROM checksum (xor of the data bytes). */ static unsigned char __init calc_idprom_cksum(struct idprom *idprom) { unsigned char cksum, i, *ptr = (unsigned char *)idprom; for (i = cksum = 0; i <= 0x0E; i++) cksum ^= *ptr++; return cksum; } /* Create a local IDPROM copy, verify integrity, and display information. */ void __init idprom_init(void) { prom_get_idprom((char *) &idprom_buffer, sizeof(idprom_buffer)); idprom = &idprom_buffer; if (idprom->id_format != 0x01) { prom_printf("IDPROM: Unknown format type!\n"); prom_halt(); } if (idprom->id_cksum != calc_idprom_cksum(idprom)) { prom_printf("IDPROM: Checksum failure (nvram=%x, calc=%x)!\n", idprom->id_cksum, calc_idprom_cksum(idprom)); prom_halt(); } display_system_type(idprom->id_machtype); printk("Ethernet address: %pM\n", idprom->id_ethaddr); }
AiJiaZone/linux-4.0
virt/arch/m68k/sun3/idprom.c
C
gpl-2.0
4,391
/* * Thickbox 3.1 - One Box To Rule Them All. * By Cody Lindley (http://www.codylindley.com) * Copyright (c) 2007 cody lindley * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php */ if ( typeof tb_pathToImage != 'string' ) { var tb_pathToImage = thickboxL10n.loadingAnimation; } if ( typeof tb_closeImage != 'string' ) { var tb_closeImage = thickboxL10n.closeImage; } /*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/ //on page load call tb_init jQuery(document).ready(function(){ tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox imgLoader = new Image();// preload image imgLoader.src = tb_pathToImage; }); //add thickbox to href & area elements that have a class of .thickbox function tb_init(domChunk){ jQuery(domChunk).live('click', tb_click); } function tb_click(){ var t = this.title || this.name || null; var a = this.href || this.alt; var g = this.rel || false; tb_show(t,a,g); this.blur(); return false; } function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link try { if (typeof document.body.style.maxHeight === "undefined") {//if IE 6 jQuery("body","html").css({height: "100%", width: "100%"}); jQuery("html").css("overflow","hidden"); if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6 jQuery("body").append("<iframe id='TB_HideSelect'>"+thickboxL10n.noiframes+"</iframe><div id='TB_overlay'></div><div id='TB_window'></div>"); jQuery("#TB_overlay").click(tb_remove); } }else{//all others if(document.getElementById("TB_overlay") === null){ jQuery("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>"); jQuery("#TB_overlay").click(tb_remove); } } if(tb_detectMacXFF()){ jQuery("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash }else{ jQuery("#TB_overlay").addClass("TB_overlayBG");//use background and opacity } if(caption===null){caption="";} jQuery("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page jQuery('#TB_load').show();//show loader var baseURL; if(url.indexOf("?")!==-1){ //ff there is a query string involved baseURL = url.substr(0, url.indexOf("?")); }else{ baseURL = url; } var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/; var urlType = baseURL.toLowerCase().match(urlString); if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images TB_PrevCaption = ""; TB_PrevURL = ""; TB_PrevHTML = ""; TB_NextCaption = ""; TB_NextURL = ""; TB_NextHTML = ""; TB_imageCount = ""; TB_FoundURL = false; if(imageGroup){ TB_TempArray = jQuery("a[rel="+imageGroup+"]").get(); for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) { var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString); if (!(TB_TempArray[TB_Counter].href == url)) { if (TB_FoundURL) { TB_NextCaption = TB_TempArray[TB_Counter].title; TB_NextURL = TB_TempArray[TB_Counter].href; TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>"+thickboxL10n.next+"</a></span>"; } else { TB_PrevCaption = TB_TempArray[TB_Counter].title; TB_PrevURL = TB_TempArray[TB_Counter].href; TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>"+thickboxL10n.prev+"</a></span>"; } } else { TB_FoundURL = true; TB_imageCount = thickboxL10n.image + ' ' + (TB_Counter + 1) + ' ' + thickboxL10n.of + ' ' + (TB_TempArray.length); } } } imgPreloader = new Image(); imgPreloader.onload = function(){ imgPreloader.onload = null; // Resizing large images - orginal by Christian Montoya edited by me. var pagesize = tb_getPageSize(); var x = pagesize[0] - 150; var y = pagesize[1] - 150; var imageWidth = imgPreloader.width; var imageHeight = imgPreloader.height; if (imageWidth > x) { imageHeight = imageHeight * (x / imageWidth); imageWidth = x; if (imageHeight > y) { imageWidth = imageWidth * (y / imageHeight); imageHeight = y; } } else if (imageHeight > y) { imageWidth = imageWidth * (y / imageHeight); imageHeight = y; if (imageWidth > x) { imageHeight = imageHeight * (x / imageWidth); imageWidth = x; } } // End Resizing TB_WIDTH = imageWidth + 30; TB_HEIGHT = imageHeight + 60; jQuery("#TB_window").append("<a href='' id='TB_ImageOff' title='"+thickboxL10n.close+"'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='"+thickboxL10n.close+"'><img src='" + tb_closeImage + "' /></a></div>"); jQuery("#TB_closeWindowButton").click(tb_remove); if (!(TB_PrevHTML === "")) { function goPrev(){ if(jQuery(document).unbind("click",goPrev)){jQuery(document).unbind("click",goPrev);} jQuery("#TB_window").remove(); jQuery("body").append("<div id='TB_window'></div>"); tb_show(TB_PrevCaption, TB_PrevURL, imageGroup); return false; } jQuery("#TB_prev").click(goPrev); } if (!(TB_NextHTML === "")) { function goNext(){ jQuery("#TB_window").remove(); jQuery("body").append("<div id='TB_window'></div>"); tb_show(TB_NextCaption, TB_NextURL, imageGroup); return false; } jQuery("#TB_next").click(goNext); } jQuery(document).bind('keydown.thickbox', function(e){ e.stopImmediatePropagation(); if ( e.which == 27 ){ // close if ( ! jQuery(document).triggerHandler( 'wp_CloseOnEscape', [{ event: e, what: 'thickbox', cb: tb_remove }] ) ) tb_remove(); } else if ( e.which == 190 ){ // display previous image if(!(TB_NextHTML == "")){ jQuery(document).unbind('thickbox'); goNext(); } } else if ( e.which == 188 ){ // display next image if(!(TB_PrevHTML == "")){ jQuery(document).unbind('thickbox'); goPrev(); } } return false; }); tb_position(); jQuery("#TB_load").remove(); jQuery("#TB_ImageOff").click(tb_remove); jQuery("#TB_window").css({'visibility':'visible'}); //for safari using css instead of show }; imgPreloader.src = url; }else{//code to show html var queryString = url.replace(/^[^\?]+\??/,''); var params = tb_parseQuery( queryString ); TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL ajaxContentW = TB_WIDTH - 30; ajaxContentH = TB_HEIGHT - 45; if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window urlNoQuery = url.split('TB_'); jQuery("#TB_iframeContent").remove(); if(params['modal'] != "true"){//iframe no modal jQuery("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='"+thickboxL10n.close+"'><img src='" + tb_closeImage + "' /></a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' >"+thickboxL10n.noiframes+"</iframe>"); }else{//iframe modal jQuery("#TB_overlay").unbind(); jQuery("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'>"+thickboxL10n.noiframes+"</iframe>"); } }else{// not an iframe, ajax if(jQuery("#TB_window").css("visibility") != "visible"){ if(params['modal'] != "true"){//ajax no modal jQuery("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'><img src='" + tb_closeImage + "' /></a></div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>"); }else{//ajax modal jQuery("#TB_overlay").unbind(); jQuery("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>"); } }else{//this means the window is already up, we are just loading new content via ajax jQuery("#TB_ajaxContent")[0].style.width = ajaxContentW +"px"; jQuery("#TB_ajaxContent")[0].style.height = ajaxContentH +"px"; jQuery("#TB_ajaxContent")[0].scrollTop = 0; jQuery("#TB_ajaxWindowTitle").html(caption); } } jQuery("#TB_closeWindowButton").click(tb_remove); if(url.indexOf('TB_inline') != -1){ jQuery("#TB_ajaxContent").append(jQuery('#' + params['inlineId']).children()); jQuery("#TB_window").bind('tb_unload', function () { jQuery('#' + params['inlineId']).append( jQuery("#TB_ajaxContent").children() ); // move elements back when you're finished }); tb_position(); jQuery("#TB_load").remove(); jQuery("#TB_window").css({'visibility':'visible'}); }else if(url.indexOf('TB_iframe') != -1){ tb_position(); if(jQuery.browser.safari){//safari needs help because it will not fire iframe onload jQuery("#TB_load").remove(); jQuery("#TB_window").css({'visibility':'visible'}); } }else{ jQuery("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method tb_position(); jQuery("#TB_load").remove(); tb_init("#TB_ajaxContent a.thickbox"); jQuery("#TB_window").css({'visibility':'visible'}); }); } } if(!params['modal']){ jQuery(document).bind('keyup.thickbox', function(e){ if ( e.which == 27 ){ // close e.stopImmediatePropagation(); if ( ! jQuery(document).triggerHandler( 'wp_CloseOnEscape', [{ event: e, what: 'thickbox', cb: tb_remove }] ) ) tb_remove(); return false; } }); } } catch(e) { //nothing here } } //helper functions below function tb_showIframe(){ jQuery("#TB_load").remove(); jQuery("#TB_window").css({'visibility':'visible'}); } function tb_remove() { jQuery("#TB_imageOff").unbind("click"); jQuery("#TB_closeWindowButton").unbind("click"); jQuery("#TB_window").fadeOut("fast",function(){jQuery('#TB_window,#TB_overlay,#TB_HideSelect').trigger("tb_unload").unbind().remove();}); jQuery("#TB_load").remove(); if (typeof document.body.style.maxHeight == "undefined") {//if IE 6 jQuery("body","html").css({height: "auto", width: "auto"}); jQuery("html").css("overflow",""); } jQuery(document).unbind('.thickbox'); return false; } function tb_position() { var isIE6 = typeof document.body.style.maxHeight === "undefined"; jQuery("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'}); if ( ! isIE6 ) { // take away IE6 jQuery("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'}); } } function tb_parseQuery ( query ) { var Params = {}; if ( ! query ) {return Params;}// return empty object var Pairs = query.split(/[;&]/); for ( var i = 0; i < Pairs.length; i++ ) { var KeyVal = Pairs[i].split('='); if ( ! KeyVal || KeyVal.length != 2 ) {continue;} var key = unescape( KeyVal[0] ); var val = unescape( KeyVal[1] ); val = val.replace(/\+/g, ' '); Params[key] = val; } return Params; } function tb_getPageSize(){ var de = document.documentElement; var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth; var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight; arrayPageSize = [w,h]; return arrayPageSize; } function tb_detectMacXFF() { var userAgent = navigator.userAgent.toLowerCase(); if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) { return true; } }
bckspacecreative/Coffee-Bean-Lv
wp-includes/js/thickbox/thickbox.js
JavaScript
gpl-2.0
12,501
// SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2010 Red Hat Inc. * Author : Dave Airlie <[email protected]> * * ATPX support for both Intel/ATI */ #include <linux/vga_switcheroo.h> #include <linux/slab.h> #include <linux/acpi.h> #include <linux/pci.h> #include <linux/delay.h> #include "amd_acpi.h" #define AMDGPU_PX_QUIRK_FORCE_ATPX (1 << 0) struct amdgpu_px_quirk { u32 chip_vendor; u32 chip_device; u32 subsys_vendor; u32 subsys_device; u32 px_quirk_flags; }; struct amdgpu_atpx_functions { bool px_params; bool power_cntl; bool disp_mux_cntl; bool i2c_mux_cntl; bool switch_start; bool switch_end; bool disp_connectors_mapping; bool disp_detection_ports; }; struct amdgpu_atpx { acpi_handle handle; struct amdgpu_atpx_functions functions; bool is_hybrid; bool dgpu_req_power_for_displays; }; static struct amdgpu_atpx_priv { bool atpx_detected; bool bridge_pm_usable; unsigned int quirks; /* handle for device - and atpx */ acpi_handle dhandle; acpi_handle other_handle; struct amdgpu_atpx atpx; } amdgpu_atpx_priv; struct atpx_verify_interface { u16 size; /* structure size in bytes (includes size field) */ u16 version; /* version */ u32 function_bits; /* supported functions bit vector */ } __packed; struct atpx_px_params { u16 size; /* structure size in bytes (includes size field) */ u32 valid_flags; /* which flags are valid */ u32 flags; /* flags */ } __packed; struct atpx_power_control { u16 size; u8 dgpu_state; } __packed; struct atpx_mux { u16 size; u16 mux; } __packed; bool amdgpu_has_atpx(void) { return amdgpu_atpx_priv.atpx_detected; } bool amdgpu_has_atpx_dgpu_power_cntl(void) { return amdgpu_atpx_priv.atpx.functions.power_cntl; } bool amdgpu_is_atpx_hybrid(void) { return amdgpu_atpx_priv.atpx.is_hybrid; } bool amdgpu_atpx_dgpu_req_power_for_displays(void) { return amdgpu_atpx_priv.atpx.dgpu_req_power_for_displays; } #if defined(CONFIG_ACPI) void *amdgpu_atpx_get_dhandle(void) { return amdgpu_atpx_priv.dhandle; } #endif /** * amdgpu_atpx_call - call an ATPX method * * @handle: acpi handle * @function: the ATPX function to execute * @params: ATPX function params * * Executes the requested ATPX function (all asics). * Returns a pointer to the acpi output buffer. */ static union acpi_object *amdgpu_atpx_call(acpi_handle handle, int function, struct acpi_buffer *params) { acpi_status status; union acpi_object atpx_arg_elements[2]; struct acpi_object_list atpx_arg; struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL }; atpx_arg.count = 2; atpx_arg.pointer = &atpx_arg_elements[0]; atpx_arg_elements[0].type = ACPI_TYPE_INTEGER; atpx_arg_elements[0].integer.value = function; if (params) { atpx_arg_elements[1].type = ACPI_TYPE_BUFFER; atpx_arg_elements[1].buffer.length = params->length; atpx_arg_elements[1].buffer.pointer = params->pointer; } else { /* We need a second fake parameter */ atpx_arg_elements[1].type = ACPI_TYPE_INTEGER; atpx_arg_elements[1].integer.value = 0; } status = acpi_evaluate_object(handle, NULL, &atpx_arg, &buffer); /* Fail only if calling the method fails and ATPX is supported */ if (ACPI_FAILURE(status) && status != AE_NOT_FOUND) { printk("failed to evaluate ATPX got %s\n", acpi_format_exception(status)); kfree(buffer.pointer); return NULL; } return buffer.pointer; } /** * amdgpu_atpx_parse_functions - parse supported functions * * @f: supported functions struct * @mask: supported functions mask from ATPX * * Use the supported functions mask from ATPX function * ATPX_FUNCTION_VERIFY_INTERFACE to determine what functions * are supported (all asics). */ static void amdgpu_atpx_parse_functions(struct amdgpu_atpx_functions *f, u32 mask) { f->px_params = mask & ATPX_GET_PX_PARAMETERS_SUPPORTED; f->power_cntl = mask & ATPX_POWER_CONTROL_SUPPORTED; f->disp_mux_cntl = mask & ATPX_DISPLAY_MUX_CONTROL_SUPPORTED; f->i2c_mux_cntl = mask & ATPX_I2C_MUX_CONTROL_SUPPORTED; f->switch_start = mask & ATPX_GRAPHICS_DEVICE_SWITCH_START_NOTIFICATION_SUPPORTED; f->switch_end = mask & ATPX_GRAPHICS_DEVICE_SWITCH_END_NOTIFICATION_SUPPORTED; f->disp_connectors_mapping = mask & ATPX_GET_DISPLAY_CONNECTORS_MAPPING_SUPPORTED; f->disp_detection_ports = mask & ATPX_GET_DISPLAY_DETECTION_PORTS_SUPPORTED; } /** * amdgpu_atpx_validate_functions - validate ATPX functions * * @atpx: amdgpu atpx struct * * Validate that required functions are enabled (all asics). * returns 0 on success, error on failure. */ static int amdgpu_atpx_validate(struct amdgpu_atpx *atpx) { u32 valid_bits = 0; if (atpx->functions.px_params) { union acpi_object *info; struct atpx_px_params output; size_t size; info = amdgpu_atpx_call(atpx->handle, ATPX_FUNCTION_GET_PX_PARAMETERS, NULL); if (!info) return -EIO; memset(&output, 0, sizeof(output)); size = *(u16 *) info->buffer.pointer; if (size < 10) { printk("ATPX buffer is too small: %zu\n", size); kfree(info); return -EINVAL; } size = min(sizeof(output), size); memcpy(&output, info->buffer.pointer, size); valid_bits = output.flags & output.valid_flags; kfree(info); } /* if separate mux flag is set, mux controls are required */ if (valid_bits & ATPX_SEPARATE_MUX_FOR_I2C) { atpx->functions.i2c_mux_cntl = true; atpx->functions.disp_mux_cntl = true; } /* if any outputs are muxed, mux controls are required */ if (valid_bits & (ATPX_CRT1_RGB_SIGNAL_MUXED | ATPX_TV_SIGNAL_MUXED | ATPX_DFP_SIGNAL_MUXED)) atpx->functions.disp_mux_cntl = true; /* some bioses set these bits rather than flagging power_cntl as supported */ if (valid_bits & (ATPX_DYNAMIC_PX_SUPPORTED | ATPX_DYNAMIC_DGPU_POWER_OFF_SUPPORTED)) atpx->functions.power_cntl = true; atpx->is_hybrid = false; if (valid_bits & ATPX_MS_HYBRID_GFX_SUPPORTED) { if (amdgpu_atpx_priv.quirks & AMDGPU_PX_QUIRK_FORCE_ATPX) { printk("ATPX Hybrid Graphics, forcing to ATPX\n"); atpx->functions.power_cntl = true; atpx->is_hybrid = false; } else { printk("ATPX Hybrid Graphics\n"); /* * Disable legacy PM methods only when pcie port PM is usable, * otherwise the device might fail to power off or power on. */ atpx->functions.power_cntl = !amdgpu_atpx_priv.bridge_pm_usable; atpx->is_hybrid = true; } } atpx->dgpu_req_power_for_displays = false; if (valid_bits & ATPX_DGPU_REQ_POWER_FOR_DISPLAYS) atpx->dgpu_req_power_for_displays = true; return 0; } /** * amdgpu_atpx_verify_interface - verify ATPX * * @atpx: amdgpu atpx struct * * Execute the ATPX_FUNCTION_VERIFY_INTERFACE ATPX function * to initialize ATPX and determine what features are supported * (all asics). * returns 0 on success, error on failure. */ static int amdgpu_atpx_verify_interface(struct amdgpu_atpx *atpx) { union acpi_object *info; struct atpx_verify_interface output; size_t size; int err = 0; info = amdgpu_atpx_call(atpx->handle, ATPX_FUNCTION_VERIFY_INTERFACE, NULL); if (!info) return -EIO; memset(&output, 0, sizeof(output)); size = *(u16 *) info->buffer.pointer; if (size < 8) { printk("ATPX buffer is too small: %zu\n", size); err = -EINVAL; goto out; } size = min(sizeof(output), size); memcpy(&output, info->buffer.pointer, size); /* TODO: check version? */ printk("ATPX version %u, functions 0x%08x\n", output.version, output.function_bits); amdgpu_atpx_parse_functions(&atpx->functions, output.function_bits); out: kfree(info); return err; } /** * amdgpu_atpx_set_discrete_state - power up/down discrete GPU * * @atpx: atpx info struct * @state: discrete GPU state (0 = power down, 1 = power up) * * Execute the ATPX_FUNCTION_POWER_CONTROL ATPX function to * power down/up the discrete GPU (all asics). * Returns 0 on success, error on failure. */ static int amdgpu_atpx_set_discrete_state(struct amdgpu_atpx *atpx, u8 state) { struct acpi_buffer params; union acpi_object *info; struct atpx_power_control input; if (atpx->functions.power_cntl) { input.size = 3; input.dgpu_state = state; params.length = input.size; params.pointer = &input; info = amdgpu_atpx_call(atpx->handle, ATPX_FUNCTION_POWER_CONTROL, &params); if (!info) return -EIO; kfree(info); /* 200ms delay is required after off */ if (state == 0) msleep(200); } return 0; } /** * amdgpu_atpx_switch_disp_mux - switch display mux * * @atpx: atpx info struct * @mux_id: mux state (0 = integrated GPU, 1 = discrete GPU) * * Execute the ATPX_FUNCTION_DISPLAY_MUX_CONTROL ATPX function to * switch the display mux between the discrete GPU and integrated GPU * (all asics). * Returns 0 on success, error on failure. */ static int amdgpu_atpx_switch_disp_mux(struct amdgpu_atpx *atpx, u16 mux_id) { struct acpi_buffer params; union acpi_object *info; struct atpx_mux input; if (atpx->functions.disp_mux_cntl) { input.size = 4; input.mux = mux_id; params.length = input.size; params.pointer = &input; info = amdgpu_atpx_call(atpx->handle, ATPX_FUNCTION_DISPLAY_MUX_CONTROL, &params); if (!info) return -EIO; kfree(info); } return 0; } /** * amdgpu_atpx_switch_i2c_mux - switch i2c/hpd mux * * @atpx: atpx info struct * @mux_id: mux state (0 = integrated GPU, 1 = discrete GPU) * * Execute the ATPX_FUNCTION_I2C_MUX_CONTROL ATPX function to * switch the i2c/hpd mux between the discrete GPU and integrated GPU * (all asics). * Returns 0 on success, error on failure. */ static int amdgpu_atpx_switch_i2c_mux(struct amdgpu_atpx *atpx, u16 mux_id) { struct acpi_buffer params; union acpi_object *info; struct atpx_mux input; if (atpx->functions.i2c_mux_cntl) { input.size = 4; input.mux = mux_id; params.length = input.size; params.pointer = &input; info = amdgpu_atpx_call(atpx->handle, ATPX_FUNCTION_I2C_MUX_CONTROL, &params); if (!info) return -EIO; kfree(info); } return 0; } /** * amdgpu_atpx_switch_start - notify the sbios of a GPU switch * * @atpx: atpx info struct * @mux_id: mux state (0 = integrated GPU, 1 = discrete GPU) * * Execute the ATPX_FUNCTION_GRAPHICS_DEVICE_SWITCH_START_NOTIFICATION ATPX * function to notify the sbios that a switch between the discrete GPU and * integrated GPU has begun (all asics). * Returns 0 on success, error on failure. */ static int amdgpu_atpx_switch_start(struct amdgpu_atpx *atpx, u16 mux_id) { struct acpi_buffer params; union acpi_object *info; struct atpx_mux input; if (atpx->functions.switch_start) { input.size = 4; input.mux = mux_id; params.length = input.size; params.pointer = &input; info = amdgpu_atpx_call(atpx->handle, ATPX_FUNCTION_GRAPHICS_DEVICE_SWITCH_START_NOTIFICATION, &params); if (!info) return -EIO; kfree(info); } return 0; } /** * amdgpu_atpx_switch_end - notify the sbios of a GPU switch * * @atpx: atpx info struct * @mux_id: mux state (0 = integrated GPU, 1 = discrete GPU) * * Execute the ATPX_FUNCTION_GRAPHICS_DEVICE_SWITCH_END_NOTIFICATION ATPX * function to notify the sbios that a switch between the discrete GPU and * integrated GPU has ended (all asics). * Returns 0 on success, error on failure. */ static int amdgpu_atpx_switch_end(struct amdgpu_atpx *atpx, u16 mux_id) { struct acpi_buffer params; union acpi_object *info; struct atpx_mux input; if (atpx->functions.switch_end) { input.size = 4; input.mux = mux_id; params.length = input.size; params.pointer = &input; info = amdgpu_atpx_call(atpx->handle, ATPX_FUNCTION_GRAPHICS_DEVICE_SWITCH_END_NOTIFICATION, &params); if (!info) return -EIO; kfree(info); } return 0; } /** * amdgpu_atpx_switchto - switch to the requested GPU * * @id: GPU to switch to * * Execute the necessary ATPX functions to switch between the discrete GPU and * integrated GPU (all asics). * Returns 0 on success, error on failure. */ static int amdgpu_atpx_switchto(enum vga_switcheroo_client_id id) { u16 gpu_id; if (id == VGA_SWITCHEROO_IGD) gpu_id = ATPX_INTEGRATED_GPU; else gpu_id = ATPX_DISCRETE_GPU; amdgpu_atpx_switch_start(&amdgpu_atpx_priv.atpx, gpu_id); amdgpu_atpx_switch_disp_mux(&amdgpu_atpx_priv.atpx, gpu_id); amdgpu_atpx_switch_i2c_mux(&amdgpu_atpx_priv.atpx, gpu_id); amdgpu_atpx_switch_end(&amdgpu_atpx_priv.atpx, gpu_id); return 0; } /** * amdgpu_atpx_power_state - power down/up the requested GPU * * @id: GPU to power down/up * @state: requested power state (0 = off, 1 = on) * * Execute the necessary ATPX function to power down/up the discrete GPU * (all asics). * Returns 0 on success, error on failure. */ static int amdgpu_atpx_power_state(enum vga_switcheroo_client_id id, enum vga_switcheroo_state state) { /* on w500 ACPI can't change intel gpu state */ if (id == VGA_SWITCHEROO_IGD) return 0; amdgpu_atpx_set_discrete_state(&amdgpu_atpx_priv.atpx, state); return 0; } /** * amdgpu_atpx_pci_probe_handle - look up the ATPX handle * * @pdev: pci device * * Look up the ATPX handles (all asics). * Returns true if the handles are found, false if not. */ static bool amdgpu_atpx_pci_probe_handle(struct pci_dev *pdev) { acpi_handle dhandle, atpx_handle; acpi_status status; dhandle = ACPI_HANDLE(&pdev->dev); if (!dhandle) return false; status = acpi_get_handle(dhandle, "ATPX", &atpx_handle); if (ACPI_FAILURE(status)) { amdgpu_atpx_priv.other_handle = dhandle; return false; } amdgpu_atpx_priv.dhandle = dhandle; amdgpu_atpx_priv.atpx.handle = atpx_handle; return true; } /** * amdgpu_atpx_init - verify the ATPX interface * * Verify the ATPX interface (all asics). * Returns 0 on success, error on failure. */ static int amdgpu_atpx_init(void) { int r; /* set up the ATPX handle */ r = amdgpu_atpx_verify_interface(&amdgpu_atpx_priv.atpx); if (r) return r; /* validate the atpx setup */ r = amdgpu_atpx_validate(&amdgpu_atpx_priv.atpx); if (r) return r; return 0; } /** * amdgpu_atpx_get_client_id - get the client id * * @pdev: pci device * * look up whether we are the integrated or discrete GPU (all asics). * Returns the client id. */ static enum vga_switcheroo_client_id amdgpu_atpx_get_client_id(struct pci_dev *pdev) { if (amdgpu_atpx_priv.dhandle == ACPI_HANDLE(&pdev->dev)) return VGA_SWITCHEROO_IGD; else return VGA_SWITCHEROO_DIS; } static const struct vga_switcheroo_handler amdgpu_atpx_handler = { .switchto = amdgpu_atpx_switchto, .power_state = amdgpu_atpx_power_state, .get_client_id = amdgpu_atpx_get_client_id, }; static const struct amdgpu_px_quirk amdgpu_px_quirk_list[] = { /* HG _PR3 doesn't seem to work on this A+A weston board */ { 0x1002, 0x6900, 0x1002, 0x0124, AMDGPU_PX_QUIRK_FORCE_ATPX }, { 0x1002, 0x6900, 0x1028, 0x0812, AMDGPU_PX_QUIRK_FORCE_ATPX }, { 0x1002, 0x6900, 0x1028, 0x0813, AMDGPU_PX_QUIRK_FORCE_ATPX }, { 0x1002, 0x699f, 0x1028, 0x0814, AMDGPU_PX_QUIRK_FORCE_ATPX }, { 0x1002, 0x6900, 0x1025, 0x125A, AMDGPU_PX_QUIRK_FORCE_ATPX }, { 0x1002, 0x6900, 0x17AA, 0x3806, AMDGPU_PX_QUIRK_FORCE_ATPX }, { 0, 0, 0, 0, 0 }, }; static void amdgpu_atpx_get_quirks(struct pci_dev *pdev) { const struct amdgpu_px_quirk *p = amdgpu_px_quirk_list; /* Apply PX quirks */ while (p && p->chip_device != 0) { if (pdev->vendor == p->chip_vendor && pdev->device == p->chip_device && pdev->subsystem_vendor == p->subsys_vendor && pdev->subsystem_device == p->subsys_device) { amdgpu_atpx_priv.quirks |= p->px_quirk_flags; break; } ++p; } } /** * amdgpu_atpx_detect - detect whether we have PX * * Check if we have a PX system (all asics). * Returns true if we have a PX system, false if not. */ static bool amdgpu_atpx_detect(void) { char acpi_method_name[255] = { 0 }; struct acpi_buffer buffer = {sizeof(acpi_method_name), acpi_method_name}; struct pci_dev *pdev = NULL; bool has_atpx = false; int vga_count = 0; bool d3_supported = false; struct pci_dev *parent_pdev; while ((pdev = pci_get_class(PCI_CLASS_DISPLAY_VGA << 8, pdev)) != NULL) { vga_count++; has_atpx |= amdgpu_atpx_pci_probe_handle(pdev); parent_pdev = pci_upstream_bridge(pdev); d3_supported |= parent_pdev && parent_pdev->bridge_d3; amdgpu_atpx_get_quirks(pdev); } while ((pdev = pci_get_class(PCI_CLASS_DISPLAY_OTHER << 8, pdev)) != NULL) { vga_count++; has_atpx |= amdgpu_atpx_pci_probe_handle(pdev); parent_pdev = pci_upstream_bridge(pdev); d3_supported |= parent_pdev && parent_pdev->bridge_d3; amdgpu_atpx_get_quirks(pdev); } if (has_atpx && vga_count == 2) { acpi_get_name(amdgpu_atpx_priv.atpx.handle, ACPI_FULL_PATHNAME, &buffer); pr_info("vga_switcheroo: detected switching method %s handle\n", acpi_method_name); amdgpu_atpx_priv.atpx_detected = true; amdgpu_atpx_priv.bridge_pm_usable = d3_supported; amdgpu_atpx_init(); return true; } return false; } /** * amdgpu_register_atpx_handler - register with vga_switcheroo * * Register the PX callbacks with vga_switcheroo (all asics). */ void amdgpu_register_atpx_handler(void) { bool r; enum vga_switcheroo_handler_flags_t handler_flags = 0; /* detect if we have any ATPX + 2 VGA in the system */ r = amdgpu_atpx_detect(); if (!r) return; vga_switcheroo_register_handler(&amdgpu_atpx_handler, handler_flags); } /** * amdgpu_unregister_atpx_handler - unregister with vga_switcheroo * * Unregister the PX callbacks with vga_switcheroo (all asics). */ void amdgpu_unregister_atpx_handler(void) { vga_switcheroo_unregister_handler(); }
openwrt-es/linux
drivers/gpu/drm/amd/amdgpu/amdgpu_atpx_handler.c
C
gpl-2.0
17,540
/* * fs/nfs/idmap.c * * UID and GID to name mapping for clients. * * Copyright (c) 2002 The Regents of the University of Michigan. * All rights reserved. * * Marius Aamodt Eriksen <[email protected]> * * 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. * 3. Neither the name of the University nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED ``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 REGENTS 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 <linux/types.h> #include <linux/parser.h> #include <linux/fs.h> #include <net/net_namespace.h> #include <linux/sunrpc/rpc_pipe_fs.h> #include <linux/nfs_fs.h> #include <linux/nfs_fs_sb.h> #include <linux/key.h> #include <linux/keyctl.h> #include <linux/key-type.h> #include <keys/user-type.h> #include <linux/module.h> #include "internal.h" #include "netns.h" #include "nfs4idmap.h" #include "nfs4trace.h" #define NFS_UINT_MAXLEN 11 static const struct cred *id_resolver_cache; static struct key_type key_type_id_resolver_legacy; struct idmap_legacy_upcalldata { struct rpc_pipe_msg pipe_msg; struct idmap_msg idmap_msg; struct key_construction *key_cons; struct idmap *idmap; }; struct idmap { struct rpc_pipe_dir_object idmap_pdo; struct rpc_pipe *idmap_pipe; struct idmap_legacy_upcalldata *idmap_upcall_data; struct mutex idmap_mutex; }; /** * nfs_fattr_init_names - initialise the nfs_fattr owner_name/group_name fields * @fattr: fully initialised struct nfs_fattr * @owner_name: owner name string cache * @group_name: group name string cache */ void nfs_fattr_init_names(struct nfs_fattr *fattr, struct nfs4_string *owner_name, struct nfs4_string *group_name) { fattr->owner_name = owner_name; fattr->group_name = group_name; } static void nfs_fattr_free_owner_name(struct nfs_fattr *fattr) { fattr->valid &= ~NFS_ATTR_FATTR_OWNER_NAME; kfree(fattr->owner_name->data); } static void nfs_fattr_free_group_name(struct nfs_fattr *fattr) { fattr->valid &= ~NFS_ATTR_FATTR_GROUP_NAME; kfree(fattr->group_name->data); } static bool nfs_fattr_map_owner_name(struct nfs_server *server, struct nfs_fattr *fattr) { struct nfs4_string *owner = fattr->owner_name; kuid_t uid; if (!(fattr->valid & NFS_ATTR_FATTR_OWNER_NAME)) return false; if (nfs_map_name_to_uid(server, owner->data, owner->len, &uid) == 0) { fattr->uid = uid; fattr->valid |= NFS_ATTR_FATTR_OWNER; } return true; } static bool nfs_fattr_map_group_name(struct nfs_server *server, struct nfs_fattr *fattr) { struct nfs4_string *group = fattr->group_name; kgid_t gid; if (!(fattr->valid & NFS_ATTR_FATTR_GROUP_NAME)) return false; if (nfs_map_group_to_gid(server, group->data, group->len, &gid) == 0) { fattr->gid = gid; fattr->valid |= NFS_ATTR_FATTR_GROUP; } return true; } /** * nfs_fattr_free_names - free up the NFSv4 owner and group strings * @fattr: a fully initialised nfs_fattr structure */ void nfs_fattr_free_names(struct nfs_fattr *fattr) { if (fattr->valid & NFS_ATTR_FATTR_OWNER_NAME) nfs_fattr_free_owner_name(fattr); if (fattr->valid & NFS_ATTR_FATTR_GROUP_NAME) nfs_fattr_free_group_name(fattr); } /** * nfs_fattr_map_and_free_names - map owner/group strings into uid/gid and free * @server: pointer to the filesystem nfs_server structure * @fattr: a fully initialised nfs_fattr structure * * This helper maps the cached NFSv4 owner/group strings in fattr into * their numeric uid/gid equivalents, and then frees the cached strings. */ void nfs_fattr_map_and_free_names(struct nfs_server *server, struct nfs_fattr *fattr) { if (nfs_fattr_map_owner_name(server, fattr)) nfs_fattr_free_owner_name(fattr); if (nfs_fattr_map_group_name(server, fattr)) nfs_fattr_free_group_name(fattr); } int nfs_map_string_to_numeric(const char *name, size_t namelen, __u32 *res) { unsigned long val; char buf[16]; if (memchr(name, '@', namelen) != NULL || namelen >= sizeof(buf)) return 0; memcpy(buf, name, namelen); buf[namelen] = '\0'; if (kstrtoul(buf, 0, &val) != 0) return 0; *res = val; return 1; } EXPORT_SYMBOL_GPL(nfs_map_string_to_numeric); static int nfs_map_numeric_to_string(__u32 id, char *buf, size_t buflen) { return snprintf(buf, buflen, "%u", id); } static struct key_type key_type_id_resolver = { .name = "id_resolver", .preparse = user_preparse, .free_preparse = user_free_preparse, .instantiate = generic_key_instantiate, .revoke = user_revoke, .destroy = user_destroy, .describe = user_describe, .read = user_read, }; static int nfs_idmap_init_keyring(void) { struct cred *cred; struct key *keyring; int ret = 0; printk(KERN_NOTICE "NFS: Registering the %s key type\n", key_type_id_resolver.name); cred = prepare_kernel_cred(NULL); if (!cred) return -ENOMEM; keyring = keyring_alloc(".id_resolver", GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, cred, (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_VIEW | KEY_USR_READ, KEY_ALLOC_NOT_IN_QUOTA, NULL); if (IS_ERR(keyring)) { ret = PTR_ERR(keyring); goto failed_put_cred; } ret = register_key_type(&key_type_id_resolver); if (ret < 0) goto failed_put_key; ret = register_key_type(&key_type_id_resolver_legacy); if (ret < 0) goto failed_reg_legacy; set_bit(KEY_FLAG_ROOT_CAN_CLEAR, &keyring->flags); cred->thread_keyring = keyring; cred->jit_keyring = KEY_REQKEY_DEFL_THREAD_KEYRING; id_resolver_cache = cred; return 0; failed_reg_legacy: unregister_key_type(&key_type_id_resolver); failed_put_key: key_put(keyring); failed_put_cred: put_cred(cred); return ret; } static void nfs_idmap_quit_keyring(void) { key_revoke(id_resolver_cache->thread_keyring); unregister_key_type(&key_type_id_resolver); unregister_key_type(&key_type_id_resolver_legacy); put_cred(id_resolver_cache); } /* * Assemble the description to pass to request_key() * This function will allocate a new string and update dest to point * at it. The caller is responsible for freeing dest. * * On error 0 is returned. Otherwise, the length of dest is returned. */ static ssize_t nfs_idmap_get_desc(const char *name, size_t namelen, const char *type, size_t typelen, char **desc) { char *cp; size_t desclen = typelen + namelen + 2; *desc = kmalloc(desclen, GFP_KERNEL); if (!*desc) return -ENOMEM; cp = *desc; memcpy(cp, type, typelen); cp += typelen; *cp++ = ':'; memcpy(cp, name, namelen); cp += namelen; *cp = '\0'; return desclen; } static struct key *nfs_idmap_request_key(const char *name, size_t namelen, const char *type, struct idmap *idmap) { char *desc; struct key *rkey; ssize_t ret; ret = nfs_idmap_get_desc(name, namelen, type, strlen(type), &desc); if (ret <= 0) return ERR_PTR(ret); rkey = request_key(&key_type_id_resolver, desc, ""); if (IS_ERR(rkey)) { mutex_lock(&idmap->idmap_mutex); rkey = request_key_with_auxdata(&key_type_id_resolver_legacy, desc, "", 0, idmap); mutex_unlock(&idmap->idmap_mutex); } if (!IS_ERR(rkey)) set_bit(KEY_FLAG_ROOT_CAN_INVAL, &rkey->flags); kfree(desc); return rkey; } static ssize_t nfs_idmap_get_key(const char *name, size_t namelen, const char *type, void *data, size_t data_size, struct idmap *idmap) { const struct cred *saved_cred; struct key *rkey; struct user_key_payload *payload; ssize_t ret; saved_cred = override_creds(id_resolver_cache); rkey = nfs_idmap_request_key(name, namelen, type, idmap); revert_creds(saved_cred); if (IS_ERR(rkey)) { ret = PTR_ERR(rkey); goto out; } rcu_read_lock(); rkey->perm |= KEY_USR_VIEW; ret = key_validate(rkey); if (ret < 0) goto out_up; payload = rcu_dereference(rkey->payload.rcudata); if (IS_ERR_OR_NULL(payload)) { ret = PTR_ERR(payload); goto out_up; } ret = payload->datalen; if (ret > 0 && ret <= data_size) memcpy(data, payload->data, ret); else ret = -EINVAL; out_up: rcu_read_unlock(); key_put(rkey); out: return ret; } /* ID -> Name */ static ssize_t nfs_idmap_lookup_name(__u32 id, const char *type, char *buf, size_t buflen, struct idmap *idmap) { char id_str[NFS_UINT_MAXLEN]; int id_len; ssize_t ret; id_len = snprintf(id_str, sizeof(id_str), "%u", id); ret = nfs_idmap_get_key(id_str, id_len, type, buf, buflen, idmap); if (ret < 0) return -EINVAL; return ret; } /* Name -> ID */ static int nfs_idmap_lookup_id(const char *name, size_t namelen, const char *type, __u32 *id, struct idmap *idmap) { char id_str[NFS_UINT_MAXLEN]; long id_long; ssize_t data_size; int ret = 0; data_size = nfs_idmap_get_key(name, namelen, type, id_str, NFS_UINT_MAXLEN, idmap); if (data_size <= 0) { ret = -EINVAL; } else { ret = kstrtol(id_str, 10, &id_long); *id = (__u32)id_long; } return ret; } /* idmap classic begins here */ enum { Opt_find_uid, Opt_find_gid, Opt_find_user, Opt_find_group, Opt_find_err }; static const match_table_t nfs_idmap_tokens = { { Opt_find_uid, "uid:%s" }, { Opt_find_gid, "gid:%s" }, { Opt_find_user, "user:%s" }, { Opt_find_group, "group:%s" }, { Opt_find_err, NULL } }; static int nfs_idmap_legacy_upcall(struct key_construction *, const char *, void *); static ssize_t idmap_pipe_downcall(struct file *, const char __user *, size_t); static void idmap_release_pipe(struct inode *); static void idmap_pipe_destroy_msg(struct rpc_pipe_msg *); static const struct rpc_pipe_ops idmap_upcall_ops = { .upcall = rpc_pipe_generic_upcall, .downcall = idmap_pipe_downcall, .release_pipe = idmap_release_pipe, .destroy_msg = idmap_pipe_destroy_msg, }; static struct key_type key_type_id_resolver_legacy = { .name = "id_legacy", .preparse = user_preparse, .free_preparse = user_free_preparse, .instantiate = generic_key_instantiate, .revoke = user_revoke, .destroy = user_destroy, .describe = user_describe, .read = user_read, .request_key = nfs_idmap_legacy_upcall, }; static void nfs_idmap_pipe_destroy(struct dentry *dir, struct rpc_pipe_dir_object *pdo) { struct idmap *idmap = pdo->pdo_data; struct rpc_pipe *pipe = idmap->idmap_pipe; if (pipe->dentry) { rpc_unlink(pipe->dentry); pipe->dentry = NULL; } } static int nfs_idmap_pipe_create(struct dentry *dir, struct rpc_pipe_dir_object *pdo) { struct idmap *idmap = pdo->pdo_data; struct rpc_pipe *pipe = idmap->idmap_pipe; struct dentry *dentry; dentry = rpc_mkpipe_dentry(dir, "idmap", idmap, pipe); if (IS_ERR(dentry)) return PTR_ERR(dentry); pipe->dentry = dentry; return 0; } static const struct rpc_pipe_dir_object_ops nfs_idmap_pipe_dir_object_ops = { .create = nfs_idmap_pipe_create, .destroy = nfs_idmap_pipe_destroy, }; int nfs_idmap_new(struct nfs_client *clp) { struct idmap *idmap; struct rpc_pipe *pipe; int error; idmap = kzalloc(sizeof(*idmap), GFP_KERNEL); if (idmap == NULL) return -ENOMEM; rpc_init_pipe_dir_object(&idmap->idmap_pdo, &nfs_idmap_pipe_dir_object_ops, idmap); pipe = rpc_mkpipe_data(&idmap_upcall_ops, 0); if (IS_ERR(pipe)) { error = PTR_ERR(pipe); goto err; } idmap->idmap_pipe = pipe; mutex_init(&idmap->idmap_mutex); error = rpc_add_pipe_dir_object(clp->cl_net, &clp->cl_rpcclient->cl_pipedir_objects, &idmap->idmap_pdo); if (error) goto err_destroy_pipe; clp->cl_idmap = idmap; return 0; err_destroy_pipe: rpc_destroy_pipe_data(idmap->idmap_pipe); err: kfree(idmap); return error; } void nfs_idmap_delete(struct nfs_client *clp) { struct idmap *idmap = clp->cl_idmap; if (!idmap) return; clp->cl_idmap = NULL; rpc_remove_pipe_dir_object(clp->cl_net, &clp->cl_rpcclient->cl_pipedir_objects, &idmap->idmap_pdo); rpc_destroy_pipe_data(idmap->idmap_pipe); kfree(idmap); } int nfs_idmap_init(void) { return nfs_idmap_init_keyring(); } void nfs_idmap_quit(void) { nfs_idmap_quit_keyring(); } static int nfs_idmap_prepare_message(char *desc, struct idmap *idmap, struct idmap_msg *im, struct rpc_pipe_msg *msg) { substring_t substr; int token, ret; im->im_type = IDMAP_TYPE_GROUP; token = match_token(desc, nfs_idmap_tokens, &substr); switch (token) { case Opt_find_uid: im->im_type = IDMAP_TYPE_USER; case Opt_find_gid: im->im_conv = IDMAP_CONV_NAMETOID; ret = match_strlcpy(im->im_name, &substr, IDMAP_NAMESZ); break; case Opt_find_user: im->im_type = IDMAP_TYPE_USER; case Opt_find_group: im->im_conv = IDMAP_CONV_IDTONAME; ret = match_int(&substr, &im->im_id); break; default: ret = -EINVAL; goto out; } msg->data = im; msg->len = sizeof(struct idmap_msg); out: return ret; } static bool nfs_idmap_prepare_pipe_upcall(struct idmap *idmap, struct idmap_legacy_upcalldata *data) { if (idmap->idmap_upcall_data != NULL) { WARN_ON_ONCE(1); return false; } idmap->idmap_upcall_data = data; return true; } static void nfs_idmap_complete_pipe_upcall_locked(struct idmap *idmap, int ret) { struct key_construction *cons = idmap->idmap_upcall_data->key_cons; kfree(idmap->idmap_upcall_data); idmap->idmap_upcall_data = NULL; complete_request_key(cons, ret); } static void nfs_idmap_abort_pipe_upcall(struct idmap *idmap, int ret) { if (idmap->idmap_upcall_data != NULL) nfs_idmap_complete_pipe_upcall_locked(idmap, ret); } static int nfs_idmap_legacy_upcall(struct key_construction *cons, const char *op, void *aux) { struct idmap_legacy_upcalldata *data; struct rpc_pipe_msg *msg; struct idmap_msg *im; struct idmap *idmap = (struct idmap *)aux; struct key *key = cons->key; int ret = -ENOMEM; /* msg and im are freed in idmap_pipe_destroy_msg */ data = kzalloc(sizeof(*data), GFP_KERNEL); if (!data) goto out1; msg = &data->pipe_msg; im = &data->idmap_msg; data->idmap = idmap; data->key_cons = cons; ret = nfs_idmap_prepare_message(key->description, idmap, im, msg); if (ret < 0) goto out2; ret = -EAGAIN; if (!nfs_idmap_prepare_pipe_upcall(idmap, data)) goto out2; ret = rpc_queue_upcall(idmap->idmap_pipe, msg); if (ret < 0) nfs_idmap_abort_pipe_upcall(idmap, ret); return ret; out2: kfree(data); out1: complete_request_key(cons, ret); return ret; } static int nfs_idmap_instantiate(struct key *key, struct key *authkey, char *data, size_t datalen) { return key_instantiate_and_link(key, data, datalen, id_resolver_cache->thread_keyring, authkey); } static int nfs_idmap_read_and_verify_message(struct idmap_msg *im, struct idmap_msg *upcall, struct key *key, struct key *authkey) { char id_str[NFS_UINT_MAXLEN]; size_t len; int ret = -ENOKEY; /* ret = -ENOKEY */ if (upcall->im_type != im->im_type || upcall->im_conv != im->im_conv) goto out; switch (im->im_conv) { case IDMAP_CONV_NAMETOID: if (strcmp(upcall->im_name, im->im_name) != 0) break; /* Note: here we store the NUL terminator too */ len = sprintf(id_str, "%d", im->im_id) + 1; ret = nfs_idmap_instantiate(key, authkey, id_str, len); break; case IDMAP_CONV_IDTONAME: if (upcall->im_id != im->im_id) break; len = strlen(im->im_name); ret = nfs_idmap_instantiate(key, authkey, im->im_name, len); break; default: ret = -EINVAL; } out: return ret; } static ssize_t idmap_pipe_downcall(struct file *filp, const char __user *src, size_t mlen) { struct rpc_inode *rpci = RPC_I(file_inode(filp)); struct idmap *idmap = (struct idmap *)rpci->private; struct key_construction *cons; struct idmap_msg im; size_t namelen_in; int ret = -ENOKEY; /* If instantiation is successful, anyone waiting for key construction * will have been woken up and someone else may now have used * idmap_key_cons - so after this point we may no longer touch it. */ if (idmap->idmap_upcall_data == NULL) goto out_noupcall; cons = idmap->idmap_upcall_data->key_cons; if (mlen != sizeof(im)) { ret = -ENOSPC; goto out; } if (copy_from_user(&im, src, mlen) != 0) { ret = -EFAULT; goto out; } if (!(im.im_status & IDMAP_STATUS_SUCCESS)) { ret = -ENOKEY; goto out; } namelen_in = strnlen(im.im_name, IDMAP_NAMESZ); if (namelen_in == 0 || namelen_in == IDMAP_NAMESZ) { ret = -EINVAL; goto out; } ret = nfs_idmap_read_and_verify_message(&im, &idmap->idmap_upcall_data->idmap_msg, cons->key, cons->authkey); if (ret >= 0) { key_set_timeout(cons->key, nfs_idmap_cache_timeout); ret = mlen; } out: nfs_idmap_complete_pipe_upcall_locked(idmap, ret); out_noupcall: return ret; } static void idmap_pipe_destroy_msg(struct rpc_pipe_msg *msg) { struct idmap_legacy_upcalldata *data = container_of(msg, struct idmap_legacy_upcalldata, pipe_msg); struct idmap *idmap = data->idmap; if (msg->errno) nfs_idmap_abort_pipe_upcall(idmap, msg->errno); } static void idmap_release_pipe(struct inode *inode) { struct rpc_inode *rpci = RPC_I(inode); struct idmap *idmap = (struct idmap *)rpci->private; nfs_idmap_abort_pipe_upcall(idmap, -EPIPE); } int nfs_map_name_to_uid(const struct nfs_server *server, const char *name, size_t namelen, kuid_t *uid) { struct idmap *idmap = server->nfs_client->cl_idmap; __u32 id = -1; int ret = 0; if (!nfs_map_string_to_numeric(name, namelen, &id)) ret = nfs_idmap_lookup_id(name, namelen, "uid", &id, idmap); if (ret == 0) { *uid = make_kuid(&init_user_ns, id); if (!uid_valid(*uid)) ret = -ERANGE; } trace_nfs4_map_name_to_uid(name, namelen, id, ret); return ret; } int nfs_map_group_to_gid(const struct nfs_server *server, const char *name, size_t namelen, kgid_t *gid) { struct idmap *idmap = server->nfs_client->cl_idmap; __u32 id = -1; int ret = 0; if (!nfs_map_string_to_numeric(name, namelen, &id)) ret = nfs_idmap_lookup_id(name, namelen, "gid", &id, idmap); if (ret == 0) { *gid = make_kgid(&init_user_ns, id); if (!gid_valid(*gid)) ret = -ERANGE; } trace_nfs4_map_group_to_gid(name, namelen, id, ret); return ret; } int nfs_map_uid_to_name(const struct nfs_server *server, kuid_t uid, char *buf, size_t buflen) { struct idmap *idmap = server->nfs_client->cl_idmap; int ret = -EINVAL; __u32 id; id = from_kuid(&init_user_ns, uid); if (!(server->caps & NFS_CAP_UIDGID_NOMAP)) ret = nfs_idmap_lookup_name(id, "user", buf, buflen, idmap); if (ret < 0) ret = nfs_map_numeric_to_string(id, buf, buflen); trace_nfs4_map_uid_to_name(buf, ret, id, ret); return ret; } int nfs_map_gid_to_group(const struct nfs_server *server, kgid_t gid, char *buf, size_t buflen) { struct idmap *idmap = server->nfs_client->cl_idmap; int ret = -EINVAL; __u32 id; id = from_kgid(&init_user_ns, gid); if (!(server->caps & NFS_CAP_UIDGID_NOMAP)) ret = nfs_idmap_lookup_name(id, "group", buf, buflen, idmap); if (ret < 0) ret = nfs_map_numeric_to_string(id, buf, buflen); trace_nfs4_map_gid_to_group(buf, ret, id, ret); return ret; }
Seagate/SMR_FS-EXT4
kernel/fs/nfs/nfs4idmap.c
C
gpl-2.0
19,849
/* Copyright (c) 2011, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html version: 2.9.0 */ (function () { var lang = YAHOO.lang, util = YAHOO.util, Ev = util.Event; /** * The DataSource utility provides a common configurable interface for widgets to * access a variety of data, from JavaScript arrays to online database servers. * * @module datasource * @requires yahoo, event * @optional json, get, connection * @title DataSource Utility */ /****************************************************************************/ /****************************************************************************/ /****************************************************************************/ /** * Base class for the YUI DataSource utility. * * @namespace YAHOO.util * @class YAHOO.util.DataSourceBase * @constructor * @param oLiveData {HTMLElement} Pointer to live data. * @param oConfigs {object} (optional) Object literal of configuration values. */ util.DataSourceBase = function(oLiveData, oConfigs) { if(oLiveData === null || oLiveData === undefined) { return; } this.liveData = oLiveData; this._oQueue = {interval:null, conn:null, requests:[]}; this.responseSchema = {}; // Set any config params passed in to override defaults if(oConfigs && (oConfigs.constructor == Object)) { for(var sConfig in oConfigs) { if(sConfig) { this[sConfig] = oConfigs[sConfig]; } } } // Validate and initialize public configs var maxCacheEntries = this.maxCacheEntries; if(!lang.isNumber(maxCacheEntries) || (maxCacheEntries < 0)) { maxCacheEntries = 0; } // Initialize interval tracker this._aIntervals = []; ///////////////////////////////////////////////////////////////////////////// // // Custom Events // ///////////////////////////////////////////////////////////////////////////// /** * Fired when a request is made to the local cache. * * @event cacheRequestEvent * @param oArgs.request {Object} The request object. * @param oArgs.callback {Object} The callback object. * @param oArgs.caller {Object} (deprecated) Use callback.scope. */ this.createEvent("cacheRequestEvent"); /** * Fired when data is retrieved from the local cache. * * @event cacheResponseEvent * @param oArgs.request {Object} The request object. * @param oArgs.response {Object} The response object. * @param oArgs.callback {Object} The callback object. * @param oArgs.caller {Object} (deprecated) Use callback.scope. */ this.createEvent("cacheResponseEvent"); /** * Fired when a request is sent to the live data source. * * @event requestEvent * @param oArgs.request {Object} The request object. * @param oArgs.callback {Object} The callback object. * @param oArgs.tId {Number} Transaction ID. * @param oArgs.caller {Object} (deprecated) Use callback.scope. */ this.createEvent("requestEvent"); /** * Fired when live data source sends response. * * @event responseEvent * @param oArgs.request {Object} The request object. * @param oArgs.response {Object} The raw response object. * @param oArgs.callback {Object} The callback object. * @param oArgs.tId {Number} Transaction ID. * @param oArgs.caller {Object} (deprecated) Use callback.scope. */ this.createEvent("responseEvent"); /** * Fired when response is parsed. * * @event responseParseEvent * @param oArgs.request {Object} The request object. * @param oArgs.response {Object} The parsed response object. * @param oArgs.callback {Object} The callback object. * @param oArgs.caller {Object} (deprecated) Use callback.scope. */ this.createEvent("responseParseEvent"); /** * Fired when response is cached. * * @event responseCacheEvent * @param oArgs.request {Object} The request object. * @param oArgs.response {Object} The parsed response object. * @param oArgs.callback {Object} The callback object. * @param oArgs.caller {Object} (deprecated) Use callback.scope. */ this.createEvent("responseCacheEvent"); /** * Fired when an error is encountered with the live data source. * * @event dataErrorEvent * @param oArgs.request {Object} The request object. * @param oArgs.response {String} The response object (if available). * @param oArgs.callback {Object} The callback object. * @param oArgs.caller {Object} (deprecated) Use callback.scope. * @param oArgs.message {String} The error message. */ this.createEvent("dataErrorEvent"); /** * Fired when the local cache is flushed. * * @event cacheFlushEvent */ this.createEvent("cacheFlushEvent"); var DS = util.DataSourceBase; this._sName = "DataSource instance" + DS._nIndex; DS._nIndex++; }; var DS = util.DataSourceBase; lang.augmentObject(DS, { ///////////////////////////////////////////////////////////////////////////// // // DataSourceBase public constants // ///////////////////////////////////////////////////////////////////////////// /** * Type is unknown. * * @property TYPE_UNKNOWN * @type Number * @final * @default -1 */ TYPE_UNKNOWN : -1, /** * Type is a JavaScript Array. * * @property TYPE_JSARRAY * @type Number * @final * @default 0 */ TYPE_JSARRAY : 0, /** * Type is a JavaScript Function. * * @property TYPE_JSFUNCTION * @type Number * @final * @default 1 */ TYPE_JSFUNCTION : 1, /** * Type is hosted on a server via an XHR connection. * * @property TYPE_XHR * @type Number * @final * @default 2 */ TYPE_XHR : 2, /** * Type is JSON. * * @property TYPE_JSON * @type Number * @final * @default 3 */ TYPE_JSON : 3, /** * Type is XML. * * @property TYPE_XML * @type Number * @final * @default 4 */ TYPE_XML : 4, /** * Type is plain text. * * @property TYPE_TEXT * @type Number * @final * @default 5 */ TYPE_TEXT : 5, /** * Type is an HTML TABLE element. Data is parsed out of TR elements from all TBODY elements. * * @property TYPE_HTMLTABLE * @type Number * @final * @default 6 */ TYPE_HTMLTABLE : 6, /** * Type is hosted on a server via a dynamic script node. * * @property TYPE_SCRIPTNODE * @type Number * @final * @default 7 */ TYPE_SCRIPTNODE : 7, /** * Type is local. * * @property TYPE_LOCAL * @type Number * @final * @default 8 */ TYPE_LOCAL : 8, /** * Error message for invalid dataresponses. * * @property ERROR_DATAINVALID * @type String * @final * @default "Invalid data" */ ERROR_DATAINVALID : "Invalid data", /** * Error message for null data responses. * * @property ERROR_DATANULL * @type String * @final * @default "Null data" */ ERROR_DATANULL : "Null data", ///////////////////////////////////////////////////////////////////////////// // // DataSourceBase private static properties // ///////////////////////////////////////////////////////////////////////////// /** * Internal class variable to index multiple DataSource instances. * * @property DataSourceBase._nIndex * @type Number * @private * @static */ _nIndex : 0, /** * Internal class variable to assign unique transaction IDs. * * @property DataSourceBase._nTransactionId * @type Number * @private * @static */ _nTransactionId : 0, ///////////////////////////////////////////////////////////////////////////// // // DataSourceBase private static methods // ///////////////////////////////////////////////////////////////////////////// /** * Clones object literal or array of object literals. * * @method DataSourceBase._cloneObject * @param o {Object} Object. * @private * @static */ _cloneObject: function(o) { if(!lang.isValue(o)) { return o; } var copy = {}; if(Object.prototype.toString.apply(o) === "[object RegExp]") { copy = o; } else if(lang.isFunction(o)) { copy = o; } else if(lang.isArray(o)) { var array = []; for(var i=0,len=o.length;i<len;i++) { array[i] = DS._cloneObject(o[i]); } copy = array; } else if(lang.isObject(o)) { for (var x in o){ if(lang.hasOwnProperty(o, x)) { if(lang.isValue(o[x]) && lang.isObject(o[x]) || lang.isArray(o[x])) { copy[x] = DS._cloneObject(o[x]); } else { copy[x] = o[x]; } } } } else { copy = o; } return copy; }, /** * Get an XPath-specified value for a given field from an XML node or document. * * @method _getLocationValue * @param field {String | Object} Field definition. * @param context {Object} XML node or document to search within. * @return {Object} Data value or null. * @static * @private */ _getLocationValue: function(field, context) { var locator = field.locator || field.key || field, xmldoc = context.ownerDocument || context, result, res, value = null; try { // Standards mode if(!lang.isUndefined(xmldoc.evaluate)) { result = xmldoc.evaluate(locator, context, xmldoc.createNSResolver(!context.ownerDocument ? context.documentElement : context.ownerDocument.documentElement), 0, null); while(res = result.iterateNext()) { value = res.textContent; } } // IE mode else { xmldoc.setProperty("SelectionLanguage", "XPath"); result = context.selectNodes(locator)[0]; value = result.value || result.text || null; } return value; } catch(e) { } }, ///////////////////////////////////////////////////////////////////////////// // // DataSourceBase public static methods // ///////////////////////////////////////////////////////////////////////////// /** * Executes a configured callback. For object literal callbacks, the third * param determines whether to execute the success handler or failure handler. * * @method issueCallback * @param callback {Function|Object} the callback to execute * @param params {Array} params to be passed to the callback method * @param error {Boolean} whether an error occurred * @param scope {Object} the scope from which to execute the callback * (deprecated - use an object literal callback) * @static */ issueCallback : function (callback,params,error,scope) { if (lang.isFunction(callback)) { callback.apply(scope, params); } else if (lang.isObject(callback)) { scope = callback.scope || scope || window; var callbackFunc = callback.success; if (error) { callbackFunc = callback.failure; } if (callbackFunc) { callbackFunc.apply(scope, params.concat([callback.argument])); } } }, /** * Converts data to type String. * * @method DataSourceBase.parseString * @param oData {String | Number | Boolean | Date | Array | Object} Data to parse. * The special values null and undefined will return null. * @return {String} A string, or null. * @static */ parseString : function(oData) { // Special case null and undefined if(!lang.isValue(oData)) { return null; } //Convert to string var string = oData + ""; // Validate if(lang.isString(string)) { return string; } else { return null; } }, /** * Converts data to type Number. * * @method DataSourceBase.parseNumber * @param oData {String | Number | Boolean} Data to convert. Note, the following * values return as null: null, undefined, NaN, "". * @return {Number} A number, or null. * @static */ parseNumber : function(oData) { if(!lang.isValue(oData) || (oData === "")) { return null; } //Convert to number var number = oData * 1; // Validate if(lang.isNumber(number)) { return number; } else { return null; } }, // Backward compatibility convertNumber : function(oData) { return DS.parseNumber(oData); }, /** * Converts data to type Date. * * @method DataSourceBase.parseDate * @param oData {Date | String | Number} Data to convert. * @return {Date} A Date instance. * @static */ parseDate : function(oData) { var date = null; //Convert to date if(lang.isValue(oData) && !(oData instanceof Date)) { date = new Date(oData); } else { return oData; } // Validate if(date instanceof Date) { return date; } else { return null; } }, // Backward compatibility convertDate : function(oData) { return DS.parseDate(oData); } }); // Done in separate step so referenced functions are defined. /** * Data parsing functions. * @property DataSource.Parser * @type Object * @static */ DS.Parser = { string : DS.parseString, number : DS.parseNumber, date : DS.parseDate }; // Prototype properties and methods DS.prototype = { ///////////////////////////////////////////////////////////////////////////// // // DataSourceBase private properties // ///////////////////////////////////////////////////////////////////////////// /** * Name of DataSource instance. * * @property _sName * @type String * @private */ _sName : null, /** * Local cache of data result object literals indexed chronologically. * * @property _aCache * @type Object[] * @private */ _aCache : null, /** * Local queue of request connections, enabled if queue needs to be managed. * * @property _oQueue * @type Object * @private */ _oQueue : null, /** * Array of polling interval IDs that have been enabled, needed to clear all intervals. * * @property _aIntervals * @type Array * @private */ _aIntervals : null, ///////////////////////////////////////////////////////////////////////////// // // DataSourceBase public properties // ///////////////////////////////////////////////////////////////////////////// /** * Max size of the local cache. Set to 0 to turn off caching. Caching is * useful to reduce the number of server connections. Recommended only for data * sources that return comprehensive results for queries or when stale data is * not an issue. * * @property maxCacheEntries * @type Number * @default 0 */ maxCacheEntries : 0, /** * Pointer to live database. * * @property liveData * @type Object */ liveData : null, /** * Where the live data is held: * * <dl> * <dt>TYPE_UNKNOWN</dt> * <dt>TYPE_LOCAL</dt> * <dt>TYPE_XHR</dt> * <dt>TYPE_SCRIPTNODE</dt> * <dt>TYPE_JSFUNCTION</dt> * </dl> * * @property dataType * @type Number * @default YAHOO.util.DataSourceBase.TYPE_UNKNOWN * */ dataType : DS.TYPE_UNKNOWN, /** * Format of response: * * <dl> * <dt>TYPE_UNKNOWN</dt> * <dt>TYPE_JSARRAY</dt> * <dt>TYPE_JSON</dt> * <dt>TYPE_XML</dt> * <dt>TYPE_TEXT</dt> * <dt>TYPE_HTMLTABLE</dt> * </dl> * * @property responseType * @type Number * @default YAHOO.util.DataSourceBase.TYPE_UNKNOWN */ responseType : DS.TYPE_UNKNOWN, /** * Response schema object literal takes a combination of the following properties: * * <dl> * <dt>resultsList</dt> <dd>Pointer to array of tabular data</dd> * <dt>resultNode</dt> <dd>Pointer to node name of row data (XML data only)</dd> * <dt>recordDelim</dt> <dd>Record delimiter (text data only)</dd> * <dt>fieldDelim</dt> <dd>Field delimiter (text data only)</dd> * <dt>fields</dt> <dd>Array of field names (aka keys), or array of object literals * such as: {key:"fieldname",parser:YAHOO.util.DataSourceBase.parseDate}</dd> * <dt>metaFields</dt> <dd>Object literal of keys to include in the oParsedResponse.meta collection</dd> * <dt>metaNode</dt> <dd>Name of the node under which to search for meta information in XML response data</dd> * </dl> * * @property responseSchema * @type Object */ responseSchema : null, /** * Additional arguments passed to the JSON parse routine. The JSON string * is the assumed first argument (where applicable). This property is not * set by default, but the parse methods will use it if present. * * @property parseJSONArgs * @type {MIXED|Array} If an Array, contents are used as individual arguments. * Otherwise, value is used as an additional argument. */ // property intentionally undefined /** * When working with XML data, setting this property to true enables support for * XPath-syntaxed locators in schema definitions. * * @property useXPath * @type Boolean * @default false */ useXPath : false, /** * Clones entries before adding to cache. * * @property cloneBeforeCaching * @type Boolean * @default false */ cloneBeforeCaching : false, ///////////////////////////////////////////////////////////////////////////// // // DataSourceBase public methods // ///////////////////////////////////////////////////////////////////////////// /** * Public accessor to the unique name of the DataSource instance. * * @method toString * @return {String} Unique name of the DataSource instance. */ toString : function() { return this._sName; }, /** * Overridable method passes request to cache and returns cached response if any, * refreshing the hit in the cache as the newest item. Returns null if there is * no cache hit. * * @method getCachedResponse * @param oRequest {Object} Request object. * @param oCallback {Object} Callback object. * @param oCaller {Object} (deprecated) Use callback object. * @return {Object} Cached response object or null. */ getCachedResponse : function(oRequest, oCallback, oCaller) { var aCache = this._aCache; // If cache is enabled... if(this.maxCacheEntries > 0) { // Initialize local cache if(!aCache) { this._aCache = []; } // Look in local cache else { var nCacheLength = aCache.length; if(nCacheLength > 0) { var oResponse = null; this.fireEvent("cacheRequestEvent", {request:oRequest,callback:oCallback,caller:oCaller}); // Loop through each cached element for(var i = nCacheLength-1; i >= 0; i--) { var oCacheElem = aCache[i]; // Defer cache hit logic to a public overridable method if(this.isCacheHit(oRequest,oCacheElem.request)) { // The cache returned a hit! // Grab the cached response oResponse = oCacheElem.response; this.fireEvent("cacheResponseEvent", {request:oRequest,response:oResponse,callback:oCallback,caller:oCaller}); // Refresh the position of the cache hit if(i < nCacheLength-1) { // Remove element from its original location aCache.splice(i,1); // Add as newest this.addToCache(oRequest, oResponse); } // Add a cache flag oResponse.cached = true; break; } } return oResponse; } } } else if(aCache) { this._aCache = null; } return null; }, /** * Default overridable method matches given request to given cached request. * Returns true if is a hit, returns false otherwise. Implementers should * override this method to customize the cache-matching algorithm. * * @method isCacheHit * @param oRequest {Object} Request object. * @param oCachedRequest {Object} Cached request object. * @return {Boolean} True if given request matches cached request, false otherwise. */ isCacheHit : function(oRequest, oCachedRequest) { return (oRequest === oCachedRequest); }, /** * Adds a new item to the cache. If cache is full, evicts the stalest item * before adding the new item. * * @method addToCache * @param oRequest {Object} Request object. * @param oResponse {Object} Response object to cache. */ addToCache : function(oRequest, oResponse) { var aCache = this._aCache; if(!aCache) { return; } // If the cache is full, make room by removing stalest element (index=0) while(aCache.length >= this.maxCacheEntries) { aCache.shift(); } // Add to cache in the newest position, at the end of the array oResponse = (this.cloneBeforeCaching) ? DS._cloneObject(oResponse) : oResponse; var oCacheElem = {request:oRequest,response:oResponse}; aCache[aCache.length] = oCacheElem; this.fireEvent("responseCacheEvent", {request:oRequest,response:oResponse}); }, /** * Flushes cache. * * @method flushCache */ flushCache : function() { if(this._aCache) { this._aCache = []; this.fireEvent("cacheFlushEvent"); } }, /** * Sets up a polling mechanism to send requests at set intervals and forward * responses to given callback. * * @method setInterval * @param nMsec {Number} Length of interval in milliseconds. * @param oRequest {Object} Request object. * @param oCallback {Function} Handler function to receive the response. * @param oCaller {Object} (deprecated) Use oCallback.scope. * @return {Number} Interval ID. */ setInterval : function(nMsec, oRequest, oCallback, oCaller) { if(lang.isNumber(nMsec) && (nMsec >= 0)) { var oSelf = this; var nId = setInterval(function() { oSelf.makeConnection(oRequest, oCallback, oCaller); }, nMsec); this._aIntervals.push(nId); return nId; } else { } }, /** * Disables polling mechanism associated with the given interval ID. Does not * affect transactions that are in progress. * * @method clearInterval * @param nId {Number} Interval ID. */ clearInterval : function(nId) { // Remove from tracker if there var tracker = this._aIntervals || []; for(var i=tracker.length-1; i>-1; i--) { if(tracker[i] === nId) { tracker.splice(i,1); clearInterval(nId); } } }, /** * Disables all known polling intervals. Does not affect transactions that are * in progress. * * @method clearAllIntervals */ clearAllIntervals : function() { var tracker = this._aIntervals || []; for(var i=tracker.length-1; i>-1; i--) { clearInterval(tracker[i]); } tracker = []; }, /** * First looks for cached response, then sends request to live data. The * following arguments are passed to the callback function: * <dl> * <dt><code>oRequest</code></dt> * <dd>The same value that was passed in as the first argument to sendRequest.</dd> * <dt><code>oParsedResponse</code></dt> * <dd>An object literal containing the following properties: * <dl> * <dt><code>tId</code></dt> * <dd>Unique transaction ID number.</dd> * <dt><code>results</code></dt> * <dd>Schema-parsed data results.</dd> * <dt><code>error</code></dt> * <dd>True in cases of data error.</dd> * <dt><code>cached</code></dt> * <dd>True when response is returned from DataSource cache.</dd> * <dt><code>meta</code></dt> * <dd>Schema-parsed meta data.</dd> * </dl> * <dt><code>oPayload</code></dt> * <dd>The same value as was passed in as <code>argument</code> in the oCallback object literal.</dd> * </dl> * * @method sendRequest * @param oRequest {Object} Request object. * @param oCallback {Object} An object literal with the following properties: * <dl> * <dt><code>success</code></dt> * <dd>The function to call when the data is ready.</dd> * <dt><code>failure</code></dt> * <dd>The function to call upon a response failure condition.</dd> * <dt><code>scope</code></dt> * <dd>The object to serve as the scope for the success and failure handlers.</dd> * <dt><code>argument</code></dt> * <dd>Arbitrary data that will be passed back to the success and failure handlers.</dd> * </dl> * @param oCaller {Object} (deprecated) Use oCallback.scope. * @return {Number} Transaction ID, or null if response found in cache. */ sendRequest : function(oRequest, oCallback, oCaller) { // First look in cache var oCachedResponse = this.getCachedResponse(oRequest, oCallback, oCaller); if(oCachedResponse) { DS.issueCallback(oCallback,[oRequest,oCachedResponse],false,oCaller); return null; } // Not in cache, so forward request to live data return this.makeConnection(oRequest, oCallback, oCaller); }, /** * Overridable default method generates a unique transaction ID and passes * the live data reference directly to the handleResponse function. This * method should be implemented by subclasses to achieve more complex behavior * or to access remote data. * * @method makeConnection * @param oRequest {Object} Request object. * @param oCallback {Object} Callback object literal. * @param oCaller {Object} (deprecated) Use oCallback.scope. * @return {Number} Transaction ID. */ makeConnection : function(oRequest, oCallback, oCaller) { var tId = DS._nTransactionId++; this.fireEvent("requestEvent", {tId:tId, request:oRequest,callback:oCallback,caller:oCaller}); /* accounts for the following cases: YAHOO.util.DataSourceBase.TYPE_UNKNOWN YAHOO.util.DataSourceBase.TYPE_JSARRAY YAHOO.util.DataSourceBase.TYPE_JSON YAHOO.util.DataSourceBase.TYPE_HTMLTABLE YAHOO.util.DataSourceBase.TYPE_XML YAHOO.util.DataSourceBase.TYPE_TEXT */ var oRawResponse = this.liveData; this.handleResponse(oRequest, oRawResponse, oCallback, oCaller, tId); return tId; }, /** * Receives raw data response and type converts to XML, JSON, etc as necessary. * Forwards oFullResponse to appropriate parsing function to get turned into * oParsedResponse. Calls doBeforeCallback() and adds oParsedResponse to * the cache when appropriate before calling issueCallback(). * * The oParsedResponse object literal has the following properties: * <dl> * <dd><dt>tId {Number}</dt> Unique transaction ID</dd> * <dd><dt>results {Array}</dt> Array of parsed data results</dd> * <dd><dt>meta {Object}</dt> Object literal of meta values</dd> * <dd><dt>error {Boolean}</dt> (optional) True if there was an error</dd> * <dd><dt>cached {Boolean}</dt> (optional) True if response was cached</dd> * </dl> * * @method handleResponse * @param oRequest {Object} Request object * @param oRawResponse {Object} The raw response from the live database. * @param oCallback {Object} Callback object literal. * @param oCaller {Object} (deprecated) Use oCallback.scope. * @param tId {Number} Transaction ID. */ handleResponse : function(oRequest, oRawResponse, oCallback, oCaller, tId) { this.fireEvent("responseEvent", {tId:tId, request:oRequest, response:oRawResponse, callback:oCallback, caller:oCaller}); var xhr = (this.dataType == DS.TYPE_XHR) ? true : false; var oParsedResponse = null; var oFullResponse = oRawResponse; // Try to sniff data type if it has not been defined if(this.responseType === DS.TYPE_UNKNOWN) { var ctype = (oRawResponse && oRawResponse.getResponseHeader) ? oRawResponse.getResponseHeader["Content-Type"] : null; if(ctype) { // xml if(ctype.indexOf("text/xml") > -1) { this.responseType = DS.TYPE_XML; } else if(ctype.indexOf("application/json") > -1) { // json this.responseType = DS.TYPE_JSON; } else if(ctype.indexOf("text/plain") > -1) { // text this.responseType = DS.TYPE_TEXT; } } else { if(YAHOO.lang.isArray(oRawResponse)) { // array this.responseType = DS.TYPE_JSARRAY; } // xml else if(oRawResponse && oRawResponse.nodeType && (oRawResponse.nodeType === 9 || oRawResponse.nodeType === 1 || oRawResponse.nodeType === 11)) { this.responseType = DS.TYPE_XML; } else if(oRawResponse && oRawResponse.nodeName && (oRawResponse.nodeName.toLowerCase() == "table")) { // table this.responseType = DS.TYPE_HTMLTABLE; } else if(YAHOO.lang.isObject(oRawResponse)) { // json this.responseType = DS.TYPE_JSON; } else if(YAHOO.lang.isString(oRawResponse)) { // text this.responseType = DS.TYPE_TEXT; } } } switch(this.responseType) { case DS.TYPE_JSARRAY: if(xhr && oRawResponse && oRawResponse.responseText) { oFullResponse = oRawResponse.responseText; } try { // Convert to JS array if it's a string if(lang.isString(oFullResponse)) { var parseArgs = [oFullResponse].concat(this.parseJSONArgs); // Check for YUI JSON Util if(lang.JSON) { oFullResponse = lang.JSON.parse.apply(lang.JSON,parseArgs); } // Look for JSON parsers using an API similar to json2.js else if(window.JSON && JSON.parse) { oFullResponse = JSON.parse.apply(JSON,parseArgs); } // Look for JSON parsers using an API similar to json.js else if(oFullResponse.parseJSON) { oFullResponse = oFullResponse.parseJSON.apply(oFullResponse,parseArgs.slice(1)); } // No JSON lib found so parse the string else { // Trim leading spaces while (oFullResponse.length > 0 && (oFullResponse.charAt(0) != "{") && (oFullResponse.charAt(0) != "[")) { oFullResponse = oFullResponse.substring(1, oFullResponse.length); } if(oFullResponse.length > 0) { // Strip extraneous stuff at the end var arrayEnd = Math.max(oFullResponse.lastIndexOf("]"),oFullResponse.lastIndexOf("}")); oFullResponse = oFullResponse.substring(0,arrayEnd+1); // Turn the string into an object literal... // ...eval is necessary here oFullResponse = eval("(" + oFullResponse + ")"); } } } } catch(e1) { } oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback); oParsedResponse = this.parseArrayData(oRequest, oFullResponse); break; case DS.TYPE_JSON: if(xhr && oRawResponse && oRawResponse.responseText) { oFullResponse = oRawResponse.responseText; } try { // Convert to JSON object if it's a string if(lang.isString(oFullResponse)) { var parseArgs = [oFullResponse].concat(this.parseJSONArgs); // Check for YUI JSON Util if(lang.JSON) { oFullResponse = lang.JSON.parse.apply(lang.JSON,parseArgs); } // Look for JSON parsers using an API similar to json2.js else if(window.JSON && JSON.parse) { oFullResponse = JSON.parse.apply(JSON,parseArgs); } // Look for JSON parsers using an API similar to json.js else if(oFullResponse.parseJSON) { oFullResponse = oFullResponse.parseJSON.apply(oFullResponse,parseArgs.slice(1)); } // No JSON lib found so parse the string else { // Trim leading spaces while (oFullResponse.length > 0 && (oFullResponse.charAt(0) != "{") && (oFullResponse.charAt(0) != "[")) { oFullResponse = oFullResponse.substring(1, oFullResponse.length); } if(oFullResponse.length > 0) { // Strip extraneous stuff at the end var objEnd = Math.max(oFullResponse.lastIndexOf("]"),oFullResponse.lastIndexOf("}")); oFullResponse = oFullResponse.substring(0,objEnd+1); // Turn the string into an object literal... // ...eval is necessary here oFullResponse = eval("(" + oFullResponse + ")"); } } } } catch(e) { } oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback); oParsedResponse = this.parseJSONData(oRequest, oFullResponse); break; case DS.TYPE_HTMLTABLE: if(xhr && oRawResponse.responseText) { var el = document.createElement('div'); el.innerHTML = oRawResponse.responseText; oFullResponse = el.getElementsByTagName('table')[0]; } oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback); oParsedResponse = this.parseHTMLTableData(oRequest, oFullResponse); break; case DS.TYPE_XML: if(xhr && oRawResponse.responseXML) { oFullResponse = oRawResponse.responseXML; } oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback); oParsedResponse = this.parseXMLData(oRequest, oFullResponse); break; case DS.TYPE_TEXT: if(xhr && lang.isString(oRawResponse.responseText)) { oFullResponse = oRawResponse.responseText; } oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback); oParsedResponse = this.parseTextData(oRequest, oFullResponse); break; default: oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback); oParsedResponse = this.parseData(oRequest, oFullResponse); break; } // Clean up for consistent signature oParsedResponse = oParsedResponse || {}; if(!oParsedResponse.results) { oParsedResponse.results = []; } if(!oParsedResponse.meta) { oParsedResponse.meta = {}; } // Success if(!oParsedResponse.error) { // Last chance to touch the raw response or the parsed response oParsedResponse = this.doBeforeCallback(oRequest, oFullResponse, oParsedResponse, oCallback); this.fireEvent("responseParseEvent", {request:oRequest, response:oParsedResponse, callback:oCallback, caller:oCaller}); // Cache the response this.addToCache(oRequest, oParsedResponse); } // Error else { // Be sure the error flag is on oParsedResponse.error = true; this.fireEvent("dataErrorEvent", {request:oRequest, response: oRawResponse, callback:oCallback, caller:oCaller, message:DS.ERROR_DATANULL}); } // Send the response back to the caller oParsedResponse.tId = tId; DS.issueCallback(oCallback,[oRequest,oParsedResponse],oParsedResponse.error,oCaller); }, /** * Overridable method gives implementers access to the original full response * before the data gets parsed. Implementers should take care not to return an * unparsable or otherwise invalid response. * * @method doBeforeParseData * @param oRequest {Object} Request object. * @param oFullResponse {Object} The full response from the live database. * @param oCallback {Object} The callback object. * @return {Object} Full response for parsing. */ doBeforeParseData : function(oRequest, oFullResponse, oCallback) { return oFullResponse; }, /** * Overridable method gives implementers access to the original full response and * the parsed response (parsed against the given schema) before the data * is added to the cache (if applicable) and then sent back to callback function. * This is your chance to access the raw response and/or populate the parsed * response with any custom data. * * @method doBeforeCallback * @param oRequest {Object} Request object. * @param oFullResponse {Object} The full response from the live database. * @param oParsedResponse {Object} The parsed response to return to calling object. * @param oCallback {Object} The callback object. * @return {Object} Parsed response object. */ doBeforeCallback : function(oRequest, oFullResponse, oParsedResponse, oCallback) { return oParsedResponse; }, /** * Overridable method parses data of generic RESPONSE_TYPE into a response object. * * @method parseData * @param oRequest {Object} Request object. * @param oFullResponse {Object} The full Array from the live database. * @return {Object} Parsed response object with the following properties:<br> * - results {Array} Array of parsed data results<br> * - meta {Object} Object literal of meta values<br> * - error {Boolean} (optional) True if there was an error<br> */ parseData : function(oRequest, oFullResponse) { if(lang.isValue(oFullResponse)) { var oParsedResponse = {results:oFullResponse,meta:{}}; return oParsedResponse; } return null; }, /** * Overridable method parses Array data into a response object. * * @method parseArrayData * @param oRequest {Object} Request object. * @param oFullResponse {Object} The full Array from the live database. * @return {Object} Parsed response object with the following properties:<br> * - results (Array) Array of parsed data results<br> * - error (Boolean) True if there was an error */ parseArrayData : function(oRequest, oFullResponse) { if(lang.isArray(oFullResponse)) { var results = [], i, j, rec, field, data; // Parse for fields if(lang.isArray(this.responseSchema.fields)) { var fields = this.responseSchema.fields; for (i = fields.length - 1; i >= 0; --i) { if (typeof fields[i] !== 'object') { fields[i] = { key : fields[i] }; } } var parsers = {}, p; for (i = fields.length - 1; i >= 0; --i) { p = (typeof fields[i].parser === 'function' ? fields[i].parser : DS.Parser[fields[i].parser+'']) || fields[i].converter; if (p) { parsers[fields[i].key] = p; } } var arrType = lang.isArray(oFullResponse[0]); for(i=oFullResponse.length-1; i>-1; i--) { var oResult = {}; rec = oFullResponse[i]; if (typeof rec === 'object') { for(j=fields.length-1; j>-1; j--) { field = fields[j]; data = arrType ? rec[j] : rec[field.key]; if (parsers[field.key]) { data = parsers[field.key].call(this,data); } // Safety measure if(data === undefined) { data = null; } oResult[field.key] = data; } } else if (lang.isString(rec)) { for(j=fields.length-1; j>-1; j--) { field = fields[j]; data = rec; if (parsers[field.key]) { data = parsers[field.key].call(this,data); } // Safety measure if(data === undefined) { data = null; } oResult[field.key] = data; } } results[i] = oResult; } } // Return entire data set else { results = oFullResponse; } var oParsedResponse = {results:results}; return oParsedResponse; } return null; }, /** * Overridable method parses plain text data into a response object. * * @method parseTextData * @param oRequest {Object} Request object. * @param oFullResponse {Object} The full text response from the live database. * @return {Object} Parsed response object with the following properties:<br> * - results (Array) Array of parsed data results<br> * - error (Boolean) True if there was an error */ parseTextData : function(oRequest, oFullResponse) { if(lang.isString(oFullResponse)) { if(lang.isString(this.responseSchema.recordDelim) && lang.isString(this.responseSchema.fieldDelim)) { var oParsedResponse = {results:[]}; var recDelim = this.responseSchema.recordDelim; var fieldDelim = this.responseSchema.fieldDelim; if(oFullResponse.length > 0) { // Delete the last line delimiter at the end of the data if it exists var newLength = oFullResponse.length-recDelim.length; if(oFullResponse.substr(newLength) == recDelim) { oFullResponse = oFullResponse.substr(0, newLength); } if(oFullResponse.length > 0) { // Split along record delimiter to get an array of strings var recordsarray = oFullResponse.split(recDelim); // Cycle through each record for(var i = 0, len = recordsarray.length, recIdx = 0; i < len; ++i) { var bError = false, sRecord = recordsarray[i]; if (lang.isString(sRecord) && (sRecord.length > 0)) { // Split each record along field delimiter to get data var fielddataarray = recordsarray[i].split(fieldDelim); var oResult = {}; // Filter for fields data if(lang.isArray(this.responseSchema.fields)) { var fields = this.responseSchema.fields; for(var j=fields.length-1; j>-1; j--) { try { // Remove quotation marks from edges, if applicable var data = fielddataarray[j]; if (lang.isString(data)) { if(data.charAt(0) == "\"") { data = data.substr(1); } if(data.charAt(data.length-1) == "\"") { data = data.substr(0,data.length-1); } var field = fields[j]; var key = (lang.isValue(field.key)) ? field.key : field; // Backward compatibility if(!field.parser && field.converter) { field.parser = field.converter; } var parser = (typeof field.parser === 'function') ? field.parser : DS.Parser[field.parser+'']; if(parser) { data = parser.call(this, data); } // Safety measure if(data === undefined) { data = null; } oResult[key] = data; } else { bError = true; } } catch(e) { bError = true; } } } // No fields defined so pass along all data as an array else { oResult = fielddataarray; } if(!bError) { oParsedResponse.results[recIdx++] = oResult; } } } } } return oParsedResponse; } } return null; }, /** * Overridable method parses XML data for one result into an object literal. * * @method parseXMLResult * @param result {XML} XML for one result. * @return {Object} Object literal of data for one result. */ parseXMLResult : function(result) { var oResult = {}, schema = this.responseSchema; try { // Loop through each data field in each result using the schema for(var m = schema.fields.length-1; m >= 0 ; m--) { var field = schema.fields[m]; var key = (lang.isValue(field.key)) ? field.key : field; var data = null; if(this.useXPath) { data = YAHOO.util.DataSource._getLocationValue(field, result); } else { // Values may be held in an attribute... var xmlAttr = result.attributes.getNamedItem(key); if(xmlAttr) { data = xmlAttr.value; } // ...or in a node else { var xmlNode = result.getElementsByTagName(key); if(xmlNode && xmlNode.item(0)) { var item = xmlNode.item(0); // For IE, then DOM... data = (item) ? ((item.text) ? item.text : (item.textContent) ? item.textContent : null) : null; // ...then fallback, but check for multiple child nodes if(!data) { var datapieces = []; for(var j=0, len=item.childNodes.length; j<len; j++) { if(item.childNodes[j].nodeValue) { datapieces[datapieces.length] = item.childNodes[j].nodeValue; } } if(datapieces.length > 0) { data = datapieces.join(""); } } } } } // Safety net if(data === null) { data = ""; } // Backward compatibility if(!field.parser && field.converter) { field.parser = field.converter; } var parser = (typeof field.parser === 'function') ? field.parser : DS.Parser[field.parser+'']; if(parser) { data = parser.call(this, data); } // Safety measure if(data === undefined) { data = null; } oResult[key] = data; } } catch(e) { } return oResult; }, /** * Overridable method parses XML data into a response object. * * @method parseXMLData * @param oRequest {Object} Request object. * @param oFullResponse {Object} The full XML response from the live database. * @return {Object} Parsed response object with the following properties<br> * - results (Array) Array of parsed data results<br> * - error (Boolean) True if there was an error */ parseXMLData : function(oRequest, oFullResponse) { var bError = false, schema = this.responseSchema, oParsedResponse = {meta:{}}, xmlList = null, metaNode = schema.metaNode, metaLocators = schema.metaFields || {}, i,k,loc,v; // In case oFullResponse is something funky try { // Pull any meta identified if(this.useXPath) { for (k in metaLocators) { oParsedResponse.meta[k] = YAHOO.util.DataSource._getLocationValue(metaLocators[k], oFullResponse); } } else { metaNode = metaNode ? oFullResponse.getElementsByTagName(metaNode)[0] : oFullResponse; if (metaNode) { for (k in metaLocators) { if (lang.hasOwnProperty(metaLocators, k)) { loc = metaLocators[k]; // Look for a node v = metaNode.getElementsByTagName(loc)[0]; if (v) { v = v.firstChild.nodeValue; } else { // Look for an attribute v = metaNode.attributes.getNamedItem(loc); if (v) { v = v.value; } } if (lang.isValue(v)) { oParsedResponse.meta[k] = v; } } } } } // For result data xmlList = (schema.resultNode) ? oFullResponse.getElementsByTagName(schema.resultNode) : null; } catch(e) { } if(!xmlList || !lang.isArray(schema.fields)) { bError = true; } // Loop through each result else { oParsedResponse.results = []; for(i = xmlList.length-1; i >= 0 ; --i) { var oResult = this.parseXMLResult(xmlList.item(i)); // Capture each array of values into an array of results oParsedResponse.results[i] = oResult; } } if(bError) { oParsedResponse.error = true; } else { } return oParsedResponse; }, /** * Overridable method parses JSON data into a response object. * * @method parseJSONData * @param oRequest {Object} Request object. * @param oFullResponse {Object} The full JSON from the live database. * @return {Object} Parsed response object with the following properties<br> * - results (Array) Array of parsed data results<br> * - error (Boolean) True if there was an error */ parseJSONData : function(oRequest, oFullResponse) { var oParsedResponse = {results:[],meta:{}}; if(lang.isObject(oFullResponse) && this.responseSchema.resultsList) { var schema = this.responseSchema, fields = schema.fields, resultsList = oFullResponse, results = [], metaFields = schema.metaFields || {}, fieldParsers = [], fieldPaths = [], simpleFields = [], bError = false, i,len,j,v,key,parser,path; // Function to convert the schema's fields into walk paths var buildPath = function (needle) { var path = null, keys = [], i = 0; if (needle) { // Strip the ["string keys"] and [1] array indexes needle = needle. replace(/\[(['"])(.*?)\1\]/g, function (x,$1,$2) {keys[i]=$2;return '.@'+(i++);}). replace(/\[(\d+)\]/g, function (x,$1) {keys[i]=parseInt($1,10)|0;return '.@'+(i++);}). replace(/^\./,''); // remove leading dot // If the cleaned needle contains invalid characters, the // path is invalid if (!/[^\w\.\$@]/.test(needle)) { path = needle.split('.'); for (i=path.length-1; i >= 0; --i) { if (path[i].charAt(0) === '@') { path[i] = keys[parseInt(path[i].substr(1),10)]; } } } else { } } return path; }; // Function to walk a path and return the pot of gold var walkPath = function (path, origin) { var v=origin,i=0,len=path.length; for (;i<len && v;++i) { v = v[path[i]]; } return v; }; // Parse the response // Step 1. Pull the resultsList from oFullResponse (default assumes // oFullResponse IS the resultsList) path = buildPath(schema.resultsList); if (path) { resultsList = walkPath(path, oFullResponse); if (resultsList === undefined) { bError = true; } } else { bError = true; } if (!resultsList) { resultsList = []; } if (!lang.isArray(resultsList)) { resultsList = [resultsList]; } if (!bError) { // Step 2. Parse out field data if identified if(schema.fields) { var field; // Build the field parser map and location paths for (i=0, len=fields.length; i<len; i++) { field = fields[i]; key = field.key || field; parser = ((typeof field.parser === 'function') ? field.parser : DS.Parser[field.parser+'']) || field.converter; path = buildPath(key); if (parser) { fieldParsers[fieldParsers.length] = {key:key,parser:parser}; } if (path) { if (path.length > 1) { fieldPaths[fieldPaths.length] = {key:key,path:path}; } else { simpleFields[simpleFields.length] = {key:key,path:path[0]}; } } else { } } // Process the results, flattening the records and/or applying parsers if needed for (i = resultsList.length - 1; i >= 0; --i) { var r = resultsList[i], rec = {}; if(r) { for (j = simpleFields.length - 1; j >= 0; --j) { // Bug 1777850: data might be held in an array rec[simpleFields[j].key] = (r[simpleFields[j].path] !== undefined) ? r[simpleFields[j].path] : r[j]; } for (j = fieldPaths.length - 1; j >= 0; --j) { rec[fieldPaths[j].key] = walkPath(fieldPaths[j].path,r); } for (j = fieldParsers.length - 1; j >= 0; --j) { var p = fieldParsers[j].key; rec[p] = fieldParsers[j].parser.call(this, rec[p]); if (rec[p] === undefined) { rec[p] = null; } } } results[i] = rec; } } else { results = resultsList; } for (key in metaFields) { if (lang.hasOwnProperty(metaFields,key)) { path = buildPath(metaFields[key]); if (path) { v = walkPath(path, oFullResponse); oParsedResponse.meta[key] = v; } } } } else { oParsedResponse.error = true; } oParsedResponse.results = results; } else { oParsedResponse.error = true; } return oParsedResponse; }, /** * Overridable method parses an HTML TABLE element reference into a response object. * Data is parsed out of TR elements from all TBODY elements. * * @method parseHTMLTableData * @param oRequest {Object} Request object. * @param oFullResponse {Object} The full HTML element reference from the live database. * @return {Object} Parsed response object with the following properties<br> * - results (Array) Array of parsed data results<br> * - error (Boolean) True if there was an error */ parseHTMLTableData : function(oRequest, oFullResponse) { var bError = false; var elTable = oFullResponse; var fields = this.responseSchema.fields; var oParsedResponse = {results:[]}; if(lang.isArray(fields)) { // Iterate through each TBODY for(var i=0; i<elTable.tBodies.length; i++) { var elTbody = elTable.tBodies[i]; // Iterate through each TR for(var j=elTbody.rows.length-1; j>-1; j--) { var elRow = elTbody.rows[j]; var oResult = {}; for(var k=fields.length-1; k>-1; k--) { var field = fields[k]; var key = (lang.isValue(field.key)) ? field.key : field; var data = elRow.cells[k].innerHTML; // Backward compatibility if(!field.parser && field.converter) { field.parser = field.converter; } var parser = (typeof field.parser === 'function') ? field.parser : DS.Parser[field.parser+'']; if(parser) { data = parser.call(this, data); } // Safety measure if(data === undefined) { data = null; } oResult[key] = data; } oParsedResponse.results[j] = oResult; } } } else { bError = true; } if(bError) { oParsedResponse.error = true; } else { } return oParsedResponse; } }; // DataSourceBase uses EventProvider lang.augmentProto(DS, util.EventProvider); /****************************************************************************/ /****************************************************************************/ /****************************************************************************/ /** * LocalDataSource class for in-memory data structs including JavaScript arrays, * JavaScript object literals (JSON), XML documents, and HTML tables. * * @namespace YAHOO.util * @class YAHOO.util.LocalDataSource * @extends YAHOO.util.DataSourceBase * @constructor * @param oLiveData {HTMLElement} Pointer to live data. * @param oConfigs {object} (optional) Object literal of configuration values. */ util.LocalDataSource = function(oLiveData, oConfigs) { this.dataType = DS.TYPE_LOCAL; if(oLiveData) { if(YAHOO.lang.isArray(oLiveData)) { // array this.responseType = DS.TYPE_JSARRAY; } // xml else if(oLiveData.nodeType && oLiveData.nodeType == 9) { this.responseType = DS.TYPE_XML; } else if(oLiveData.nodeName && (oLiveData.nodeName.toLowerCase() == "table")) { // table this.responseType = DS.TYPE_HTMLTABLE; oLiveData = oLiveData.cloneNode(true); } else if(YAHOO.lang.isString(oLiveData)) { // text this.responseType = DS.TYPE_TEXT; } else if(YAHOO.lang.isObject(oLiveData)) { // json this.responseType = DS.TYPE_JSON; } } else { oLiveData = []; this.responseType = DS.TYPE_JSARRAY; } util.LocalDataSource.superclass.constructor.call(this, oLiveData, oConfigs); }; // LocalDataSource extends DataSourceBase lang.extend(util.LocalDataSource, DS); // Copy static members to LocalDataSource class lang.augmentObject(util.LocalDataSource, DS); /****************************************************************************/ /****************************************************************************/ /****************************************************************************/ /** * FunctionDataSource class for JavaScript functions. * * @namespace YAHOO.util * @class YAHOO.util.FunctionDataSource * @extends YAHOO.util.DataSourceBase * @constructor * @param oLiveData {HTMLElement} Pointer to live data. * @param oConfigs {object} (optional) Object literal of configuration values. */ util.FunctionDataSource = function(oLiveData, oConfigs) { this.dataType = DS.TYPE_JSFUNCTION; oLiveData = oLiveData || function() {}; util.FunctionDataSource.superclass.constructor.call(this, oLiveData, oConfigs); }; // FunctionDataSource extends DataSourceBase lang.extend(util.FunctionDataSource, DS, { ///////////////////////////////////////////////////////////////////////////// // // FunctionDataSource public properties // ///////////////////////////////////////////////////////////////////////////// /** * Context in which to execute the function. By default, is the DataSource * instance itself. If set, the function will receive the DataSource instance * as an additional argument. * * @property scope * @type Object * @default null */ scope : null, ///////////////////////////////////////////////////////////////////////////// // // FunctionDataSource public methods // ///////////////////////////////////////////////////////////////////////////// /** * Overriding method passes query to a function. The returned response is then * forwarded to the handleResponse function. * * @method makeConnection * @param oRequest {Object} Request object. * @param oCallback {Object} Callback object literal. * @param oCaller {Object} (deprecated) Use oCallback.scope. * @return {Number} Transaction ID. */ makeConnection : function(oRequest, oCallback, oCaller) { var tId = DS._nTransactionId++; this.fireEvent("requestEvent", {tId:tId,request:oRequest,callback:oCallback,caller:oCaller}); // Pass the request in as a parameter and // forward the return value to the handler var oRawResponse = (this.scope) ? this.liveData.call(this.scope, oRequest, this, oCallback) : this.liveData(oRequest, oCallback); // Try to sniff data type if it has not been defined if(this.responseType === DS.TYPE_UNKNOWN) { if(YAHOO.lang.isArray(oRawResponse)) { // array this.responseType = DS.TYPE_JSARRAY; } // xml else if(oRawResponse && oRawResponse.nodeType && oRawResponse.nodeType == 9) { this.responseType = DS.TYPE_XML; } else if(oRawResponse && oRawResponse.nodeName && (oRawResponse.nodeName.toLowerCase() == "table")) { // table this.responseType = DS.TYPE_HTMLTABLE; } else if(YAHOO.lang.isObject(oRawResponse)) { // json this.responseType = DS.TYPE_JSON; } else if(YAHOO.lang.isString(oRawResponse)) { // text this.responseType = DS.TYPE_TEXT; } } this.handleResponse(oRequest, oRawResponse, oCallback, oCaller, tId); return tId; } }); // Copy static members to FunctionDataSource class lang.augmentObject(util.FunctionDataSource, DS); /****************************************************************************/ /****************************************************************************/ /****************************************************************************/ /** * ScriptNodeDataSource class for accessing remote data via the YUI Get Utility. * * @namespace YAHOO.util * @class YAHOO.util.ScriptNodeDataSource * @extends YAHOO.util.DataSourceBase * @constructor * @param oLiveData {HTMLElement} Pointer to live data. * @param oConfigs {object} (optional) Object literal of configuration values. */ util.ScriptNodeDataSource = function(oLiveData, oConfigs) { this.dataType = DS.TYPE_SCRIPTNODE; oLiveData = oLiveData || ""; util.ScriptNodeDataSource.superclass.constructor.call(this, oLiveData, oConfigs); }; // ScriptNodeDataSource extends DataSourceBase lang.extend(util.ScriptNodeDataSource, DS, { ///////////////////////////////////////////////////////////////////////////// // // ScriptNodeDataSource public properties // ///////////////////////////////////////////////////////////////////////////// /** * Alias to YUI Get Utility, to allow implementers to use a custom class. * * @property getUtility * @type Object * @default YAHOO.util.Get */ getUtility : util.Get, /** * Defines request/response management in the following manner: * <dl> * <!--<dt>queueRequests</dt> * <dd>If a request is already in progress, wait until response is returned before sending the next request.</dd> * <dt>cancelStaleRequests</dt> * <dd>If a request is already in progress, cancel it before sending the next request.</dd>--> * <dt>ignoreStaleResponses</dt> * <dd>Send all requests, but handle only the response for the most recently sent request.</dd> * <dt>allowAll</dt> * <dd>Send all requests and handle all responses.</dd> * </dl> * * @property asyncMode * @type String * @default "allowAll" */ asyncMode : "allowAll", /** * Callback string parameter name sent to the remote script. By default, * requests are sent to * &#60;URI&#62;?&#60;scriptCallbackParam&#62;=callback * * @property scriptCallbackParam * @type String * @default "callback" */ scriptCallbackParam : "callback", ///////////////////////////////////////////////////////////////////////////// // // ScriptNodeDataSource public methods // ///////////////////////////////////////////////////////////////////////////// /** * Creates a request callback that gets appended to the script URI. Implementers * can customize this string to match their server's query syntax. * * @method generateRequestCallback * @return {String} String fragment that gets appended to script URI that * specifies the callback function */ generateRequestCallback : function(id) { return "&" + this.scriptCallbackParam + "=YAHOO.util.ScriptNodeDataSource.callbacks["+id+"]" ; }, /** * Overridable method gives implementers access to modify the URI before the dynamic * script node gets inserted. Implementers should take care not to return an * invalid URI. * * @method doBeforeGetScriptNode * @param {String} URI to the script * @return {String} URI to the script */ doBeforeGetScriptNode : function(sUri) { return sUri; }, /** * Overriding method passes query to Get Utility. The returned * response is then forwarded to the handleResponse function. * * @method makeConnection * @param oRequest {Object} Request object. * @param oCallback {Object} Callback object literal. * @param oCaller {Object} (deprecated) Use oCallback.scope. * @return {Number} Transaction ID. */ makeConnection : function(oRequest, oCallback, oCaller) { var tId = DS._nTransactionId++; this.fireEvent("requestEvent", {tId:tId,request:oRequest,callback:oCallback,caller:oCaller}); // If there are no global pending requests, it is safe to purge global callback stack and global counter if(util.ScriptNodeDataSource._nPending === 0) { util.ScriptNodeDataSource.callbacks = []; util.ScriptNodeDataSource._nId = 0; } // ID for this request var id = util.ScriptNodeDataSource._nId; util.ScriptNodeDataSource._nId++; // Dynamically add handler function with a closure to the callback stack var oSelf = this; util.ScriptNodeDataSource.callbacks[id] = function(oRawResponse) { if((oSelf.asyncMode !== "ignoreStaleResponses")|| (id === util.ScriptNodeDataSource.callbacks.length-1)) { // Must ignore stale responses // Try to sniff data type if it has not been defined if(oSelf.responseType === DS.TYPE_UNKNOWN) { if(YAHOO.lang.isArray(oRawResponse)) { // array oSelf.responseType = DS.TYPE_JSARRAY; } // xml else if(oRawResponse.nodeType && oRawResponse.nodeType == 9) { oSelf.responseType = DS.TYPE_XML; } else if(oRawResponse.nodeName && (oRawResponse.nodeName.toLowerCase() == "table")) { // table oSelf.responseType = DS.TYPE_HTMLTABLE; } else if(YAHOO.lang.isObject(oRawResponse)) { // json oSelf.responseType = DS.TYPE_JSON; } else if(YAHOO.lang.isString(oRawResponse)) { // text oSelf.responseType = DS.TYPE_TEXT; } } oSelf.handleResponse(oRequest, oRawResponse, oCallback, oCaller, tId); } else { } delete util.ScriptNodeDataSource.callbacks[id]; }; // We are now creating a request util.ScriptNodeDataSource._nPending++; var sUri = this.liveData + oRequest + this.generateRequestCallback(id); sUri = this.doBeforeGetScriptNode(sUri); this.getUtility.script(sUri, {autopurge: true, onsuccess: util.ScriptNodeDataSource._bumpPendingDown, onfail: util.ScriptNodeDataSource._bumpPendingDown}); return tId; } }); // Copy static members to ScriptNodeDataSource class lang.augmentObject(util.ScriptNodeDataSource, DS); // Copy static members to ScriptNodeDataSource class lang.augmentObject(util.ScriptNodeDataSource, { ///////////////////////////////////////////////////////////////////////////// // // ScriptNodeDataSource private static properties // ///////////////////////////////////////////////////////////////////////////// /** * Unique ID to track requests. * * @property _nId * @type Number * @private * @static */ _nId : 0, /** * Counter for pending requests. When this is 0, it is safe to purge callbacks * array. * * @property _nPending * @type Number * @private * @static */ _nPending : 0, /** * Global array of callback functions, one for each request sent. * * @property callbacks * @type Function[] * @static */ callbacks : [] }); /****************************************************************************/ /****************************************************************************/ /****************************************************************************/ /** * XHRDataSource class for accessing remote data via the YUI Connection Manager * Utility * * @namespace YAHOO.util * @class YAHOO.util.XHRDataSource * @extends YAHOO.util.DataSourceBase * @constructor * @param oLiveData {HTMLElement} Pointer to live data. * @param oConfigs {object} (optional) Object literal of configuration values. */ util.XHRDataSource = function(oLiveData, oConfigs) { this.dataType = DS.TYPE_XHR; this.connMgr = this.connMgr || util.Connect; oLiveData = oLiveData || ""; util.XHRDataSource.superclass.constructor.call(this, oLiveData, oConfigs); }; // XHRDataSource extends DataSourceBase lang.extend(util.XHRDataSource, DS, { ///////////////////////////////////////////////////////////////////////////// // // XHRDataSource public properties // ///////////////////////////////////////////////////////////////////////////// /** * Alias to YUI Connection Manager, to allow implementers to use a custom class. * * @property connMgr * @type Object * @default YAHOO.util.Connect */ connMgr: null, /** * Defines request/response management in the following manner: * <dl> * <dt>queueRequests</dt> * <dd>If a request is already in progress, wait until response is returned * before sending the next request.</dd> * * <dt>cancelStaleRequests</dt> * <dd>If a request is already in progress, cancel it before sending the next * request.</dd> * * <dt>ignoreStaleResponses</dt> * <dd>Send all requests, but handle only the response for the most recently * sent request.</dd> * * <dt>allowAll</dt> * <dd>Send all requests and handle all responses.</dd> * * </dl> * * @property connXhrMode * @type String * @default "allowAll" */ connXhrMode: "allowAll", /** * True if data is to be sent via POST. By default, data will be sent via GET. * * @property connMethodPost * @type Boolean * @default false */ connMethodPost: false, /** * The connection timeout defines how many milliseconds the XHR connection will * wait for a server response. Any non-zero value will enable the Connection Manager's * Auto-Abort feature. * * @property connTimeout * @type Number * @default 0 */ connTimeout: 0, ///////////////////////////////////////////////////////////////////////////// // // XHRDataSource public methods // ///////////////////////////////////////////////////////////////////////////// /** * Overriding method passes query to Connection Manager. The returned * response is then forwarded to the handleResponse function. * * @method makeConnection * @param oRequest {Object} Request object. * @param oCallback {Object} Callback object literal. * @param oCaller {Object} (deprecated) Use oCallback.scope. * @return {Number} Transaction ID. */ makeConnection : function(oRequest, oCallback, oCaller) { var oRawResponse = null; var tId = DS._nTransactionId++; this.fireEvent("requestEvent", {tId:tId,request:oRequest,callback:oCallback,caller:oCaller}); // Set up the callback object and // pass the request in as a URL query and // forward the response to the handler var oSelf = this; var oConnMgr = this.connMgr; var oQueue = this._oQueue; /** * Define Connection Manager success handler * * @method _xhrSuccess * @param oResponse {Object} HTTPXMLRequest object * @private */ var _xhrSuccess = function(oResponse) { // If response ID does not match last made request ID, // silently fail and wait for the next response if(oResponse && (this.connXhrMode == "ignoreStaleResponses") && (oResponse.tId != oQueue.conn.tId)) { return null; } // Error if no response else if(!oResponse) { this.fireEvent("dataErrorEvent", {request:oRequest, response:null, callback:oCallback, caller:oCaller, message:DS.ERROR_DATANULL}); // Send error response back to the caller with the error flag on DS.issueCallback(oCallback,[oRequest, {error:true}], true, oCaller); return null; } // Forward to handler else { // Try to sniff data type if it has not been defined if(this.responseType === DS.TYPE_UNKNOWN) { var ctype = (oResponse.getResponseHeader) ? oResponse.getResponseHeader["Content-Type"] : null; if(ctype) { // xml if(ctype.indexOf("text/xml") > -1) { this.responseType = DS.TYPE_XML; } else if(ctype.indexOf("application/json") > -1) { // json this.responseType = DS.TYPE_JSON; } else if(ctype.indexOf("text/plain") > -1) { // text this.responseType = DS.TYPE_TEXT; } } } this.handleResponse(oRequest, oResponse, oCallback, oCaller, tId); } }; /** * Define Connection Manager failure handler * * @method _xhrFailure * @param oResponse {Object} HTTPXMLRequest object * @private */ var _xhrFailure = function(oResponse) { this.fireEvent("dataErrorEvent", {request:oRequest, response: oResponse, callback:oCallback, caller:oCaller, message:DS.ERROR_DATAINVALID}); // Backward compatibility if(lang.isString(this.liveData) && lang.isString(oRequest) && (this.liveData.lastIndexOf("?") !== this.liveData.length-1) && (oRequest.indexOf("?") !== 0)){ } // Send failure response back to the caller with the error flag on oResponse = oResponse || {}; oResponse.error = true; DS.issueCallback(oCallback,[oRequest,oResponse],true, oCaller); return null; }; /** * Define Connection Manager callback object * * @property _xhrCallback * @param oResponse {Object} HTTPXMLRequest object * @private */ var _xhrCallback = { success:_xhrSuccess, failure:_xhrFailure, scope: this }; // Apply Connection Manager timeout if(lang.isNumber(this.connTimeout)) { _xhrCallback.timeout = this.connTimeout; } // Cancel stale requests if(this.connXhrMode == "cancelStaleRequests") { // Look in queue for stale requests if(oQueue.conn) { if(oConnMgr.abort) { oConnMgr.abort(oQueue.conn); oQueue.conn = null; } else { } } } // Get ready to send the request URL if(oConnMgr && oConnMgr.asyncRequest) { var sLiveData = this.liveData; var isPost = this.connMethodPost; var sMethod = (isPost) ? "POST" : "GET"; // Validate request var sUri = (isPost || !lang.isValue(oRequest)) ? sLiveData : sLiveData+oRequest; var sRequest = (isPost) ? oRequest : null; // Send the request right away if(this.connXhrMode != "queueRequests") { oQueue.conn = oConnMgr.asyncRequest(sMethod, sUri, _xhrCallback, sRequest); } // Queue up then send the request else { // Found a request already in progress if(oQueue.conn) { var allRequests = oQueue.requests; // Add request to queue allRequests.push({request:oRequest, callback:_xhrCallback}); // Interval needs to be started if(!oQueue.interval) { oQueue.interval = setInterval(function() { // Connection is in progress if(oConnMgr.isCallInProgress(oQueue.conn)) { return; } else { // Send next request if(allRequests.length > 0) { // Validate request sUri = (isPost || !lang.isValue(allRequests[0].request)) ? sLiveData : sLiveData+allRequests[0].request; sRequest = (isPost) ? allRequests[0].request : null; oQueue.conn = oConnMgr.asyncRequest(sMethod, sUri, allRequests[0].callback, sRequest); // Remove request from queue allRequests.shift(); } // No more requests else { clearInterval(oQueue.interval); oQueue.interval = null; } } }, 50); } } // Nothing is in progress else { oQueue.conn = oConnMgr.asyncRequest(sMethod, sUri, _xhrCallback, sRequest); } } } else { // Send null response back to the caller with the error flag on DS.issueCallback(oCallback,[oRequest,{error:true}],true,oCaller); } return tId; } }); // Copy static members to XHRDataSource class lang.augmentObject(util.XHRDataSource, DS); /****************************************************************************/ /****************************************************************************/ /****************************************************************************/ /** * Factory class for creating a BaseDataSource subclass instance. The sublcass is * determined by oLiveData's type, unless the dataType config is explicitly passed in. * * @namespace YAHOO.util * @class YAHOO.util.DataSource * @constructor * @param oLiveData {HTMLElement} Pointer to live data. * @param oConfigs {object} (optional) Object literal of configuration values. */ util.DataSource = function(oLiveData, oConfigs) { oConfigs = oConfigs || {}; // Point to one of the subclasses, first by dataType if given, then by sniffing oLiveData type. var dataType = oConfigs.dataType; if(dataType) { if(dataType == DS.TYPE_LOCAL) { return new util.LocalDataSource(oLiveData, oConfigs); } else if(dataType == DS.TYPE_XHR) { return new util.XHRDataSource(oLiveData, oConfigs); } else if(dataType == DS.TYPE_SCRIPTNODE) { return new util.ScriptNodeDataSource(oLiveData, oConfigs); } else if(dataType == DS.TYPE_JSFUNCTION) { return new util.FunctionDataSource(oLiveData, oConfigs); } } if(YAHOO.lang.isString(oLiveData)) { // strings default to xhr return new util.XHRDataSource(oLiveData, oConfigs); } else if(YAHOO.lang.isFunction(oLiveData)) { return new util.FunctionDataSource(oLiveData, oConfigs); } else { // ultimate default is local return new util.LocalDataSource(oLiveData, oConfigs); } }; // Copy static members to DataSource class lang.augmentObject(util.DataSource, DS); })(); /****************************************************************************/ /****************************************************************************/ /****************************************************************************/ /** * The static Number class provides helper functions to deal with data of type * Number. * * @namespace YAHOO.util * @requires yahoo * @class Number * @static */ YAHOO.util.Number = { /** * Takes a native JavaScript Number and formats to a string for display. * * @method format * @param nData {Number} Number. * @param oConfig {Object} (Optional) Optional configuration values: * <dl> * <dt>format</dt> * <dd>String used as a template for formatting positive numbers. * {placeholders} in the string are applied from the values in this * config object. {number} is used to indicate where the numeric portion * of the output goes. For example &quot;{prefix}{number} per item&quot; * might yield &quot;$5.25 per item&quot;. The only required * {placeholder} is {number}.</dd> * * <dt>negativeFormat</dt> * <dd>Like format, but applied to negative numbers. If set to null, * defaults from the configured format, prefixed with -. This is * separate from format to support formats like &quot;($12,345.67)&quot;. * * <dt>prefix {String} (deprecated, use format/negativeFormat)</dt> * <dd>String prepended before each number, like a currency designator "$"</dd> * <dt>decimalPlaces {Number}</dt> * <dd>Number of decimal places to round.</dd> * * <dt>decimalSeparator {String}</dt> * <dd>Decimal separator</dd> * * <dt>thousandsSeparator {String}</dt> * <dd>Thousands separator</dd> * * <dt>suffix {String} (deprecated, use format/negativeFormat)</dt> * <dd>String appended after each number, like " items" (note the space)</dd> * </dl> * @return {String} Formatted number for display. Note, the following values * return as "": null, undefined, NaN, "". */ format : function(n, cfg) { if (n === '' || n === null || !isFinite(n)) { return ''; } n = +n; cfg = YAHOO.lang.merge(YAHOO.util.Number.format.defaults, (cfg || {})); var stringN = n+'', absN = Math.abs(n), places = cfg.decimalPlaces || 0, sep = cfg.thousandsSeparator, negFmt = cfg.negativeFormat || ('-' + cfg.format), s, bits, i, precision; if (negFmt.indexOf('#') > -1) { // for backward compatibility of negativeFormat supporting '-#' negFmt = negFmt.replace(/#/, cfg.format); } if (places < 0) { // Get rid of the decimal info s = absN - (absN % 1) + ''; i = s.length + places; // avoid 123 vs decimalPlaces -4 (should return "0") if (i > 0) { // leverage toFixed by making 123 => 0.123 for the rounding // operation, then add the appropriate number of zeros back on s = Number('.' + s).toFixed(i).slice(2) + new Array(s.length - i + 1).join('0'); } else { s = "0"; } } else { // Avoid toFixed on floats: // Bug 2528976 // Bug 2528977 var unfloatedN = absN+''; if(places > 0 || unfloatedN.indexOf('.') > 0) { var power = Math.pow(10, places); s = Math.round(absN * power) / power + ''; var dot = s.indexOf('.'), padding, zeroes; // Add padding if(dot < 0) { padding = places; zeroes = (Math.pow(10, padding) + '').substring(1); if(places > 0) { s = s + '.' + zeroes; } } else { padding = places - (s.length - dot - 1); zeroes = (Math.pow(10, padding) + '').substring(1); s = s + zeroes; } } else { s = absN.toFixed(places)+''; } } bits = s.split(/\D/); if (absN >= 1000) { i = bits[0].length % 3 || 3; bits[0] = bits[0].slice(0,i) + bits[0].slice(i).replace(/(\d{3})/g, sep + '$1'); } return YAHOO.util.Number.format._applyFormat( (n < 0 ? negFmt : cfg.format), bits.join(cfg.decimalSeparator), cfg); } }; /** * <p>Default values for Number.format behavior. Override properties of this * object if you want every call to Number.format in your system to use * specific presets.</p> * * <p>Available keys include:</p> * <ul> * <li>format</li> * <li>negativeFormat</li> * <li>decimalSeparator</li> * <li>decimalPlaces</li> * <li>thousandsSeparator</li> * <li>prefix/suffix or any other token you want to use in the format templates</li> * </ul> * * @property Number.format.defaults * @type {Object} * @static */ YAHOO.util.Number.format.defaults = { format : '{prefix}{number}{suffix}', negativeFormat : null, // defaults to -(format) decimalSeparator : '.', decimalPlaces : null, thousandsSeparator : '' }; /** * Apply any special formatting to the "d,ddd.dd" string. Takes either the * cfg.format or cfg.negativeFormat template and replaces any {placeholders} * with either the number or a value from a so-named property of the config * object. * * @method Number.format._applyFormat * @static * @param tmpl {String} the cfg.format or cfg.numberFormat template string * @param num {String} the number with separators and decimalPlaces applied * @param data {Object} the config object, used here to populate {placeholder}s * @return {String} the number with any decorators added */ YAHOO.util.Number.format._applyFormat = function (tmpl, num, data) { return tmpl.replace(/\{(\w+)\}/g, function (_, token) { return token === 'number' ? num : token in data ? data[token] : ''; }); }; /****************************************************************************/ /****************************************************************************/ /****************************************************************************/ (function () { var xPad=function (x, pad, r) { if(typeof r === 'undefined') { r=10; } for( ; parseInt(x, 10)<r && r>1; r/=10) { x = pad.toString() + x; } return x.toString(); }; /** * The static Date class provides helper functions to deal with data of type Date. * * @namespace YAHOO.util * @requires yahoo * @class Date * @static */ var Dt = { formats: { a: function (d, l) { return l.a[d.getDay()]; }, A: function (d, l) { return l.A[d.getDay()]; }, b: function (d, l) { return l.b[d.getMonth()]; }, B: function (d, l) { return l.B[d.getMonth()]; }, C: function (d) { return xPad(parseInt(d.getFullYear()/100, 10), 0); }, d: ['getDate', '0'], e: ['getDate', ' '], g: function (d) { return xPad(parseInt(Dt.formats.G(d)%100, 10), 0); }, G: function (d) { var y = d.getFullYear(); var V = parseInt(Dt.formats.V(d), 10); var W = parseInt(Dt.formats.W(d), 10); if(W > V) { y++; } else if(W===0 && V>=52) { y--; } return y; }, H: ['getHours', '0'], I: function (d) { var I=d.getHours()%12; return xPad(I===0?12:I, 0); }, j: function (d) { var gmd_1 = new Date('' + d.getFullYear() + '/1/1 GMT'); var gmdate = new Date('' + d.getFullYear() + '/' + (d.getMonth()+1) + '/' + d.getDate() + ' GMT'); var ms = gmdate - gmd_1; var doy = parseInt(ms/60000/60/24, 10)+1; return xPad(doy, 0, 100); }, k: ['getHours', ' '], l: function (d) { var I=d.getHours()%12; return xPad(I===0?12:I, ' '); }, m: function (d) { return xPad(d.getMonth()+1, 0); }, M: ['getMinutes', '0'], p: function (d, l) { return l.p[d.getHours() >= 12 ? 1 : 0 ]; }, P: function (d, l) { return l.P[d.getHours() >= 12 ? 1 : 0 ]; }, s: function (d, l) { return parseInt(d.getTime()/1000, 10); }, S: ['getSeconds', '0'], u: function (d) { var dow = d.getDay(); return dow===0?7:dow; }, U: function (d) { var doy = parseInt(Dt.formats.j(d), 10); var rdow = 6-d.getDay(); var woy = parseInt((doy+rdow)/7, 10); return xPad(woy, 0); }, V: function (d) { var woy = parseInt(Dt.formats.W(d), 10); var dow1_1 = (new Date('' + d.getFullYear() + '/1/1')).getDay(); // First week is 01 and not 00 as in the case of %U and %W, // so we add 1 to the final result except if day 1 of the year // is a Monday (then %W returns 01). // We also need to subtract 1 if the day 1 of the year is // Friday-Sunday, so the resulting equation becomes: var idow = woy + (dow1_1 > 4 || dow1_1 <= 1 ? 0 : 1); if(idow === 53 && (new Date('' + d.getFullYear() + '/12/31')).getDay() < 4) { idow = 1; } else if(idow === 0) { idow = Dt.formats.V(new Date('' + (d.getFullYear()-1) + '/12/31')); } return xPad(idow, 0); }, w: 'getDay', W: function (d) { var doy = parseInt(Dt.formats.j(d), 10); var rdow = 7-Dt.formats.u(d); var woy = parseInt((doy+rdow)/7, 10); return xPad(woy, 0, 10); }, y: function (d) { return xPad(d.getFullYear()%100, 0); }, Y: 'getFullYear', z: function (d) { var o = d.getTimezoneOffset(); var H = xPad(parseInt(Math.abs(o/60), 10), 0); var M = xPad(Math.abs(o%60), 0); return (o>0?'-':'+') + H + M; }, Z: function (d) { var tz = d.toString().replace(/^.*:\d\d( GMT[+-]\d+)? \(?([A-Za-z ]+)\)?\d*$/, '$2').replace(/[a-z ]/g, ''); if(tz.length > 4) { tz = Dt.formats.z(d); } return tz; }, '%': function (d) { return '%'; } }, aggregates: { c: 'locale', D: '%m/%d/%y', F: '%Y-%m-%d', h: '%b', n: '\n', r: 'locale', R: '%H:%M', t: '\t', T: '%H:%M:%S', x: 'locale', X: 'locale' //'+': '%a %b %e %T %Z %Y' }, /** * Takes a native JavaScript Date and formats to string for display to user. * * @method format * @param oDate {Date} Date. * @param oConfig {Object} (Optional) Object literal of configuration values: * <dl> * <dt>format &lt;String&gt;</dt> * <dd> * <p> * Any strftime string is supported, such as "%I:%M:%S %p". strftime has several format specifiers defined by the Open group at * <a href="http://www.opengroup.org/onlinepubs/007908799/xsh/strftime.html">http://www.opengroup.org/onlinepubs/007908799/xsh/strftime.html</a> * </p> * <p> * PHP added a few of its own, defined at <a href="http://www.php.net/strftime">http://www.php.net/strftime</a> * </p> * <p> * This javascript implementation supports all the PHP specifiers and a few more. The full list is below: * </p> * <dl> * <dt>%a</dt> <dd>abbreviated weekday name according to the current locale</dd> * <dt>%A</dt> <dd>full weekday name according to the current locale</dd> * <dt>%b</dt> <dd>abbreviated month name according to the current locale</dd> * <dt>%B</dt> <dd>full month name according to the current locale</dd> * <dt>%c</dt> <dd>preferred date and time representation for the current locale</dd> * <dt>%C</dt> <dd>century number (the year divided by 100 and truncated to an integer, range 00 to 99)</dd> * <dt>%d</dt> <dd>day of the month as a decimal number (range 01 to 31)</dd> * <dt>%D</dt> <dd>same as %m/%d/%y</dd> * <dt>%e</dt> <dd>day of the month as a decimal number, a single digit is preceded by a space (range ' 1' to '31')</dd> * <dt>%F</dt> <dd>same as %Y-%m-%d (ISO 8601 date format)</dd> * <dt>%g</dt> <dd>like %G, but without the century</dd> * <dt>%G</dt> <dd>The 4-digit year corresponding to the ISO week number</dd> * <dt>%h</dt> <dd>same as %b</dd> * <dt>%H</dt> <dd>hour as a decimal number using a 24-hour clock (range 00 to 23)</dd> * <dt>%I</dt> <dd>hour as a decimal number using a 12-hour clock (range 01 to 12)</dd> * <dt>%j</dt> <dd>day of the year as a decimal number (range 001 to 366)</dd> * <dt>%k</dt> <dd>hour as a decimal number using a 24-hour clock (range 0 to 23); single digits are preceded by a blank. (See also %H.)</dd> * <dt>%l</dt> <dd>hour as a decimal number using a 12-hour clock (range 1 to 12); single digits are preceded by a blank. (See also %I.) </dd> * <dt>%m</dt> <dd>month as a decimal number (range 01 to 12)</dd> * <dt>%M</dt> <dd>minute as a decimal number</dd> * <dt>%n</dt> <dd>newline character</dd> * <dt>%p</dt> <dd>either `AM' or `PM' according to the given time value, or the corresponding strings for the current locale</dd> * <dt>%P</dt> <dd>like %p, but lower case</dd> * <dt>%r</dt> <dd>time in a.m. and p.m. notation equal to %I:%M:%S %p</dd> * <dt>%R</dt> <dd>time in 24 hour notation equal to %H:%M</dd> * <dt>%s</dt> <dd>number of seconds since the Epoch, ie, since 1970-01-01 00:00:00 UTC</dd> * <dt>%S</dt> <dd>second as a decimal number</dd> * <dt>%t</dt> <dd>tab character</dd> * <dt>%T</dt> <dd>current time, equal to %H:%M:%S</dd> * <dt>%u</dt> <dd>weekday as a decimal number [1,7], with 1 representing Monday</dd> * <dt>%U</dt> <dd>week number of the current year as a decimal number, starting with the * first Sunday as the first day of the first week</dd> * <dt>%V</dt> <dd>The ISO 8601:1988 week number of the current year as a decimal number, * range 01 to 53, where week 1 is the first week that has at least 4 days * in the current year, and with Monday as the first day of the week.</dd> * <dt>%w</dt> <dd>day of the week as a decimal, Sunday being 0</dd> * <dt>%W</dt> <dd>week number of the current year as a decimal number, starting with the * first Monday as the first day of the first week</dd> * <dt>%x</dt> <dd>preferred date representation for the current locale without the time</dd> * <dt>%X</dt> <dd>preferred time representation for the current locale without the date</dd> * <dt>%y</dt> <dd>year as a decimal number without a century (range 00 to 99)</dd> * <dt>%Y</dt> <dd>year as a decimal number including the century</dd> * <dt>%z</dt> <dd>numerical time zone representation</dd> * <dt>%Z</dt> <dd>time zone name or abbreviation</dd> * <dt>%%</dt> <dd>a literal `%' character</dd> * </dl> * </dd> * </dl> * @param sLocale {String} (Optional) The locale to use when displaying days of week, * months of the year, and other locale specific strings. The following locales are * built in: * <dl> * <dt>en</dt> * <dd>English</dd> * <dt>en-US</dt> * <dd>US English</dd> * <dt>en-GB</dt> * <dd>British English</dd> * <dt>en-AU</dt> * <dd>Australian English (identical to British English)</dd> * </dl> * More locales may be added by subclassing of YAHOO.util.DateLocale. * See YAHOO.util.DateLocale for more information. * @return {HTML} Formatted date for display. Non-date values are passed * through as-is. * @sa YAHOO.util.DateLocale */ format : function (oDate, oConfig, sLocale) { oConfig = oConfig || {}; if(!(oDate instanceof Date)) { return YAHOO.lang.isValue(oDate) ? oDate : ""; } var format = oConfig.format || "%m/%d/%Y"; // Be backwards compatible, support strings that are // exactly equal to YYYY/MM/DD, DD/MM/YYYY and MM/DD/YYYY if(format === 'YYYY/MM/DD') { format = '%Y/%m/%d'; } else if(format === 'DD/MM/YYYY') { format = '%d/%m/%Y'; } else if(format === 'MM/DD/YYYY') { format = '%m/%d/%Y'; } // end backwards compatibility block sLocale = sLocale || "en"; // Make sure we have a definition for the requested locale, or default to en. if(!(sLocale in YAHOO.util.DateLocale)) { if(sLocale.replace(/-[a-zA-Z]+$/, '') in YAHOO.util.DateLocale) { sLocale = sLocale.replace(/-[a-zA-Z]+$/, ''); } else { sLocale = "en"; } } var aLocale = YAHOO.util.DateLocale[sLocale]; var replace_aggs = function (m0, m1) { var f = Dt.aggregates[m1]; return (f === 'locale' ? aLocale[m1] : f); }; var replace_formats = function (m0, m1) { var f = Dt.formats[m1]; if(typeof f === 'string') { // string => built in date function return oDate[f](); } else if(typeof f === 'function') { // function => our own function return f.call(oDate, oDate, aLocale); } else if(typeof f === 'object' && typeof f[0] === 'string') { // built in function with padding return xPad(oDate[f[0]](), f[1]); } else { return m1; } }; // First replace aggregates (run in a loop because an agg may be made up of other aggs) while(format.match(/%[cDFhnrRtTxX]/)) { format = format.replace(/%([cDFhnrRtTxX])/g, replace_aggs); } // Now replace formats (do not run in a loop otherwise %%a will be replace with the value of %a) var str = format.replace(/%([aAbBCdegGHIjklmMpPsSuUVwWyYzZ%])/g, replace_formats); replace_aggs = replace_formats = undefined; return str; } }; YAHOO.namespace("YAHOO.util"); YAHOO.util.Date = Dt; /** * The DateLocale class is a container and base class for all * localised date strings used by YAHOO.util.Date. It is used * internally, but may be extended to provide new date localisations. * * To create your own DateLocale, follow these steps: * <ol> * <li>Find an existing locale that matches closely with your needs</li> * <li>Use this as your base class. Use YAHOO.util.DateLocale if nothing * matches.</li> * <li>Create your own class as an extension of the base class using * YAHOO.lang.merge, and add your own localisations where needed.</li> * </ol> * See the YAHOO.util.DateLocale['en-US'] and YAHOO.util.DateLocale['en-GB'] * classes which extend YAHOO.util.DateLocale['en']. * * For example, to implement locales for French french and Canadian french, * we would do the following: * <ol> * <li>For French french, we have no existing similar locale, so use * YAHOO.util.DateLocale as the base, and extend it: * <pre> * YAHOO.util.DateLocale['fr'] = YAHOO.lang.merge(YAHOO.util.DateLocale, { * a: ['dim', 'lun', 'mar', 'mer', 'jeu', 'ven', 'sam'], * A: ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'], * b: ['jan', 'f&eacute;v', 'mar', 'avr', 'mai', 'jun', 'jui', 'ao&ucirc;', 'sep', 'oct', 'nov', 'd&eacute;c'], * B: ['janvier', 'f&eacute;vrier', 'mars', 'avril', 'mai', 'juin', 'juillet', 'ao&ucirc;t', 'septembre', 'octobre', 'novembre', 'd&eacute;cembre'], * c: '%a %d %b %Y %T %Z', * p: ['', ''], * P: ['', ''], * x: '%d.%m.%Y', * X: '%T' * }); * </pre> * </li> * <li>For Canadian french, we start with French french and change the meaning of \%x: * <pre> * YAHOO.util.DateLocale['fr-CA'] = YAHOO.lang.merge(YAHOO.util.DateLocale['fr'], { * x: '%Y-%m-%d' * }); * </pre> * </li> * </ol> * * With that, you can use your new locales: * <pre> * var d = new Date("2008/04/22"); * YAHOO.util.Date.format(d, {format: "%A, %d %B == %x"}, "fr"); * </pre> * will return: * <pre> * mardi, 22 avril == 22.04.2008 * </pre> * And * <pre> * YAHOO.util.Date.format(d, {format: "%A, %d %B == %x"}, "fr-CA"); * </pre> * Will return: * <pre> * mardi, 22 avril == 2008-04-22 * </pre> * @namespace YAHOO.util * @requires yahoo * @class DateLocale */ YAHOO.util.DateLocale = { a: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], A: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], b: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], B: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], c: '%a %d %b %Y %T %Z', p: ['AM', 'PM'], P: ['am', 'pm'], r: '%I:%M:%S %p', x: '%d/%m/%y', X: '%T' }; YAHOO.util.DateLocale['en'] = YAHOO.lang.merge(YAHOO.util.DateLocale, {}); YAHOO.util.DateLocale['en-US'] = YAHOO.lang.merge(YAHOO.util.DateLocale['en'], { c: '%a %d %b %Y %I:%M:%S %p %Z', x: '%m/%d/%Y', X: '%I:%M:%S %p' }); YAHOO.util.DateLocale['en-GB'] = YAHOO.lang.merge(YAHOO.util.DateLocale['en'], { r: '%l:%M:%S %P %Z' }); YAHOO.util.DateLocale['en-AU'] = YAHOO.lang.merge(YAHOO.util.DateLocale['en']); })(); YAHOO.register("datasource", YAHOO.util.DataSource, {version: "2.9.0", build: "2800"});
recap/weevilscout
yui/build/datasource/datasource.js
JavaScript
apache-2.0
106,266
/* * Kernel CAPI 2.0 Module - /proc/capi handling * * Copyright 1999 by Carsten Paeth <[email protected]> * Copyright 2002 by Kai Germaschewski <[email protected]> * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * */ #include "kcapi.h" #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/init.h> static char *state2str(unsigned short state) { switch (state) { case CAPI_CTR_DETECTED: return "detected"; case CAPI_CTR_LOADING: return "loading"; case CAPI_CTR_RUNNING: return "running"; default: return "???"; } } // /proc/capi // =========================================================================== // /proc/capi/controller: // cnr driver cardstate name driverinfo // /proc/capi/contrstats: // cnr nrecvctlpkt nrecvdatapkt nsentctlpkt nsentdatapkt // --------------------------------------------------------------------------- static void *controller_start(struct seq_file *seq, loff_t *pos) __acquires(capi_controller_lock) { mutex_lock(&capi_controller_lock); if (*pos < CAPI_MAXCONTR) return &capi_controller[*pos]; return NULL; } static void *controller_next(struct seq_file *seq, void *v, loff_t *pos) { ++*pos; if (*pos < CAPI_MAXCONTR) return &capi_controller[*pos]; return NULL; } static void controller_stop(struct seq_file *seq, void *v) __releases(capi_controller_lock) { mutex_unlock(&capi_controller_lock); } static int controller_show(struct seq_file *seq, void *v) { struct capi_ctr *ctr = *(struct capi_ctr **) v; if (!ctr) return 0; seq_printf(seq, "%d %-10s %-8s %-16s %s\n", ctr->cnr, ctr->driver_name, state2str(ctr->state), ctr->name, ctr->procinfo ? ctr->procinfo(ctr) : ""); return 0; } static int contrstats_show(struct seq_file *seq, void *v) { struct capi_ctr *ctr = *(struct capi_ctr **) v; if (!ctr) return 0; seq_printf(seq, "%d %lu %lu %lu %lu\n", ctr->cnr, ctr->nrecvctlpkt, ctr->nrecvdatapkt, ctr->nsentctlpkt, ctr->nsentdatapkt); return 0; } static const struct seq_operations seq_controller_ops = { .start = controller_start, .next = controller_next, .stop = controller_stop, .show = controller_show, }; static const struct seq_operations seq_contrstats_ops = { .start = controller_start, .next = controller_next, .stop = controller_stop, .show = contrstats_show, }; static int seq_controller_open(struct inode *inode, struct file *file) { return seq_open(file, &seq_controller_ops); } static int seq_contrstats_open(struct inode *inode, struct file *file) { return seq_open(file, &seq_contrstats_ops); } static const struct file_operations proc_controller_ops = { .owner = THIS_MODULE, .open = seq_controller_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static const struct file_operations proc_contrstats_ops = { .owner = THIS_MODULE, .open = seq_contrstats_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; // /proc/capi/applications: // applid l3cnt dblkcnt dblklen #ncci recvqueuelen // /proc/capi/applstats: // applid nrecvctlpkt nrecvdatapkt nsentctlpkt nsentdatapkt // --------------------------------------------------------------------------- static void *applications_start(struct seq_file *seq, loff_t *pos) __acquires(capi_controller_lock) { mutex_lock(&capi_controller_lock); if (*pos < CAPI_MAXAPPL) return &capi_applications[*pos]; return NULL; } static void * applications_next(struct seq_file *seq, void *v, loff_t *pos) { ++*pos; if (*pos < CAPI_MAXAPPL) return &capi_applications[*pos]; return NULL; } static void applications_stop(struct seq_file *seq, void *v) __releases(capi_controller_lock) { mutex_unlock(&capi_controller_lock); } static int applications_show(struct seq_file *seq, void *v) { struct capi20_appl *ap = *(struct capi20_appl **) v; if (!ap) return 0; seq_printf(seq, "%u %d %d %d\n", ap->applid, ap->rparam.level3cnt, ap->rparam.datablkcnt, ap->rparam.datablklen); return 0; } static int applstats_show(struct seq_file *seq, void *v) { struct capi20_appl *ap = *(struct capi20_appl **) v; if (!ap) return 0; seq_printf(seq, "%u %lu %lu %lu %lu\n", ap->applid, ap->nrecvctlpkt, ap->nrecvdatapkt, ap->nsentctlpkt, ap->nsentdatapkt); return 0; } static const struct seq_operations seq_applications_ops = { .start = applications_start, .next = applications_next, .stop = applications_stop, .show = applications_show, }; static const struct seq_operations seq_applstats_ops = { .start = applications_start, .next = applications_next, .stop = applications_stop, .show = applstats_show, }; static int seq_applications_open(struct inode *inode, struct file *file) { return seq_open(file, &seq_applications_ops); } static int seq_applstats_open(struct inode *inode, struct file *file) { return seq_open(file, &seq_applstats_ops); } static const struct file_operations proc_applications_ops = { .owner = THIS_MODULE, .open = seq_applications_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static const struct file_operations proc_applstats_ops = { .owner = THIS_MODULE, .open = seq_applstats_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; // --------------------------------------------------------------------------- static void *capi_driver_start(struct seq_file *seq, loff_t *pos) __acquires(&capi_drivers_lock) { mutex_lock(&capi_drivers_lock); return seq_list_start(&capi_drivers, *pos); } static void *capi_driver_next(struct seq_file *seq, void *v, loff_t *pos) { return seq_list_next(v, &capi_drivers, pos); } static void capi_driver_stop(struct seq_file *seq, void *v) __releases(&capi_drivers_lock) { mutex_unlock(&capi_drivers_lock); } static int capi_driver_show(struct seq_file *seq, void *v) { struct capi_driver *drv = list_entry(v, struct capi_driver, list); seq_printf(seq, "%-32s %s\n", drv->name, drv->revision); return 0; } static const struct seq_operations seq_capi_driver_ops = { .start = capi_driver_start, .next = capi_driver_next, .stop = capi_driver_stop, .show = capi_driver_show, }; static int seq_capi_driver_open(struct inode *inode, struct file *file) { int err; err = seq_open(file, &seq_capi_driver_ops); return err; } static const struct file_operations proc_driver_ops = { .owner = THIS_MODULE, .open = seq_capi_driver_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; // --------------------------------------------------------------------------- void __init kcapi_proc_init(void) { proc_mkdir("capi", NULL); proc_mkdir("capi/controllers", NULL); proc_create("capi/controller", 0, NULL, &proc_controller_ops); proc_create("capi/contrstats", 0, NULL, &proc_contrstats_ops); proc_create("capi/applications", 0, NULL, &proc_applications_ops); proc_create("capi/applstats", 0, NULL, &proc_applstats_ops); proc_create("capi/driver", 0, NULL, &proc_driver_ops); } void __exit kcapi_proc_exit(void) { remove_proc_entry("capi/driver", NULL); remove_proc_entry("capi/controller", NULL); remove_proc_entry("capi/contrstats", NULL); remove_proc_entry("capi/applications", NULL); remove_proc_entry("capi/applstats", NULL); remove_proc_entry("capi/controllers", NULL); remove_proc_entry("capi", NULL); }
JijonHyuni/HyperKernel-JB
virt/drivers/isdn/capi/kcapi_proc.c
C
gpl-2.0
7,528
/* * hdaps.c - driver for IBM's Hard Drive Active Protection System * * Copyright (C) 2005 Robert Love <[email protected]> * Copyright (C) 2005 Jesper Juhl <[email protected]> * * The HardDisk Active Protection System (hdaps) is present in IBM ThinkPads * starting with the R40, T41, and X40. It provides a basic two-axis * accelerometer and other data, such as the device's temperature. * * This driver is based on the document by Mark A. Smith available at * http://www.almaden.ibm.com/cs/people/marksmith/tpaps.html and a lot of trial * and error. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License v2 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. * * 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., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/delay.h> #include <linux/platform_device.h> #include <linux/input-polldev.h> #include <linux/kernel.h> #include <linux/mutex.h> #include <linux/module.h> #include <linux/timer.h> #include <linux/dmi.h> #include <linux/jiffies.h> #include <linux/io.h> #define HDAPS_LOW_PORT 0x1600 /* first port used by hdaps */ #define HDAPS_NR_PORTS 0x30 /* number of ports: 0x1600 - 0x162f */ #define HDAPS_PORT_STATE 0x1611 /* device state */ #define HDAPS_PORT_YPOS 0x1612 /* y-axis position */ #define HDAPS_PORT_XPOS 0x1614 /* x-axis position */ #define HDAPS_PORT_TEMP1 0x1616 /* device temperature, in Celsius */ #define HDAPS_PORT_YVAR 0x1617 /* y-axis variance (what is this?) */ #define HDAPS_PORT_XVAR 0x1619 /* x-axis variance (what is this?) */ #define HDAPS_PORT_TEMP2 0x161b /* device temperature (again?) */ #define HDAPS_PORT_UNKNOWN 0x161c /* what is this? */ #define HDAPS_PORT_KMACT 0x161d /* keyboard or mouse activity */ #define STATE_FRESH 0x50 /* accelerometer data is fresh */ #define KEYBD_MASK 0x20 /* set if keyboard activity */ #define MOUSE_MASK 0x40 /* set if mouse activity */ #define KEYBD_ISSET(n) (!! (n & KEYBD_MASK)) /* keyboard used? */ #define MOUSE_ISSET(n) (!! (n & MOUSE_MASK)) /* mouse used? */ #define INIT_TIMEOUT_MSECS 4000 /* wait up to 4s for device init ... */ #define INIT_WAIT_MSECS 200 /* ... in 200ms increments */ #define HDAPS_POLL_INTERVAL 50 /* poll for input every 1/20s (50 ms)*/ #define HDAPS_INPUT_FUZZ 4 /* input event threshold */ #define HDAPS_INPUT_FLAT 4 #define HDAPS_X_AXIS (1 << 0) #define HDAPS_Y_AXIS (1 << 1) #define HDAPS_BOTH_AXES (HDAPS_X_AXIS | HDAPS_Y_AXIS) static struct platform_device *pdev; static struct input_polled_dev *hdaps_idev; static unsigned int hdaps_invert; static u8 km_activity; static int rest_x; static int rest_y; static DEFINE_MUTEX(hdaps_mtx); /* * __get_latch - Get the value from a given port. Callers must hold hdaps_mtx. */ static inline u8 __get_latch(u16 port) { return inb(port) & 0xff; } /* * __check_latch - Check a port latch for a given value. Returns zero if the * port contains the given value. Callers must hold hdaps_mtx. */ static inline int __check_latch(u16 port, u8 val) { if (__get_latch(port) == val) return 0; return -EINVAL; } /* * __wait_latch - Wait up to 100us for a port latch to get a certain value, * returning zero if the value is obtained. Callers must hold hdaps_mtx. */ static int __wait_latch(u16 port, u8 val) { unsigned int i; for (i = 0; i < 20; i++) { if (!__check_latch(port, val)) return 0; udelay(5); } return -EIO; } /* * __device_refresh - request a refresh from the accelerometer. Does not wait * for refresh to complete. Callers must hold hdaps_mtx. */ static void __device_refresh(void) { udelay(200); if (inb(0x1604) != STATE_FRESH) { outb(0x11, 0x1610); outb(0x01, 0x161f); } } /* * __device_refresh_sync - request a synchronous refresh from the * accelerometer. We wait for the refresh to complete. Returns zero if * successful and nonzero on error. Callers must hold hdaps_mtx. */ static int __device_refresh_sync(void) { __device_refresh(); return __wait_latch(0x1604, STATE_FRESH); } /* * __device_complete - indicate to the accelerometer that we are done reading * data, and then initiate an async refresh. Callers must hold hdaps_mtx. */ static inline void __device_complete(void) { inb(0x161f); inb(0x1604); __device_refresh(); } /* * hdaps_readb_one - reads a byte from a single I/O port, placing the value in * the given pointer. Returns zero on success or a negative error on failure. * Can sleep. */ static int hdaps_readb_one(unsigned int port, u8 *val) { int ret; mutex_lock(&hdaps_mtx); /* do a sync refresh -- we need to be sure that we read fresh data */ ret = __device_refresh_sync(); if (ret) goto out; *val = inb(port); __device_complete(); out: mutex_unlock(&hdaps_mtx); return ret; } /* __hdaps_read_pair - internal lockless helper for hdaps_read_pair(). */ static int __hdaps_read_pair(unsigned int port1, unsigned int port2, int *x, int *y) { /* do a sync refresh -- we need to be sure that we read fresh data */ if (__device_refresh_sync()) return -EIO; *y = inw(port2); *x = inw(port1); km_activity = inb(HDAPS_PORT_KMACT); __device_complete(); /* hdaps_invert is a bitvector to negate the axes */ if (hdaps_invert & HDAPS_X_AXIS) *x = -*x; if (hdaps_invert & HDAPS_Y_AXIS) *y = -*y; return 0; } /* * hdaps_read_pair - reads the values from a pair of ports, placing the values * in the given pointers. Returns zero on success. Can sleep. */ static int hdaps_read_pair(unsigned int port1, unsigned int port2, int *val1, int *val2) { int ret; mutex_lock(&hdaps_mtx); ret = __hdaps_read_pair(port1, port2, val1, val2); mutex_unlock(&hdaps_mtx); return ret; } /* * hdaps_device_init - initialize the accelerometer. Returns zero on success * and negative error code on failure. Can sleep. */ static int hdaps_device_init(void) { int total, ret = -ENXIO; mutex_lock(&hdaps_mtx); outb(0x13, 0x1610); outb(0x01, 0x161f); if (__wait_latch(0x161f, 0x00)) goto out; /* * Most ThinkPads return 0x01. * * Others--namely the R50p, T41p, and T42p--return 0x03. These laptops * have "inverted" axises. * * The 0x02 value occurs when the chip has been previously initialized. */ if (__check_latch(0x1611, 0x03) && __check_latch(0x1611, 0x02) && __check_latch(0x1611, 0x01)) goto out; printk(KERN_DEBUG "hdaps: initial latch check good (0x%02x)\n", __get_latch(0x1611)); outb(0x17, 0x1610); outb(0x81, 0x1611); outb(0x01, 0x161f); if (__wait_latch(0x161f, 0x00)) goto out; if (__wait_latch(0x1611, 0x00)) goto out; if (__wait_latch(0x1612, 0x60)) goto out; if (__wait_latch(0x1613, 0x00)) goto out; outb(0x14, 0x1610); outb(0x01, 0x1611); outb(0x01, 0x161f); if (__wait_latch(0x161f, 0x00)) goto out; outb(0x10, 0x1610); outb(0xc8, 0x1611); outb(0x00, 0x1612); outb(0x02, 0x1613); outb(0x01, 0x161f); if (__wait_latch(0x161f, 0x00)) goto out; if (__device_refresh_sync()) goto out; if (__wait_latch(0x1611, 0x00)) goto out; /* we have done our dance, now let's wait for the applause */ for (total = INIT_TIMEOUT_MSECS; total > 0; total -= INIT_WAIT_MSECS) { int x, y; /* a read of the device helps push it into action */ __hdaps_read_pair(HDAPS_PORT_XPOS, HDAPS_PORT_YPOS, &x, &y); if (!__wait_latch(0x1611, 0x02)) { ret = 0; break; } msleep(INIT_WAIT_MSECS); } out: mutex_unlock(&hdaps_mtx); return ret; } /* Device model stuff */ static int hdaps_probe(struct platform_device *dev) { int ret; ret = hdaps_device_init(); if (ret) return ret; pr_info("device successfully initialized\n"); return 0; } static int hdaps_resume(struct platform_device *dev) { return hdaps_device_init(); } static struct platform_driver hdaps_driver = { .probe = hdaps_probe, .resume = hdaps_resume, .driver = { .name = "hdaps", .owner = THIS_MODULE, }, }; /* * hdaps_calibrate - Set our "resting" values. Callers must hold hdaps_mtx. */ static void hdaps_calibrate(void) { __hdaps_read_pair(HDAPS_PORT_XPOS, HDAPS_PORT_YPOS, &rest_x, &rest_y); } static void hdaps_mousedev_poll(struct input_polled_dev *dev) { struct input_dev *input_dev = dev->input; int x, y; mutex_lock(&hdaps_mtx); if (__hdaps_read_pair(HDAPS_PORT_XPOS, HDAPS_PORT_YPOS, &x, &y)) goto out; input_report_abs(input_dev, ABS_X, x - rest_x); input_report_abs(input_dev, ABS_Y, y - rest_y); input_sync(input_dev); out: mutex_unlock(&hdaps_mtx); } /* Sysfs Files */ static ssize_t hdaps_position_show(struct device *dev, struct device_attribute *attr, char *buf) { int ret, x, y; ret = hdaps_read_pair(HDAPS_PORT_XPOS, HDAPS_PORT_YPOS, &x, &y); if (ret) return ret; return sprintf(buf, "(%d,%d)\n", x, y); } static ssize_t hdaps_variance_show(struct device *dev, struct device_attribute *attr, char *buf) { int ret, x, y; ret = hdaps_read_pair(HDAPS_PORT_XVAR, HDAPS_PORT_YVAR, &x, &y); if (ret) return ret; return sprintf(buf, "(%d,%d)\n", x, y); } static ssize_t hdaps_temp1_show(struct device *dev, struct device_attribute *attr, char *buf) { u8 uninitialized_var(temp); int ret; ret = hdaps_readb_one(HDAPS_PORT_TEMP1, &temp); if (ret) return ret; return sprintf(buf, "%u\n", temp); } static ssize_t hdaps_temp2_show(struct device *dev, struct device_attribute *attr, char *buf) { u8 uninitialized_var(temp); int ret; ret = hdaps_readb_one(HDAPS_PORT_TEMP2, &temp); if (ret) return ret; return sprintf(buf, "%u\n", temp); } static ssize_t hdaps_keyboard_activity_show(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf, "%u\n", KEYBD_ISSET(km_activity)); } static ssize_t hdaps_mouse_activity_show(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf, "%u\n", MOUSE_ISSET(km_activity)); } static ssize_t hdaps_calibrate_show(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf, "(%d,%d)\n", rest_x, rest_y); } static ssize_t hdaps_calibrate_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { mutex_lock(&hdaps_mtx); hdaps_calibrate(); mutex_unlock(&hdaps_mtx); return count; } static ssize_t hdaps_invert_show(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf, "%u\n", hdaps_invert); } static ssize_t hdaps_invert_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int invert; if (sscanf(buf, "%d", &invert) != 1 || invert < 0 || invert > HDAPS_BOTH_AXES) return -EINVAL; hdaps_invert = invert; hdaps_calibrate(); return count; } static DEVICE_ATTR(position, 0444, hdaps_position_show, NULL); static DEVICE_ATTR(variance, 0444, hdaps_variance_show, NULL); static DEVICE_ATTR(temp1, 0444, hdaps_temp1_show, NULL); static DEVICE_ATTR(temp2, 0444, hdaps_temp2_show, NULL); static DEVICE_ATTR(keyboard_activity, 0444, hdaps_keyboard_activity_show, NULL); static DEVICE_ATTR(mouse_activity, 0444, hdaps_mouse_activity_show, NULL); static DEVICE_ATTR(calibrate, 0644, hdaps_calibrate_show,hdaps_calibrate_store); static DEVICE_ATTR(invert, 0644, hdaps_invert_show, hdaps_invert_store); static struct attribute *hdaps_attributes[] = { &dev_attr_position.attr, &dev_attr_variance.attr, &dev_attr_temp1.attr, &dev_attr_temp2.attr, &dev_attr_keyboard_activity.attr, &dev_attr_mouse_activity.attr, &dev_attr_calibrate.attr, &dev_attr_invert.attr, NULL, }; static struct attribute_group hdaps_attribute_group = { .attrs = hdaps_attributes, }; /* Module stuff */ /* hdaps_dmi_match - found a match. return one, short-circuiting the hunt. */ static int __init hdaps_dmi_match(const struct dmi_system_id *id) { pr_info("%s detected\n", id->ident); return 1; } /* hdaps_dmi_match_invert - found an inverted match. */ static int __init hdaps_dmi_match_invert(const struct dmi_system_id *id) { hdaps_invert = (unsigned long)id->driver_data; pr_info("inverting axis (%u) readings\n", hdaps_invert); return hdaps_dmi_match(id); } #define HDAPS_DMI_MATCH_INVERT(vendor, model, axes) { \ .ident = vendor " " model, \ .callback = hdaps_dmi_match_invert, \ .driver_data = (void *)axes, \ .matches = { \ DMI_MATCH(DMI_BOARD_VENDOR, vendor), \ DMI_MATCH(DMI_PRODUCT_VERSION, model) \ } \ } #define HDAPS_DMI_MATCH_NORMAL(vendor, model) \ HDAPS_DMI_MATCH_INVERT(vendor, model, 0) /* Note that HDAPS_DMI_MATCH_NORMAL("ThinkPad T42") would match "ThinkPad T42p", so the order of the entries matters. If your ThinkPad is not recognized, please update to latest BIOS. This is especially the case for some R52 ThinkPads. */ static struct dmi_system_id __initdata hdaps_whitelist[] = { HDAPS_DMI_MATCH_INVERT("IBM", "ThinkPad R50p", HDAPS_BOTH_AXES), HDAPS_DMI_MATCH_NORMAL("IBM", "ThinkPad R50"), HDAPS_DMI_MATCH_NORMAL("IBM", "ThinkPad R51"), HDAPS_DMI_MATCH_NORMAL("IBM", "ThinkPad R52"), HDAPS_DMI_MATCH_INVERT("LENOVO", "ThinkPad R61i", HDAPS_BOTH_AXES), HDAPS_DMI_MATCH_INVERT("LENOVO", "ThinkPad R61", HDAPS_BOTH_AXES), HDAPS_DMI_MATCH_INVERT("IBM", "ThinkPad T41p", HDAPS_BOTH_AXES), HDAPS_DMI_MATCH_NORMAL("IBM", "ThinkPad T41"), HDAPS_DMI_MATCH_INVERT("IBM", "ThinkPad T42p", HDAPS_BOTH_AXES), HDAPS_DMI_MATCH_NORMAL("IBM", "ThinkPad T42"), HDAPS_DMI_MATCH_NORMAL("IBM", "ThinkPad T43"), HDAPS_DMI_MATCH_INVERT("LENOVO", "ThinkPad T400", HDAPS_BOTH_AXES), HDAPS_DMI_MATCH_INVERT("LENOVO", "ThinkPad T60", HDAPS_BOTH_AXES), HDAPS_DMI_MATCH_INVERT("LENOVO", "ThinkPad T61p", HDAPS_BOTH_AXES), HDAPS_DMI_MATCH_INVERT("LENOVO", "ThinkPad T61", HDAPS_BOTH_AXES), HDAPS_DMI_MATCH_NORMAL("IBM", "ThinkPad X40"), HDAPS_DMI_MATCH_INVERT("IBM", "ThinkPad X41", HDAPS_Y_AXIS), HDAPS_DMI_MATCH_INVERT("LENOVO", "ThinkPad X60", HDAPS_BOTH_AXES), HDAPS_DMI_MATCH_INVERT("LENOVO", "ThinkPad X61s", HDAPS_BOTH_AXES), HDAPS_DMI_MATCH_INVERT("LENOVO", "ThinkPad X61", HDAPS_BOTH_AXES), HDAPS_DMI_MATCH_NORMAL("IBM", "ThinkPad Z60m"), HDAPS_DMI_MATCH_INVERT("LENOVO", "ThinkPad Z61m", HDAPS_BOTH_AXES), HDAPS_DMI_MATCH_INVERT("LENOVO", "ThinkPad Z61p", HDAPS_BOTH_AXES), { .ident = NULL } }; static int __init hdaps_init(void) { struct input_dev *idev; int ret; if (!dmi_check_system(hdaps_whitelist)) { pr_warn("supported laptop not found!\n"); ret = -ENODEV; goto out; } if (!request_region(HDAPS_LOW_PORT, HDAPS_NR_PORTS, "hdaps")) { ret = -ENXIO; goto out; } ret = platform_driver_register(&hdaps_driver); if (ret) goto out_region; pdev = platform_device_register_simple("hdaps", -1, NULL, 0); if (IS_ERR(pdev)) { ret = PTR_ERR(pdev); goto out_driver; } ret = sysfs_create_group(&pdev->dev.kobj, &hdaps_attribute_group); if (ret) goto out_device; hdaps_idev = input_allocate_polled_device(); if (!hdaps_idev) { ret = -ENOMEM; goto out_group; } hdaps_idev->poll = hdaps_mousedev_poll; hdaps_idev->poll_interval = HDAPS_POLL_INTERVAL; /* initial calibrate for the input device */ hdaps_calibrate(); /* initialize the input class */ idev = hdaps_idev->input; idev->name = "hdaps"; idev->phys = "isa1600/input0"; idev->id.bustype = BUS_ISA; idev->dev.parent = &pdev->dev; idev->evbit[0] = BIT_MASK(EV_ABS); input_set_abs_params(idev, ABS_X, -256, 256, HDAPS_INPUT_FUZZ, HDAPS_INPUT_FLAT); input_set_abs_params(idev, ABS_Y, -256, 256, HDAPS_INPUT_FUZZ, HDAPS_INPUT_FLAT); ret = input_register_polled_device(hdaps_idev); if (ret) goto out_idev; pr_info("driver successfully loaded\n"); return 0; out_idev: input_free_polled_device(hdaps_idev); out_group: sysfs_remove_group(&pdev->dev.kobj, &hdaps_attribute_group); out_device: platform_device_unregister(pdev); out_driver: platform_driver_unregister(&hdaps_driver); out_region: release_region(HDAPS_LOW_PORT, HDAPS_NR_PORTS); out: pr_warn("driver init failed (ret=%d)!\n", ret); return ret; } static void __exit hdaps_exit(void) { input_unregister_polled_device(hdaps_idev); input_free_polled_device(hdaps_idev); sysfs_remove_group(&pdev->dev.kobj, &hdaps_attribute_group); platform_device_unregister(pdev); platform_driver_unregister(&hdaps_driver); release_region(HDAPS_LOW_PORT, HDAPS_NR_PORTS); pr_info("driver unloaded\n"); } module_init(hdaps_init); module_exit(hdaps_exit); module_param_named(invert, hdaps_invert, int, 0); MODULE_PARM_DESC(invert, "invert data along each axis. 1 invert x-axis, " "2 invert y-axis, 3 invert both axes."); MODULE_AUTHOR("Robert Love"); MODULE_DESCRIPTION("IBM Hard Drive Active Protection System (HDAPS) driver"); MODULE_LICENSE("GPL v2");
talnoah/android_kernel_htc_dlx
virt/drivers/platform/x86/hdaps.c
C
gpl-2.0
17,127
// { dg-do assemble } // The default assignment operator for B uses array assignment, so we can't // just disallow it... struct A { A& operator=(const A&); }; struct B { A f[20]; }; int a1[20], a2[20]; B b1, b2; void test () { b1 = b2; /* OK */ a1 = a2; /* { dg-error "" } array assignment */ }
SanDisk-Open-Source/SSD_Dashboard
uefi/gcc/gcc-4.6.3/gcc/testsuite/g++.old-deja/g++.jason/rfg17.C
C++
gpl-2.0
315
/* * Copyright (c) 2017, Mellanox Technologies. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * 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. * * 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 <linux/etherdevice.h> #include <linux/mlx5/driver.h> #include <linux/mlx5/device.h> #include "mlx5_core.h" #include "fpga/cmd.h" #define MLX5_FPGA_ACCESS_REG_SZ (MLX5_ST_SZ_DW(fpga_access_reg) + \ MLX5_FPGA_ACCESS_REG_SIZE_MAX) int mlx5_fpga_access_reg(struct mlx5_core_dev *dev, u8 size, u64 addr, void *buf, bool write) { u32 in[MLX5_FPGA_ACCESS_REG_SZ] = {0}; u32 out[MLX5_FPGA_ACCESS_REG_SZ]; int err; if (size & 3) return -EINVAL; if (addr & 3) return -EINVAL; if (size > MLX5_FPGA_ACCESS_REG_SIZE_MAX) return -EINVAL; MLX5_SET(fpga_access_reg, in, size, size); MLX5_SET64(fpga_access_reg, in, address, addr); if (write) memcpy(MLX5_ADDR_OF(fpga_access_reg, in, data), buf, size); err = mlx5_core_access_reg(dev, in, sizeof(in), out, sizeof(out), MLX5_REG_FPGA_ACCESS_REG, 0, write); if (err) return err; if (!write) memcpy(buf, MLX5_ADDR_OF(fpga_access_reg, out, data), size); return 0; } int mlx5_fpga_caps(struct mlx5_core_dev *dev) { u32 in[MLX5_ST_SZ_DW(fpga_cap)] = {0}; return mlx5_core_access_reg(dev, in, sizeof(in), dev->caps.fpga, MLX5_ST_SZ_BYTES(fpga_cap), MLX5_REG_FPGA_CAP, 0, 0); } int mlx5_fpga_ctrl_op(struct mlx5_core_dev *dev, u8 op) { u32 in[MLX5_ST_SZ_DW(fpga_ctrl)] = {0}; u32 out[MLX5_ST_SZ_DW(fpga_ctrl)]; MLX5_SET(fpga_ctrl, in, operation, op); return mlx5_core_access_reg(dev, in, sizeof(in), out, sizeof(out), MLX5_REG_FPGA_CTRL, 0, true); } int mlx5_fpga_sbu_caps(struct mlx5_core_dev *dev, void *caps, int size) { unsigned int cap_size = MLX5_CAP_FPGA(dev, sandbox_extended_caps_len); u64 addr = MLX5_CAP64_FPGA(dev, sandbox_extended_caps_addr); unsigned int read; int ret = 0; if (cap_size > size) { mlx5_core_warn(dev, "Not enough buffer %u for FPGA SBU caps %u", size, cap_size); return -EINVAL; } while (cap_size > 0) { read = min_t(unsigned int, cap_size, MLX5_FPGA_ACCESS_REG_SIZE_MAX); ret = mlx5_fpga_access_reg(dev, read, addr, caps, false); if (ret) { mlx5_core_warn(dev, "Error reading FPGA SBU caps %u bytes at address 0x%llx: %d", read, addr, ret); return ret; } cap_size -= read; addr += read; caps += read; } return ret; } int mlx5_fpga_query(struct mlx5_core_dev *dev, struct mlx5_fpga_query *query) { u32 in[MLX5_ST_SZ_DW(fpga_ctrl)] = {0}; u32 out[MLX5_ST_SZ_DW(fpga_ctrl)]; int err; err = mlx5_core_access_reg(dev, in, sizeof(in), out, sizeof(out), MLX5_REG_FPGA_CTRL, 0, false); if (err) return err; query->status = MLX5_GET(fpga_ctrl, out, status); query->admin_image = MLX5_GET(fpga_ctrl, out, flash_select_admin); query->oper_image = MLX5_GET(fpga_ctrl, out, flash_select_oper); return 0; } int mlx5_fpga_create_qp(struct mlx5_core_dev *dev, void *fpga_qpc, u32 *fpga_qpn) { u32 out[MLX5_ST_SZ_DW(fpga_create_qp_out)] = {}; u32 in[MLX5_ST_SZ_DW(fpga_create_qp_in)] = {}; int ret; MLX5_SET(fpga_create_qp_in, in, opcode, MLX5_CMD_OP_FPGA_CREATE_QP); memcpy(MLX5_ADDR_OF(fpga_create_qp_in, in, fpga_qpc), fpga_qpc, MLX5_FLD_SZ_BYTES(fpga_create_qp_in, fpga_qpc)); ret = mlx5_cmd_exec_inout(dev, fpga_create_qp, in, out); if (ret) return ret; memcpy(fpga_qpc, MLX5_ADDR_OF(fpga_create_qp_out, out, fpga_qpc), MLX5_FLD_SZ_BYTES(fpga_create_qp_out, fpga_qpc)); *fpga_qpn = MLX5_GET(fpga_create_qp_out, out, fpga_qpn); return ret; } int mlx5_fpga_modify_qp(struct mlx5_core_dev *dev, u32 fpga_qpn, enum mlx5_fpga_qpc_field_select fields, void *fpga_qpc) { u32 in[MLX5_ST_SZ_DW(fpga_modify_qp_in)] = {}; MLX5_SET(fpga_modify_qp_in, in, opcode, MLX5_CMD_OP_FPGA_MODIFY_QP); MLX5_SET(fpga_modify_qp_in, in, field_select, fields); MLX5_SET(fpga_modify_qp_in, in, fpga_qpn, fpga_qpn); memcpy(MLX5_ADDR_OF(fpga_modify_qp_in, in, fpga_qpc), fpga_qpc, MLX5_FLD_SZ_BYTES(fpga_modify_qp_in, fpga_qpc)); return mlx5_cmd_exec_in(dev, fpga_modify_qp, in); } int mlx5_fpga_query_qp(struct mlx5_core_dev *dev, u32 fpga_qpn, void *fpga_qpc) { u32 out[MLX5_ST_SZ_DW(fpga_query_qp_out)] = {}; u32 in[MLX5_ST_SZ_DW(fpga_query_qp_in)] = {}; int ret; MLX5_SET(fpga_query_qp_in, in, opcode, MLX5_CMD_OP_FPGA_QUERY_QP); MLX5_SET(fpga_query_qp_in, in, fpga_qpn, fpga_qpn); ret = mlx5_cmd_exec_inout(dev, fpga_query_qp, in, out); if (ret) return ret; memcpy(fpga_qpc, MLX5_ADDR_OF(fpga_query_qp_out, out, fpga_qpc), MLX5_FLD_SZ_BYTES(fpga_query_qp_out, fpga_qpc)); return ret; } int mlx5_fpga_destroy_qp(struct mlx5_core_dev *dev, u32 fpga_qpn) { u32 in[MLX5_ST_SZ_DW(fpga_destroy_qp_in)] = {}; MLX5_SET(fpga_destroy_qp_in, in, opcode, MLX5_CMD_OP_FPGA_DESTROY_QP); MLX5_SET(fpga_destroy_qp_in, in, fpga_qpn, fpga_qpn); return mlx5_cmd_exec_in(dev, fpga_destroy_qp, in); } int mlx5_fpga_query_qp_counters(struct mlx5_core_dev *dev, u32 fpga_qpn, bool clear, struct mlx5_fpga_qp_counters *data) { u32 out[MLX5_ST_SZ_DW(fpga_query_qp_counters_out)] = {}; u32 in[MLX5_ST_SZ_DW(fpga_query_qp_counters_in)] = {}; int ret; MLX5_SET(fpga_query_qp_counters_in, in, opcode, MLX5_CMD_OP_FPGA_QUERY_QP_COUNTERS); MLX5_SET(fpga_query_qp_counters_in, in, clear, clear); MLX5_SET(fpga_query_qp_counters_in, in, fpga_qpn, fpga_qpn); ret = mlx5_cmd_exec_inout(dev, fpga_query_qp_counters, in, out); if (ret) return ret; data->rx_ack_packets = MLX5_GET64(fpga_query_qp_counters_out, out, rx_ack_packets); data->rx_send_packets = MLX5_GET64(fpga_query_qp_counters_out, out, rx_send_packets); data->tx_ack_packets = MLX5_GET64(fpga_query_qp_counters_out, out, tx_ack_packets); data->tx_send_packets = MLX5_GET64(fpga_query_qp_counters_out, out, tx_send_packets); data->rx_total_drop = MLX5_GET64(fpga_query_qp_counters_out, out, rx_total_drop); return ret; }
CSE3320/kernel-code
linux-5.8/drivers/net/ethernet/mellanox/mlx5/core/fpga/cmd.c
C
gpl-2.0
7,245
/* arch/arm/mach-msm/qdsp5/adsp_driver.c * * Copyright (C) 2008 Google, Inc. * Copyright (c) 2009, Code Aurora Forum. All rights reserved. * Author: Iliyan Malchev <[email protected]> * * 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. * */ #include <linux/cdev.h> #include <linux/fs.h> #include <linux/list.h> #include <linux/platform_device.h> #include <linux/sched.h> #include <linux/uaccess.h> #include "adsp.h" #include <linux/msm_adsp.h> #include <linux/android_pmem.h> #include <mach/debug_mm.h> struct adsp_pmem_info { int fd; void *vaddr; }; struct adsp_pmem_region { struct hlist_node list; void *vaddr; unsigned long paddr; unsigned long kvaddr; unsigned long len; struct file *file; }; struct adsp_device { struct msm_adsp_module *module; spinlock_t event_queue_lock; wait_queue_head_t event_wait; struct list_head event_queue; int abort; const char *name; struct device *device; struct cdev cdev; }; static struct adsp_device *inode_to_device(struct inode *inode); #define __CONTAINS(r, v, l) ({ \ typeof(r) __r = r; \ typeof(v) __v = v; \ typeof(v) __e = __v + l; \ int res = __v >= __r->vaddr && \ __e <= __r->vaddr + __r->len; \ res; \ }) #define CONTAINS(r1, r2) ({ \ typeof(r2) __r2 = r2; \ __CONTAINS(r1, __r2->vaddr, __r2->len); \ }) #define IN_RANGE(r, v) ({ \ typeof(r) __r = r; \ typeof(v) __vv = v; \ int res = ((__vv >= __r->vaddr) && \ (__vv < (__r->vaddr + __r->len))); \ res; \ }) #define OVERLAPS(r1, r2) ({ \ typeof(r1) __r1 = r1; \ typeof(r2) __r2 = r2; \ typeof(__r2->vaddr) __v = __r2->vaddr; \ typeof(__v) __e = __v + __r2->len - 1; \ int res = (IN_RANGE(__r1, __v) || IN_RANGE(__r1, __e)); \ res; \ }) static int adsp_pmem_check(struct msm_adsp_module *module, void *vaddr, unsigned long len) { struct adsp_pmem_region *region_elt; struct hlist_node *node; struct adsp_pmem_region t = { .vaddr = vaddr, .len = len }; hlist_for_each_entry(region_elt, node, &module->pmem_regions, list) { if (CONTAINS(region_elt, &t) || CONTAINS(&t, region_elt) || OVERLAPS(region_elt, &t)) { MM_ERR("module %s:" " region (vaddr %p len %ld)" " clashes with registered region" " (vaddr %p paddr %p len %ld)\n", module->name, vaddr, len, region_elt->vaddr, (void *)region_elt->paddr, region_elt->len); return -EINVAL; } } return 0; } static int adsp_pmem_add(struct msm_adsp_module *module, struct adsp_pmem_info *info) { unsigned long paddr, kvaddr, len; struct file *file; struct adsp_pmem_region *region; int rc = -EINVAL; mutex_lock(&module->pmem_regions_lock); region = kmalloc(sizeof(*region), GFP_KERNEL); if (!region) { rc = -ENOMEM; goto end; } INIT_HLIST_NODE(&region->list); if (get_pmem_file(info->fd, &paddr, &kvaddr, &len, &file)) { kfree(region); goto end; } rc = adsp_pmem_check(module, info->vaddr, len); if (rc < 0) { put_pmem_file(file); kfree(region); goto end; } region->vaddr = info->vaddr; region->paddr = paddr; region->kvaddr = kvaddr; region->len = len; region->file = file; hlist_add_head(&region->list, &module->pmem_regions); end: mutex_unlock(&module->pmem_regions_lock); return rc; } static int adsp_pmem_lookup_vaddr(struct msm_adsp_module *module, void **addr, unsigned long len, struct adsp_pmem_region **region) { struct hlist_node *node; void *vaddr = *addr; struct adsp_pmem_region *region_elt; int match_count = 0; *region = NULL; /* returns physical address or zero */ hlist_for_each_entry(region_elt, node, &module->pmem_regions, list) { if (vaddr >= region_elt->vaddr && vaddr < region_elt->vaddr + region_elt->len && vaddr + len <= region_elt->vaddr + region_elt->len) { /* offset since we could pass vaddr inside a registerd * pmem buffer */ match_count++; if (!*region) *region = region_elt; } } if (match_count > 1) { MM_ERR("module %s: " "multiple hits for vaddr %p, len %ld\n", module->name, vaddr, len); hlist_for_each_entry(region_elt, node, &module->pmem_regions, list) { if (vaddr >= region_elt->vaddr && vaddr < region_elt->vaddr + region_elt->len && vaddr + len <= region_elt->vaddr + region_elt->len) MM_ERR("%p, %ld --> %p\n", region_elt->vaddr, region_elt->len, (void *)region_elt->paddr); } } return *region ? 0 : -1; } int adsp_pmem_fixup_kvaddr(struct msm_adsp_module *module, void **addr, unsigned long *kvaddr, unsigned long len, struct file **filp, unsigned long *offset) { struct adsp_pmem_region *region; void *vaddr = *addr; unsigned long *paddr = (unsigned long *)addr; int ret; ret = adsp_pmem_lookup_vaddr(module, addr, len, &region); if (ret) { MM_ERR("not patching %s (paddr & kvaddr)," " lookup (%p, %ld) failed\n", module->name, vaddr, len); return ret; } *paddr = region->paddr + (vaddr - region->vaddr); *kvaddr = region->kvaddr + (vaddr - region->vaddr); if (filp) *filp = region->file; if (offset) *offset = vaddr - region->vaddr; return 0; } int adsp_pmem_fixup(struct msm_adsp_module *module, void **addr, unsigned long len) { struct adsp_pmem_region *region; void *vaddr = *addr; unsigned long *paddr = (unsigned long *)addr; int ret; ret = adsp_pmem_lookup_vaddr(module, addr, len, &region); if (ret) { MM_ERR("not patching %s, lookup (%p, %ld) failed\n", module->name, vaddr, len); return ret; } *paddr = region->paddr + (vaddr - region->vaddr); return 0; } static int adsp_verify_cmd(struct msm_adsp_module *module, unsigned int queue_id, void *cmd_data, size_t cmd_size) { /* call the per module verifier */ if (module->verify_cmd) return module->verify_cmd(module, queue_id, cmd_data, cmd_size); else MM_INFO("no packet verifying function " "for task %s\n", module->name); return 0; } static long adsp_write_cmd(struct adsp_device *adev, void __user *arg) { struct adsp_command_t cmd; unsigned char buf[256]; void *cmd_data; long rc; if (copy_from_user(&cmd, (void __user *)arg, sizeof(cmd))) return -EFAULT; if (cmd.len > 256) { cmd_data = kmalloc(cmd.len, GFP_USER); if (!cmd_data) return -ENOMEM; } else { cmd_data = buf; } if (copy_from_user(cmd_data, (void __user *)(cmd.data), cmd.len)) { rc = -EFAULT; goto end; } mutex_lock(&adev->module->pmem_regions_lock); if (adsp_verify_cmd(adev->module, cmd.queue, cmd_data, cmd.len)) { MM_ERR("module %s: verify failed.\n", adev->module->name); rc = -EINVAL; goto end; } /* complete the writes to the buffer */ wmb(); rc = msm_adsp_write(adev->module, cmd.queue, cmd_data, cmd.len); end: mutex_unlock(&adev->module->pmem_regions_lock); if (cmd.len > 256) kfree(cmd_data); return rc; } static int adsp_events_pending(struct adsp_device *adev) { unsigned long flags; int yes; spin_lock_irqsave(&adev->event_queue_lock, flags); yes = !list_empty(&adev->event_queue); spin_unlock_irqrestore(&adev->event_queue_lock, flags); return yes || adev->abort; } static int adsp_pmem_lookup_paddr(struct msm_adsp_module *module, void **addr, struct adsp_pmem_region **region) { struct hlist_node *node; unsigned long paddr = (unsigned long)(*addr); struct adsp_pmem_region *region_elt; hlist_for_each_entry(region_elt, node, &module->pmem_regions, list) { if (paddr >= region_elt->paddr && paddr < region_elt->paddr + region_elt->len) { *region = region_elt; return 0; } } return -1; } int adsp_pmem_paddr_fixup(struct msm_adsp_module *module, void **addr) { struct adsp_pmem_region *region; unsigned long paddr = (unsigned long)(*addr); unsigned long *vaddr = (unsigned long *)addr; int ret; ret = adsp_pmem_lookup_paddr(module, addr, &region); if (ret) { MM_ERR("not patching %s, paddr %p lookup failed\n", module->name, vaddr); return ret; } *vaddr = (unsigned long)region->vaddr + (paddr - region->paddr); return 0; } static int adsp_patch_event(struct msm_adsp_module *module, struct adsp_event *event) { /* call the per-module msg verifier */ if (module->patch_event) return module->patch_event(module, event); return 0; } static long adsp_get_event(struct adsp_device *adev, void __user *arg) { unsigned long flags; struct adsp_event *data = NULL; struct adsp_event_t evt; int timeout; long rc = 0; if (copy_from_user(&evt, arg, sizeof(struct adsp_event_t))) return -EFAULT; timeout = (int)evt.timeout_ms; if (timeout > 0) { rc = wait_event_interruptible_timeout( adev->event_wait, adsp_events_pending(adev), msecs_to_jiffies(timeout)); if (rc == 0) return -ETIMEDOUT; } else { rc = wait_event_interruptible( adev->event_wait, adsp_events_pending(adev)); } if (rc < 0) return rc; if (adev->abort) return -ENODEV; spin_lock_irqsave(&adev->event_queue_lock, flags); if (!list_empty(&adev->event_queue)) { data = list_first_entry(&adev->event_queue, struct adsp_event, list); list_del(&data->list); } spin_unlock_irqrestore(&adev->event_queue_lock, flags); if (!data) return -EAGAIN; /* DSP messages are type 0; they may contain physical addresses */ if (data->type == 0) adsp_patch_event(adev->module, data); /* map adsp_event --> adsp_event_t */ if (evt.len < data->size) { rc = -ETOOSMALL; goto end; } /* order the reads to the buffer */ rmb(); if (data->msg_id != EVENT_MSG_ID) { if (copy_to_user((void *)(evt.data), data->data.msg16, data->size)) { rc = -EFAULT; goto end; } } else { if (copy_to_user((void *)(evt.data), data->data.msg32, data->size)) { rc = -EFAULT; goto end; } } evt.type = data->type; /* 0 --> from aDSP, 1 --> from ARM9 */ evt.msg_id = data->msg_id; evt.flags = data->is16; evt.len = data->size; if (copy_to_user(arg, &evt, sizeof(evt))) rc = -EFAULT; end: kfree(data); return rc; } static int adsp_pmem_del(struct msm_adsp_module *module) { struct hlist_node *node, *tmp; struct adsp_pmem_region *region; mutex_lock(&module->pmem_regions_lock); hlist_for_each_safe(node, tmp, &module->pmem_regions) { region = hlist_entry(node, struct adsp_pmem_region, list); hlist_del(node); put_pmem_file(region->file); kfree(region); } mutex_unlock(&module->pmem_regions_lock); BUG_ON(!hlist_empty(&module->pmem_regions)); return 0; } static long adsp_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { struct adsp_device *adev = filp->private_data; switch (cmd) { case ADSP_IOCTL_ENABLE: return msm_adsp_enable(adev->module); case ADSP_IOCTL_DISABLE: return msm_adsp_disable(adev->module); case ADSP_IOCTL_DISABLE_EVENT_RSP: return msm_adsp_disable_event_rsp(adev->module); case ADSP_IOCTL_DISABLE_ACK: MM_ERR("ADSP_IOCTL_DISABLE_ACK is not implemented\n"); break; case ADSP_IOCTL_WRITE_COMMAND: return adsp_write_cmd(adev, (void __user *) arg); case ADSP_IOCTL_GET_EVENT: return adsp_get_event(adev, (void __user *) arg); case ADSP_IOCTL_SET_CLKRATE: { unsigned long clk_rate; if (copy_from_user(&clk_rate, (void *) arg, sizeof(clk_rate))) return -EFAULT; return adsp_set_clkrate(adev->module, clk_rate); } case ADSP_IOCTL_REGISTER_PMEM: { struct adsp_pmem_info info; if (copy_from_user(&info, (void *) arg, sizeof(info))) return -EFAULT; return adsp_pmem_add(adev->module, &info); } case ADSP_IOCTL_ABORT_EVENT_READ: adev->abort = 1; wake_up(&adev->event_wait); break; case ADSP_IOCTL_UNREGISTER_PMEM: return adsp_pmem_del(adev->module); default: break; } return -EINVAL; } static int adsp_release(struct inode *inode, struct file *filp) { struct adsp_device *adev = filp->private_data; struct msm_adsp_module *module = adev->module; int rc = 0; MM_INFO("release '%s'\n", adev->name); /* clear module before putting it to avoid race with open() */ adev->module = NULL; rc = adsp_pmem_del(module); msm_adsp_put(module); return rc; } static void adsp_event(void *driver_data, unsigned id, size_t len, void (*getevent)(void *ptr, size_t len)) { struct adsp_device *adev = driver_data; struct adsp_event *event; unsigned long flags; if (len > ADSP_EVENT_MAX_SIZE) { MM_ERR("event too large (%d bytes)\n", len); return; } event = kmalloc(sizeof(*event), GFP_ATOMIC); if (!event) { MM_ERR("cannot allocate buffer\n"); return; } if (id != EVENT_MSG_ID) { event->type = 0; event->is16 = 0; event->msg_id = id; event->size = len; getevent(event->data.msg16, len); } else { event->type = 1; event->is16 = 1; event->msg_id = id; event->size = len; getevent(event->data.msg32, len); } spin_lock_irqsave(&adev->event_queue_lock, flags); list_add_tail(&event->list, &adev->event_queue); spin_unlock_irqrestore(&adev->event_queue_lock, flags); wake_up(&adev->event_wait); } static struct msm_adsp_ops adsp_ops = { .event = adsp_event, }; static int adsp_open(struct inode *inode, struct file *filp) { struct adsp_device *adev; int rc; rc = nonseekable_open(inode, filp); if (rc < 0) return rc; adev = inode_to_device(inode); if (!adev) return -ENODEV; MM_INFO("open '%s'\n", adev->name); rc = msm_adsp_get(adev->name, &adev->module, &adsp_ops, adev); if (rc) return rc; MM_INFO("opened module '%s' adev %p\n", adev->name, adev); filp->private_data = adev; adev->abort = 0; INIT_HLIST_HEAD(&adev->module->pmem_regions); mutex_init(&adev->module->pmem_regions_lock); return 0; } static unsigned adsp_device_count; static struct adsp_device *adsp_devices; static struct adsp_device *inode_to_device(struct inode *inode) { unsigned n = MINOR(inode->i_rdev); if (n < adsp_device_count) { if (adsp_devices[n].device) return adsp_devices + n; } return NULL; } static dev_t adsp_devno; static struct class *adsp_class; static struct file_operations adsp_fops = { .owner = THIS_MODULE, .open = adsp_open, .unlocked_ioctl = adsp_ioctl, .release = adsp_release, }; static void adsp_create(struct adsp_device *adev, const char *name, struct device *parent, dev_t devt) { struct device *dev; int rc; dev = device_create(adsp_class, parent, devt, "%s", name); if (IS_ERR(dev)) return; init_waitqueue_head(&adev->event_wait); INIT_LIST_HEAD(&adev->event_queue); spin_lock_init(&adev->event_queue_lock); cdev_init(&adev->cdev, &adsp_fops); adev->cdev.owner = THIS_MODULE; rc = cdev_add(&adev->cdev, devt, 1); if (rc < 0) { device_destroy(adsp_class, devt); } else { adev->device = dev; adev->name = name; } } void msm_adsp_publish_cdevs(struct msm_adsp_module *modules, unsigned n) { int rc; adsp_devices = kzalloc(sizeof(struct adsp_device) * n, GFP_KERNEL); if (!adsp_devices) return; adsp_class = class_create(THIS_MODULE, "adsp"); if (IS_ERR(adsp_class)) goto fail_create_class; rc = alloc_chrdev_region(&adsp_devno, 0, n, "adsp"); if (rc < 0) goto fail_alloc_region; adsp_device_count = n; for (n = 0; n < adsp_device_count; n++) { adsp_create(adsp_devices + n, modules[n].name, &modules[n].pdev.dev, MKDEV(MAJOR(adsp_devno), n)); } return; fail_alloc_region: class_unregister(adsp_class); fail_create_class: kfree(adsp_devices); }
arkas/Samsung-GT-I5510-Kernel
kernel/arch/arm/mach-msm/qdsp5/adsp_driver.c
C
gpl-2.0
15,644
!function(n){var t,a,o="mmenu";n(document).on("ready",function(){a=n("html"),t=a.attr("class")}),n(document).on("page:load",function(){a.attr("class",t),n[o].glbl=!1})}(jQuery);
hiragiayako/Portfolio
portfolio2/wp-content/themes/portfolio/javascripts/jQuery.mmenu/dist/wrappers/js/jquery.mmenu.turbolinks.min.js
JavaScript
gpl-2.0
177
/* * Common code to disable/enable mixer emulation at run time * * Copyright (C) 2013 Red Hat, Inc. * * Written by Bandan Das <[email protected]> * with important bits picked up from hda-codec.c * * 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 or * (at your option) version 3 of the License. * * 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, see <http://www.gnu.org/licenses/>. */ /* * HDA codec descriptions */ #ifdef HDA_MIXER #define QEMU_HDA_ID_OUTPUT ((QEMU_HDA_ID_VENDOR << 16) | 0x12) #define QEMU_HDA_ID_DUPLEX ((QEMU_HDA_ID_VENDOR << 16) | 0x22) #define QEMU_HDA_ID_MICRO ((QEMU_HDA_ID_VENDOR << 16) | 0x32) #define QEMU_HDA_AMP_CAPS \ (AC_AMPCAP_MUTE | \ (QEMU_HDA_AMP_STEPS << AC_AMPCAP_OFFSET_SHIFT) | \ (QEMU_HDA_AMP_STEPS << AC_AMPCAP_NUM_STEPS_SHIFT) | \ (3 << AC_AMPCAP_STEP_SIZE_SHIFT)) #else #define QEMU_HDA_ID_OUTPUT ((QEMU_HDA_ID_VENDOR << 16) | 0x11) #define QEMU_HDA_ID_DUPLEX ((QEMU_HDA_ID_VENDOR << 16) | 0x21) #define QEMU_HDA_ID_MICRO ((QEMU_HDA_ID_VENDOR << 16) | 0x31) #define QEMU_HDA_AMP_CAPS QEMU_HDA_AMP_NONE #endif /* common: audio output widget */ static const desc_param glue(common_params_audio_dac_, PARAM)[] = { { .id = AC_PAR_AUDIO_WIDGET_CAP, .val = ((AC_WID_AUD_OUT << AC_WCAP_TYPE_SHIFT) | AC_WCAP_FORMAT_OVRD | AC_WCAP_AMP_OVRD | AC_WCAP_OUT_AMP | AC_WCAP_STEREO), },{ .id = AC_PAR_PCM, .val = QEMU_HDA_PCM_FORMATS, },{ .id = AC_PAR_STREAM, .val = AC_SUPFMT_PCM, },{ .id = AC_PAR_AMP_IN_CAP, .val = QEMU_HDA_AMP_NONE, },{ .id = AC_PAR_AMP_OUT_CAP, .val = QEMU_HDA_AMP_CAPS, }, }; /* common: audio input widget */ static const desc_param glue(common_params_audio_adc_, PARAM)[] = { { .id = AC_PAR_AUDIO_WIDGET_CAP, .val = ((AC_WID_AUD_IN << AC_WCAP_TYPE_SHIFT) | AC_WCAP_CONN_LIST | AC_WCAP_FORMAT_OVRD | AC_WCAP_AMP_OVRD | AC_WCAP_IN_AMP | AC_WCAP_STEREO), },{ .id = AC_PAR_CONNLIST_LEN, .val = 1, },{ .id = AC_PAR_PCM, .val = QEMU_HDA_PCM_FORMATS, },{ .id = AC_PAR_STREAM, .val = AC_SUPFMT_PCM, },{ .id = AC_PAR_AMP_IN_CAP, .val = QEMU_HDA_AMP_CAPS, },{ .id = AC_PAR_AMP_OUT_CAP, .val = QEMU_HDA_AMP_NONE, }, }; /* common: pin widget (line-out) */ static const desc_param glue(common_params_audio_lineout_, PARAM)[] = { { .id = AC_PAR_AUDIO_WIDGET_CAP, .val = ((AC_WID_PIN << AC_WCAP_TYPE_SHIFT) | AC_WCAP_CONN_LIST | AC_WCAP_STEREO), },{ .id = AC_PAR_PIN_CAP, .val = AC_PINCAP_OUT, },{ .id = AC_PAR_CONNLIST_LEN, .val = 1, },{ .id = AC_PAR_AMP_IN_CAP, .val = QEMU_HDA_AMP_NONE, },{ .id = AC_PAR_AMP_OUT_CAP, .val = QEMU_HDA_AMP_NONE, }, }; /* common: pin widget (line-in) */ static const desc_param glue(common_params_audio_linein_, PARAM)[] = { { .id = AC_PAR_AUDIO_WIDGET_CAP, .val = ((AC_WID_PIN << AC_WCAP_TYPE_SHIFT) | AC_WCAP_STEREO), },{ .id = AC_PAR_PIN_CAP, .val = AC_PINCAP_IN, },{ .id = AC_PAR_AMP_IN_CAP, .val = QEMU_HDA_AMP_NONE, },{ .id = AC_PAR_AMP_OUT_CAP, .val = QEMU_HDA_AMP_NONE, }, }; /* output: root node */ static const desc_param glue(output_params_root_, PARAM)[] = { { .id = AC_PAR_VENDOR_ID, .val = QEMU_HDA_ID_OUTPUT, },{ .id = AC_PAR_SUBSYSTEM_ID, .val = QEMU_HDA_ID_OUTPUT, },{ .id = AC_PAR_REV_ID, .val = 0x00100101, },{ .id = AC_PAR_NODE_COUNT, .val = 0x00010001, }, }; /* output: audio function */ static const desc_param glue(output_params_audio_func_, PARAM)[] = { { .id = AC_PAR_FUNCTION_TYPE, .val = AC_GRP_AUDIO_FUNCTION, },{ .id = AC_PAR_SUBSYSTEM_ID, .val = QEMU_HDA_ID_OUTPUT, },{ .id = AC_PAR_NODE_COUNT, .val = 0x00020002, },{ .id = AC_PAR_PCM, .val = QEMU_HDA_PCM_FORMATS, },{ .id = AC_PAR_STREAM, .val = AC_SUPFMT_PCM, },{ .id = AC_PAR_AMP_IN_CAP, .val = QEMU_HDA_AMP_NONE, },{ .id = AC_PAR_AMP_OUT_CAP, .val = QEMU_HDA_AMP_NONE, },{ .id = AC_PAR_GPIO_CAP, .val = 0, },{ .id = AC_PAR_AUDIO_FG_CAP, .val = 0x00000808, },{ .id = AC_PAR_POWER_STATE, .val = 0, }, }; /* output: nodes */ static const desc_node glue(output_nodes_, PARAM)[] = { { .nid = AC_NODE_ROOT, .name = "root", .params = glue(output_params_root_, PARAM), .nparams = ARRAY_SIZE(glue(output_params_root_, PARAM)), },{ .nid = 1, .name = "func", .params = glue(output_params_audio_func_, PARAM), .nparams = ARRAY_SIZE(glue(output_params_audio_func_, PARAM)), },{ .nid = 2, .name = "dac", .params = glue(common_params_audio_dac_, PARAM), .nparams = ARRAY_SIZE(glue(common_params_audio_dac_, PARAM)), .stindex = 0, },{ .nid = 3, .name = "out", .params = glue(common_params_audio_lineout_, PARAM), .nparams = ARRAY_SIZE(glue(common_params_audio_lineout_, PARAM)), .config = ((AC_JACK_PORT_COMPLEX << AC_DEFCFG_PORT_CONN_SHIFT) | (AC_JACK_LINE_OUT << AC_DEFCFG_DEVICE_SHIFT) | (AC_JACK_CONN_UNKNOWN << AC_DEFCFG_CONN_TYPE_SHIFT) | (AC_JACK_COLOR_GREEN << AC_DEFCFG_COLOR_SHIFT) | 0x10), .pinctl = AC_PINCTL_OUT_EN, .conn = (uint32_t[]) { 2 }, } }; /* output: codec */ static const desc_codec glue(output_, PARAM) = { .name = "output", .iid = QEMU_HDA_ID_OUTPUT, .nodes = glue(output_nodes_, PARAM), .nnodes = ARRAY_SIZE(glue(output_nodes_, PARAM)), }; /* duplex: root node */ static const desc_param glue(duplex_params_root_, PARAM)[] = { { .id = AC_PAR_VENDOR_ID, .val = QEMU_HDA_ID_DUPLEX, },{ .id = AC_PAR_SUBSYSTEM_ID, .val = QEMU_HDA_ID_DUPLEX, },{ .id = AC_PAR_REV_ID, .val = 0x00100101, },{ .id = AC_PAR_NODE_COUNT, .val = 0x00010001, }, }; /* duplex: audio function */ static const desc_param glue(duplex_params_audio_func_, PARAM)[] = { { .id = AC_PAR_FUNCTION_TYPE, .val = AC_GRP_AUDIO_FUNCTION, },{ .id = AC_PAR_SUBSYSTEM_ID, .val = QEMU_HDA_ID_DUPLEX, },{ .id = AC_PAR_NODE_COUNT, .val = 0x00020004, },{ .id = AC_PAR_PCM, .val = QEMU_HDA_PCM_FORMATS, },{ .id = AC_PAR_STREAM, .val = AC_SUPFMT_PCM, },{ .id = AC_PAR_AMP_IN_CAP, .val = QEMU_HDA_AMP_NONE, },{ .id = AC_PAR_AMP_OUT_CAP, .val = QEMU_HDA_AMP_NONE, },{ .id = AC_PAR_GPIO_CAP, .val = 0, },{ .id = AC_PAR_AUDIO_FG_CAP, .val = 0x00000808, },{ .id = AC_PAR_POWER_STATE, .val = 0, }, }; /* duplex: nodes */ static const desc_node glue(duplex_nodes_, PARAM)[] = { { .nid = AC_NODE_ROOT, .name = "root", .params = glue(duplex_params_root_, PARAM), .nparams = ARRAY_SIZE(glue(duplex_params_root_, PARAM)), },{ .nid = 1, .name = "func", .params = glue(duplex_params_audio_func_, PARAM), .nparams = ARRAY_SIZE(glue(duplex_params_audio_func_, PARAM)), },{ .nid = 2, .name = "dac", .params = glue(common_params_audio_dac_, PARAM), .nparams = ARRAY_SIZE(glue(common_params_audio_dac_, PARAM)), .stindex = 0, },{ .nid = 3, .name = "out", .params = glue(common_params_audio_lineout_, PARAM), .nparams = ARRAY_SIZE(glue(common_params_audio_lineout_, PARAM)), .config = ((AC_JACK_PORT_COMPLEX << AC_DEFCFG_PORT_CONN_SHIFT) | (AC_JACK_LINE_OUT << AC_DEFCFG_DEVICE_SHIFT) | (AC_JACK_CONN_UNKNOWN << AC_DEFCFG_CONN_TYPE_SHIFT) | (AC_JACK_COLOR_GREEN << AC_DEFCFG_COLOR_SHIFT) | 0x10), .pinctl = AC_PINCTL_OUT_EN, .conn = (uint32_t[]) { 2 }, },{ .nid = 4, .name = "adc", .params = glue(common_params_audio_adc_, PARAM), .nparams = ARRAY_SIZE(glue(common_params_audio_adc_, PARAM)), .stindex = 1, .conn = (uint32_t[]) { 5 }, },{ .nid = 5, .name = "in", .params = glue(common_params_audio_linein_, PARAM), .nparams = ARRAY_SIZE(glue(common_params_audio_linein_, PARAM)), .config = ((AC_JACK_PORT_COMPLEX << AC_DEFCFG_PORT_CONN_SHIFT) | (AC_JACK_LINE_IN << AC_DEFCFG_DEVICE_SHIFT) | (AC_JACK_CONN_UNKNOWN << AC_DEFCFG_CONN_TYPE_SHIFT) | (AC_JACK_COLOR_RED << AC_DEFCFG_COLOR_SHIFT) | 0x20), .pinctl = AC_PINCTL_IN_EN, } }; /* duplex: codec */ static const desc_codec glue(duplex_, PARAM) = { .name = "duplex", .iid = QEMU_HDA_ID_DUPLEX, .nodes = glue(duplex_nodes_, PARAM), .nnodes = ARRAY_SIZE(glue(duplex_nodes_, PARAM)), }; /* micro: root node */ static const desc_param glue(micro_params_root_, PARAM)[] = { { .id = AC_PAR_VENDOR_ID, .val = QEMU_HDA_ID_MICRO, },{ .id = AC_PAR_SUBSYSTEM_ID, .val = QEMU_HDA_ID_MICRO, },{ .id = AC_PAR_REV_ID, .val = 0x00100101, },{ .id = AC_PAR_NODE_COUNT, .val = 0x00010001, }, }; /* micro: audio function */ static const desc_param glue(micro_params_audio_func_, PARAM)[] = { { .id = AC_PAR_FUNCTION_TYPE, .val = AC_GRP_AUDIO_FUNCTION, },{ .id = AC_PAR_SUBSYSTEM_ID, .val = QEMU_HDA_ID_MICRO, },{ .id = AC_PAR_NODE_COUNT, .val = 0x00020004, },{ .id = AC_PAR_PCM, .val = QEMU_HDA_PCM_FORMATS, },{ .id = AC_PAR_STREAM, .val = AC_SUPFMT_PCM, },{ .id = AC_PAR_AMP_IN_CAP, .val = QEMU_HDA_AMP_NONE, },{ .id = AC_PAR_AMP_OUT_CAP, .val = QEMU_HDA_AMP_NONE, },{ .id = AC_PAR_GPIO_CAP, .val = 0, },{ .id = AC_PAR_AUDIO_FG_CAP, .val = 0x00000808, },{ .id = AC_PAR_POWER_STATE, .val = 0, }, }; /* micro: nodes */ static const desc_node glue(micro_nodes_, PARAM)[] = { { .nid = AC_NODE_ROOT, .name = "root", .params = glue(micro_params_root_, PARAM), .nparams = ARRAY_SIZE(glue(micro_params_root_, PARAM)), },{ .nid = 1, .name = "func", .params = glue(micro_params_audio_func_, PARAM), .nparams = ARRAY_SIZE(glue(micro_params_audio_func_, PARAM)), },{ .nid = 2, .name = "dac", .params = glue(common_params_audio_dac_, PARAM), .nparams = ARRAY_SIZE(glue(common_params_audio_dac_, PARAM)), .stindex = 0, },{ .nid = 3, .name = "out", .params = glue(common_params_audio_lineout_, PARAM), .nparams = ARRAY_SIZE(glue(common_params_audio_lineout_, PARAM)), .config = ((AC_JACK_PORT_COMPLEX << AC_DEFCFG_PORT_CONN_SHIFT) | (AC_JACK_SPEAKER << AC_DEFCFG_DEVICE_SHIFT) | (AC_JACK_CONN_UNKNOWN << AC_DEFCFG_CONN_TYPE_SHIFT) | (AC_JACK_COLOR_GREEN << AC_DEFCFG_COLOR_SHIFT) | 0x10), .pinctl = AC_PINCTL_OUT_EN, .conn = (uint32_t[]) { 2 }, },{ .nid = 4, .name = "adc", .params = glue(common_params_audio_adc_, PARAM), .nparams = ARRAY_SIZE(glue(common_params_audio_adc_, PARAM)), .stindex = 1, .conn = (uint32_t[]) { 5 }, },{ .nid = 5, .name = "in", .params = glue(common_params_audio_linein_, PARAM), .nparams = ARRAY_SIZE(glue(common_params_audio_linein_, PARAM)), .config = ((AC_JACK_PORT_COMPLEX << AC_DEFCFG_PORT_CONN_SHIFT) | (AC_JACK_MIC_IN << AC_DEFCFG_DEVICE_SHIFT) | (AC_JACK_CONN_UNKNOWN << AC_DEFCFG_CONN_TYPE_SHIFT) | (AC_JACK_COLOR_RED << AC_DEFCFG_COLOR_SHIFT) | 0x20), .pinctl = AC_PINCTL_IN_EN, } }; /* micro: codec */ static const desc_codec glue(micro_, PARAM) = { .name = "micro", .iid = QEMU_HDA_ID_MICRO, .nodes = glue(micro_nodes_, PARAM), .nnodes = ARRAY_SIZE(glue(micro_nodes_, PARAM)), }; #undef PARAM #undef HDA_MIXER #undef QEMU_HDA_ID_OUTPUT #undef QEMU_HDA_ID_DUPLEX #undef QEMU_HDA_ID_MICRO #undef QEMU_HDA_AMP_CAPS
JavaGuy147/RT-Xen-Scheduler
tools/qemu-xen/hw/audio/hda-codec-common.h
C
gpl-2.0
13,884
<!DOCTYPE html> <html><head> <title> scheduler: DOM added script, late .src </title> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="testlib/testlib.js"></script> </head> <body> <div id="log">FAILED (This TC requires JavaScript enabled)</div> <script>log('inline script #1'); var script = testlib.addScript('', { }, document.getElementsByTagName('body')[0], false); script.src='scripts/include-1.js'; log('end script #1'); </script> <script type="text/javascript"> log( 'inline script #2' ); var t = async_test() onload = function() {setTimeout(t.step_func( function() { assert_any(assert_array_equals, eventOrder, [['inline script #1', 'end script #1', 'external script #1', 'inline script #2'], ['inline script #1', 'end script #1', 'inline script #2', 'external script #1']]); t.done() }), 100)} </script> </body></html>
cr/fxos-certsuite
web-platform-tests/tests/old-tests/submission/Opera/script_scheduling/022.html
HTML
mpl-2.0
1,027
// { dg-do assemble } // Origin: Mark Mitchell <[email protected]> extern "C" void f (); namespace N { extern "C" void f (); } using N::f; void g () { f (); }
SanDisk-Open-Source/SSD_Dashboard
uefi/gcc/gcc-4.6.3/gcc/testsuite/g++.old-deja/g++.ns/using14.C
C++
gpl-2.0
170